package com.yuchen.saas.park.service.service.fire.inspect.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.thinkunion.park.service.common.utils.ReceiptCodeUtil;
import com.yuchen.saas.manage.system.api.entity.NestOrgUser;
import com.yuchen.saas.manage.system.api.feign.IOrgUserClient;
import com.yuchen.saas.park.api.dto.fire.inspect.plan.*;
import com.yuchen.saas.park.api.entity.fire.inspect.SaasParkFireInspectPlanConfig;
import com.yuchen.saas.park.api.entity.fire.inspect.SaasParkFireInspectPlanTask;
import com.yuchen.saas.park.api.enums.inspect.PlanExecuteStateEnum;
import com.yuchen.saas.park.api.enums.inspect.TaskStateEnum;
import com.yuchen.saas.park.api.vo.fire.inspect.FireInspectConfigVO;
import com.yuchen.saas.park.api.vo.fire.inspect.FireInspectFormVO;
import com.yuchen.saas.park.api.vo.fire.inspect.plan.FireInspectPlanConfigDetailVO;
import com.yuchen.saas.park.api.vo.fire.inspect.plan.FireInspectPlanTaskCountVO;
import com.yuchen.saas.park.api.vo.fire.inspect.plan.FireInspectPlanTaskDetailVO;
import com.yuchen.saas.park.api.vo.fire.inspect.plan.FireInspectPlanTaskVO;
import com.yuchen.saas.park.service.mapper.fire.inspect.SaasParkFireInspectPlanTaskMapper;
import com.yuchen.saas.park.service.service.fire.inspect.*;
import com.yuchen.saas.park.service.util.PageConverterUtils;
import lombok.RequiredArgsConstructor;
import org.nest.springwrap.core.log.exception.ServiceException;
import org.nest.springwrap.core.mp.base.BaseEntity;
import org.nest.springwrap.core.mp.base.BaseServiceImpl;
import org.nest.springwrap.core.mp.support.Condition;
import org.nest.springwrap.core.mp.support.NestPage;
import org.nest.springwrap.core.mp.support.Query;
import org.nest.springwrap.core.secure.ContextUser;
import org.nest.springwrap.core.secure.utils.AuthUtil;
import org.nest.springwrap.core.tool.utils.Func;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 巡检任务表 服务实现类
 * </p>
 *
 * @author zhouhanwei
 * @since 2024-04-03
 */
@Service
@RequiredArgsConstructor
public class SaasParkFireInspectPlanTaskServiceImpl extends BaseServiceImpl<SaasParkFireInspectPlanTaskMapper, SaasParkFireInspectPlanTask> implements ISaasParkFireInspectPlanTaskService {

    private final IOrgUserClient iOrgUserClient;

    private final ISaasParkFireInspectTypeService inspectTypeService;

    private final ISaasParkFireInspectPlanConfigService inspectPlanConfigService;

    private final ISaasParkFireInspectConfigService inspectConfigService;

    private final ISaasParkFireInspectFormService inspectFormService;

    @Override
    public NestPage<FireInspectPlanTaskVO> findFireInspectPlanTaskPage(FireInspectPlanTaskReqDTO reqDTO) {
        Page<FireInspectPlanTaskVO> resultPage = new Page<>();
        // 赋值数据
        LambdaQueryWrapper<SaasParkFireInspectPlanTask> lambdaWrapper = Wrappers.lambdaQuery();
        lambdaWrapper.like(Func.isNotEmpty(reqDTO.getOrgUserId()), SaasParkFireInspectPlanTask::getTaskPeopleIds, String.valueOf(reqDTO.getOrgUserId()));
        lambdaWrapper.eq(Func.isNotEmpty(reqDTO.getCustomerId()), SaasParkFireInspectPlanTask::getCustomerId, reqDTO.getCustomerId());
        lambdaWrapper.eq(Func.isNotEmpty(reqDTO.getBusinessId()), SaasParkFireInspectPlanTask::getBusinessId, reqDTO.getBusinessId());
        lambdaWrapper.eq(Func.isNotEmpty(reqDTO.getProjectId()), SaasParkFireInspectPlanTask::getProjectId, reqDTO.getProjectId());
        lambdaWrapper.eq(Func.isNotEmpty(reqDTO.getInspectTypeId()), SaasParkFireInspectPlanTask::getInspectTypeId, reqDTO.getInspectTypeId());
        lambdaWrapper.eq(Func.isNotEmpty(reqDTO.getTaskState()), SaasParkFireInspectPlanTask::getTaskState, reqDTO.getTaskState());
        lambdaWrapper.eq(Func.isNotEmpty(reqDTO.getExecuteState()), SaasParkFireInspectPlanTask::getExecuteState, reqDTO.getExecuteState());
        lambdaWrapper.like(Func.isNotEmpty(reqDTO.getTaskName()), SaasParkFireInspectPlanTask::getTaskName, reqDTO.getTaskName());
        lambdaWrapper.eq(Func.isNotEmpty(reqDTO.getCloseType()), SaasParkFireInspectPlanTask::getCloseType, reqDTO.getCloseType());
        lambdaWrapper.ge(Func.isNotEmpty(reqDTO.getTaskStartDate()), SaasParkFireInspectPlanTask::getTaskDate, reqDTO.getTaskStartDate());
        lambdaWrapper.le(Func.isNotEmpty(reqDTO.getTaskEndDate()), SaasParkFireInspectPlanTask::getTaskDate, reqDTO.getTaskEndDate());
        if (StrUtil.isNotBlank(reqDTO.getInspectConfigName())) {
            // 获取巡检点配置对应的任务id
            List<SaasParkFireInspectPlanConfig> planConfigList = inspectPlanConfigService.list(new LambdaQueryWrapper<SaasParkFireInspectPlanConfig>()
                    .eq(SaasParkFireInspectPlanConfig::getTaskPlanType, "2")
                    .eq(SaasParkFireInspectPlanConfig::getCustomerId, reqDTO.getCustomerId())
                    .like(SaasParkFireInspectPlanConfig::getInspectConfigName, reqDTO.getInspectConfigName()));
            if (CollUtil.isNotEmpty(planConfigList)) {
                List<Long> taskPlanIdList = planConfigList.stream().map(SaasParkFireInspectPlanConfig::getTaskPlanId).collect(Collectors.toList());
                lambdaWrapper.in(BaseEntity::getId, taskPlanIdList);
            }

        }
        if (Objects.nonNull(reqDTO.getOrgUserId())) {
            lambdaWrapper.orderByAsc(SaasParkFireInspectPlanTask::getTaskDate);
        } else {
            lambdaWrapper.orderByAsc(SaasParkFireInspectPlanTask::getExecuteState);
            lambdaWrapper.orderByAsc(SaasParkFireInspectPlanTask::getTaskState);
            lambdaWrapper.orderByAsc(SaasParkFireInspectPlanTask::getTaskDate);
            lambdaWrapper.orderByDesc(BaseEntity::getCreateTime);
        }
        IPage<SaasParkFireInspectPlanTask> page = page(Condition.getPage(reqDTO),lambdaWrapper);
        List<SaasParkFireInspectPlanTask> fireInspectPlanTaskList = page.getRecords();
        // 返回数据列表
        List<FireInspectPlanTaskVO> resultList = new ArrayList<>();
        if (CollUtil.isEmpty(fireInspectPlanTaskList)) {
            resultPage.setTotal(page.getTotal());
            resultPage.setSize(page.getSize());
            resultPage.setCurrent(page.getCurrent());
            resultPage.setRecords(resultList);
            return PageConverterUtils.convert(resultPage);
        }
        // 获取巡检类型id列表
        List<Long> typeIds = fireInspectPlanTaskList.stream().map(SaasParkFireInspectPlanTask::getInspectTypeId).collect(Collectors.toList());
        Map<Long, String> inspectTypeMap = inspectTypeService.findFireInspectTypeMap(typeIds);
        // 获取所有的人员列表
        List<Long> orgUserAllList = new ArrayList<>();
        for (SaasParkFireInspectPlanTask planTask : fireInspectPlanTaskList) {
            if (StrUtil.isNotBlank(planTask.getInspectPeopleIds())) {
                List<Long> inspectPeopleIds = Arrays.stream(planTask.getInspectPeopleIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
                orgUserAllList.addAll(inspectPeopleIds);
            }
            if (StrUtil.isNotBlank(planTask.getTaskPeopleIds())) {
                List<Long> taskPeopleIds = Arrays.stream(planTask.getTaskPeopleIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
                orgUserAllList.addAll(taskPeopleIds);
            }

            orgUserAllList.add(planTask.getCreateOrgUser());
        }
        // 获取所有人员数据
        List<NestOrgUser> orgUserList = iOrgUserClient.findOrgUserListByIds(orgUserAllList.stream().distinct().collect(Collectors.toList())).getData();
        Map<Long, String> orgUserMap = orgUserList.stream().collect(Collectors.toMap(BaseEntity::getId, NestOrgUser::getName));
        for (SaasParkFireInspectPlanTask planTask : fireInspectPlanTaskList) {
            FireInspectPlanTaskVO vo = new FireInspectPlanTaskVO();
            BeanUtil.copyProperties(planTask, vo);
            vo.setInspectTypeName(inspectTypeMap.get(vo.getInspectTypeId()));
            vo.setOrgUserName(orgUserMap.get(vo.getCreateOrgUser()));
            // 获取计划巡检人
            setInspectPeopleNamesValue(orgUserMap, vo);
            // 获取任务处理人
            setTaskPeopleNamesValue(orgUserMap, vo);
            if (!StrUtil.equals(vo.getTaskState(), TaskStateEnum.PROCESSED.getCode())) {
                vo.setInspectResult(null);
            }
            resultList.add(vo);
        }
        resultPage.setTotal(page.getTotal());
        resultPage.setSize(page.getSize());
        resultPage.setCurrent(page.getCurrent());
        resultPage.setRecords(resultList);
        return PageConverterUtils.convert(resultPage);
    }

    @Override
    public FireInspectPlanTaskCountVO getPlanTaskCount(FireInspectPlanTaskReqDTO reqDTO) {
        ContextUser contextUser = AuthUtil.getUser();
        if (Objects.isNull(contextUser)) {
            throw new ServiceException("用户不存在");
        }
        // 赋值数据
        LambdaQueryWrapper<SaasParkFireInspectPlanTask> lambdaWrapper = Wrappers.lambdaQuery();
        lambdaWrapper.eq(SaasParkFireInspectPlanTask::getCustomerId, contextUser.getCustomerManageId());
        lambdaWrapper.eq(Func.isNotEmpty(reqDTO.getProjectId()), SaasParkFireInspectPlanTask::getProjectId, reqDTO.getProjectId());
        lambdaWrapper.eq(Func.isNotEmpty(reqDTO.getInspectTypeId()), SaasParkFireInspectPlanTask::getInspectTypeId, reqDTO.getInspectTypeId());
        lambdaWrapper.eq(Func.isNotEmpty(reqDTO.getTaskState()), SaasParkFireInspectPlanTask::getTaskState, reqDTO.getTaskState());
        lambdaWrapper.eq(Func.isNotEmpty(reqDTO.getExecuteState()), SaasParkFireInspectPlanTask::getExecuteState, reqDTO.getExecuteState());
        lambdaWrapper.like(Func.isNotEmpty(reqDTO.getTaskName()), SaasParkFireInspectPlanTask::getTaskName, reqDTO.getTaskName());
        lambdaWrapper.eq(Func.isNotEmpty(reqDTO.getCloseType()), SaasParkFireInspectPlanTask::getCloseType, reqDTO.getCloseType());
        lambdaWrapper.ge(Func.isNotEmpty(reqDTO.getTaskStartDate()), SaasParkFireInspectPlanTask::getTaskDate, reqDTO.getTaskStartDate());
        lambdaWrapper.le(Func.isNotEmpty(reqDTO.getTaskEndDate()), SaasParkFireInspectPlanTask::getTaskDate, reqDTO.getTaskEndDate());
        List<SaasParkFireInspectPlanTask> resultList = list(lambdaWrapper);
        // 返回数据
        FireInspectPlanTaskCountVO countVO = new FireInspectPlanTaskCountVO();
        if (CollUtil.isEmpty(resultList)) {
            return countVO;
        }
        // 巡检计划任务总数
        long planTaskSum = resultList.stream().filter(s -> s.getTaskType().equals("1")).count();
        countVO.setPlanTaskSum(planTaskSum);
        // 巡检计划已完成任务总数
        long planTaskProcessedSum = resultList.stream().filter(s -> s.getTaskType().equals("1")
                && TaskStateEnum.PROCESSED.getCode().equals(s.getTaskState())).count();
        countVO.setPlanTaskProcessedSum(planTaskProcessedSum);
        Date newDate = new Date();
        // 应巡检任务数
        long shouldInspectTaskNum = resultList.stream().filter(s -> s.getTaskStartTime().getTime() < newDate.getTime()
                && !TaskStateEnum.ClOSE.getCode().equals(s.getTaskState())).count();
        countVO.setShouldInspectTaskNum(shouldInspectTaskNum);
        // 已巡检任务数
        long inspectedTaskNum = resultList.stream().filter(s -> s.getTaskStartTime().getTime() < newDate.getTime()
                && TaskStateEnum.PROCESSED.getCode().equals(s.getTaskState())).count();
        countVO.setInspectedTaskNum(inspectedTaskNum);
        // 逾期未巡检任务数
        long outNoInspectTaskNum = resultList.stream().filter(s ->
                PlanExecuteStateEnum.OUT_NO_INSPECT.getCode().equals(s.getExecuteState())).count();
        countVO.setOutNoInspectTaskNum(outNoInspectTaskNum);
        // 逾期完成任务数
        long outInspectedTaskNum = resultList.stream()
                .filter(s -> StrUtil.equals(s.getTaskState(), TaskStateEnum.PROCESSED.getCode()))
                .filter(s -> s.getTaskProcessedTime().getTime() > s.getTaskEndTime().getTime()).count();
        countVO.setOutInspectedTaskNum(outInspectedTaskNum);
        // 异常结果任务数
        long exceptionTaskNum = resultList.stream().filter(s -> "2".equals(s.getInspectResult())).count();
        countVO.setExceptionTaskNum(exceptionTaskNum);
        return countVO;
    }

    @Override
    public FireInspectPlanTaskDetailVO getFireInspectPlanTaskById(Long planTaskId) {
        SaasParkFireInspectPlanTask saasParkFireInspectPlanTask = getById(planTaskId);
        if (Objects.isNull(saasParkFireInspectPlanTask)) {
            throw new ServiceException("巡检任务数据不存在");
        }
        FireInspectPlanTaskDetailVO detailVO = new FireInspectPlanTaskDetailVO();
        BeanUtil.copyProperties(saasParkFireInspectPlanTask, detailVO);
        // 判断逾期几个小时
        Date newDate = new Date();
        if (newDate.getTime() > detailVO.getTaskEndTime().getTime()) {
            detailVO.setOutFlag(true);
        }
        if (newDate.getTime() > detailVO.getTaskOutTime().getTime()) {
            detailVO.setOutFlag(true);
        }
        long hour = DateUtil.between(newDate, detailVO.getTaskEndTime(), DateUnit.HOUR);
        detailVO.setOutHours(hour);
        // 获取任务巡检点配置
        LambdaQueryWrapper<SaasParkFireInspectPlanConfig> lambdaWrapper = Wrappers.lambdaQuery();
        lambdaWrapper.eq(SaasParkFireInspectPlanConfig::getTaskPlanId, detailVO.getId());
        lambdaWrapper.orderByAsc(SaasParkFireInspectPlanConfig::getSort);
        List<SaasParkFireInspectPlanConfig> planConfigList = inspectPlanConfigService.list(lambdaWrapper);
        // 获取所有的人员列表
        List<Long> inspectPeopleIds = Arrays.stream(detailVO.getInspectPeopleIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
        List<Long> orgUserAllList = new ArrayList<>(inspectPeopleIds);
        if (StrUtil.isNotBlank(detailVO.getTaskPeopleIds())) {
            List<Long> taskPeopleIds = Arrays.stream(detailVO.getTaskPeopleIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
            orgUserAllList.addAll(taskPeopleIds);
        }
        // 获取所有人员数据
        List<NestOrgUser> orgUserList = iOrgUserClient.findOrgUserListByIds(orgUserAllList.stream().distinct().collect(Collectors.toList())).getData();
        Map<Long, String> orgUserMap = orgUserList.stream().collect(Collectors.toMap(BaseEntity::getId, NestOrgUser::getName));
        // 返回巡检任务配置信息
        List<FireInspectPlanConfigDetailVO> planConfigDetailVOList = new ArrayList<>();
        for (SaasParkFireInspectPlanConfig planConfig : planConfigList) {
            FireInspectPlanConfigDetailVO planConfigDetailVO = new FireInspectPlanConfigDetailVO();
            planConfigDetailVO.setId(planConfig.getId());
            planConfigDetailVO.setPlanTaskId(planConfig.getTaskPlanId());
            // 获取巡检点配置信息
            FireInspectConfigVO inspectConfig = inspectConfigService.getFireInspectConfigById(planConfig.getInspectConfigId());
            planConfigDetailVO.setInspectConfig(inspectConfig);
            // 巡检点名称取存的
            inspectConfig.setInspectConfigName(planConfig.getInspectConfigName());
            // 获取表单信息
            FireInspectFormVO inspectForm = inspectFormService.getFireInspectTypeById(planConfig.getInspectFormId());
            // 已巡检取当时得检查项
            if (StrUtil.equals(planConfig.getInspectStatus(), "1")) {
                inspectForm.setInspectCheckItem(planConfig.getInspectCheckItem());
            }
            // 表单名称取存的
            inspectForm.setInspectTitle(planConfig.getInspectFormName());
            planConfigDetailVO.setInspectForm(inspectForm);
            planConfigDetailVO.setInspectResult(planConfig.getInspectResult());
            planConfigDetailVO.setInspectStatus(planConfig.getInspectStatus());
            planConfigDetailVO.setRemark(planConfig.getRemark());
            planConfigDetailVO.setInspectDate(planConfig.getInspectDate());
            if (StrUtil.equals(planConfig.getInspectStatus(), "1")) {
                if (Objects.nonNull(planConfig.getInspectUser())) {
                    planConfigDetailVO.setInspectUserName(orgUserMap.get(planConfig.getInspectUser()));
                }

            }
            planConfigDetailVOList.add(planConfigDetailVO);
        }
        detailVO.setPlanConfigDetailVOList(planConfigDetailVOList);
        // 获取计划巡检人
        setInspectPeopleNamesValue(orgUserMap, detailVO);
        // 获取任务处理人
        setTaskPeopleNamesValue(orgUserMap, detailVO);
        return detailVO;
    }

    @Override
    public Boolean closePlanTask(ClosePlanTaskReqDTO reqDTO) {
        ContextUser contextUser = AuthUtil.getUser();
        if (Objects.isNull(contextUser)) {
            throw new ServiceException("用户不存在");
        }
        SaasParkFireInspectPlanTask saasParkFireInspectPlanTask = getById(reqDTO.getPlanTaskId());
        if (Objects.isNull(saasParkFireInspectPlanTask)) {
            throw new ServiceException("巡检任务数据不存在");
        }
        if (StrUtil.equals(saasParkFireInspectPlanTask.getTaskState(), TaskStateEnum.PROCESSED.getCode())) {
            throw new ServiceException("任务已完成，无法进行相应操作");
        }
        if (StrUtil.equals(saasParkFireInspectPlanTask.getTaskState(), TaskStateEnum.ClOSE.getCode())) {
            throw new ServiceException("任务已关闭，无需重复关闭");
        }
        saasParkFireInspectPlanTask.setTaskState(TaskStateEnum.ClOSE.getCode());
        saasParkFireInspectPlanTask.setCloseType("2");
        saasParkFireInspectPlanTask.setCloseReason(reqDTO.getCloseReason());
        saasParkFireInspectPlanTask.setCloseRemark(reqDTO.getCloseRemark());
        saasParkFireInspectPlanTask.setExecuteState(PlanExecuteStateEnum.ClOSE.getCode());
        saasParkFireInspectPlanTask.setUpdateOrgUser(contextUser.getOrgUserId());
        return updateById(saasParkFireInspectPlanTask);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addTemporaryTask(AddTemporaryTaskReqDTO reqDTO) {
        ContextUser contextUser = AuthUtil.getUser();
        if (Objects.isNull(contextUser)) {
            throw new ServiceException("用户不存在");
        }
        // 校验入参
        verifySubmitParam(reqDTO);
        Date newDate = new Date();
        // 创建临时任务
        SaasParkFireInspectPlanTask planTask = new SaasParkFireInspectPlanTask();
        planTask.setCustomerId(contextUser.getCustomerManageId());
        planTask.setProjectId(reqDTO.getProjectId());
        planTask.setInspectTypeId(reqDTO.getInspectTypeId());
        planTask.setReceiptCode(ReceiptCodeUtil.setReceiptCodeValue("XJRW"));
        planTask.setTaskType("2");
        planTask.setTaskName(reqDTO.getInspectTaskName());
        planTask.setTaskDate(reqDTO.getTaskDate());
        // 时间段
        PlanTimePeriodValueDTO timePeriodValue = reqDTO.getPlanTimePeriodValueDTO();
        String periodValue;
        if (timePeriodValue.getTimePeriod() > 0) {
            periodValue = timePeriodValue.getPlanStartTimePeriod() + "~" + timePeriodValue.getPlanEndTimePeriod() + "(+" + timePeriodValue.getTimePeriod() + "天)";
        } else {
            periodValue = timePeriodValue.getPlanStartTimePeriod() + "~" + timePeriodValue.getPlanEndTimePeriod();
        }
        String startPeriod = timePeriodValue.getPlanStartTimePeriod() + ":00";
        String endPeriod = timePeriodValue.getPlanEndTimePeriod() + ":00";
        int period = timePeriodValue.getTimePeriod();
        // 任务日期
        String taskDate = DateUtil.formatDate(reqDTO.getTaskDate());
        String taskStartTime = taskDate + " " + startPeriod;
        // 任务开始时间
        planTask.setTaskStartTime(DateUtil.parseDateTime(taskStartTime));
        String taskEndTime = taskDate + " " + endPeriod;
        // 任务结束时间
        Date endTime = DateUtil.parseDateTime(taskEndTime);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(endTime);
        // 增加period天
        calendar.add(Calendar.DATE, period);
        planTask.setTaskEndTime(calendar.getTime());
        planTask.setPlanTimePeriodValue(periodValue);
        planTask.setInspectNum(reqDTO.getPlanConfigDTOList().size());
        planTask.setInspectedNum(0);
        planTask.setTaskState(TaskStateEnum.TO_START.getCode());
        if (planTask.getTaskStartTime().getTime() >= planTask.getTaskEndTime().getTime()) {
            throw new ServiceException("任务开始时间不能大于任务结束时间");
        }
        if (newDate.getTime() < planTask.getTaskEndTime().getTime()) {
            planTask.setExecuteState(PlanExecuteStateEnum.EXECUTING.getCode());
        } else {
            throw new ServiceException("任务结束时间不能小于当前时间");
        }
        // 巡检人员
        planTask.setInspectPeopleIds(CollUtil.join(reqDTO.getOrgUserIdList(), ","));
        planTask.setTaskPeopleIds(planTask.getInspectPeopleIds());
        // 任务要求
        planTask.setTaskStartNotifyDemand(reqDTO.getTaskStartNotifyDemand());
        planTask.setTaskStartNotify(reqDTO.getTaskStartNotify());
        planTask.setTaskStartNotifyType(reqDTO.getTaskStartNotifyType());
        planTask.setTaskEndNotifyDemand(reqDTO.getTaskEndNotifyDemand());
        planTask.setTaskEndNotify(reqDTO.getTaskEndNotify());
        planTask.setTaskEndNotifyType(reqDTO.getTaskStartNotifyType());
        planTask.setTaskAutoCloseDemand(reqDTO.getTaskAutoCloseDemand());
        planTask.setTaskOutAllowDemand(reqDTO.getTaskOutAllowDemand());
        planTask.setTaskSequenceDemand(reqDTO.getTaskSequenceDemand());
        planTask.setTaskPhotoDemand(reqDTO.getTaskPhotoDemand());
        // 有开启任务通知任务通知时间赋值
        if ("1".equals(reqDTO.getTaskStartNotifyDemand())) {
            setTaskNotifyTimeValue(planTask);
        }
        // 有开启任务到期通知赋值
        setTaskOutTimeValue(planTask);
        // 任务执行模式
        planTask.setTaskExecuteType(reqDTO.getTaskExecuteType());
        planTask.setCreateOrgUser(contextUser.getOrgUserId());
        // 去重
        validRepeat(planTask);
        save(planTask);
        // 保存任务巡检点
        List<SaasParkFireInspectPlanConfig> planConfigList = new ArrayList<>();
        int sort = 1;
        for (FireInspectPlanConfigDTO planConfigDTO : reqDTO.getPlanConfigDTOList()) {
            SaasParkFireInspectPlanConfig planConfig = new SaasParkFireInspectPlanConfig();
            BeanUtil.copyProperties(planConfigDTO, planConfig);
            planConfig.setCustomerId(planTask.getCustomerId());
            planConfig.setTaskPlanId(planTask.getId());
            planConfig.setTaskPlanType("2");
            planConfig.setInspectStatus("0");
            planConfig.setCreateOrgUser(contextUser.getOrgUserId());
            planConfig.setSort(sort);
            planConfigList.add(planConfig);
            sort++;
        }
        inspectPlanConfigService.saveBatch(planConfigList);
        return Boolean.TRUE;
    }

    private void validRepeat(SaasParkFireInspectPlanTask planTask) {
        int count = count(new LambdaQueryWrapper<SaasParkFireInspectPlanTask>()
                .eq(SaasParkFireInspectPlanTask::getTaskName, planTask.getTaskName())
                .eq(Objects.nonNull(planTask.getProjectId()), SaasParkFireInspectPlanTask::getProjectId, planTask.getProjectId())
                .notIn(Objects.nonNull(planTask.getId()), BaseEntity::getId, planTask.getId()));
        if (count > 0) {
            throw new ServiceException("巡检任务名称不能重复");
        }
    }

    private void setTaskOutTimeValue(SaasParkFireInspectPlanTask planTask) {
        // 过期时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(planTask.getTaskEndTime());
        if ("1".equals(planTask.getTaskEndNotifyType())) {
            // 增加分钟
            calendar.add(Calendar.MINUTE, planTask.getTaskEndNotify());
        }
        if ("2".equals(planTask.getTaskEndNotifyType())) {
            // 增加小时
            calendar.add(Calendar.HOUR, planTask.getTaskEndNotify());
        }
        if ("3".equals(planTask.getTaskEndNotifyType())) {
            // 增加天
            calendar.add(Calendar.DATE, planTask.getTaskEndNotify());
        }
        planTask.setTaskOutTime(calendar.getTime());

    }

    private void setTaskNotifyTimeValue(SaasParkFireInspectPlanTask planTask) {
        // 过期时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(planTask.getTaskStartTime());
        if ("1".equals(planTask.getTaskEndNotifyType())) {
            // 增加分钟
            calendar.add(Calendar.MINUTE, planTask.getTaskEndNotify());
        } else
        if ("2".equals(planTask.getTaskEndNotifyType())) {
            // 增加小时
            calendar.add(Calendar.HOUR, planTask.getTaskEndNotify());
        } else
        if ("3".equals(planTask.getTaskEndNotifyType())) {
            // 增加天
            calendar.add(Calendar.DATE, planTask.getTaskEndNotify());
        } else {
            throw new ServiceException("任务通知选择时间周期不正确");
        }
        planTask.setTaskNotifyTime(calendar.getTime());

    }

    @Override
    public Boolean adjustPlanTask(AdjustPlanTaskReqDTO reqDTO) {
        ContextUser contextUser = AuthUtil.getUser();
        if (Objects.isNull(contextUser)) {
            throw new ServiceException("用户不存在");
        }
        // 巡检配置不能为空
        if (CollUtil.isEmpty(reqDTO.getPlanConfigDTOList())) {
            throw new ServiceException("计划排班任务数不能为空");
        }
        // 巡检人类型为成员
        if (CollUtil.isEmpty(reqDTO.getOrgUserIdList())) {
            throw new ServiceException("巡检人不能为空");
        }
        SaasParkFireInspectPlanTask planTask = getById(reqDTO.getId());
        if (Objects.isNull(planTask)) {
            throw new ServiceException("巡检任务数据不存在");
        }
        if (!StrUtil.equals(planTask.getTaskState(), TaskStateEnum.TO_START.getCode())) {
            throw new ServiceException("只有待开始任务才可以进行调整");
        }
        // 巡检人员
        planTask.setTaskPeopleIds(CollUtil.join(reqDTO.getOrgUserIdList(), ","));
        // 任务要求
        planTask.setTaskStartNotifyDemand(reqDTO.getTaskStartNotifyDemand());
        planTask.setTaskStartNotify(reqDTO.getTaskStartNotify());
        planTask.setTaskStartNotifyType(reqDTO.getTaskStartNotifyType());
        planTask.setTaskEndNotifyDemand(reqDTO.getTaskEndNotifyDemand());
        planTask.setTaskEndNotify(reqDTO.getTaskEndNotify());
        planTask.setTaskAutoCloseDemand(reqDTO.getTaskAutoCloseDemand());
        planTask.setTaskOutAllowDemand(reqDTO.getTaskOutAllowDemand());
        planTask.setTaskSequenceDemand(reqDTO.getTaskSequenceDemand());
        planTask.setTaskPhotoDemand(reqDTO.getTaskPhotoDemand());
        // 有开启任务通知任务通知时间赋值
        if ("1".equals(reqDTO.getTaskStartNotifyDemand())) {
            setTaskNotifyTimeValue(planTask);
        }
        // 有开启任务到期通知赋值
        if ("1".equals(reqDTO.getTaskEndNotifyDemand())) {
            setTaskOutTimeValue(planTask);
        }
        // 任务执行模式
        planTask.setTaskExecuteType(reqDTO.getTaskExecuteType());
        planTask.setUpdateOrgUser(contextUser.getOrgUserId());
        planTask.setInspectNum(reqDTO.getPlanConfigDTOList().size());
//        // 去重
//        validRepeat(planTask);
        updateById(planTask);
        // 删除任务巡检点
        inspectPlanConfigService.remove(new LambdaUpdateWrapper<SaasParkFireInspectPlanConfig>()
                .eq(SaasParkFireInspectPlanConfig::getTaskPlanId, planTask.getId()));
        List<SaasParkFireInspectPlanConfig> planConfigList = new ArrayList<>();
        int sort = 1;
        for (FireInspectPlanConfigDTO planConfigDTO : reqDTO.getPlanConfigDTOList()) {
            SaasParkFireInspectPlanConfig planConfig = new SaasParkFireInspectPlanConfig();
            BeanUtil.copyProperties(planConfigDTO, planConfig);
            planConfig.setCustomerId(planTask.getCustomerId());
            planConfig.setTaskPlanId(planTask.getId());
            planConfig.setTaskPlanType("2");
            planConfig.setInspectStatus("0");
            planConfig.setCreateOrgUser(contextUser.getOrgUserId());
            planConfig.setSort(sort);
            planConfigList.add(planConfig);
            sort++;
        }
        // 保存任务巡检点数据
        inspectPlanConfigService.saveBatch(planConfigList);
        return Boolean.TRUE;
    }

    @Override
    public List<SaasParkFireInspectPlanTask> getInspectTaskBoardChart(FireInspectTaskBoardReqDTO reqDTO) {
        return baseMapper.getInspectTaskBoardChart(reqDTO);
    }

    private void verifySubmitParam(AddTemporaryTaskReqDTO reqDTO) {
        // 巡检配置不能为空
        if (CollUtil.isEmpty(reqDTO.getPlanConfigDTOList())) {
            throw new ServiceException("计划排班任务数不能为空");
        }
        // 巡检人类型为成员
        if (CollUtil.isEmpty(reqDTO.getOrgUserIdList())) {
            throw new ServiceException("巡检人不能为空");
        }
        // 判断任务要求，是否通知
        if ("1".equals(reqDTO.getTaskStartNotifyDemand())) {
            if (Objects.isNull(reqDTO.getTaskStartNotify()) && StrUtil.isBlank(reqDTO.getTaskStartNotifyType())) {
                throw new ServiceException("开启任务通知时，任务通知时间内容不能为空");
            }
        }
        if ("1".equals(reqDTO.getTaskEndNotifyDemand())) {
            if (Objects.isNull(reqDTO.getTaskEndNotify()) && StrUtil.isBlank(reqDTO.getTaskEndNotifyType())) {
                throw new ServiceException("开启任务过期时，任务过期时间内容不能为空");
            }
        }
    }

    private void setTaskPeopleNamesValue(Map<Long, String> orgUserMap, FireInspectPlanTaskVO vo) {
        List<String> taskPeopleNames = new ArrayList<>();
        if (StrUtil.isNotBlank(vo.getTaskPeopleIds())) {
            List<Long> taskPeopleIds = Arrays.stream(vo.getTaskPeopleIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
            for (Long orgUserId : taskPeopleIds) {
                taskPeopleNames.add(orgUserMap.get(orgUserId));
            }
        }
        vo.setTaskPeopleNames(CollUtil.join(taskPeopleNames, ","));
    }

    private void setTaskPeopleNamesValue(Map<Long, String> orgUserMap, FireInspectPlanTaskDetailVO vo) {
        List<String> taskPeopleNames = new ArrayList<>();
        if (StrUtil.isNotBlank(vo.getTaskPeopleIds())) {
            List<Long> taskPeopleIds = Arrays.stream(vo.getTaskPeopleIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
            for (Long orgUserId : taskPeopleIds) {
                taskPeopleNames.add(orgUserMap.get(orgUserId));
            }
        }
        vo.setTaskPeopleNames(CollUtil.join(taskPeopleNames, ","));
    }

    private void setInspectPeopleNamesValue(Map<Long, String> orgUserMap, FireInspectPlanTaskVO vo) {
        List<String> inspectPeopleNames = new ArrayList<>();
        if (StrUtil.isNotBlank(vo.getInspectPeopleIds())) {
            List<Long> inspectPeopleIds = Arrays.stream(vo.getInspectPeopleIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
            for (Long orgUserId : inspectPeopleIds) {
                inspectPeopleNames.add(orgUserMap.get(orgUserId));
            }
        }
        vo.setInspectPeopleNames(CollUtil.join(inspectPeopleNames, ","));

    }

    private void setInspectPeopleNamesValue(Map<Long, String> orgUserMap, FireInspectPlanTaskDetailVO vo) {
        List<String> inspectPeopleNames = new ArrayList<>();
        if (StrUtil.isNotBlank(vo.getInspectPeopleIds())) {
            List<Long> inspectPeopleIds = Arrays.stream(vo.getInspectPeopleIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
            for (Long orgUserId : inspectPeopleIds) {
                inspectPeopleNames.add(orgUserMap.get(orgUserId));
            }
        }
        vo.setInspectPeopleNames(CollUtil.join(inspectPeopleNames, ","));

    }
}
