package com.bs.ct.controller;

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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.model.LoginUser;
import com.bs.ct.domain.*;
import com.bs.ct.service.ICtTaskBranchService;
import com.bs.ct.service.ICtTaskFeedbackService;
import com.bs.ct.service.ICtTaskTagService;
import com.bs.system.service.ISysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.service.ICtTaskInfoService;
import javax.annotation.Resource;

/**
 * 任务信息Controller
 *
 * @author bs
 * @date 2025-02-22
 */
@Api(tags = "任务信息")
@RestController
@RequestMapping("/task/info")
public class CtTaskInfoController extends BaseController {
    @Resource
    private ICtTaskInfoService ctTaskInfoService;
    @Autowired
    private ISysDeptService deptService;
    @Resource
    private ICtTaskBranchService ctTaskBranchService;
    @Resource
    private ICmAttachService cmAttachService;
    @Resource
    private ICtTaskFeedbackService ctTaskFeedbackService;
    @Resource
    private ICtTaskTagService ctTaskTagService;

    /**
     * 分页查询任务信息列表
     */
    @ApiOperation("分页查询任务信息列表")
    @GetMapping("/pageList")
    public TableDataInfo pageList(CtTaskInfo ctTaskInfo) {
        startPage();
        LambdaQueryWrapper<CtTaskInfo> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,ctTaskInfo);
        List<CtTaskInfo> list = ctTaskInfoService.list(queryWrapper);
        setAll(list);
        return getDataTable(list);
    }

    /**
     * 分页查询任务信息列表
     */
    @ApiOperation("分页查询任务信息列表")
    @GetMapping("/pageListByBranch")
    public TableDataInfo pageListByBranch(CtTaskInfo ctTaskInfo) {
        startPage();
        LambdaQueryWrapper<CtTaskInfo> queryWrapper = new LambdaQueryWrapper();
        ctTaskInfo.setStatus("1");
        condition(queryWrapper,ctTaskInfo);
        List<CtTaskInfo> list = ctTaskInfoService.list(queryWrapper);
        setAll(list);
        return getDataTable(list);
    }

    /**
     * 分页查询任务信息列表
     */
    @ApiOperation("分页查询任务信息列表")
    @GetMapping("/pageListByUser")
    public TableDataInfo pageListByUser(CtTaskInfo ctTaskInfo) {
        Integer pageNum = ctTaskInfo.getPageNum() != null ? ctTaskInfo.getPageNum() : 1;
        Integer pageSize = ctTaskInfo.getPageSize() != null ? ctTaskInfo.getPageSize() : 10;
        String userId = String.valueOf(getUserId());
        LambdaQueryWrapper<CtTaskInfo> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,ctTaskInfo);
        List<CtTaskInfo> list = ctTaskInfoService.list(queryWrapper);
        setAll(list);
        List<CtTaskInfo> filteredList = filterTaskInfos(list, userId);
        Integer start = (pageNum - 1) * pageSize;
        List<CtTaskInfo> result = filteredList.stream()
                .skip(start)  // 跳过前4条数据
                .limit(pageSize) // 最多取6条数据
                .collect(Collectors.toList());
        for (CtTaskInfo taskOtherBranch : result) {
            // 从 sdTaskOtherFeedbackService 中查询符合条件的 SdTaskOtherFeedback 列表：
            // 1. taskBranchId 等于当前 SdTaskOtherBranch 的 id
            // 2. status 不等于 0
            // 3. 按照创建时间（CreateTime）倒序排列
            List<CtTaskFeedback> feedbackListByCreateTime = ctTaskFeedbackService.list(new LambdaQueryWrapper<CtTaskFeedback>()
                    .eq(CtTaskFeedback::getTaskBranchId, taskOtherBranch.getId())
                    .ne(CtTaskFeedback::getStatus, 0)
                    .orderByDesc(CtTaskFeedback::getCreateTime));
            // 如果根据创建时间查询到的反馈列表不为空且至少有一个元素
            if (!feedbackListByCreateTime.isEmpty() && feedbackListByCreateTime.size() > 0) {
                // 将该列表中的第一个元素（因为是倒序排列，所以是最新的一条）设置到当前 SdTaskOtherBranch 对象中
                taskOtherBranch.setSdTaskOtherFeedbackByCreate(feedbackListByCreateTime.get(0));
            }
            // 从 sdTaskOtherFeedbackService 中查询符合条件的 SdTaskOtherFeedback 列表：
            // 1. taskBranchId 等于当前 SdTaskOtherBranch 的 id
            // 2. status 等于 1
            // 3. 按照反馈时间（FeedbackTime）倒序排列
            List<CtTaskFeedback> feedbackListByFeedbackTime = ctTaskFeedbackService.list(new LambdaQueryWrapper<CtTaskFeedback>()
                    .eq(CtTaskFeedback::getTaskId, taskOtherBranch.getId())
                    .eq(CtTaskFeedback::getStatus, 1)
                    .orderByDesc(CtTaskFeedback::getFeedbackTime));
            // 如果根据反馈时间查询到的反馈列表不为空且至少有一个元素
            if (!feedbackListByFeedbackTime.isEmpty() && feedbackListByFeedbackTime.size() > 0) {
                // 将该列表中的第一个元素（因为是倒序排列，所以是最新的一条）设置到当前 SdTaskOtherBranch 对象中
                taskOtherBranch.setSdTaskOtherFeedbackByFeedback(feedbackListByFeedbackTime.get(0));
            }
        }

        TableDataInfo data = getDataTable(result);
        data.setTotal(filteredList.size());
        return data;
    }

    public static List<CtTaskInfo> filterTaskInfos(List<CtTaskInfo> list, String userId) {
        List<CtTaskInfo> filteredList = new ArrayList<>();
        for (CtTaskInfo taskInfo : list) {
            if (taskInfo.getUserIds() != null && taskInfo.getUserIds().contains(userId)) {
                filteredList.add(taskInfo);
            }
        }
        return filteredList;
    }

    /**
     * 查询任务信息列表
     */
    @ApiOperation("查询任务信息列表")
    @GetMapping("/list")
    public AjaxResult list(CtTaskInfo ctTaskInfo) {
        LambdaQueryWrapper<CtTaskInfo> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,ctTaskInfo);
        List<CtTaskInfo> list = ctTaskInfoService.list(queryWrapper);
        return success(list);
    }

    private void setAll(List<CtTaskInfo> list) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        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));
        for (CtTaskInfo taskInfo : list) {
            List<CmAttach> cmAttachList = cmAttachService.list(new LambdaQueryWrapper<CmAttach>().eq(CmAttach::getFileId,taskInfo.getFileId()));
            taskInfo.setFile(cmAttachList);
            Date startDate = taskInfo.getStartDate();
            Date endDate = taskInfo.getEndDate();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            // 转换日期为字符串
            if (null != startDate && endDate != endDate) {
                String startDateStr = sdf.format(startDate);
                String endDateStr = sdf.format(endDate);
                taskInfo.setStartToEndDate(startDateStr + "-" + endDateStr);
            }
            String deptName = deptMap.get(taskInfo.getDeptId());
            taskInfo.setDeptName(deptName);
            if ("1".equals(taskInfo.getStatus()) || "0".equals(taskInfo.getStatus())) {
                taskInfo.setTaskStatus("未完成");
                // 获取当前日期
                Date currentDate = new Date();
                if (endDate.compareTo(currentDate) < 0) {
                    taskInfo.setTaskStatus("已逾期");
                }
            } else if ("2".equals(taskInfo.getStatus())) {
                taskInfo.setTaskStatus("已完成");
            }
            List<CtTaskBranch> ctTaskBranches = ctTaskBranchService.list(new LambdaQueryWrapper<CtTaskBranch>()
                    .eq(CtTaskBranch::getTaskId,taskInfo.getId())
                    .eq(CtTaskBranch::getType,"人员"));
            String transactDeptNames = "";
            String transactInitiator = "";
            String transactBranchNames = "";
            if (null != ctTaskBranches) {
                List<String> deptNameList = new ArrayList<>();
                List<String> parentDeptNameList = new ArrayList<>();
                List<String> userNameList = new ArrayList<>();
                List<String> userIdList = new ArrayList<>();
                for (CtTaskBranch ctTaskBranchesItem : ctTaskBranches) {
                    String deptNameVo = deptMap.get(Long.valueOf(ctTaskBranchesItem.getBranchCode()));
                    Long parentTaskId = deptMapByParent.get(Long.valueOf(ctTaskBranchesItem.getBranchCode()));
                    String parentDeptName = deptMap.get(parentTaskId);
                    String userName = ctTaskBranchesItem.getUserName();
                    String userId = ctTaskBranchesItem.getUserId();
                    if (deptNameVo != null) {
                        deptNameList.add(deptNameVo);
                    }
                    if (parentDeptName != null) {
                        parentDeptNameList.add(parentDeptName);
                    }
                    if (userName != null) {
                        userNameList.add(userName);
                    }
                    if (null != userId) {
                        userIdList.add(userId);
                    }
                }
                transactDeptNames = String.join(",", deptNameList);
                transactInitiator = String.join(",", userNameList);
                transactBranchNames =  String.join(",", parentDeptNameList);
                taskInfo.setTransactDeptName(transactDeptNames);
                taskInfo.setTransactInitiator(transactInitiator);
                taskInfo.setTransactBranchName(transactBranchNames);
                taskInfo.setUserIds(userIdList);
            }
        }
    }

    /**
     * 撤回其他任务
     */
    @ApiOperation("撤回其他任务")
    @GetMapping("/withdraw/{ids}")
    public void withdraw(@PathVariable List<Long> ids) {
        List<CtTaskInfo> sdTaskOthers = ctTaskInfoService.listByIds(ids);
        for (CtTaskInfo sdTaskOther : sdTaskOthers) {
            sdTaskOther.setStatus("0");
            sdTaskOther.setTaskDate(null);
        }
        List<CtTaskBranch> sdTaskOtherBranches = ctTaskBranchService.list(new LambdaQueryWrapper<CtTaskBranch>()
                .in(CtTaskBranch::getTaskId, ids));
        for (CtTaskBranch sdTaskOtherBranch : sdTaskOtherBranches) {
            sdTaskOtherBranch.setTaskStatus("0");
        }
        ctTaskBranchService.updateBatchById(sdTaskOtherBranches);
        ctTaskInfoService.updateBatchById(sdTaskOthers);
    }

    /**
     * 发布其他任务
     */
    @ApiOperation("发布其他任务")
    @GetMapping("/publishOther/{ids}")
    public AjaxResult publishOther(@PathVariable List<Long> ids) {
        List<CtTaskInfo> sdTaskOthers = ctTaskInfoService.listByIds(ids);
        for (CtTaskInfo sdTaskOther : sdTaskOthers) {
            if ("2".equals(sdTaskOther.getStatus())) {
                return AjaxResult.error("任务已办结，无法发布");
            }
            sdTaskOther.setStatus("1");
            sdTaskOther.setTaskDate(new Date());
        }
        List<CtTaskBranch> sdTaskOtherBranches = ctTaskBranchService.list(new LambdaQueryWrapper<CtTaskBranch>()
                .in(CtTaskBranch::getTaskId, ids));
        for (CtTaskBranch sdTaskOtherBranch : sdTaskOtherBranches) {
            sdTaskOtherBranch.setTaskStatus("1");
        }
        ctTaskBranchService.updateBatchById(sdTaskOtherBranches);
        ctTaskInfoService.updateBatchById(sdTaskOthers);
        return AjaxResult.success(true);
    }

    /**
     * 导出任务信息列表
     */
    @ApiOperation("导出任务信息列表")
    @Log(title = "任务信息导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CtTaskInfo ctTaskInfo) {
        LambdaQueryWrapper<CtTaskInfo> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,ctTaskInfo);
        List<CtTaskInfo> list = ctTaskInfoService.list(queryWrapper);
        ExcelUtil<CtTaskInfo> util = new ExcelUtil<CtTaskInfo>(CtTaskInfo. class);
        util.exportExcel(response, list, "任务信息数据");
    }



    /**
     * 获取任务信息详细信息
     */
    @ApiOperation("获取任务信息详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(ctTaskInfoService.getById(id));
    }

    /**
     * 新增任务信息
     */
    @ApiOperation("新增任务信息")
    @Log(title = "任务信息新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CtTaskInfo ctTaskInfo) {
        Long newId = System.currentTimeMillis() + new Random().nextInt(1000);
        updateFile(ctTaskInfo);
        ctTaskInfo.setId(newId);
        List<CtTaskBranch> branchList = ctTaskInfo.getBranchList();
        for (CtTaskBranch sdTaskOtherBranch : branchList) {
            sdTaskOtherBranch.setTaskId(ctTaskInfo.getId());
            sdTaskOtherBranch.setType("机构");
            ctTaskBranchService.saveOrUpdate(sdTaskOtherBranch);
        }
        //设置发起单位与部门
        LoginUser loginUser = getLoginUser();
        Long deptId = loginUser.getDeptId();
        if (null != deptId) {
            ctTaskInfo.setDeptId(deptId);
            SysDept sysDept = deptService.selectDeptById(deptId);
            Long parentId = sysDept.getParentId();
            SysDept parentDept = deptService.selectDeptById(parentId);
            if (null != parentDept) {
                ctTaskInfo.setBranchCode(String.valueOf(parentDept.getDeptId()));
                ctTaskInfo.setBranchName(parentDept.getDeptName());
            }
        }
        if ("1".equals(ctTaskInfo.getStatus())) {
            ctTaskInfo.setTaskDate(new Date());
        }
        boolean save = ctTaskInfoService.save(ctTaskInfo);
        if (save) {
            List<CtTaskTag> tasgs = ctTaskInfo.getTags();
            if (null != tasgs && tasgs.size() > 0) {
                for (CtTaskTag taskTag : tasgs){
                    taskTag.setTaskId(ctTaskInfo.getId());
                }
                ctTaskTagService.saveBatch(tasgs);
            }
        }
        return toAjax(true);
    }

    /**
     * 修改任务信息
     */
    @ApiOperation("修改任务信息")
    @Log(title = "任务信息修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CtTaskInfo ctTaskInfo) {
        updateFile(ctTaskInfo);
        List<CtTaskBranch> branchList = ctTaskInfo.getBranchList();
        if (branchList != null && branchList.size() > 0) {
            for (CtTaskBranch sdTaskOtherBranch : branchList) {
                sdTaskOtherBranch.setTaskId(ctTaskInfo.getId());
                sdTaskOtherBranch.setType("机构");
                if (sdTaskOtherBranch.getId() == null) {
                    ctTaskBranchService.save(sdTaskOtherBranch);
                } else {
                    ctTaskBranchService.updateById(sdTaskOtherBranch);
                }
            }
        }
        if ("1".equals(ctTaskInfo.getStatus())) {
            LoginUser loginUser = getLoginUser();
            ctTaskInfo.setTaskDate(new Date());
            ctTaskInfo.setTaskInitiator(loginUser.getUsername());
        }
        List<CtTaskTag> tasgs = ctTaskInfo.getTags();
        if (null != tasgs && tasgs.size() > 0) {
            for (CtTaskTag taskTag : tasgs) {
                taskTag.setTaskId(ctTaskInfo.getId());
            }
            ctTaskTagService.saveOrUpdateBatch(tasgs);
        }
        return toAjax(ctTaskInfoService.updateById(ctTaskInfo));
    }

    private void updateFile(CtTaskInfo ctTaskInfo) {
        Long newId = System.currentTimeMillis() + new Random().nextInt(1000);
        List<CmAttach> file = ctTaskInfo.getFile();
        if (null != file) {
            for (CmAttach cmAttach : file) {
                cmAttach.setFileId(String.valueOf(newId));
            }
            cmAttachService.updateBatchById(file);
            ctTaskInfo.setFileId(newId);
        }
    }

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

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


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

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

        //任务标题
        if(Validator.isNotEmpty(ctTaskInfo.getTaskTitle())){
            queryWrapper.like(CtTaskInfo::getTaskTitle,ctTaskInfo.getTaskTitle());
        }

        //任务编号
        if(Validator.isNotEmpty(ctTaskInfo.getTaskCode())){
            queryWrapper.eq(CtTaskInfo::getTaskCode,ctTaskInfo.getTaskCode());
        }

        //开始时间
        if(Validator.isNotEmpty(ctTaskInfo.getStartDate())){
            queryWrapper.ge(CtTaskInfo::getStartDate,ctTaskInfo.getStartDate());
        }

        //结束时间
        if(Validator.isNotEmpty(ctTaskInfo.getEndDate())){
            queryWrapper.le(CtTaskInfo::getEndDate,ctTaskInfo.getEndDate());
        }

        // 查询逾期任务.
        if (Validator.isNotEmpty(ctTaskInfo.getQueryDate())) {
            queryWrapper.le(CtTaskInfo::getEndDate,ctTaskInfo.getQueryDate()).eq(CtTaskInfo::getStatus, "1");
        }

        //任务要求
        if(Validator.isNotEmpty(ctTaskInfo.getTaskContent())){
            queryWrapper.like(CtTaskInfo::getTaskContent,ctTaskInfo.getTaskContent());
        }

        //完成状态
        if(Validator.isNotEmpty(ctTaskInfo.getStatus())){
            queryWrapper.eq(CtTaskInfo::getStatus,ctTaskInfo.getStatus());
        }

        //附件id
        if(Validator.isNotEmpty(ctTaskInfo.getFileId())){
            queryWrapper.eq(CtTaskInfo::getFileId,ctTaskInfo.getFileId());
        }

        //任务发起人
        if(Validator.isNotEmpty(ctTaskInfo.getTaskInitiator())){
            queryWrapper.eq(CtTaskInfo::getTaskInitiator,ctTaskInfo.getTaskInitiator());
        }

        //任务发起单位机构代码
        if(Validator.isNotEmpty(ctTaskInfo.getBranchCode())){
            queryWrapper.eq(CtTaskInfo::getBranchCode,ctTaskInfo.getBranchCode());
        }

        //任务发起单位
        if(Validator.isNotEmpty(ctTaskInfo.getBranchName())){
            queryWrapper.eq(CtTaskInfo::getBranchName,ctTaskInfo.getBranchName());
        }

        //任务发起部门
        if(Validator.isNotEmpty(ctTaskInfo.getDeptId())){
            queryWrapper.eq(CtTaskInfo::getDeptId,ctTaskInfo.getDeptId());
        }

        //任务发布日期
        if(Validator.isNotEmpty(ctTaskInfo.getTaskDate())){
            queryWrapper.eq(CtTaskInfo::getTaskDate,ctTaskInfo.getTaskDate());
        }

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

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

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

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

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

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

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

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

        }

}
