package com.bs.ct.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.bs.cm.domain.CmAttach;
import com.bs.cm.service.ICmAttachService;
import com.bs.common.core.domain.entity.SysDept;
import com.bs.common.core.domain.entity.SysUser;
import com.bs.common.utils.StringUtils;
import com.bs.ct.domain.CtTag;
import com.bs.ct.domain.CtTaskTemplateTag;
import com.bs.ct.service.ICtTagService;
import com.bs.ct.service.ICtTaskTemplateTagService;
import com.bs.ct.utils.HtmlUtils;
import com.bs.ct.vo.CtTaskTemplateVO;
import com.bs.system.mapper.SysDeptMapper;
import com.bs.system.mapper.SysUserMapper;
import com.bs.system.service.ISysDeptService;
import com.bs.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bs.common.annotation.Log;
import com.bs.common.core.controller.BaseController;
import com.bs.common.core.domain.AjaxResult;
import com.bs.common.core.page.TableDataInfo;
import com.bs.common.enums.BusinessType;
import com.bs.common.utils.poi.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.hutool.core.lang.Validator;
import com.bs.ct.domain.CtTaskTemplate;
import com.bs.ct.service.ICtTaskTemplateService;
import javax.annotation.Resource;

/**
 * 任务模板Controller
 *
 * @author bs
 * @date 2025-02-22
 */
@Api(tags = "任务模板")
@RestController
@RequestMapping("/task/template")
public class CtTaskTemplateController extends BaseController {
    @Resource
    private ICtTaskTemplateService ctTaskTemplateService;
    @Resource
    private ICtTaskTemplateTagService ctTaskTemplateTagService;
    @Resource
    private ICtTagService ctTagService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Resource
    private ICmAttachService cmAttachService;
    /**
     * 分页查询任务模板列表
     */
    @ApiOperation("分页查询任务模板列表")
    @GetMapping("/pageList")
    public TableDataInfo pageList(CtTaskTemplate ctTaskTemplate) {
        Integer pageNum = ctTaskTemplate.getPageNum() != null ? ctTaskTemplate.getPageNum() : 1;
        Integer pageSize = ctTaskTemplate.getPageSize() != null ? ctTaskTemplate.getPageSize() : 10;
        LambdaQueryWrapper<CtTaskTemplate> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,ctTaskTemplate);
        List<CtTaskTemplate> list = ctTaskTemplateService.list(queryWrapper);
        getAll(list);
        List<CtTaskTemplate> ctTaskTemplates = filterData(list, ctTaskTemplate);
        Integer start = (pageNum - 1) * pageSize;
        List<CtTaskTemplate> result = ctTaskTemplates.stream()
                .skip(start)  // 跳过前4条数据
                .limit(pageSize) // 最多取6条数据
                .collect(Collectors.toList());
        for (CtTaskTemplate taskTemplate : result) {
            List<CtTaskTemplateTag> listTag = ctTaskTemplateTagService.list(new LambdaQueryWrapper<CtTaskTemplateTag>()
                    .eq(CtTaskTemplateTag::getTemplateId,taskTemplate.getId()));
            for (CtTaskTemplateTag ctTaskTemplateTag : listTag) {
                List<CmAttach> cmAttaches = cmAttachService.list(new LambdaQueryWrapper<CmAttach>().eq(CmAttach::getFileId, ctTaskTemplateTag.getFileId()));
                if (null != cmAttaches && cmAttaches.size() > 0) {
                    ctTaskTemplateTag.setFiles(cmAttaches);
                }
            }
            taskTemplate.setTags(listTag);
        }
        TableDataInfo data = getDataTable(result);
        data.setTotal(ctTaskTemplates.size());
        return data;
    }

    private void getAll(List<CtTaskTemplate> list) {
        List<CtTaskTemplateTag> ctTaskTemplateTags = ctTaskTemplateTagService.list();
        Map<Long, String> collect = ctTaskTemplateTags.stream()
                .filter(tag -> tag.getTemplateId() != null) // 过滤null值
                .collect(Collectors.groupingBy(
                        CtTaskTemplateTag::getTemplateId,
                        Collectors.mapping(
                                CtTaskTemplateTag::getTagName,
                                Collectors.joining(", ")
                        )
                ));
        List<SysDept> depts = sysDeptMapper.selectDeptListAll();
        Map<Long, String> deptMap = depts.stream()
                .collect(Collectors.toMap(SysDept::getDeptId, SysDept::getDeptName));
        Map<Long, Long> deptMapByParent = depts.stream()
                .collect(Collectors.toMap(SysDept::getDeptId, SysDept::getParentId));
        List<SysUser> sysUsers = sysUserMapper.selectUserAll();
        Map<Long, String> stringHashMap = sysUsers.stream()
                .collect(Collectors.toMap(
                        SysUser::getUserId,
                        SysUser::getUserName,
                        (existing, replacement) -> existing,
                        HashMap::new
                ));
        for (CtTaskTemplate tag : list) {
            String tagName = collect.get(tag.getId());
            tag.setTagNames(tagName);
            String deptName = deptMap.get(tag.getCreateDept());
            Long parentId = deptMapByParent.get(tag.getCreateDept());
            String parentName = deptMap.get(parentId);
            String userName = stringHashMap.get(tag.getCreateBy());
            Date createTime = tag.getCreateTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedDate = sdf.format(createTime);
            tag.setCreateByUserName(userName);
            tag.setCreateByDeptName(deptName);
            tag.setCreateByBranch(parentName);
            tag.setCreateTimeVo(formattedDate);
        }
    }

    private List<CtTaskTemplate> filterData(List<CtTaskTemplate> allList, CtTaskTemplate ctTaskTemplate) {
        return allList.stream()
                .filter(item -> {
                    boolean match = true;
                    if (StringUtils.isNotBlank(ctTaskTemplate.getCreateByBranch())) {
                        match = match && item.getCreateByBranch() != null && item.getCreateByBranch().contains(ctTaskTemplate.getCreateByBranch());
                    }
                    if (StringUtils.isNotBlank(ctTaskTemplate.getCreateByDeptName())) {
                        match = match && item.getCreateByDeptName() != null && item.getCreateByDeptName().contains(ctTaskTemplate.getCreateByDeptName());
                    }
                    if (StringUtils.isNotBlank(ctTaskTemplate.getCreateByUserName())) {
                        match = match && item.getCreateByUserName() != null && item.getCreateByUserName().contains(ctTaskTemplate.getCreateByUserName());
                    }
                    if (ctTaskTemplate.getStartCreateTime() != null || ctTaskTemplate.getEndCreateTime() != null) {
                        Date itemCreateTime = item.getCreateTime();
                        if (ctTaskTemplate.getStartCreateTime() != null && (itemCreateTime == null || itemCreateTime.before(ctTaskTemplate.getStartCreateTime()))) {
                            match = false;
                        }
                        if (ctTaskTemplate.getEndCreateTime() != null && (itemCreateTime == null || itemCreateTime.after(ctTaskTemplate.getEndCreateTime()))) {
                            match = false;
                        }
                    }
                    if (StringUtils.isNotBlank(ctTaskTemplate.getTagNames())) {
                        // 这里假设CtTaskTemplate类有一个方法可以获取标签名称的字符串
                        String tagNamesStr = item.getTagNames();
                        match = match && tagNamesStr != null && tagNamesStr.contains(ctTaskTemplate.getTagNames());
                    }
                    return match;
                })
                .collect(Collectors.toList());
    }


    /**
     * 查询任务模板列表
     */
    @ApiOperation("查询任务模板列表")
    @GetMapping("/list")
    public AjaxResult list(CtTaskTemplate ctTaskTemplate) {
        LambdaQueryWrapper<CtTaskTemplate> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,ctTaskTemplate);
        List<CtTaskTemplate> list = ctTaskTemplateService.list(queryWrapper);
        return success(list);
    }

    /**
     * 导出任务模板列表
     */
    @ApiOperation("导出任务模板列表")
    @Log(title = "任务模板导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CtTaskTemplate ctTaskTemplate) {
        LambdaQueryWrapper<CtTaskTemplate> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,ctTaskTemplate);
        List<CtTaskTemplate> list = ctTaskTemplateService.list(queryWrapper);
        getAll(list);
        List<CtTaskTemplate> ctTaskTemplates = filterData(list, ctTaskTemplate);
        List<CtTaskTemplateVO> ctTaskTemplateVOList = new ArrayList<>();
        for (CtTaskTemplate ctTaskTemp : ctTaskTemplates) {
            CtTaskTemplateVO ctTaskTemplateVO = new CtTaskTemplateVO();
            BeanUtils.copyProperties(ctTaskTemp, ctTaskTemplateVO);
            ctTaskTemplateVO.setTaskContent(HtmlUtils.stripHtmlTags(ctTaskTemplateVO.getTaskContent()));
            ctTaskTemplateVOList.add(ctTaskTemplateVO);
        }
        ExcelUtil<CtTaskTemplateVO> util = new ExcelUtil<CtTaskTemplateVO>(CtTaskTemplateVO. class);
        util.exportExcel(response, ctTaskTemplateVOList, "任务模板数据");
    }

    /**
     * 获取任务模板详细信息
     */
    @ApiOperation("获取任务模板详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        CtTaskTemplate templateServiceById = ctTaskTemplateService.getById(id);
        List<CtTaskTemplateTag> list = ctTaskTemplateTagService.list(new LambdaQueryWrapper<CtTaskTemplateTag>()
                .eq(CtTaskTemplateTag::getTemplateId,id));
        for (CtTaskTemplateTag ctTaskTemplateTag : list) {
            List<CmAttach> cmAttaches = cmAttachService.list(new LambdaQueryWrapper<CmAttach>().eq(CmAttach::getFileId, ctTaskTemplateTag.getFileId()));
            if (null != cmAttaches && cmAttaches.size() > 0) {
                ctTaskTemplateTag.setFiles(cmAttaches);
            }
        }
        templateServiceById.setTags(list);
        return success(templateServiceById);
    }

    /**
     * 修改任务模板相关标签
     */
    @ApiOperation("删除任务模板相关标签")
    @Log(title = "删除任务模板相关标签", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/removeTag")
    public AjaxResult removeTag(@RequestBody CtTaskTemplate ctTaskTemplate) {
        List<String> ids = ctTaskTemplate.getTagIds();
        boolean remove = ctTaskTemplateTagService.remove(new LambdaQueryWrapper<CtTaskTemplateTag>().in(CtTaskTemplateTag::getId, ids));
        return toAjax(remove);
    }

    /**
     * 修改任务模板相关标签
     */
    @ApiOperation("新增任务模板相关标签")
    @Log(title = "新增任务模板相关标签", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/addTag")
    public AjaxResult addTag(@RequestBody CtTaskTemplate ctTaskTemplate) {
        saveTags(ctTaskTemplate);
        return toAjax(true);
    }

    /**
     * 新增任务模板
     */
    @ApiOperation("新增任务模板")
    @Log(title = "任务模板新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CtTaskTemplate ctTaskTemplate) {
        boolean save = ctTaskTemplateService.save(ctTaskTemplate);
        if (save) {
            saveTags(ctTaskTemplate);
        }
        return toAjax(true);
    }

    /**
     * 修改任务模板
     */
    @ApiOperation("修改任务模板")
    @Log(title = "任务模板修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CtTaskTemplate ctTaskTemplate) {
        saveTags(ctTaskTemplate);
        return toAjax(ctTaskTemplateService.updateById(ctTaskTemplate));
    }

    private void saveTags(CtTaskTemplate ctTaskTemplate) {
        List<String> tagIds = ctTaskTemplate.getTagIds();
        if (null != tagIds && tagIds.size() > 0) {
            List<CtTag> ctTags = ctTagService.list(new LambdaQueryWrapper<CtTag>().in(CtTag::getId, tagIds));
            for (CtTag ctTag : ctTags) {
                Long ctTaskTemplateId = ctTaskTemplate.getId();
                CtTaskTemplateTag ctTaskTemplateTag = new CtTaskTemplateTag();
                ctTaskTemplateTag.setTemplateId(ctTaskTemplateId);
                ctTaskTemplateTag.setTagName(ctTag.getTagName());
                ctTaskTemplateTag.setTagDesc(ctTag.getTagDesc());
                ctTaskTemplateTag.setIsPhoto(ctTag.getIsPhoto());
                ctTaskTemplateTag.setPhotoNum(ctTag.getPhotoNum());
                ctTaskTemplateTag.setSaveDir(ctTag.getSaveDir());
                ctTaskTemplateTag.setFileId(ctTag.getFileId());
                ctTaskTemplateTagService.save(ctTaskTemplateTag);
            }
        }
    }

    /**
     * 删除任务模板
     */
    @ApiOperation("删除任务模板")
    @Log(title = "任务模板删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(ctTaskTemplateService.removeBatchByIds(ids));
    }

    /**
      * 条件设置
      */
    private void condition (LambdaQueryWrapper<CtTaskTemplate> queryWrapper,CtTaskTemplate ctTaskTemplate){


        //id
        if(Validator.isNotEmpty(ctTaskTemplate.getId())){
            queryWrapper.eq(CtTaskTemplate::getId,ctTaskTemplate.getId());
        }

        //任务类型
        if(Validator.isNotEmpty(ctTaskTemplate.getTaskType())){
            queryWrapper.eq(CtTaskTemplate::getTaskType,ctTaskTemplate.getTaskType());
        }

        //模板名称
        if(Validator.isNotEmpty(ctTaskTemplate.getTemplateName())){
            queryWrapper.eq(CtTaskTemplate::getTemplateName,ctTaskTemplate.getTemplateName());
        }

        //任务标题
        if(Validator.isNotEmpty(ctTaskTemplate.getTaskTitle())){
            queryWrapper.eq(CtTaskTemplate::getTaskTitle,ctTaskTemplate.getTaskTitle());
        }

        //任务要求
        if(Validator.isNotEmpty(ctTaskTemplate.getTaskContent())){
            queryWrapper.eq(CtTaskTemplate::getTaskContent,ctTaskTemplate.getTaskContent());
        }

        //备注
        if(Validator.isNotEmpty(ctTaskTemplate.getRemarks())){
            queryWrapper.eq(CtTaskTemplate::getRemarks,ctTaskTemplate.getRemarks());
        }

        //删除标志（0代表存在 2代表删除）
        if(Validator.isNotEmpty(ctTaskTemplate.getDelFlag())){
            queryWrapper.eq(CtTaskTemplate::getDelFlag,ctTaskTemplate.getDelFlag());
        }

        //创建部门
        if(Validator.isNotEmpty(ctTaskTemplate.getCreateDept())){
            queryWrapper.eq(CtTaskTemplate::getCreateDept,ctTaskTemplate.getCreateDept());
        }

        //创建人
        if(Validator.isNotEmpty(ctTaskTemplate.getCreateBy())){
            queryWrapper.eq(CtTaskTemplate::getCreateBy,ctTaskTemplate.getCreateBy());
        }

        //创建时间
        if(Validator.isNotEmpty(ctTaskTemplate.getCreateTime())){
            queryWrapper.eq(CtTaskTemplate::getCreateTime,ctTaskTemplate.getCreateTime());
        }

        //修改人
        if(Validator.isNotEmpty(ctTaskTemplate.getUpdateBy())){
            queryWrapper.eq(CtTaskTemplate::getUpdateBy,ctTaskTemplate.getUpdateBy());
        }

        //修改时间
        if(Validator.isNotEmpty(ctTaskTemplate.getUpdateTime())){
            queryWrapper.eq(CtTaskTemplate::getUpdateTime,ctTaskTemplate.getUpdateTime());
        }

        //租户ID
        if(Validator.isNotEmpty(ctTaskTemplate.getTenantId())){
            queryWrapper.eq(CtTaskTemplate::getTenantId,ctTaskTemplate.getTenantId());
        }

        }

}
