package com.yuchen.saas.park.service.controller.fire.inspect.client;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuchen.saas.manage.system.api.entity.NestOrgUser;
import com.yuchen.saas.manage.system.api.feign.IOrgUserClient;
import com.yuchen.saas.park.api.constant.ParkRedisKeyConstants;
import com.yuchen.saas.park.api.dto.fire.inspect.FireInspectTypeReqDTO;
import com.yuchen.saas.park.api.dto.fire.inspect.client.FireInspectLogReqDTO;
import com.yuchen.saas.park.api.dto.fire.inspect.client.OperateTaskReqDTO;
import com.yuchen.saas.park.api.dto.fire.inspect.client.ProcessTaskReqDTO;
import com.yuchen.saas.park.api.dto.fire.inspect.client.SubmitTaskReqDTO;
import com.yuchen.saas.park.api.dto.fire.inspect.plan.FireInspectPlanReqDTO;
import com.yuchen.saas.park.api.dto.fire.inspect.plan.FireInspectPlanTaskReqDTO;
import com.yuchen.saas.park.api.entity.fire.inspect.SaasParkFireInspectLog;
import com.yuchen.saas.park.api.entity.fire.inspect.SaasParkFireInspectPlan;
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.feign.imspect.ClientPlanTaskFeign;
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.FireInspectTypeVO;
import com.yuchen.saas.park.api.vo.fire.inspect.plan.*;
import com.yuchen.saas.park.service.listener.inspect.FireInspectLogEvent;
import com.yuchen.saas.park.service.service.fire.inspect.*;
import com.yuchen.saas.park.service.util.PageConverterUtils;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.nest.springwrap.core.log.exception.ServiceException;
import org.nest.springwrap.core.mp.base.BaseEntity;
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.redis.cache.NestRedis;
import org.nest.springwrap.core.secure.ContextUser;
import org.nest.springwrap.core.secure.utils.AuthUtil;
import org.nest.springwrap.core.tool.api.R;
import org.nest.springwrap.core.tool.utils.DateUtil;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

/**
 * @author zhouhanwei
 * @create 2024/4/9 16:14
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/client/planTask")
public class InspectPlanTaskClient implements ClientPlanTaskFeign {

    private final ISaasParkFireInspectPlanService planService;

    private final ISaasParkFireInspectPlanTaskService planTaskService;

    private final ISaasParkFireInspectTypeService inspectTypeService;

    private final ISaasParkFireInspectPlanConfigService inspectPlanConfigService;

    private final ISaasParkFireInspectConfigService inspectConfigService;

    private final ISaasParkFireInspectFormService inspectFormService;

    private final NestRedis nestRedis;

    private final ApplicationEventPublisher publisher;

    private final ISaasParkFireInspectLogService inspectLogService;

    private final IOrgUserClient iOrgUserClient;

    /**
     * 巡检计划分页列表
     */
    @Override
    @PostMapping("/findClientPlanPage")
    @ApiOperation(value = "巡检计划分页列表", notes = "巡检计划分页列表")
    public R<NestPage<FireInspectPlanVO>> findClientPlanPage(@RequestBody FireInspectPlanReqDTO reqDTO) {
        Page<FireInspectPlanVO> resultPage = new Page<>();
        // 分页数据
        Query query = new Query();
        query.setCurrent(reqDTO.getCurrent());
        query.setSize(reqDTO.getSize());
        // 赋值数据
        LambdaQueryWrapper<SaasParkFireInspectPlan> lambdaWrapper = Wrappers.lambdaQuery();
        lambdaWrapper.like(Objects.nonNull(reqDTO.getOrgUserId()), SaasParkFireInspectPlan::getInspectPeopleIds, String.valueOf(reqDTO.getOrgUserId()));
        lambdaWrapper.eq(SaasParkFireInspectPlan::getCustomerId, reqDTO.getCustomerId());
        lambdaWrapper.eq(Objects.nonNull(reqDTO.getProjectId()), SaasParkFireInspectPlan::getProjectId, reqDTO.getProjectId());
        lambdaWrapper.eq(Objects.nonNull(reqDTO.getInspectTypeId()), SaasParkFireInspectPlan::getInspectTypeId, reqDTO.getInspectTypeId());
        lambdaWrapper.eq(StrUtil.isNotBlank(reqDTO.getPlanState()), SaasParkFireInspectPlan::getPlanState, reqDTO.getPlanState());
        lambdaWrapper.like(StrUtil.isNotBlank(reqDTO.getInspectPlanName()), SaasParkFireInspectPlan::getInspectPlanName, reqDTO.getInspectPlanName());
        if (StrUtil.isNotBlank(reqDTO.getInspectConfigName())) {
            // 获取巡检点配置对应的任务id
            List<SaasParkFireInspectPlanConfig> planConfigList = inspectPlanConfigService.list(new LambdaQueryWrapper<SaasParkFireInspectPlanConfig>()
                    .eq(SaasParkFireInspectPlanConfig::getTaskPlanType, "1")
                    .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);
            }

        }
        lambdaWrapper.orderByDesc(BaseEntity::getCreateTime);
        IPage<SaasParkFireInspectPlan> page = planService.page(Condition.getPage(query),lambdaWrapper);
        List<SaasParkFireInspectPlan> fireInspectPlanList = page.getRecords();
        // 返回数据列表
        List<FireInspectPlanVO> resultList = new ArrayList<>();
        for (SaasParkFireInspectPlan saasParkFireInspectPlan : fireInspectPlanList) {
            FireInspectPlanVO vo = new FireInspectPlanVO();
            BeanUtil.copyProperties(saasParkFireInspectPlan, vo);
            resultList.add(vo);
        }
        resultPage.setTotal(page.getTotal());
        resultPage.setSize(page.getSize());
        resultPage.setCurrent(page.getCurrent());
        resultPage.setRecords(resultList);
        return R.data(PageConverterUtils.convert(resultPage));
    }

    /**
     * 我的巡检任务分页列表
     */
    @Override
    @PostMapping("/findClientPlanTaskPage")
    @ApiOperation(value = "我的巡检任务分页列表", notes = "我的巡检任务分页列表")
    public R<NestPage<FireInspectPlanTaskVO>> findClientPlanTaskPage(@RequestBody FireInspectPlanTaskReqDTO reqDTO) {
        return R.data(planTaskService.findFireInspectPlanTaskPage(reqDTO));
    }

    /**
     * 巡检日志列表
     */
    @Override
    @PostMapping("/findClientPlanTaskLogList")
    @ApiOperation(value = "巡检日志列表", notes = "巡检日志列表")
    public R<List<SaasParkFireInspectLogVO>> findClientPlanTaskLogList(@Validated @RequestBody FireInspectLogReqDTO reqDTO) {
        List<SaasParkFireInspectLogVO> resultList = new ArrayList<>();
        // 赋值数据
        LambdaQueryWrapper<SaasParkFireInspectLog> lambdaWrapper = Wrappers.lambdaQuery();
        lambdaWrapper.eq(SaasParkFireInspectLog::getPlanTaskId, reqDTO.getPlanTaskId());
        lambdaWrapper.eq(Objects.nonNull(reqDTO.getInspectUser()), SaasParkFireInspectLog::getInspectUser, reqDTO.getInspectUser());
        List<SaasParkFireInspectLog> inspectLogList = inspectLogService.list(lambdaWrapper);
        if (CollUtil.isEmpty(inspectLogList)) {
            return R.data(resultList);
        }
        // 获取巡检人员id
        List<Long> inspectUserList = inspectLogList.stream().map(SaasParkFireInspectLog::getInspectUser).collect(Collectors.toList());
        List<NestOrgUser> orgUserList = iOrgUserClient.findOrgUserListByIds(inspectUserList).getData();
        Map<Long, String> orgUserMap = orgUserList.stream().collect(Collectors.toMap(BaseEntity::getId, NestOrgUser::getName));
        for (SaasParkFireInspectLog inspectLog : inspectLogList) {
            SaasParkFireInspectLogVO vo = new SaasParkFireInspectLogVO();
            BeanUtil.copyProperties(inspectLog, vo);
            vo.setInspectUserName(orgUserMap.get(inspectLog.getInspectUser()));
            resultList.add(vo);
        }
        return R.data(resultList);
    }

    @Override
    @GetMapping("/getAdminPlanDetail/{planId}")
    @ApiOperation(value = "巡检计划详情", notes = "巡检计划详情")
    public R<FireInspectPlanDetailVO> getAdminPlanDetail(@PathVariable Long planId) {
        return R.data(planService.getFireInspectPlan(planId));
    }

    /**
     * 巡检类型列表 - 不分页
     */
    @Override
    @PostMapping("/getClientInspectTypeList")
    @ApiOperation(value = "巡检类型列表", notes = "巡检类型列表")
    public R<List<FireInspectTypeVO>> getClientInspectTypeList(@RequestBody FireInspectTypeReqDTO reqDTO) {
        return R.data(inspectTypeService.getClientInspectTypeList(reqDTO));
    }

    /**
     * 我的巡检任务详情
     */
    @Override
    @GetMapping("/getClientPlanTaskDetail/{planTaskId}")
    @ApiOperation(value = "我的巡检任务详情", notes = "我的巡检任务详情")
    public R<FireInspectPlanTaskDetailVO> getClientPlanTaskDetail(@PathVariable Long planTaskId) {
        return R.data(planTaskService.getFireInspectPlanTaskById(planTaskId));
    }

    /**
     * 巡检点配置信息详情
     */
    @Override
    @GetMapping("/getClientPlanConfigDetail/{planConfigId}")
    @ApiOperation(value = "巡检点配置信息详情", notes = "巡检点配置信息详情")
    public R<FireInspectPlanConfigDetailVO> getClientPlanConfigDetail(@PathVariable Long planConfigId) {
        SaasParkFireInspectPlanConfig planConfig = inspectPlanConfigService.getById(planConfigId);
        if (Objects.isNull(planConfig)) {
            throw new ServiceException("巡检配置信息数据不存在");
        }
        FireInspectPlanConfigDetailVO planConfigDetailVO = new FireInspectPlanConfigDetailVO();
        planConfigDetailVO.setId(planConfig.getId());
        planConfigDetailVO.setPlanTaskId(planConfig.getTaskPlanId());
        // 获取巡检点配置信息
        FireInspectConfigVO inspectConfig = inspectConfigService.getFireInspectConfigById(planConfig.getInspectConfigId());
        planConfigDetailVO.setInspectConfig(inspectConfig);
        // 获取表单信息
        FireInspectFormVO inspectForm = inspectFormService.getFireInspectTypeById(planConfig.getInspectFormId());
        // 已巡检取当时得检查项
        if (StrUtil.equals(planConfig.getInspectStatus(), "1")) {
            inspectForm.setInspectCheckItem(planConfig.getInspectCheckItem());
        }
        planConfigDetailVO.setInspectForm(inspectForm);
        planConfigDetailVO.setInspectResult(planConfig.getInspectResult());
        planConfigDetailVO.setInspectStatus(planConfig.getInspectStatus());
        return R.data(planConfigDetailVO);
    }

    /**
     * 操作任务（1：转派，2：退回, 3: 分配）
     */
    @Override
    @PostMapping("/operateTask")
    @ApiOperation(value = "操作任务", notes = "操作任务")
    @Transactional(rollbackFor = Exception.class)
    public R operateTask(@Validated @RequestBody OperateTaskReqDTO reqDTO) {
        ContextUser contextUser = AuthUtil.getUser();
        if (Objects.isNull(contextUser)) {
            throw new ServiceException("用户不存在");
        }
        SaasParkFireInspectPlanTask planTask = planTaskService.getById(reqDTO.getPlanTaskId());
        if (Objects.isNull(planTask)) {
            throw new ServiceException("巡检任务数据不存在");
        }
        if (StrUtil.equals(planTask.getTaskState(), TaskStateEnum.PROCESSED.getCode())) {
            throw new ServiceException("任务已完成，无法进行相应操作");
        }
        if (StrUtil.equals(planTask.getTaskState(), TaskStateEnum.ClOSE.getCode())) {
            throw new ServiceException("任务已关闭，无法进行相应操作");
        }
//        if (!StrUtil.equals(planTask.getTaskState(), TaskStateEnum.DISPOSING.getCode())) {
//            throw new ServiceException("任务处理中，无法进行相应操作");
//        }
        Date newDate = new Date();
        if (StrUtil.equals(reqDTO.getOperateType(), "1")) {
            // 判断过期不能转派
            if (newDate.getTime() > planTask.getTaskOutTime().getTime()) {
                if (StrUtil.equals(planTask.getTaskOutAllowDemand(), "1")) {
                    throw new ServiceException("任务已过期，无法转派任务");
                }
            }
            if (Objects.isNull(reqDTO.getRedeployOrgUserId())) {
                throw new ServiceException("转派人不能为空");
            }
            if (reqDTO.getRedeployOrgUserId().equals(contextUser.getOrgUserId())) {
                throw new ServiceException("转派人不能给自己");
            }
            List<Long> orgUserIdList = Arrays.stream(planTask.getTaskPeopleIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
            // 删除当前用户
            orgUserIdList.remove(contextUser.getOrgUserId());
            // 添加转派用户
            orgUserIdList.add(reqDTO.getRedeployOrgUserId());
//            planTask.setInspectPeopleIds(CollUtil.join(orgUserIdList, ","));
            planTask.setTaskPeopleIds(CollUtil.join(orgUserIdList, ","));
            planTask.setUpdateOrgUser(contextUser.getOrgUserId());
            return R.status(planTaskService.updateById(planTask));
        } else
        if (StrUtil.equals(reqDTO.getOperateType(), "2")) {
            // 判断过期不能退回
            if (newDate.getTime() > planTask.getTaskOutTime().getTime()) {
                if (StrUtil.equals(planTask.getTaskOutAllowDemand(), "1")) {
                    throw new ServiceException("任务已过期，无法退回任务");
                }
            }
            List<Long> orgUserIdList = Arrays.stream(planTask.getTaskPeopleIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
            if (!orgUserIdList.contains(contextUser.getOrgUserId())) {
                throw new ServiceException("此任务您已退回，无需重复退回");
            }
            // 删除当前用户
            orgUserIdList.remove(contextUser.getOrgUserId());
            if (CollUtil.isEmpty(orgUserIdList)) {
                planTask.setTaskPeopleIds(null);
            } else {
//                planTask.setInspectPeopleIds(CollUtil.join(orgUserIdList, ","));
                planTask.setTaskPeopleIds(CollUtil.join(orgUserIdList, ","));
            }
            planTask.setBackReason(reqDTO.getBackReason());
            planTask.setUpdateOrgUser(contextUser.getOrgUserId());
            return R.status(planTaskService.updateById(planTask));
        } else if (StrUtil.equals(reqDTO.getOperateType(), "3")) {
            // 判断过期不能分配
            if (newDate.getTime() > planTask.getTaskOutTime().getTime()) {
                if (StrUtil.equals(planTask.getTaskOutAllowDemand(), "1")) {
                    throw new ServiceException("任务已过期，无法分配任务");
                }
            }
            if (Objects.isNull(reqDTO.getOrgUserIdList())) {
                throw new ServiceException("分配人不能为空");
            }
            if (StrUtil.isNotBlank(planTask.getTaskPeopleIds())) {
                throw new ServiceException("此任务还有处理人，无需分配人员");
            }
//            planTask.setInspectPeopleIds(CollUtil.join(reqDTO.getOrgUserIdList(), ","));
            planTask.setTaskPeopleIds(CollUtil.join(reqDTO.getOrgUserIdList(), ","));
            planTask.setUpdateOrgUser(contextUser.getOrgUserId());
            return R.status(planTaskService.updateById(planTask));
        } else {
            throw new ServiceException("任务操作类型不正确");
        }

    }

    /**
     * 开始处理任务
     */
    @Override
    @PostMapping("/startProcessTask")
    @ApiOperation(value = "开始处理任务", notes = "开始处理任务")
    @Transactional(rollbackFor = Exception.class)
    public R startProcessTask(@Validated @RequestBody ProcessTaskReqDTO reqDTO) {
        ContextUser contextUser = AuthUtil.getUser();
        if (Objects.isNull(contextUser)) {
            throw new ServiceException("用户不存在");
        }
        SaasParkFireInspectPlanTask planTask = planTaskService.getById(reqDTO.getPlanTaskId());
        if (Objects.isNull(planTask)) {
            throw new ServiceException("巡检任务数据不存在");
        }
        if (StrUtil.equals(planTask.getTaskState(), TaskStateEnum.PROCESSED.getCode())) {
            throw new ServiceException("任务已完成，无需处理任务");
        }
        if (StrUtil.equals(planTask.getTaskState(), TaskStateEnum.ClOSE.getCode())) {
            throw new ServiceException("任务已关闭，无需处理任务");
        }
        // 判断任务日期是否大于当前日期
        Date newDate = DateUtil.parse(DateUtil.formatDate(new Date()), DateUtil.PATTERN_DATE);
        if (planTask.getTaskDate().after(newDate)) {
            throw new ServiceException("任务开始日期大于当前日期，任务无法开始处理");
        }
        if (!StrUtil.equals(planTask.getTaskState(), TaskStateEnum.TO_START.getCode())) {
            throw new ServiceException("任务已开始，无需重复开始");
        }
        // 判断过期不能开始任务
        if (StrUtil.equals(planTask.getTaskOutAllowDemand(), "1")) {
            if (new Date().getTime() > planTask.getTaskOutTime().getTime()) {
                throw new ServiceException("任务已过期，无法开始任务");
            }
        }
        planTask.setTaskState(TaskStateEnum.DISPOSING.getCode());
        planTask.setUpdateOrgUser(contextUser.getOrgUserId());
        return R.status(planTaskService.updateById(planTask));
    }

    /**
     * 提交巡检点任务
     */
    @Override
    @PostMapping("/submitTask")
    @ApiOperation(value = "提交巡检点任务", notes = "提交巡检点任务")
    @Transactional(rollbackFor = Exception.class)
    public R submitTask(@Validated @RequestBody SubmitTaskReqDTO reqDTO) {
        ContextUser contextUser = AuthUtil.getUser();
        if (Objects.isNull(contextUser)) {
            throw new ServiceException("用户不存在");
        }
        SaasParkFireInspectPlanTask planTask = planTaskService.getById(reqDTO.getPlanTaskId());
        if (Objects.isNull(planTask)) {
            throw new ServiceException("巡检任务数据不存在");
        }
        if (StrUtil.equals(planTask.getTaskState(), TaskStateEnum.ClOSE.getCode())) {
            throw new ServiceException("任务已关闭，无需处理任务");
        }
        if (StrUtil.equals(planTask.getTaskState(), TaskStateEnum.PROCESSED.getCode())) {
            throw new ServiceException("任务已完成，无需处理任务");
        }
        if (!StrUtil.equals(planTask.getTaskState(), TaskStateEnum.DISPOSING.getCode())) {
            throw new ServiceException("请先确认开始处理任务，在进行巡检点任务提交");
        }
        SaasParkFireInspectPlanConfig planConfig = inspectPlanConfigService.getById(reqDTO.getPlanTaskConfigId());
        if (Objects.isNull(planConfig)) {
            throw new ServiceException("巡检配置信息数据不存在");
        }
        if (!planConfig.getTaskPlanId().equals(planTask.getId())) {
            throw new ServiceException("巡检点任务不一致");
        }
        // 判断逾期任务不能巡检
//        if (StrUtil.equals(planTask.getExecuteState(), PlanExecuteStateEnum.OUT_NO_INSPECT.getCode()) ||
//                StrUtil.equals(planTask.getExecuteState(), PlanExecuteStateEnum.OUT_NO_COMPLETE.getCode())) {
//            if (StrUtil.equals(planTask.getTaskOutAllowDemand(), "1")) {
//                throw new ServiceException("任务已逾期，无法提交");
//            }
//        }
        // 判断过期不能开始任务
        if (StrUtil.equals(planTask.getTaskOutAllowDemand(), "1")) {
            if (new Date().getTime() > planTask.getTaskOutTime().getTime()) {
                throw new ServiceException("任务已过期，无法开始任务");
            }
        }

        // 判断当前是否需要顺序巡检
        if (StrUtil.equals(planTask.getTaskSequenceDemand(), "1")) {
            List<SaasParkFireInspectPlanConfig> list = inspectPlanConfigService.list(new LambdaQueryWrapper<SaasParkFireInspectPlanConfig>()
                    .eq(SaasParkFireInspectPlanConfig::getTaskPlanId, reqDTO.getPlanTaskId())
                    .orderByAsc(SaasParkFireInspectPlanConfig::getSort));
            int sort = list.indexOf(planConfig);
            if (sort > 1) {
                // 判断上一个巡检点是否已巡检
                if (!StrUtil.equals(list.get(sort-1).getInspectStatus(), "1")) {
                    throw new ServiceException("上一个巡检点未巡检，请顺序巡检");
                }
            }
        }
        // 判断是不是未巡检
        if (StrUtil.equals(planConfig.getInspectStatus(), "0")) {
            // 更新任务应巡检数，判断是否全部完成
            updateTask(planConfig, reqDTO);
        }
        // 更新巡检点状态
        planConfig.setInspectStatus("1");
        planConfig.setInspectResult(reqDTO.getInspectResult());
        planConfig.setInspectCheckItem(reqDTO.getInspectCheckItem());
        planConfig.setInspectUser(contextUser.getOrgUserId());
        planConfig.setInspectDate(new Date());
        planConfig.setRemark(reqDTO.getRemark());
        planConfig.setUpdateOrgUser(contextUser.getOrgUserId());
        inspectPlanConfigService.updateById(planConfig);
        // 保存巡检日志
        publisher.publishEvent(new FireInspectLogEvent(planTask.getCustomerId(), planTask.getProjectId(), planTask.getId(), planConfig.getId(),
                planConfig.getInspectResult(), planConfig.getInspectUser(), planConfig.getInspectDate(), planConfig.getRemark()));
        return R.status(Boolean.TRUE);
    }

    @Override
    @PostMapping("/editConfigTask")
    @ApiOperation(value = "编辑巡检点任务", notes = "编辑巡检点任务")
    @Transactional(rollbackFor = Exception.class)
    public R editConfigTask(SubmitTaskReqDTO reqDTO) {
        ContextUser contextUser = AuthUtil.getUser();
        if (Objects.isNull(contextUser)) {
            throw new ServiceException("用户不存在");
        }
        SaasParkFireInspectPlanConfig planConfig = inspectPlanConfigService.getById(reqDTO.getPlanTaskConfigId());
        if (Objects.isNull(planConfig)) {
            throw new ServiceException("巡检配置信息数据不存在");
        }
        planConfig.setInspectCheckItem(reqDTO.getInspectCheckItem());
        planConfig.setInspectUser(contextUser.getOrgUserId());
        planConfig.setInspectDate(new Date());
        planConfig.setRemark(reqDTO.getRemark());
        planConfig.setUpdateOrgUser(contextUser.getOrgUserId());
        return R.status(inspectPlanConfigService.updateById(planConfig));

    }

    private void updateTask(SaasParkFireInspectPlanConfig planConfig, SubmitTaskReqDTO reqDTO) {
        String key = ParkRedisKeyConstants.TASK_INFO_CHANGE_KEY + reqDTO.getPlanTaskId();
        log.info("提交任务获取任务锁{}", key);
        try {
            if (!nestRedis.exists(key)) {
                nestRedis.setEx(key, Thread.currentThread().getId(), 5L);
                SaasParkFireInspectPlanTask planTask = planTaskService.getById(reqDTO.getPlanTaskId());
                planTask.setInspectedNum(planTask.getInspectedNum() + 1);
                planTask.setTaskState(TaskStateEnum.DISPOSING.getCode());
                if (StrUtil.equals(reqDTO.getInspectResult(), "2")) {
                    planTask.setInspectedExceptionNum(planTask.getInspectedExceptionNum() + 1);
                }
//                planTask.setInspectResult(reqDTO.getInspectResult());
                planTask.setUpdateOrgUser(planConfig.getUpdateOrgUser());
                planTaskService.updateById(planTask);
            } else {
                // 阻塞线程一直调用此方法
                updateTask(planConfig, reqDTO);
            }
        } catch (Exception e){
            log.error("提交任务出现异常：", e);
            throw new ServiceException(e.getMessage());
        } finally {
            //删除redis
            log.info("释放任务锁{}", key);
            nestRedis.del(key);
        }
    }

    /**
     * 完成处理任务
     */
    @Override
    @PostMapping("/completeProcessTask")
    @ApiOperation(value = "完成处理任务", notes = "完成处理任务")
    @Transactional(rollbackFor = Exception.class)
    public R completeProcessTask(@Validated @RequestBody ProcessTaskReqDTO reqDTO) {
        ContextUser contextUser = AuthUtil.getUser();
        if (Objects.isNull(contextUser)) {
            throw new ServiceException("用户不存在");
        }
        SaasParkFireInspectPlanTask planTask = planTaskService.getById(reqDTO.getPlanTaskId());
        if (Objects.isNull(planTask)) {
            throw new ServiceException("巡检任务数据不存在");
        }
        if (StrUtil.equals(planTask.getTaskState(), TaskStateEnum.PROCESSED.getCode())) {
            throw new ServiceException("任务已完成，无需重复提交");
        }
        if (StrUtil.equals(planTask.getTaskState(), TaskStateEnum.ClOSE.getCode())) {
            throw new ServiceException("任务已关闭，无需处理任务");
        }
        // 判断过期不能开始任务
        if (StrUtil.equals(planTask.getTaskOutAllowDemand(), "1")) {
            if (new Date().getTime() > planTask.getTaskOutTime().getTime()) {
                throw new ServiceException("任务已过期，无法开始任务");
            }
        }
        if (planTask.getInspectedNum().equals(planTask.getInspectNum())) {
            planTask.setTaskState(TaskStateEnum.PROCESSED.getCode());
            planTask.setExecuteState(PlanExecuteStateEnum.EXECUTED.getCode());
            planTask.setTaskProcessedTime(new Date());
            if (planTask.getInspectedExceptionNum() > 0) {
                planTask.setInspectResult("2");
            } else {
                planTask.setInspectResult("1");
            }
        } else {
            throw new ServiceException("还有未完成的巡检点，无法提交");
        }
        planTask.setUpdateOrgUser(contextUser.getOrgUserId());
        return R.status(planTaskService.updateById(planTask));
    }




}
