package com.testor.module.safeCheck.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.sys.dict.data.model.domain.SysDictData;
import com.testor.biz.sys.dict.data.service.SysDictDataService;
import com.testor.biz.sys.user.model.domain.SysUser;
import com.testor.biz.sys.user.service.SysUserService;
import com.testor.common.core.utils.StringUtils;
import com.testor.common.util.cron.CheckFrequencyEnum;
import com.testor.module.messageNotice.model.domain.TMsgNotice;
import com.testor.module.messageNotice.model.vo.MsgTemplateVO;
import com.testor.module.messageNotice.service.TMsgNoticeService;
import com.testor.module.safeCheck.dao.TSafeCheckTaskDao;
import com.testor.module.safeCheck.model.domain.*;
import com.testor.module.safeCheck.model.dto.TSafeCheckPlanParam;
import com.testor.module.safeCheck.model.dto.TSafeCheckTaskParam;
import com.testor.module.safeCheck.model.vo.TSafeCheckTaskRecordVo;
import com.testor.module.safeCheck.model.vo.TSafeCheckTaskVo;
import com.testor.module.safeCheck.service.*;
import com.testor.module.sys.model.domian.NewSysOrg;
import com.testor.module.sys.service.NewSysOrgService;
import com.testor.xxl.job.task.util.CronUtil;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import com.tongtech.tfw.workflow.apis.task.controller.WfTaskController;
import com.tongtech.tfw.workflow.apis.task.model.dto.CompleteTask;
import com.tongtech.tfw.workflow.service.TfwProcessInsService;
import com.tongtech.tfw.workflow.service.dto.ProcessInsStartParams;
import com.tongtech.tfw.workflow.service.dto.ProcessInsStartResult;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 安全检查计划任务Service业务层处理
 * 
 * @author testor-framework
 * @date 2024-09-03 08:04:19
 */
@Slf4j
@Service
public class TSafeCheckTaskServiceImpl extends SuperServiceImpl<TSafeCheckTaskDao, TSafeCheckTask> implements TSafeCheckTaskService
{
    @Autowired(required = false)
    private TSafeCheckTaskDao tSafeCheckTaskDao;

    @Autowired
    private TSafeCheckPlanService tSafeCheckPlanService;

    @Autowired
    private TSafeCheckPersonService tSafeCheckPersonService;

    @Autowired
    private TfwProcessInsService tfwProcessInsService;

    @Autowired
    private WfTaskController wfTaskController;

    @Autowired
    private TSafeCheckPersonArrangeService tSafeCheckPersonArrangeService;

    @Autowired
    private TSafeCheckTaskRecordService tSafeCheckTaskRecordService;

    @Autowired
    private TSafeCheckTaskPostponeService tSafeCheckTaskPostponeService;

    @Autowired
    private NewSysOrgService sysOrgService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysDictDataService sysDictDataService;

    @Autowired
    private TSafeCheckOrgService tSafeCheckOrgService;

    @Autowired
    private TMsgNoticeService tMsgNoticeService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TSafeCheckTask generateTasks(TSafeCheckPerson tSafeCheckPerson, TSafeCheckPlan tSafeCheckPlan, LocalDateTime taskStartDate, LocalDateTime taskEndDate) {
        TSafeCheckTask tSafeCheckTask = new TSafeCheckTask();
        tSafeCheckTask.setCheckPersonId(tSafeCheckPerson.getId());
        tSafeCheckTask.setPlanId(tSafeCheckPerson.getPlanId());
        tSafeCheckTask.setIsOverdue("0");
        tSafeCheckTask.setName(tSafeCheckPlan.getName());
        tSafeCheckTask.setCheckType(tSafeCheckPerson.getCheckType());
        tSafeCheckTask.setOrgId(tSafeCheckPlan.getOrgId());
        Date date = com.testor.common.util.DateUtil.localDateTimeToDate(taskStartDate);
        tSafeCheckTask.setStartTime(date);
        Date date2 = com.testor.common.util.DateUtil.localDateTimeToDate(taskEndDate);
        tSafeCheckTask.setEndTime(date2);
        tSafeCheckTask.setInitialEndDate(date2);
        // 任务时间
        tSafeCheckTask.setIsOverdue("0");
        save(tSafeCheckTask);
        String createBy = tSafeCheckPlan.getCreateBy();
        SysUser byId = sysUserService.getById(createBy);
        List<TSafeCheckPersonArrange> tSafeCheckPersonArranges = tSafeCheckPersonArrangeService.list(new LambdaQueryWrapper<TSafeCheckPersonArrange>().eq(TSafeCheckPersonArrange::getCheckPersonId, tSafeCheckPerson.getId()));
        for (TSafeCheckPersonArrange tSafeCheckPersonArrange : tSafeCheckPersonArranges) {
            ProcessInsStartParams processInsStartParams = new ProcessInsStartParams();
            processInsStartParams.setBizKey(tSafeCheckTask.getId());
            processInsStartParams.setProcessDefinitionKey("safetyCheck");
            processInsStartParams.setUserId(tSafeCheckPlan.getCreateBy());
            processInsStartParams.setOrgId(byId.getOrgId());
            Map<String, Object> varMap = new HashMap<>();
            varMap.put("processStatus", "3");
            varMap.put("checkUser", tSafeCheckPersonArrange.getUserId());
            processInsStartParams.setVariables(varMap);
            ProcessInsStartResult processInsStartResult = tfwProcessInsService.startProcessInsByKey(processInsStartParams);
            // processInsStartResult.getCode();
            // 更新 task：写入流程id
            tSafeCheckPersonArrange.setProcessId(processInsStartResult.getCode());
            tSafeCheckPersonArrange.setProcessStatus("3");
            tSafeCheckPersonArrangeService.updateById(tSafeCheckPersonArrange);
            //存储记录
            TSafeCheckTaskRecord tSafeCheckTaskRecord = new TSafeCheckTaskRecord();
            tSafeCheckTaskRecord.setCheckPersonId(tSafeCheckPersonArrange.getCheckPersonId());
            tSafeCheckTaskRecord.setTaskId(tSafeCheckTask.getId());
            tSafeCheckTaskRecord.setProcessStatus("3");
            tSafeCheckTaskRecord.setProcessId(processInsStartResult.getCode());
            tSafeCheckTaskRecord.setRefId(tSafeCheckPersonArrange.getUserId());
            tSafeCheckTaskRecord.setRefType(TSafeCheckTaskRecord.RefType.USER.getCode());
            tSafeCheckTaskRecord.setPlanId(tSafeCheckPersonArrange.getPlanId());
            tSafeCheckTaskRecord.setOrgId(tSafeCheckTask.getOrgId());
            tSafeCheckTaskRecordService.save(tSafeCheckTaskRecord);
            //发送通知
            sendTaskMessage(tSafeCheckPlan.getName(),tSafeCheckPersonArrange.getUserId(),tSafeCheckTask.getId());
        }
        //设置已生成
        tSafeCheckPerson.setGenerateTask("1");
        tSafeCheckPersonService.updateById(tSafeCheckPerson);
        return tSafeCheckTask;
    }

    private void sendTaskMessage(String taskName,String checkUser,String taskId) {
        String time = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒").format(new Date());
        String msg = "安全检查任务[" + taskName + "]于" + time + "开始,请您及时处理";
        // 发送消息
        String bizKey = "safetyCheck";
        TMsgNotice msgNotice = new TMsgNotice();
        msgNotice.setBusinessId(taskId);
        msgNotice.setBusinessKey(bizKey);
        msgNotice.setMsgType("notice");
        msgNotice.setMsgTypeName("通知");
        msgNotice.setContent(msg);
        msgNotice.setIsRead("0");
        msgNotice.setUserId(checkUser);
        tMsgNoticeService.save(msgNotice);
    }

    @Override
    @XxlJob("createCheckTaskExecutor")
    public void createCheckTaskExecutor() {
        LocalDateTime nowTime = LocalDateTime.now();
        //获取所有正常运行的计划
        List<TSafeCheckPlan> list = tSafeCheckPlanService.findOngoingList();
        if (CollectionUtils.isEmpty(list)) {
            log.info("当前没有正在运行的安全检查计划:"+LocalDateTime.now());
            return;
        }
        for (TSafeCheckPlan tSafeCheckPlan : list) {
            List<TSafeCheckPerson> listByPlanId = tSafeCheckPersonService.getListByPlanId(tSafeCheckPlan.getId());
            //生成每个人员任务
            for (TSafeCheckPerson tSafeCheckPerson : listByPlanId) {
                if (!BizConstants.STATUS_ENABLE.equals(tSafeCheckPerson.getStatus())) {
                    continue;
                }
                TSafeCheckPlan tSafeCheckPlan1 = buildStartAndEndTime(tSafeCheckPerson, nowTime);
                LocalDateTime startDate = com.testor.common.util.DateUtil.dateToLocalDateTime(tSafeCheckPlan1.getStartDate()) ;
                LocalDateTime endDate = com.testor.common.util.DateUtil.dateToLocalDateTime(tSafeCheckPlan1.getEndDate());
                // 一天的结束时间，例如：2020-02-02 23:59:59,999
                LocalDateTime endOfDay = LocalDateTimeUtil.endOfDay(nowTime);
                // 开始时间非今天的 过滤掉
                if(LocalDateTimeUtil.between(startDate, endOfDay, ChronoUnit.SECONDS) < 0) {
                    continue;
                }
                //跳过已创建的任务
                int count = this.count(new LambdaQueryWrapper<TSafeCheckTask>().eq(TSafeCheckTask::getCheckPersonId, tSafeCheckPerson.getId())
                        .eq(TSafeCheckTask::getStartTime,  tSafeCheckPlan1.getStartDate()));
                if (count > 0) {
                    continue;
                }
                //创建任务
                generateTasks(tSafeCheckPerson,tSafeCheckPlan,startDate,endDate);
            }
        }
    }


    @Override
    public TSafeCheckPlan buildStartAndEndTime(TSafeCheckPerson tSafeCheckPerson, LocalDateTime nowTime){
        TSafeCheckPlan tSafeCheckPlan = new TSafeCheckPlan();
        Integer type = 1;
        LocalDateTime startDate = null;
        LocalDateTime endDate = null;
        if (tSafeCheckPerson.getFrequency().equals(CheckFrequencyEnum.one.getCode())){
            startDate = combineDateAndTime(tSafeCheckPerson.getStartDate(), tSafeCheckPerson.getStartTime());
            endDate = combineDateAndTime(tSafeCheckPerson.getEndDate(), tSafeCheckPerson.getEndTime());
        }else{
            // 计算上次执行时间
            ZonedDateTime startZonedDateTime = CronUtil.calculateTime(tSafeCheckPerson.getStartCronExpression(), type);
            ZonedDateTime endZonedDateTime = CronUtil.calculateTime(tSafeCheckPerson.getEndCronExpression(), type);

            if (startZonedDateTime != null && endZonedDateTime != null) {
                startDate = startZonedDateTime.toLocalDateTime();
                endDate = endZonedDateTime.toLocalDateTime();
                // 如果当前时间不在上次执行日期
                if (!(nowTime.isAfter(startDate) && nowTime.isBefore(endDate))) {
                    type = 2; // 获取下次执行时间
                    startZonedDateTime = CronUtil.calculateTime(tSafeCheckPerson.getStartCronExpression(), type);
                    endZonedDateTime = CronUtil.calculateTime(tSafeCheckPerson.getEndCronExpression(), type);
                    if (startZonedDateTime != null && endZonedDateTime != null) {
                        startDate = startZonedDateTime.toLocalDateTime();
                        endDate = endZonedDateTime.toLocalDateTime();
                        //如果开始时间在结束日期后
                        if (startDate.isAfter(endDate)) {
                            type = 1;
                            startZonedDateTime = CronUtil.calculateTime(tSafeCheckPerson.getStartCronExpression(), type);
                            //设置上次执行日期
                            startDate = startZonedDateTime.toLocalDateTime();
                        }
                        //如果结束日期在开始日期之前
                        if (endDate.isBefore(startDate)) {
                            type = 2;
                            //设置下次执行日期
                            endZonedDateTime = CronUtil.calculateTime(tSafeCheckPerson.getEndCronExpression(), type);
                            endDate = endZonedDateTime.toLocalDateTime();
                        }
                    }
                }
            }
        }
        tSafeCheckPlan.setStartDate(DateUtil.date(startDate));
        tSafeCheckPlan.setEndDate(DateUtil.date(endDate));
        return tSafeCheckPlan;
    }

    // 将日期字符串和时间字符串拼接成 LocalDateTime 对象
    public static LocalDateTime combineDateAndTime(String dateString, String timeString) {
        // 定义日期和时间的格式
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");

        // 解析日期和时间字符串
        LocalDate date = LocalDate.parse(dateString, dateFormatter);
        LocalTime time = LocalTime.parse(timeString, timeFormatter);

        // 合并日期和时间为 LocalDateTime 对象
        return LocalDateTime.of(date, time);
    }






    @Override
    public boolean postponed(TSafeCheckTaskPostpone addRequest) {
        boolean save = tSafeCheckTaskPostponeService.save(addRequest);
        if (save){
            TSafeCheckTask tSafeCheckTask = new TSafeCheckTask();
            tSafeCheckTask.setId(addRequest.getTaskId());
            tSafeCheckTask.setEndTime(addRequest.getExtensionDate());
            //发送通知
            LocalDateTime localDateTime = com.testor.common.util.DateUtil.dateToLocalDateTime(addRequest.getExtensionDate());
            sendMessage(addRequest.getTaskId(),localDateTime);
            return this.updateById(tSafeCheckTask);
        }
        return false;
    }

    private void sendMessage(String taskId,LocalDateTime endTime) {
        TSafeCheckTask byId = this.getById(taskId);
        if (byId != null) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
            String time = endTime.format(formatter);
            String msg = String.format("安全检查任务[%s}]已延期至:%s",byId.getName(),time);
            // 发送消息
            MsgTemplateVO msgTemplateVO = new MsgTemplateVO();
            msgTemplateVO.setTemplateContent(msg);
            msgTemplateVO.setTemplateType("notice");
            msgTemplateVO.setTemplateTypeName("通知");
            String bizKey = "safetyCheck";
            List<TSafeCheckPersonArrange> listByPlanId = tSafeCheckPersonArrangeService.getListByPlanId(byId.getPlanId());
            List<String> userIds = listByPlanId.stream().map(TSafeCheckPersonArrange::getUserId).collect(Collectors.toList());
            List<TMsgNotice> tMsgNotices = tMsgNoticeService.generateMsgNotice(bizKey, taskId, userIds, msgTemplateVO);
            tMsgNoticeService.saveBatch(tMsgNotices);
        }
    }


    @Override
    public Page<TSafeCheckTask> pageList(TSafeCheckTaskParam param) {
        /*String orgId = param.getOrgId();
        if (StringUtils.isBlank(orgId)) {
            param.setOrgId(ContextUtils.getLoginUser().getOrgId());
        }*/
        Long page=
                StringHelper.isEmpty(param.getPage())?BizConstants.PAGE:Long.valueOf(param.getPage());
        Long limit=
                StringHelper.isEmpty(param.getLimit())?BizConstants.LIMIT:Long.valueOf(param.getLimit());
        Page<TSafeCheckTask> resultPage=new Page<>(page,limit);
        // TODO 根据需求修改查询条件及查询参数
        Date now = new Date();
        /*UserInfo loginUser = ContextUtils.getLoginUser();
        List<String> childOrgIdByParentId = sysOrgService.getChildOrgIdByParentId(loginUser.getOrgId());
        if (StringUtils.isNotBlank(param.getIsOverdue())){
            //所有为空的任务id
            tSafeCheckTaskRecordService.listObjs(new LambdaQueryWrapper<TSafeCheckTaskRecord>().select(TSafeCheckTaskRecord::getTaskId)
                    .in(TSafeCheckTaskRecord::getOrgId, childOrgIdByParentId).isNull(TSafeCheckTaskRecord::getCompleteTime)
                    .groupBy(TSafeCheckTaskRecord::getTaskId).orderByAsc(TSafeCheckTaskRecord::getTaskId));

        }*/
        String orgIds = param.getOrgId();
        if (StringUtils.isBlank(orgIds)) {
            UserInfo loginUser = ContextUtils.getLoginUser();
            if(loginUser != null) {
                List<String> childOrgIdByParentId = sysOrgService.getIdsChildrenById(loginUser.getOrgId());
                param.setOrgIdList(childOrgIdByParentId);
            }
        }else {
            param.setOrgIdList(Arrays.asList(orgIds.split(",")));
        }
        Page<TSafeCheckTask> pageList = this.baseMapper.pageList(resultPage,param);
        List<TSafeCheckTask> records = pageList.getRecords();
        for (TSafeCheckTask record : records) {
            // 计算任务状态
            setTaskStatus(record, now);
            // 设置检查类型
            //setCheckType(record);
            // 设置检查人员
            setCheckPeople(record);
        }
        return pageList;
    }

    @Override
    public List<TSafeCheckTask> listList(TSafeCheckTaskParam param) {
        // TODO 根据需求修改查询条件及查询参数
        QueryWrapper<TSafeCheckTask> queryWrapper=this.createQuery(param);
        return this.list(queryWrapper);
    }

    @Override
    public TSafeCheckTaskVo details(String id) {
        Date now = new Date();
        TSafeCheckTask byId = this.getById(id);
        //设置机构名称
        setOrgName(byId);
        //设置被检查机构
        TSafeCheckTaskVo tSafeCheckTaskVo = BeanHelper.beanToBean(byId, TSafeCheckTaskVo.class);
        setIsCheckedOrg(tSafeCheckTaskVo);
        //设置检查类型
        setCheckType(tSafeCheckTaskVo);
        //设置检查人
        setCheckPeople(tSafeCheckTaskVo);
        //设置完成情况
        setTaskStatus(tSafeCheckTaskVo, now);
        //存入检查记录
        setRecord(tSafeCheckTaskVo);
        //设置延期信息
        setPostponed(tSafeCheckTaskVo);
        return tSafeCheckTaskVo;
    }

    @Override
    public boolean completeTask(TSafeCheckTaskRecordVo addRequest) {
        String loginUserId = ContextUtils.getLoginUserId();
        Date now = new Date();
        String taskId = addRequest.getTaskId();
        TSafeCheckTask byId = this.getById(taskId);
        //获取任务结束日期
        Date endTime = byId.getEndTime();
        String isOverdue = "0";
        //如果当前日期在任务结束日期之后
        if (now.compareTo(endTime)>0){
            //设置逾期
            isOverdue = "1";
        }
        int count = tSafeCheckTaskRecordService.count(new LambdaQueryWrapper<TSafeCheckTaskRecord>().eq(TSafeCheckTaskRecord::getTaskId, taskId)
                .ne(TSafeCheckTaskRecord::getRefId, loginUserId).eq(TSafeCheckTaskRecord::getRefType, "1").isNull(TSafeCheckTaskRecord::getCompleteTime));
        //如果当前提交人是最后提交的
        if (count == 0 ){
            //修改任务是否逾期状态和完成时间
            byId.setIsOverdue(isOverdue);
            byId.setCompleteTime(now);
            this.updateById(byId);
        }
        //完成任务
        completeProcess(addRequest);
        //修改状态
        tSafeCheckTaskRecordService.update(new LambdaUpdateWrapper<TSafeCheckTaskRecord>().eq(TSafeCheckTaskRecord::getTaskId, taskId)
                .eq(TSafeCheckTaskRecord::getRefId, loginUserId).eq(TSafeCheckTaskRecord::getRefType, "1").set(TSafeCheckTaskRecord::getProcessStatus,"5")
        );
        return tSafeCheckTaskRecordService.update(new LambdaUpdateWrapper<TSafeCheckTaskRecord>().eq(TSafeCheckTaskRecord::getRefId,loginUserId)
                .eq(TSafeCheckTaskRecord::getTaskId, taskId).eq(TSafeCheckTaskRecord::getRefType, "1")
                .set(TSafeCheckTaskRecord::getCompleteTime,now).set(TSafeCheckTaskRecord::getIsOverdue, isOverdue));
    }

    void completeProcess(TSafeCheckTaskRecordVo addRequest){
        CompleteTask completeTask = new CompleteTask();
        completeTask.setOrgId(addRequest.getOrgId());
        completeTask.setBizId(addRequest.getTaskId());
        completeTask.setTaskId(addRequest.getProcessTasksId());
        completeTask.setLocalScope(true);
        Map<String,Object> vars =  new HashMap<>();
        vars.put("processStatus", "5");
        completeTask.setVars(vars);
        wfTaskController.completeTask(completeTask);
    }



    private void setOrgName(TSafeCheckTask record) {
        NewSysOrg sysOrg = sysOrgService.getById(record.getOrgId());
        if (sysOrg != null) {
            record.setOrgName(sysOrg.getOrgName());
        }
    }

    private void setIsCheckedOrg(TSafeCheckTaskVo tSafeCheckTaskVo){
        List<TSafeCheckOrg> listByPlanId1 = tSafeCheckOrgService.getListByPlanId(tSafeCheckTaskVo.getPlanId());
        listByPlanId1 = listByPlanId1.stream().peek(tSafeCheckOrg -> {
            NewSysOrg byId = sysOrgService.getById(tSafeCheckOrg.getCheckOrgId());
            if (byId != null) {
                tSafeCheckOrg.setCheckOrgName(byId.getOrgName());
                tSafeCheckOrg.setTreeLevel(byId.getTreeLevel());
                tSafeCheckOrg.setNature(byId.getNature());
            }
        }).collect(Collectors.toList());
        tSafeCheckTaskVo.setTSafeCheckOrgs(listByPlanId1);
    }

    private void setTaskStatus(TSafeCheckTask record, Date now) {
        Date startDate = record.getStartTime();
        Date endDate = record.getEndTime();



        if (startDate == null || endDate == null) {
            record.setTaskStatus(TSafeCheckTask.TaskStatus.NOT_STARTED.getCode());
            record.setTaskStatusName(TSafeCheckTask.TaskStatus.NOT_STARTED.getName());
        } else if (now.compareTo(startDate)<0) {
            record.setTaskStatus(TSafeCheckTask.TaskStatus.NOT_STARTED.getCode());
            record.setTaskStatusName(TSafeCheckTask.TaskStatus.NOT_STARTED.getName());
        } else if (record.getCompleteTime() != null) {
            record.setTaskStatus(TSafeCheckTask.TaskStatus.COMPLETED.getCode());
            record.setTaskStatusName(TSafeCheckTask.TaskStatus.COMPLETED.getName());
        } else {
            record.setTaskStatus(TSafeCheckTask.TaskStatus.IN_PROGRESS.getCode());
            record.setTaskStatusName(TSafeCheckTask.TaskStatus.IN_PROGRESS.getName());
        }
        //如果完成时间为空
        if (record.getCompleteTime() == null) {
            //如果当前日期在结束日期之后
            if (endDate!=null && now.compareTo(endDate)>0) {
                //设置逾期
                record.setIsOverdue("1");
            }
        }
    }


    private void setRecord(TSafeCheckTaskVo tSafeCheckTaskVo) {
        List<TSafeCheckTaskRecord> userRecordByTaskId = tSafeCheckTaskRecordService.findUserRecordByTaskId(tSafeCheckTaskVo.getId());
        for (TSafeCheckTaskRecord tSafeCheckTaskRecord : userRecordByTaskId) {
            SysUser byId = sysUserService.getById(tSafeCheckTaskRecord.getRefId());
            if (byId != null) {
                tSafeCheckTaskRecord.setName(byId.getUserName());
            }
        }
        tSafeCheckTaskVo.setTaskUserRecords(userRecordByTaskId);
        /*List<TSafeCheckTaskRecord> hazardRecordByTaskId = tSafeCheckTaskRecordService.findHazardRecordByTaskId(tSafeCheckTaskVo.getId());
        tSafeCheckTaskVo.setTaskHazardRecords(hazardRecordByTaskId);*/
    }


    private void setPostponed(TSafeCheckTaskVo tSafeCheckTaskVo) {
        List<TSafeCheckTaskPostpone> byTaskId = tSafeCheckTaskPostponeService.findByTaskId(tSafeCheckTaskVo.getId());
        tSafeCheckTaskVo.setTSafeCheckTaskPostpones(byTaskId);
    }

    private void setCheckType(TSafeCheckTaskVo record) {
        SysDictData byId = sysDictDataService.getById(record.getCheckType());
        if (byId != null){
            record.setCheckTypeName(byId.getDictValue());
        }
    }

    private void setCheckPeople(TSafeCheckTask record) {
        List<TSafeCheckPersonArrange> personArranges = tSafeCheckPersonArrangeService.getListByCheckPersonId(record.getCheckPersonId());
        List<String> userNames = personArranges.stream()
                .map(tSafeCheckPersonArrange -> sysUserService.getById(tSafeCheckPersonArrange.getUserId()))
                .filter(sysUser -> sysUser != null)
                .map(SysUser::getUserName)
                .collect(Collectors.toList());

        record.setCheckPeople(String.join(", ", userNames));
    }

    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TSafeCheckTask> createQuery(TSafeCheckTaskParam queryParam){
        QueryWrapper<TSafeCheckTask> queryWrapper=new QueryWrapper<>();
        if(StringHelper.isNotEmpty(queryParam.getPlanId())){
            queryWrapper.eq(TSafeCheckTask.PLAN_ID,queryParam.getPlanId());
        }
        if(StringHelper.isNotEmpty(queryParam.getTaskStatus())){
            Date now = new Date();
            if (TSafeCheckTask.TaskStatus.NOT_STARTED.getCode().equals(queryParam.getTaskStatus())){
                queryWrapper.gt(TSafeCheckTask.START_TIME,now);
            }else if (TSafeCheckTask.TaskStatus.COMPLETED.getCode().equals(queryParam.getTaskStatus())){
                queryWrapper.isNotNull(TSafeCheckTask.COMPLETE_TIME);
            }else {
                queryWrapper.lt(TSafeCheckTask.START_TIME,now);
                queryWrapper.isNotNull(TSafeCheckTask.COMPLETE_TIME);
            }
        }

        if (StringHelper.isNotEmpty(queryParam.getCheckPeople())){
            List<String> ids = this.listList(null).stream().map(TSafeCheckTask::getCheckPersonId).collect(Collectors.toList());
            List<String> checkPersonIds = tSafeCheckPersonArrangeService.list(new LambdaQueryWrapper<TSafeCheckPersonArrange>().in(TSafeCheckPersonArrange::getCheckPersonId, ids)
                    .eq(TSafeCheckPersonArrange::getUserId, queryParam.getCheckPeople())).stream().map(TSafeCheckPersonArrange::getCheckPersonId).collect(Collectors.toList());
            queryWrapper.in(TSafeCheckTask.CHECK_PERSON_ID,checkPersonIds);
        }
        if(StringHelper.isNotEmpty(queryParam.getIsOverdue())){
            queryWrapper.eq(TSafeCheckTask.IS_OVERDUE,queryParam.getIsOverdue());
        }
        if(ObjectHelper.isNotEmpty(queryParam.getStartTime())){
            queryWrapper.eq(TSafeCheckTask.START_TIME,queryParam.getStartTime());
        }
        if(ObjectHelper.isNotEmpty(queryParam.getEndTime())){
            queryWrapper.eq(TSafeCheckTask.END_TIME,queryParam.getEndTime());
        }
        if(ObjectHelper.isNotEmpty(queryParam.getCompleteTime())){
            queryWrapper.eq(TSafeCheckTask.COMPLETE_TIME,queryParam.getCompleteTime());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TSafeCheckTask.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TSafeCheckTask.STATUS, BizConstants.STATUS_DELETE);
        }
        if (StringHelper.isNotEmpty(queryParam.getOrderBy())){
            if(StringHelper.isNotEmpty(queryParam.getOrderType())
                    &&BizConstants.ASC.equals(queryParam.getOrderType())){
                queryWrapper.orderByAsc(queryParam.getOrderBy());
            }else{
                queryWrapper.orderByDesc(queryParam.getOrderBy());
            }
        }else{
            queryWrapper.orderByDesc(TSafeCheckTask.UPDATE_DATE);
        }
        return queryWrapper;
    }
}
