package com.ruoyi.worktecket.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.constant.*;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.domain.AppLogin;
import com.ruoyi.system.domain.ContractorUser;
import com.ruoyi.system.dto.ContractorUserDTO;
import com.ruoyi.system.mapper.ContractorUserMapper;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.service.IAppLoginService;
import com.ruoyi.system.service.IContractorUserService;
import com.ruoyi.system.service.ISysNoticeService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.worktecket.domain.*;
import com.ruoyi.worktecket.dto.*;
import com.ruoyi.worktecket.dto.res.WorkTicketBasicDataResultDTO;
import com.ruoyi.worktecket.dto.res.WorkTicketOperateRecordDTO;
import com.ruoyi.worktecket.mapper.*;
import com.ruoyi.worktecket.service.IWorkTicketBasicDataService;
import com.ruoyi.worktecket.service.IWorkTicketSafetyMeasuresService;
import com.ruoyi.worktecket.service.IWorkTicketSignatureTemplateService;
import io.swagger.annotations.ApiModelProperty;
import nonapi.io.github.classgraph.utils.Join;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 作业票基础信息Service业务层处理
 *
 * @author ruoyi
 * @date 2023-08-04
 */
@Service
public class WorkTicketBasicDataServiceImpl implements IWorkTicketBasicDataService {
    @Autowired
    private WorkTicketBasicDataMapper workTicketBasicDataMapper;

    @Autowired
    private WorkTicketExtendMapper workTicketExtendMapper;

    @Autowired
    private WorkTicketSignOptionRunMapper workTicketSignOptionRunMapper;

    @Autowired
    private IWorkTicketSignatureTemplateService iWorkTicketSignatureTemplateService;
    @Autowired
    private IWorkTicketSafetyMeasuresService iWorkTicketSafetyMeasuresService;

    @Autowired
    private WorkTicketSmOptionRunMapper workTicketSmOptionRunMapper;

    @Autowired
    private WorkTicketExecuteUserMapper workTicketExecuteUserMapper;

    @Autowired
    private WorkTicketOperateRecordMapper workTicketOperateRecordMapper;

    @Autowired
    private WorkTicketGasAnalysisMapper workTicketGasAnalysisMapper;

    @Autowired
    private SysPostMapper sysPostMapper;
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IAppLoginService appLoginService;
    @Autowired
    private IContractorUserService contractorUserService;
    @Autowired
    private ISysNoticeService sysNoticeService;

    /**
     * 查询作业票基础信息
     *
     * @param id 作业票基础信息主键
     * @return 作业票基础信息
     */
    @Override
    public WorkTicketBasicDataResultDTO selectWorkTicketBasicDataById(String id) {
        WorkTicketBasicData workTicketBasicData = workTicketBasicDataMapper.selectById(id);
        WorkTicketBasicDataResultDTO workTicketBasicDataDTO = new WorkTicketBasicDataResultDTO();
        BeanUtils.copyProperties(workTicketBasicData, workTicketBasicDataDTO);
        //查询扩展信息
        LambdaQueryWrapper<WorkTicketExtend> wteQueryWrapper = new LambdaQueryWrapper<>();
        wteQueryWrapper.eq(WorkTicketExtend::getWorkTicketId, id);
        List<WorkTicketExtend> workTicketExtends = workTicketExtendMapper.selectList(wteQueryWrapper);
        WorkTicketExtendDTO workTicketExtendDTO = new WorkTicketExtendDTO();
        BeanUtils.copyProperties(workTicketExtends.get(0), workTicketExtendDTO);
        workTicketBasicDataDTO.setWorkTicketExtendDTO(workTicketExtendDTO);
        //查询措施信息
        LambdaQueryWrapper<WorkTicketSmOptionRun> smQueryWrapper = new LambdaQueryWrapper<>();
        smQueryWrapper.eq(WorkTicketSmOptionRun::getWorkTicketId, id);
        List<WorkTicketSmOptionRun> workTicketSmOptionRunList = workTicketSmOptionRunMapper.selectList(smQueryWrapper);
        if (!CollectionUtils.isEmpty(workTicketSmOptionRunList)) {
            List<WorkTicketSmOptionRunDTO> workTicketSmOptionRunDTOList = workTicketSmOptionRunList.stream().map(workTicketSmOptionRun -> convertWorkTicketSmOptionRunDTO(workTicketSmOptionRun)).collect(Collectors.toList());
            workTicketBasicDataDTO.setWorkTicketSmOptionRunDTOList(workTicketSmOptionRunDTOList);
        }
        //查询签字项
        LambdaQueryWrapper<WorkTicketSignOptionRun> signOptionRunLambdaQueryWrapper = new LambdaQueryWrapper<>();
        signOptionRunLambdaQueryWrapper.eq(WorkTicketSignOptionRun::getWorkTicketId, id);
        signOptionRunLambdaQueryWrapper.orderByAsc(WorkTicketSignOptionRun::getWorkTicketSignStore);
        List<WorkTicketSignOptionRun> workTicketSignOptionRunList = workTicketSignOptionRunMapper.selectList(signOptionRunLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(workTicketSignOptionRunList)) {
            List<WorkTicketSignOptionRunDTO> workTicketSignOptionRunDTOList = workTicketSignOptionRunList
                    .stream()
                    .map(workTicketSignOptionRun -> convertWorkTicketSignOptionRunDTO(workTicketSignOptionRun)).collect(Collectors.toList());
            workTicketBasicDataDTO.setWorkTicketSignOptionRunDTOList(workTicketSignOptionRunDTOList);
        }
        //气体取样分析
        LambdaQueryWrapper<WorkTicketGasAnalysis> workTicketGasAnalysisLambdaQueryWrapper = new LambdaQueryWrapper<>();
        workTicketGasAnalysisLambdaQueryWrapper.eq(WorkTicketGasAnalysis::getWorkTicketId, id);
        List<WorkTicketGasAnalysis> workTicketGasAnalyses = workTicketGasAnalysisMapper.selectList(workTicketGasAnalysisLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(workTicketGasAnalyses)) {
            List<WorkTicketGasAnalysisDTO> workTicketGasAnalysisDTOList = workTicketGasAnalyses.stream().map(workTicketGasAnalysis -> convertWorkTicketGasAnalysisDTO(workTicketGasAnalysis)).collect(Collectors.toList());
            workTicketBasicDataDTO.setWorkTicketGasAnalysisDTOList(workTicketGasAnalysisDTOList);
        }
        //作业人
        LambdaQueryWrapper<WorkTicketExecuteUser> workTicketExecuteUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        workTicketExecuteUserLambdaQueryWrapper.eq(WorkTicketExecuteUser::getWorkTicketId, id);
        workTicketExecuteUserLambdaQueryWrapper.eq(WorkTicketExecuteUser::getIsDel, DeletedEnum.VALID.getValue());
        List<WorkTicketExecuteUser> workTicketExecuteUsers = workTicketExecuteUserMapper.selectList(workTicketExecuteUserLambdaQueryWrapper);
        //内部
        if (workTicketBasicDataDTO.getWorkTicketCompanyType().equals(CompanyTypeEnum.INTERIOR.getValue())) {
            List<Long> userIdList = workTicketExecuteUsers.stream().map(workTicketExecuteUser -> workTicketExecuteUser.getExecuteUser()).collect(Collectors.toList());
            workTicketBasicDataDTO.setExecuteUserIdList(userIdList);//内部作业人ID列表

            List<SysUser> sysUsers = sysUserService.selectUserByIds(userIdList);
            List<String> userNickNameList = sysUsers.stream().map(sysUser -> sysUser.getNickName()).collect(Collectors.toList());
            workTicketBasicDataDTO.setExecuteUserNameList(userNickNameList);//内部作业人姓名列表

            String workTicketGuardianUser = workTicketBasicDataDTO.getWorkTicketGuardianUser();//作业监护人
            SysUser sysUser = sysUserService.selectUserById(Long.parseLong(workTicketGuardianUser));
            if (Objects.nonNull(sysUser))
                workTicketBasicDataDTO.setWorkTicketGuardianUserName(sysUser.getNickName());
        }
        //承包商
        else {
            List<String> contractorUserIdList = workTicketExecuteUsers.stream().map(workTicketExecuteUser -> workTicketExecuteUser.getContractorUser()).collect(Collectors.toList());
            workTicketBasicDataDTO.setContractorUserIdList(contractorUserIdList);//承包商作业人ID列表
            List<ContractorUser> contractorUserList = contractorUserService.selectContractorUserByIds(contractorUserIdList);
            List<String> contractorUserNameList = contractorUserList.stream().map(contractorUser -> contractorUser.getCompellation()).collect(Collectors.toList());
            workTicketBasicDataDTO.setContractorUserNameList(contractorUserNameList);//承包商作业人姓名列表

            String workTicketGuardianUser = workTicketBasicDataDTO.getWorkTicketGuardianUser();
            ContractorUserDTO contractorUserDTO = contractorUserService.selectContractorUserById(workTicketGuardianUser);
            if (Objects.nonNull(contractorUserDTO)) {
                workTicketBasicDataDTO.setWorkTicketGuardianUserName(contractorUserDTO.getCompellation());
            }
        }

        //监护人
//        作业单位类型 10承包商、20内部
//        IF(work_ticket_company_type ){


        return workTicketBasicDataDTO;
    }


    /**
     * //废弃：从其他接口返回->获取作业票信息详细信息
     * 获取作业票签字项及签字人员范围
     * <p>
     * param workTicketId 作业票ID
     *
     * @return
     */
//    @Override
//    public String getSignOptionList(String workTicketId) {
//        return null;
//    }
    private WorkTicketGasAnalysisDTO convertWorkTicketGasAnalysisDTO(WorkTicketGasAnalysis workTicketGasAnalysis) {
        WorkTicketGasAnalysisDTO workTicketGasAnalysisDTO = new WorkTicketGasAnalysisDTO();
        BeanUtils.copyProperties(workTicketGasAnalysis, workTicketGasAnalysisDTO);
        return workTicketGasAnalysisDTO;
    }

    private WorkTicketSmOptionRunDTO convertWorkTicketSmOptionRunDTO(WorkTicketSmOptionRun workTicketSmOptionRun) {
        WorkTicketSmOptionRunDTO workTicketSmOptionRunDTO = new WorkTicketSmOptionRunDTO();
        BeanUtils.copyProperties(workTicketSmOptionRun, workTicketSmOptionRunDTO);
        return workTicketSmOptionRunDTO;
    }


    private WorkTicketSignOptionRunDTO convertWorkTicketSignOptionRunDTO(WorkTicketSignOptionRun workTicketSignOptionRun) {
        WorkTicketSignOptionRunDTO workTicketSignOptionRunDTO = new WorkTicketSignOptionRunDTO();
        BeanUtils.copyProperties(workTicketSignOptionRun, workTicketSignOptionRunDTO);
        // 作业票签字类型10人员、20岗位
        String workTicketSignType = workTicketSignOptionRun.getWorkTicketSignType();
        String workTicketSignUser = workTicketSignOptionRun.getWorkTicketSignUser();
        String[] dataArr = workTicketSignUser.split(",");//用户ID或或者岗位ID
        List<Long> dataList = new ArrayList<>();
        for (int i = 0; i < dataArr.length; i++) {
            dataList.add(Long.parseLong(dataArr[i]));
        }

        //查询用户：根据用户ID
        if ("10".equals(workTicketSignType)) {
            List<SysUser> sysUserList = sysUserService.selectUserByIds(dataList);
            workTicketSignOptionRunDTO.getUserSignList().addAll(sysUserList);
        }
        //查询用户：根据岗位
        else if ("20".equals(workTicketSignType)) {
            List<SysUser> sysUserList = sysUserService.selectUserByPostIds(dataList);
            workTicketSignOptionRunDTO.getUserSignList().addAll(sysUserList);
        }

        return workTicketSignOptionRunDTO;
    }

    /**
     * 查询作业票基础信息列表
     * 注意：APP作业列表 和 PC作业列表都走这里
     *
     * @param workTicketBasicDataDTO 作业票基础信息
     * @return 作业票基础信息
     */
    @Override
    public List<WorkTicketBasicDataResultDTO> selectWorkTicketBasicDataList(WorkTicketBasicDataDTO workTicketBasicDataDTO) {
        //TODO 待发布：开发环境时才生效，线上环境依旧显示全部数据
        HttpServletRequest request = ServletUtils.getRequest();
        String localAddr = request.getLocalAddr();
        if (localAddr.startsWith("192.168.3.")) {

            //1、领导角色查看全部
            //非领导角色：
            //2、申请人
            //3、作业负责人
            //4、审核人（作业签字模板中配置的），单据到审核中时才能查看：申请作业票时执行签字人表中取值，不能从模板表取值，因为模板表可以随时修改，审核人范围是在申请作业票时定下来的
            String requestToken = JWTUtil.getRequestToken();

            String appUserType = null;
            try {
                appUserType = JWTUtil.getAppUserType();
            } catch (Exception e) {

            }
            //承包商不让查看，直接返回空集合
            if (appUserType != null && AppUserTypeEnum.CONTRACTOR.getValue() == Integer.parseInt(appUserType)) {
                return new ArrayList<>();
            }
            // APP请求时
            else if (StringUtils.isNotBlank(requestToken)) {
                //<if test="applicantUserId != null and workTicketDirectorId != null signOptionUserIdList != null and signOptionPostIdList != null">
                boolean leader = JWTUtil.isLeader();
                String pcUserId = JWTUtil.getPCUserId();
                List<Long> signOptionUserIdList = new ArrayList<>();
                signOptionUserIdList.add(Long.parseLong(pcUserId));
                //APP登录人员的岗位集合
                List<Long> postIdList = JWTUtil.getPostIdList();
                // 非领导角色不能查看全部，需要筛选
                if (!leader) {
                    workTicketBasicDataDTO.setApplicantUserId(Long.parseLong(pcUserId));//申请人
                    workTicketBasicDataDTO.setWorkTicketDirectorId(Long.parseLong(pcUserId));//作业负责人
                    workTicketBasicDataDTO.setSignOptionUserIdList(signOptionUserIdList);//签字人用户ID
                    workTicketBasicDataDTO.setSignOptionPostIdList(postIdList);//签字人岗位ID
                }
            }

        }
        return workTicketBasicDataMapper.selectWorkTicketBasicDataList(workTicketBasicDataDTO);
    }

    /**
     * 新增作业票基础信息
     *
     * @param workTicketBasicDataDTO 作业票基础信息
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult insertWorkTicketBasicData(WorkTicketBasicDataDTO workTicketBasicDataDTO, boolean isPc) {
        //作业负责人
        Long workTicketDirectorId = workTicketBasicDataDTO.getWorkTicketDirectorId();
        //作业监护人
        String workTicketGuardianUser = workTicketBasicDataDTO.getWorkTicketGuardianUser();
        if (workTicketDirectorId == null) {
            return AjaxResult.error("请选择作业负责人");
        }
        if (StringUtils.isBlank(workTicketGuardianUser)) {
            return AjaxResult.error("请选择监护人");
        }

        //签字流程模板查询条件
        WorkTicketSignatureTemplateDTO workTicketSignatureTemplateDTO = new WorkTicketSignatureTemplateDTO();
        workTicketSignatureTemplateDTO.setWorkTicketType(workTicketBasicDataDTO.getWorkTicketType());//作业票类型 10动火、20受限、30盲板抽堵、40高处、50吊装、60临时、70动土、80断路
        //安全措施模板查询条件
        WorkTicketSafetyMeasuresDTO workTicketSafetyMeasuresDTO = new WorkTicketSafetyMeasuresDTO();
        workTicketSafetyMeasuresDTO.setWorkTicketType(workTicketBasicDataDTO.getWorkTicketType());

        // HW("动火作业","10"),
        if (WorkTicketTypeEnum.HW.getValue().equals(workTicketSignatureTemplateDTO.getWorkTicketType())) {
            workTicketSignatureTemplateDTO.setWorkTicketLevel(workTicketBasicDataDTO.getWorkTicketExtendDTO().getHwWorkLevel());//动火作业级别
            workTicketSafetyMeasuresDTO.setWorkTicketLevel(workTicketBasicDataDTO.getWorkTicketExtendDTO().getHwWorkLevel());
        }
        // HA("高处作业","40"),
        else if (WorkTicketTypeEnum.HA.getValue().equals(workTicketSignatureTemplateDTO.getWorkTicketType())) {
            workTicketSignatureTemplateDTO.setWorkTicketLevel(workTicketBasicDataDTO.getWorkTicketExtendDTO().getHaWorkLevel());//高处作业-级别
            workTicketSafetyMeasuresDTO.setWorkTicketLevel(workTicketBasicDataDTO.getWorkTicketExtendDTO().getHaWorkLevel());
        }
        // HO("吊装作业","50"),
        else if (WorkTicketTypeEnum.HO.getValue().equals(workTicketSignatureTemplateDTO.getWorkTicketType())) {
            workTicketSignatureTemplateDTO.setWorkTicketLevel(workTicketBasicDataDTO.getWorkTicketExtendDTO().getHoWorkLevel());//作业票级别 10特级、20一级、30二级
            workTicketSafetyMeasuresDTO.setWorkTicketLevel(workTicketBasicDataDTO.getWorkTicketExtendDTO().getHoWorkLevel());
        }

        //查询作业票安全措施模板
        List<WorkTicketSafetyMeasuresDTO> workTicketSafetyMeasuresDTOS = iWorkTicketSafetyMeasuresService.selectWorkTicketSafetyMeasuresList(workTicketSafetyMeasuresDTO);
        if (CollectionUtils.isEmpty(workTicketSafetyMeasuresDTOS)) {
            return AjaxResult.error("请上传安全措施模板");
        }

        //查询签字流程可用模板
        List<WorkTicketSignatureTemplateDTO> workTicketSignatureTemplateDTOS = iWorkTicketSignatureTemplateService.selectWorkTicketSignatureTemplateList(workTicketSignatureTemplateDTO);
        if (CollectionUtils.isEmpty(workTicketSignatureTemplateDTOS)) {
            return AjaxResult.error("请上传签字模板");
        }
        if (workTicketSignatureTemplateDTOS.size() != 1) {
            return AjaxResult.error("存在多个签字项模板，请检查！");
        }


        List<Long> executeUserIdList = workTicketBasicDataDTO.getExecuteUserIdList();

        List<String> contractorUserIdList = workTicketBasicDataDTO.getContractorUserIdList();
        if (workTicketBasicDataDTO.getWorkTicketCompanyType().equals(CompanyTypeEnum.CONTRACTOR.getValue()) && CollectionUtils.isEmpty(contractorUserIdList)) {
            return AjaxResult.error("请选择承包商作业人员！");
        } else if (workTicketBasicDataDTO.getWorkTicketCompanyType().equals(CompanyTypeEnum.INTERIOR.getValue()) && CollectionUtils.isEmpty(executeUserIdList)) {
            return AjaxResult.error("请选择内部作业人员！");
        }

        WorkTicketBasicData workTicketBasicData = new WorkTicketBasicData();
        BeanUtils.copyProperties(workTicketBasicDataDTO, workTicketBasicData);
        if (isPc) {
            workTicketBasicData.setCreateDefault();
        } else {
            workTicketBasicData.setCreateDefaultForApp();
        }
        workTicketBasicData.setWorkTicketStatus(WorkTicketStatusEnum.DISCLOSE_v2.getValue());//设置为待交底
        workTicketBasicData.setWorkTicketNo(WorkTicketNoUtils.NextOrderNo());
        workTicketBasicData.setApplicantTime(new Date());
        int count = workTicketBasicDataMapper.insert(workTicketBasicData);
        //处理扩展信息
        WorkTicketExtend workTicketExtend = new WorkTicketExtend();
        BeanUtils.copyProperties(workTicketBasicDataDTO.getWorkTicketExtendDTO(), workTicketExtend);
        workTicketExtend.setWorkTicketId(workTicketBasicData.getId());
        workTicketExtend.setId(workTicketBasicData.getId());
        if (isPc) {
            workTicketExtend.setCreateDefault();
        } else {
            workTicketExtend.setCreateDefaultForApp();
        }
        workTicketExtendMapper.insert(workTicketExtend);
        //作业人
        if (workTicketBasicDataDTO.getWorkTicketCompanyType().equals(CompanyTypeEnum.CONTRACTOR.getValue())) {
            for (String contractorUserId : contractorUserIdList) {
                WorkTicketExecuteUser workTicketExecuteUser = new WorkTicketExecuteUser();
                workTicketExecuteUser.setContractorUser(contractorUserId);
                workTicketExecuteUser.setWorkTicketId(workTicketBasicData.getId());
                workTicketExecuteUser.setExecuteCompanyType(workTicketBasicDataDTO.getWorkTicketCompanyType());
                if (isPc) {
                    workTicketExecuteUser.setCreateDefault();
                } else {
                    workTicketExecuteUser.setCreateDefaultForApp();
                }
                workTicketExecuteUserMapper.insert(workTicketExecuteUser);
            }
        } else {
            for (Long userId : executeUserIdList) {
                WorkTicketExecuteUser workTicketExecuteUser = new WorkTicketExecuteUser();
                workTicketExecuteUser.setExecuteUser(userId);
                workTicketExecuteUser.setWorkTicketId(workTicketBasicData.getId());
                workTicketExecuteUser.setExecuteCompanyType(workTicketBasicDataDTO.getWorkTicketCompanyType());
                if (isPc) {
                    workTicketExecuteUser.setCreateDefault();
                } else {
                    workTicketExecuteUser.setCreateDefaultForApp();
                }
                workTicketExecuteUserMapper.insert(workTicketExecuteUser);
            }
        }

        /****处理安全措施****/
        WorkTicketSafetyMeasuresDTO workTicketSafetyMeasuresDTO1 = iWorkTicketSafetyMeasuresService.selectWorkTicketSafetyMeasuresById(workTicketSafetyMeasuresDTOS.get(0).getId());
        List<WorkTicketSmOptionDTO> workTicketSmOptionDTOList = workTicketSafetyMeasuresDTO1.getWorkTicketSmOptionDTOList();
        if (!CollectionUtils.isEmpty(workTicketSmOptionDTOList)) {
            for (WorkTicketSmOptionDTO workTicketSmOptionDTO : workTicketSmOptionDTOList) {
                WorkTicketSmOptionRun workTicketSmOptionRun = new WorkTicketSmOptionRun();
                workTicketSmOptionRun.setWorkTicketType(workTicketBasicData.getWorkTicketType());
                workTicketSmOptionRun.setWorkTicketId(workTicketBasicData.getId());
                workTicketSmOptionRun.setSmOptionName(workTicketSmOptionDTO.getWorkTicketSmOption());
                if (isPc) {
                    workTicketSmOptionRun.setCreateDefault();
                } else {
                    workTicketSmOptionRun.setCreateDefaultForApp();
                }
                workTicketSmOptionRunMapper.insert(workTicketSmOptionRun);
            }
        }

        /****处理签字流程****/
        WorkTicketSignatureTemplateDTO workTicketSignatureTemplateDTO1 = iWorkTicketSignatureTemplateService.selectWorkTicketSignatureTemplateById(workTicketSignatureTemplateDTOS.get(0).getId());
        List<WorkTicketSignOptionDTO> workTicketSignOptionDTOList = workTicketSignatureTemplateDTO1.getWorkTicketSignOptionDTOList();
        if (!CollectionUtils.isEmpty(workTicketSignOptionDTOList)) {
            for (WorkTicketSignOptionDTO workTicketSignOptionDTO : workTicketSignOptionDTOList) {
                WorkTicketSignOptionRun workTicketSignOptionRun = new WorkTicketSignOptionRun();
                workTicketSignOptionRun.setWorkTicketId(workTicketBasicData.getId());
                workTicketSignOptionRun.setWorkTicketSignOption(workTicketSignOptionDTO.getWorkTicketSignOption());//作业票签字项名称
                workTicketSignOptionRun.setWorkTicketSignStore(workTicketSignOptionDTO.getWorkTicketSignStore());//废弃了，目前按创建时间倒叙了
                workTicketSignOptionRun.setWorkTicketSignType(workTicketSignOptionDTO.getWorkTicketSignType());//作业票签字类型10人员、20岗位
                workTicketSignOptionRun.setWorkTicketSignUser(Join.join(",", workTicketSignOptionDTO.getWorkTicketSignUserIdList()));//作业票签字人或岗位ID,多个以逗号分割
                workTicketSignOptionRun.setWorkTicketType(workTicketBasicData.getWorkTicketType());//作业票类型 10动火、20受限、30盲板抽堵、40高处、50吊装、60临时、70动土、80断路
                if (isPc) {
                    workTicketSignOptionRun.setCreateDefault();
                } else {
                    workTicketSignOptionRun.setCreateDefaultForApp();
                }
                workTicketSignOptionRunMapper.insert(workTicketSignOptionRun);
            }
        }
        //处理流程记录：插入创建和待交底
        handleWorkTicketOperateRecord(true, workTicketBasicData.getId(), WorkTicketStatusEnum.DISCLOSE_v2.getValue(), isPc);
        return AjaxResult.success(count);
    }

    /**
     * 处理作业票状态流转记录
     *
     * @param isCreate
     * @param workTicketId
     * @param workTicketStatus
     */
    private void handleWorkTicketOperateRecord(boolean isCreate, String workTicketId, String workTicketStatus, boolean isPc) {
        try {
            //发消息
//            String userId = JWTUtil.getUserId();
            WorkTicketBasicData workTicketBasicDataDB = null;
            // 作业票：
            // 1、带交底（申请完成后）：给负责人发消息 -> xxx申请了作业票单据，请及时审核，单据号：xxxx
            if (WorkTicketStatusEnum.DISCLOSE_v2.getValue().equals(workTicketStatus)) {
                workTicketBasicDataDB = workTicketBasicDataMapper.selectById(workTicketId);
                if (!Objects.isNull(workTicketBasicDataDB)) {
                    //申请人
                    Long applicantUserId = workTicketBasicDataDB.getApplicantUserId();
                    SysUser sysUser = sysUserService.selectUserById(applicantUserId);
                    String noticeContent = (sysUser != null ? sysUser.getNickName() : "") + "申请了作业票单据，请及时审核，单据号：" + workTicketBasicDataDB.getWorkTicketNo();
                    //收消息的人：负责人
                    Long userId = workTicketBasicDataDB.getWorkTicketDirectorId();
                    AppLogin appLogin = appLoginService.selectAppLoginByUserId(userId);
                    if (!Objects.isNull(appLogin)) {
                        sysNoticeService.insertNoticeToUser(appLogin.getId(), noticeContent, SysNoticeTitleRouteEnum.WORK);
                    }
                }
            }
            // 2、交底完成：给审核人（会签人员列表，查询签字模板执行项）发消息 -> 单据号：XXXX的作业票需要流程审核，请及时处理！
            else if (WorkTicketStatusEnum.COUNTERSIGN_v2.getValue().equals(workTicketStatus)) {
                workTicketBasicDataDB = workTicketBasicDataMapper.selectById(workTicketId);
                if (!Objects.isNull(workTicketBasicDataDB)) {

                    //查询全部签字人
                    LambdaQueryWrapper<WorkTicketSignOptionRun> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(WorkTicketSignOptionRun::getWorkTicketId, workTicketId);
                    queryWrapper.eq(WorkTicketSignOptionRun::getIsDel, DeletedEnum.VALID.getValue());
                    List<WorkTicketSignOptionRun> workTicketSignOptionRuns = workTicketSignOptionRunMapper.selectList(queryWrapper);
                    List<WorkTicketSignOptionRun> yesSignOption = workTicketSignOptionRuns.stream().
                            filter(workTicketSignOptionRun1 -> StringUtils.isNotEmpty(workTicketSignOptionRun1.getWorkSignOptionUserImg())).collect(Collectors.toList());

                    //没有人签字时才发送消息，防止重复发消息
                    if (CollectionUtils.isEmpty(yesSignOption)) {
                        String noticeContent = "单据号：" + workTicketBasicDataDB.getWorkTicketNo() + "的作业票需要流程审核，请及时处理！";
                        //接收消息的用户
                        Set<Long> appUseridList = new HashSet<>();
                        for (WorkTicketSignOptionRun signOptionRun : workTicketSignOptionRuns) {
                            String workTicketSignType = signOptionRun.getWorkTicketSignType();
                            String[] workTicketSignUserOrPostArr = signOptionRun.getWorkTicketSignUser().split(",");
                            //配置的人员
                            if (workTicketSignType.equals(WorkTicketSignOptionUserTypeEnum.USER.getValue())) {
                                List<String> useridList = Arrays.asList(workTicketSignUserOrPostArr);
                                for (String userId : useridList) {
                                    AppLogin appLogin = appLoginService.selectAppLoginByUserId(Long.parseLong(userId));
                                    if (!Objects.isNull(appLogin)) {
                                        appUseridList.add(appLogin.getId());
                                    }
                                }
                            }
                            //配置的岗位
                            else if (workTicketSignType.equals(WorkTicketSignOptionUserTypeEnum.POST.getValue())) {
                                List<Long> postList = new ArrayList<>(workTicketSignUserOrPostArr.length);
                                for (String postId : workTicketSignUserOrPostArr) {
                                    postList.add(Long.parseLong(postId));
                                }
                                List<SysUser> sysUserList = sysUserService.selectUserByPostIds(postList);
                                for (SysUser sysUser : sysUserList) {
                                    Long appUserId = sysUser.getAppUserId();
                                    if (appUserId != null) {
                                        appUseridList.add(appUserId);
                                    }
                                }
                            }
                        }
                        appUseridList.forEach(userId -> {
                            sysNoticeService.insertNoticeToUser(userId, noticeContent, SysNoticeTitleRouteEnum.WORK);
                        });
                    }
                }
            }
            // 3、审核完成（最后一个审核人，审核后->原是会签）：给负责人发消息 -> 单据号：XXXX当前为作业中，作业完成后请及时验收！
            else if (WorkTicketStatusEnum.OPERATION_v2.getValue().equals(workTicketStatus)) {
                workTicketBasicDataDB = workTicketBasicDataMapper.selectById(workTicketId);
                if (!Objects.isNull(workTicketBasicDataDB)) {
                    String noticeContent = "单据号：" + workTicketBasicDataDB.getWorkTicketNo() + "当前为作业中，作业完成后请及时验收！";
                    //收消息的人：负责人
                    Long userId = workTicketBasicDataDB.getWorkTicketDirectorId();
                    AppLogin appLogin = appLoginService.selectAppLoginByUserId(userId);
                    if (!Objects.isNull(appLogin)) {
                        sysNoticeService.insertNoticeToUser(appLogin.getId(), noticeContent, SysNoticeTitleRouteEnum.WORK);
                    }
                }
            }


            //操作时间
            Date operateTime = new Date();
            //用户昵称
            String nickName = JWTUtil.getNickName();
           /* //用户类型：1内部，2承包商
            if ("1".equals(JWTUtil.getAppUserType())) {
                //设置人员姓名
                SysUser sysUser = sysUserService.selectUserById(Long.parseLong(JWTUtil.getPCUserId()));
                if (Objects.nonNull(sysUser)) {
                    nickName = sysUser.getNickName();
                }
            } else {
                AppLogin appLogin = appLoginService.selectAppLoginById(JWTUtil.getUserId());
                if (Objects.nonNull(appLogin)) {
                    ContractorUserDTO contractorUserDTO = contractorUserService.selectContractorUserById(appLogin.getContractorUserId());
                    if (Objects.nonNull(contractorUserDTO)) {
                        nickName = contractorUserDTO.getCompellation();
                    }
                }
            }*/

            //创建作业单时，生成一条完整操作记录
            if (isCreate) {
                WorkTicketOperateRecord workTicketOperateRecord = new WorkTicketOperateRecord();
                workTicketOperateRecord.setWorkTicketId(workTicketId);
                workTicketOperateRecord.setOperateUserId(Long.parseLong(JWTUtil.getUserId()));
                workTicketOperateRecord.setOperateUserName(nickName);
                workTicketOperateRecord.setOperateTime(operateTime);
                workTicketOperateRecord.setWorkTicketStatus(WorkTicketStatusEnum.CREATE.getValue());//创建
                if (isPc) {
                    workTicketOperateRecord.setCreateDefault();
                } else {
                    workTicketOperateRecord.setCreateDefaultForApp();
                }
                workTicketOperateRecord.setCreateDate(operateTime);
                workTicketOperateRecordMapper.insert(workTicketOperateRecord);

                //申请作业票时，连续添加2条记录，让第二条记录操作时间加999毫秒
                operateTime = DateUtils.addSeconds(operateTime, 1);
            } else {
                //找到待完成的操作，改成完成
                WorkTicketOperateRecord update = new WorkTicketOperateRecord();
                update.setOperateTime(operateTime);
                update.setOperateUserId(Long.parseLong(JWTUtil.getUserId()));
                update.setOperateUserName(nickName);
                if (isPc) {
                    update.setUpdateDefault();
                } else {
                    update.setUpdateDefaultForApp();
                }
                LambdaQueryWrapper<WorkTicketOperateRecord> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(WorkTicketOperateRecord::getWorkTicketId, workTicketId);
                queryWrapper.isNull(WorkTicketOperateRecord::getOperateUserId);
                workTicketOperateRecordMapper.update(update, queryWrapper);
            }
            //非验收状态时，新增一条待完成操作记录
            if (!WorkTicketStatusEnum.APPROVED_v2.getValue().equals(workTicketStatus)) {
                WorkTicketOperateRecord workTicketOperateRecord = new WorkTicketOperateRecord();
                workTicketOperateRecord.setWorkTicketId(workTicketId);
                workTicketOperateRecord.setWorkTicketStatus(workTicketStatus);
//                workTicketOperateRecord.setOperateTime(operateTime);
                if (isPc) {
                    workTicketOperateRecord.setCreateDefault();
                } else {
                    workTicketOperateRecord.setCreateDefaultForApp();
                }
                workTicketOperateRecord.setCreateDate(operateTime);
                workTicketOperateRecordMapper.insert(workTicketOperateRecord);
            }
            //验收时添加当前人为验收人
            else {
                WorkTicketOperateRecord workTicketOperateRecord = new WorkTicketOperateRecord();
                workTicketOperateRecord.setWorkTicketId(workTicketId);
                workTicketOperateRecord.setWorkTicketStatus(workTicketStatus);
                workTicketOperateRecord.setOperateTime(operateTime);
                workTicketOperateRecord.setOperateUserId(Long.parseLong(JWTUtil.getUserId()));
                workTicketOperateRecord.setOperateUserName(nickName);
                if (isPc) {
                    workTicketOperateRecord.setCreateDefault();
                } else {
                    workTicketOperateRecord.setCreateDefaultForApp();
                }
                workTicketOperateRecord.setCreateDate(operateTime);
                workTicketOperateRecordMapper.insert(workTicketOperateRecord);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 修改作业票基础信息
     *
     * @param workTicketBasicDataDTO 作业票基础信息
     * @return 结果
     */
    @Override
    public AjaxResult updateWorkTicketBasicData(WorkTicketBasicDataDTO workTicketBasicDataDTO, boolean isPc) {
        //只有待交底状态可修改
        WorkTicketBasicData workTicketBasicData1 = workTicketBasicDataMapper.selectById(workTicketBasicDataDTO.getId());
        if (Objects.isNull(workTicketBasicData1)) {
            return AjaxResult.error("作业票不存在");
        }
        if (!workTicketBasicData1.getWorkTicketStatus().equals(WorkTicketStatusEnum.DISCLOSE_v2.getValue())) {
            return AjaxResult.error("非待交底状态的作业票不可修改");
        }
        List<Long> executeUserIdList = workTicketBasicDataDTO.getExecuteUserIdList();


        List<String> contractorUserIdList = workTicketBasicDataDTO.getContractorUserIdList();
        if (workTicketBasicDataDTO.getWorkTicketCompanyType().equals(CompanyTypeEnum.CONTRACTOR.getValue()) && CollectionUtils.isEmpty(contractorUserIdList)) {
            return AjaxResult.error("请选择承包商作业人员！");
        } else if (workTicketBasicDataDTO.getWorkTicketCompanyType().equals(CompanyTypeEnum.INTERIOR.getValue()) && CollectionUtils.isEmpty(executeUserIdList)) {
            return AjaxResult.error("请选择内部作业人员！");
        }


        WorkTicketBasicData workTicketBasicData = new WorkTicketBasicData();
        BeanUtils.copyProperties(workTicketBasicDataDTO, workTicketBasicData);
//        workTicketBasicData.setUpdateDefault();
        if (isPc) {
            workTicketBasicData.setUpdateDefault();
        } else {
            workTicketBasicData.setUpdateDefaultForApp();
        }
        int count = workTicketBasicDataMapper.updateById(workTicketBasicData);

        //处理扩展信息
        WorkTicketExtend workTicketExtend = new WorkTicketExtend();
        BeanUtils.copyProperties(workTicketBasicDataDTO.getWorkTicketExtendDTO(), workTicketExtend);
        workTicketExtend.setWorkTicketId(workTicketBasicData.getId());
        workTicketExtend.setId(workTicketBasicData.getId());
//        workTicketExtend.setUpdateDefault();
        if (isPc) {
            workTicketExtend.setUpdateDefault();
        } else {
            workTicketBasicData.setUpdateDefaultForApp();
        }
        workTicketExtendMapper.updateById(workTicketExtend);
        //作业人
        LambdaQueryWrapper<WorkTicketExecuteUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkTicketExecuteUser::getWorkTicketId, workTicketBasicDataDTO.getId());
        queryWrapper.eq(WorkTicketExecuteUser::getIsDel, DeletedEnum.VALID.getValue());
        WorkTicketExecuteUser updateWorkTicketExecuteUser = new WorkTicketExecuteUser();
        updateWorkTicketExecuteUser.setIsDel(DeletedEnum.INVALID.getValue());
        if (isPc) {
            updateWorkTicketExecuteUser.setUpdateDefault();
        } else {
            updateWorkTicketExecuteUser.setUpdateDefaultForApp();
        }
        workTicketExecuteUserMapper.update(updateWorkTicketExecuteUser, queryWrapper);
        if (workTicketBasicDataDTO.getWorkTicketCompanyType().equals(CompanyTypeEnum.CONTRACTOR.getValue())) {
            for (String contractorUserId : contractorUserIdList) {
                WorkTicketExecuteUser workTicketExecuteUser = new WorkTicketExecuteUser();
                workTicketExecuteUser.setContractorUser(contractorUserId);
                workTicketExecuteUser.setWorkTicketId(workTicketBasicData.getId());
                workTicketExecuteUser.setExecuteCompanyType(workTicketBasicDataDTO.getWorkTicketCompanyType());
                if (isPc) {
                    workTicketExecuteUser.setCreateDefault();
                } else {
                    workTicketExecuteUser.setCreateDefaultForApp();
                }
                workTicketExecuteUserMapper.insert(workTicketExecuteUser);
            }
        } else {
            for (Long userId : executeUserIdList) {
                WorkTicketExecuteUser workTicketExecuteUser = new WorkTicketExecuteUser();
                workTicketExecuteUser.setExecuteUser(userId);
                workTicketExecuteUser.setWorkTicketId(workTicketBasicData.getId());
                workTicketExecuteUser.setExecuteCompanyType(workTicketBasicDataDTO.getWorkTicketCompanyType());
                if (isPc) {
                    workTicketExecuteUser.setCreateDefault();
                } else {
                    workTicketExecuteUser.setCreateDefaultForApp();
                }
                workTicketExecuteUserMapper.insert(workTicketExecuteUser);
            }
        }
        return AjaxResult.success(count);
    }

    /**
     * 批量删除作业票基础信息
     *
     * @param ids 需要删除的作业票基础信息主键
     * @return 结果
     */
    @Override
    public int deleteWorkTicketBasicDataByIds(String[] ids) {
        LambdaQueryWrapper<WorkTicketBasicData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(WorkTicketBasicData::getId, ids);
        WorkTicketBasicData workTicketBasicData = new WorkTicketBasicData();
        workTicketBasicData.setIsDel(DeletedEnum.INVALID.getValue());
        workTicketBasicData.setUpdateDefault();
        int count = workTicketBasicDataMapper.update(workTicketBasicData, queryWrapper);

        LambdaQueryWrapper<WorkTicketExtend> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(WorkTicketExtend::getId, ids);
        WorkTicketExtend workTicketExtend = new WorkTicketExtend();
        workTicketExtend.setIsDel(DeletedEnum.INVALID.getValue());
        workTicketExtend.setUpdateDefault();
        workTicketExtendMapper.update(workTicketExtend, queryWrapper1);
        return count;
    }

    /**
     * 审核作业票
     *
     * @param type         审核类型：1驳回，2通过
     * @param workTicketId 作业票ID
     * @param remark       备注：驳回原因或审核通过备注
     * @return
     */
    @Override
    public AjaxResult checkWorkTicket(int type, String workTicketId, String remark) {
//        WorkTicketBasicData workTicketBasicData1 = workTicketBasicDataMapper.selectById(workTicketId);
//        if (Objects.isNull(workTicketBasicData1)) {
//            return AjaxResult.error("作业票不存在");
//        }
//        if (!workTicketBasicData1.getWorkTicketStatus().equals(WorkTicketStatusEnum.CHECK_PENDING.getValue())) {
//            return AjaxResult.error("作业票已审核");
//        }
//        //判断是否作业负责人
//        if (!workTicketBasicData1.getWorkTicketDirectorId().toString().equals(JWTUtil.getPCUserId())) {
//            return AjaxResult.error("暂无审核权限！");
//        }
//        WorkTicketBasicData workTicketBasicData = new WorkTicketBasicData();
//        workTicketBasicData.setId(workTicketId);
//        //审核通过
//        if (type == 2) {
//            workTicketBasicData.setWorkTicketStatus(WorkTicketStatusEnum.APPLICATION.getValue());
//        } else {//驳回
//            workTicketBasicData.setWorkTicketStatus(WorkTicketStatusEnum.REJECT.getValue());
//            workTicketBasicData.setRejectReason(remark);
//        }
//        workTicketBasicData.setUpdateDefaultForApp();
//        int count = workTicketBasicDataMapper.updateById(workTicketBasicData);
//        handleWorkTicketOperateRecord(false, workTicketId, workTicketBasicData.getWorkTicketStatus(), false);
//        return AjaxResult.success(count);
        return AjaxResult.success(0);
    }


    /**
     * 设置作业票安全措施编制人
     *
     * @param checkWorkTicketMeasureDTO
     * @return
     */
    @Override
    public AjaxResult checkMeasuresComplementUser(CheckWorkTicketMeasureDTO checkWorkTicketMeasureDTO) {

        if (StringUtils.isEmpty(checkWorkTicketMeasureDTO.getWorkTicketId())) {
            return AjaxResult.error("作业票ID不可为空！");
        }
        if (StringUtils.isEmpty(checkWorkTicketMeasureDTO.getSignImg())) {
            return AjaxResult.error("安全措施编制人签字不可为空！");
        }
//        List<WorkTicketSmOptionRunDTO> workTicketSmOptionRunDTOList = checkWorkTicketMeasureDTO.getWorkTicketSmOptionRunDTOList();
//        if (CollectionUtils.isEmpty(workTicketSmOptionRunDTOList)) {
//            return AjaxResult.error("作业票措施入参不可为空！");
//        }
        WorkTicketBasicData workTicketBasicData1 = workTicketBasicDataMapper.selectById(checkWorkTicketMeasureDTO.getWorkTicketId());
        if (Objects.isNull(workTicketBasicData1)) {
            return AjaxResult.error("作业票不存在！");
        }
        if (!workTicketBasicData1.getWorkTicketStatus().equals(WorkTicketStatusEnum.DISCLOSE_v2.getValue())) {
            return AjaxResult.error("作业票非申请状态！");
        }
        //判断是否作业负责人
        if (!workTicketBasicData1.getWorkTicketDirectorId().toString().equals(JWTUtil.getPCUserId())) {
            return AjaxResult.error("暂无审核权限（作业负责人才可以操作）！");
        }
        //修改措施是否涉及字段
//        Map<String, List<String>> workTicketSmOptionRunListMap = workTicketSmOptionRunDTOList
//                .stream()
//                .collect(Collectors.groupingBy(WorkTicketSmOptionRunDTO::getSmOptionState, Collectors.mapping(WorkTicketSmOptionRunDTO::getId, Collectors.toList())));
//        workTicketSmOptionRunListMap.forEach((smOptionState, smOptionRunIdList) -> {
//            WorkTicketSmOptionRun workTicketSmOptionRun = new WorkTicketSmOptionRun();
//            workTicketSmOptionRun.setUpdateDefaultForApp();
//            workTicketSmOptionRun.setSmOptionState(smOptionState);
//            LambdaQueryWrapper<WorkTicketSmOptionRun> queryWrapper = new LambdaQueryWrapper<>();
//            queryWrapper.in(WorkTicketSmOptionRun::getId, smOptionRunIdList);
//            queryWrapper.eq(WorkTicketSmOptionRun::getIsDel, DeletedEnum.VALID.getValue());
//            workTicketSmOptionRunMapper.update(workTicketSmOptionRun, queryWrapper);
//        });
        //签字处理
        WorkTicketBasicData workTicketBasicData = new WorkTicketBasicData();
        workTicketBasicData.setUpdateDefaultForApp();
        workTicketBasicData.setId(checkWorkTicketMeasureDTO.getWorkTicketId());
        workTicketBasicData.setMeasuresComplementUser(Long.parseLong(JWTUtil.getUserId()));
        workTicketBasicData.setMeasuresComplementUserSignImg(checkWorkTicketMeasureDTO.getSignImg());
        workTicketBasicData.setWorkTicketStatus(WorkTicketStatusEnum.ACCEPT_v2.getValue());
        int count = workTicketBasicDataMapper.updateById(workTicketBasicData);
        //处理流程记录
        handleWorkTicketOperateRecord(false, checkWorkTicketMeasureDTO.getWorkTicketId(), workTicketBasicData.getWorkTicketStatus(), false);
        return AjaxResult.success(count);
    }

    /**
     * 安全交底人签字
     * 添加APP自定义的措施
     *
     * @param checkWorkTicketMeasureDTO
     * @return
     */
    @Override
    @Transactional
    public AjaxResult checkWorkTicketMeasure(CheckWorkTicketMeasureDTO checkWorkTicketMeasureDTO) {
        if (StringUtils.isEmpty(checkWorkTicketMeasureDTO.getWorkTicketId())) {
            return AjaxResult.error("作业票ID不可为空！");
        }
//        if (StringUtils.isEmpty(checkWorkTicketMeasureDTO.getSignImg())) {
//            return AjaxResult.error("措施确认签字不可为空！");
//        }
        List<WorkTicketSmOptionRunDTO> workTicketSmOptionRunDTOList = checkWorkTicketMeasureDTO.getWorkTicketSmOptionRunDTOList();
        if (CollectionUtils.isEmpty(workTicketSmOptionRunDTOList)) {
            return AjaxResult.error("作业票措施入参不可为空！");
        }
        WorkTicketBasicData workTicketBasicDataDB = workTicketBasicDataMapper.selectById(checkWorkTicketMeasureDTO.getWorkTicketId());
        if (Objects.isNull(workTicketBasicDataDB)) {
            return AjaxResult.error("作业票不存在！");
        }
        if (!workTicketBasicDataDB.getWorkTicketStatus().equals(WorkTicketStatusEnum.DISCLOSE_v2.getValue())) {
            return AjaxResult.error("作业票待交底状态！");
        }
        //判断是否监护人
        // 1、根据作业单位类型判断不同的用户表 10承包商、20内部
        String workTicketCompanyType = workTicketBasicDataDB.getWorkTicketCompanyType();
        String workTicketGuardianUser = workTicketBasicDataDB.getWorkTicketGuardianUser();
        if ("10".equals(workTicketCompanyType)) {
            String id = JWTUtil.getUserId();
            AppLogin appLogin = appLoginService.selectAppLoginById(id);
            String contractorId = appLogin.getContractorUserId();
            if (!workTicketGuardianUser.equals(contractorId)) {
                return AjaxResult.error("交底失败（监护人才可以操作）！");
            }
        } else if ("20".equals(workTicketCompanyType)) {
            if (!workTicketGuardianUser.equals(JWTUtil.getPCUserId())) {
                return AjaxResult.error("交底失败（监护人才可以操作）！");
            }
        }

        //判断页面是否单独添加了措施项
        Map<Integer, List<WorkTicketSmOptionRunDTO>> workTicketIsOptionRunListMap = workTicketSmOptionRunDTOList
                .stream()
                .collect(Collectors.groupingBy(WorkTicketSmOptionRunDTO::getIsOption));
        List<WorkTicketSmOptionRunDTO> isOptionMapList = workTicketIsOptionRunListMap.get(1);//自定义的措施

        //修改措施是否涉及字段
        Map<String, List<String>> workTicketSmOptionRunListMap = workTicketSmOptionRunDTOList
                .stream()
                .collect(Collectors.groupingBy(WorkTicketSmOptionRunDTO::getSmOptionState, Collectors.mapping(WorkTicketSmOptionRunDTO::getId, Collectors.toList())));
        workTicketSmOptionRunListMap.forEach((smOptionState, smOptionRunIdList) -> {
            WorkTicketSmOptionRun workTicketSmOptionRun = new WorkTicketSmOptionRun();
            workTicketSmOptionRun.setUpdateDefaultForApp();
            workTicketSmOptionRun.setSmOptionState(smOptionState);
            LambdaQueryWrapper<WorkTicketSmOptionRun> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(WorkTicketSmOptionRun::getId, smOptionRunIdList);
            queryWrapper.eq(WorkTicketSmOptionRun::getIsDel, DeletedEnum.VALID.getValue());
            workTicketSmOptionRunMapper.update(workTicketSmOptionRun, queryWrapper);
        });

        //签字处理
        WorkTicketBasicData workTicketBasicData = new WorkTicketBasicData();
        workTicketBasicData.setId(checkWorkTicketMeasureDTO.getWorkTicketId());
        workTicketBasicData.setWorkTicketStatus(WorkTicketStatusEnum.ACCEPT_v2.getValue());//待接受
        workTicketBasicData.setUpdateDefaultForApp();
        //1、安全交底人（监护人）
        workTicketBasicData.setWorkTicketDiscloseUser(Long.parseLong(JWTUtil.getUserId()));
        workTicketBasicData.setWorkTicketDiscloseUserSignImg(checkWorkTicketMeasureDTO.getSignImg());
        //2、安全措施确认人
        workTicketBasicData.setWorkTicketMeasuresUser(Long.parseLong(JWTUtil.getUserId()));
        workTicketBasicData.setWorkTicketMeasuresUserSignImg(checkWorkTicketMeasureDTO.getSignImg());
        //3、设置编制人
        if (isOptionMapList != null && !isOptionMapList.isEmpty()) {
            workTicketBasicData.setMeasuresComplementUser(Long.parseLong(JWTUtil.getUserId()));
            workTicketBasicData.setMeasuresComplementUserSignImg(checkWorkTicketMeasureDTO.getSignImg());
            //将页面添加的措施插入到数据库中
            for (WorkTicketSmOptionRunDTO workTicketSmOptionRunDTO : isOptionMapList) {
                WorkTicketSmOptionRun workTicketSmOptionRun = new WorkTicketSmOptionRun();
                workTicketSmOptionRun.setWorkTicketType(workTicketBasicDataDB.getWorkTicketType());
                workTicketSmOptionRun.setWorkTicketId(workTicketBasicData.getId());
                workTicketSmOptionRun.setSmOptionName(workTicketSmOptionRunDTO.getSmOptionName());
                workTicketSmOptionRun.setSmOptionState(workTicketSmOptionRunDTO.getSmOptionState());

                workTicketSmOptionRun.setCreateDefaultForApp();
                int insertCount = workTicketSmOptionRunMapper.insert(workTicketSmOptionRun);

                if (insertCount <= 0) {
                    throw new RuntimeException("处理自定义措施错误，稍后请重试！");
                }
            }
        }


        int count = workTicketBasicDataMapper.updateById(workTicketBasicData);
        //处理流程记录
//        handleWorkTicketOperateRecord(false, checkWorkTicketMeasureDTO.getWorkTicketId(), workTicketBasicData.getWorkTicketStatus(), false);
        handleWorkTicketOperateRecord(false, checkWorkTicketMeasureDTO.getWorkTicketId(), WorkTicketStatusEnum.ACCEPT_v2.getValue(), false);
        return AjaxResult.success(count);
    }

    /**
     * 安全交底人签字&接受交底人签字
     * 添加APP自定义的措施
     *
     * @param checkWorkTicketMeasureDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult checkWorkTicketMeasureV2(CheckWorkTicketMeasureDTO checkWorkTicketMeasureDTO) {

        if (StringUtils.isEmpty(checkWorkTicketMeasureDTO.getWorkTicketId())) {
            return AjaxResult.error("作业票ID不可为空！");
        }
        String workTicketStatus = checkWorkTicketMeasureDTO.getWorkTicketStatus();
        if (StringUtils.isBlank(workTicketStatus) || (!"10".equals(workTicketStatus) && !"20".equals(workTicketStatus))) {
            return AjaxResult.error("签字类型错误【" + workTicketStatus + "】！");
        }
        List<WorkTicketSmOptionRunDTO> workTicketSmOptionRunDTOList = checkWorkTicketMeasureDTO.getWorkTicketSmOptionRunDTOList();
        if (CollectionUtils.isEmpty(workTicketSmOptionRunDTOList)) {
            return AjaxResult.error("作业票措施入参不可为空！");
        }
        WorkTicketBasicData workTicketBasicDataDB = workTicketBasicDataMapper.selectById(checkWorkTicketMeasureDTO.getWorkTicketId());
        if (Objects.isNull(workTicketBasicDataDB)) {
            return AjaxResult.error("作业票不存在！");
        }
        if (!workTicketBasicDataDB.getWorkTicketStatus().equals(WorkTicketStatusEnum.DISCLOSE_v2.getValue())) {
            return AjaxResult.error("作业票非待交底状态！");
        }
        //判断是否负责人
        Long workTicketDirectorId = workTicketBasicDataDB.getWorkTicketDirectorId();
        if (!workTicketDirectorId.toString().equals(JWTUtil.getPCUserId())) {
            return AjaxResult.error("交底失败（请切换作业负责人操作）！");
        }


        //1、添加APP自定义措施
        Map<Integer, List<WorkTicketSmOptionRunDTO>> workTicketIsOptionRunListMap = workTicketSmOptionRunDTOList
                .stream()
                .collect(Collectors.groupingBy(WorkTicketSmOptionRunDTO::getIsOption));
        List<WorkTicketSmOptionRunDTO> isOptionMapList = workTicketIsOptionRunListMap.get(1);//自定义的措施
        if (isOptionMapList != null && !isOptionMapList.isEmpty()) {
            for (WorkTicketSmOptionRunDTO workTicketSmOptionRunDTO : isOptionMapList) {
                WorkTicketSmOptionRun workTicketSmOptionRun = new WorkTicketSmOptionRun();
                workTicketSmOptionRun.setWorkTicketType(workTicketBasicDataDB.getWorkTicketType());
                workTicketSmOptionRun.setWorkTicketId(checkWorkTicketMeasureDTO.getWorkTicketId());
                workTicketSmOptionRun.setSmOptionName(workTicketSmOptionRunDTO.getSmOptionName());
                workTicketSmOptionRun.setSmOptionState(workTicketSmOptionRunDTO.getSmOptionState());//是否涉及
                workTicketSmOptionRun.setCreateDefaultForApp();
                int insertCount = workTicketSmOptionRunMapper.insert(workTicketSmOptionRun);
                if (insertCount <= 0) {
                    throw new RuntimeException("处理自定义措施错误，稍后请重试！");
                }
            }
        }

        //2、修改措施是否涉及字段
        Map<String, List<String>> workTicketSmOptionRunListMap = workTicketSmOptionRunDTOList
                .stream()
                .collect(Collectors.groupingBy(WorkTicketSmOptionRunDTO::getSmOptionState, Collectors.mapping(WorkTicketSmOptionRunDTO::getId, Collectors.toList())));
        workTicketSmOptionRunListMap.forEach((smOptionState, smOptionRunIdList) -> {
            WorkTicketSmOptionRun workTicketSmOptionRun = new WorkTicketSmOptionRun();
            workTicketSmOptionRun.setUpdateDefaultForApp();
            workTicketSmOptionRun.setSmOptionState(smOptionState);
            LambdaQueryWrapper<WorkTicketSmOptionRun> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(WorkTicketSmOptionRun::getId, smOptionRunIdList);
            queryWrapper.eq(WorkTicketSmOptionRun::getIsDel, DeletedEnum.VALID.getValue());
            workTicketSmOptionRunMapper.update(workTicketSmOptionRun, queryWrapper);
        });

        //最后一个签名标识
        boolean lastSign = false;
        Long workTicketDiscloseUser = workTicketBasicDataDB.getWorkTicketDiscloseUser();//作业交底人 Long
        Long workTicketAcceptUser = workTicketBasicDataDB.getWorkTicketAcceptUser();//作业接受人 Long
        //3、签字处理：判断签字人员类型：10-交底；20-接受；
        WorkTicketBasicData workTicketBasicData = new WorkTicketBasicData();
        workTicketBasicData.setId(checkWorkTicketMeasureDTO.getWorkTicketId());
        workTicketBasicData.setUpdateDefaultForApp();
        //3.1、10-交底人签字
        if ("10".equals(workTicketStatus)) {
            workTicketBasicData.setWorkTicketDiscloseUser(Long.parseLong(JWTUtil.getUserId()));
            workTicketBasicData.setWorkTicketDiscloseUserSignImg(checkWorkTicketMeasureDTO.getSignImg());
            if (workTicketAcceptUser != null) {
                lastSign = true;
            }
        }
        //3.2、20-接受人签字
        else if ("20".equals(workTicketStatus)) {
            workTicketBasicData.setWorkTicketAcceptUser(Long.parseLong(JWTUtil.getUserId()));
            workTicketBasicData.setWorkTicketAcceptUserSignImg(checkWorkTicketMeasureDTO.getSignImg());
            if (workTicketDiscloseUser != null) {
                lastSign = true;
            }
        }
        //4、安全措施确认人
        workTicketBasicData.setWorkTicketMeasuresUser(Long.parseLong(JWTUtil.getUserId()));
        workTicketBasicData.setWorkTicketMeasuresUserSignImg(checkWorkTicketMeasureDTO.getSignImg());

        //5、设置编制人
        if (isOptionMapList != null && !isOptionMapList.isEmpty()) {
            workTicketBasicData.setMeasuresComplementUser(Long.parseLong(JWTUtil.getUserId()));
            workTicketBasicData.setMeasuresComplementUserSignImg(checkWorkTicketMeasureDTO.getSignImg());
        }
        if (lastSign) {
            workTicketBasicData.setWorkTicketStatus(WorkTicketStatusEnum.COUNTERSIGN_v2.getValue());//审核中：原会签中
            handleWorkTicketOperateRecord(false, checkWorkTicketMeasureDTO.getWorkTicketId(), WorkTicketStatusEnum.COUNTERSIGN_v2.getValue(), false);
        }
        int count = workTicketBasicDataMapper.updateById(workTicketBasicData);
        return AjaxResult.success(count);
    }

    /**
     * 新增气体分析
     *
     * @param workTicketGasAnalysisDTO
     * @return
     */
    @Override
    public AjaxResult addWorkTicketGasAnalysis(WorkTicketGasAnalysisDTO workTicketGasAnalysisDTO) {
        if (StringUtils.isEmpty(workTicketGasAnalysisDTO.getWorkTicketId())) {
            return AjaxResult.error("作业票ID不可为空！");
        }
        WorkTicketBasicData workTicketBasicDataDB = workTicketBasicDataMapper.selectById(workTicketGasAnalysisDTO.getWorkTicketId());
        if (Objects.isNull(workTicketBasicDataDB)) {
            return AjaxResult.error("作业票不存在！");
        }
        //判断是否作业负责人
        if (!workTicketBasicDataDB.getWorkTicketDirectorId().toString().equals(JWTUtil.getPCUserId())) {
            return AjaxResult.error("暂无审核权限！");
        }
        String workTicketStatus = workTicketBasicDataDB.getWorkTicketStatus();
        if (!workTicketStatus.equals(WorkTicketStatusEnum.OPERATION_v2.getValue())) {
            return AjaxResult.error("作业中状态才可以提交气体分析数据！");
        }
        WorkTicketGasAnalysis workTicketGasAnalysis = new WorkTicketGasAnalysis();
        BeanUtils.copyProperties(workTicketGasAnalysisDTO, workTicketGasAnalysis);
        workTicketGasAnalysis.setCreateDefaultForApp();
        int count = workTicketGasAnalysisMapper.insert(workTicketGasAnalysis);
        return AjaxResult.success(count);
    }

    /**
     * 接受交底人签字
     * <p>
     * 废弃参数-param type 签字类型：1安全交底人，2接受交底人
     *
     * @param workTicketId
     * @param signImg      签字图片
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
//    public AjaxResult workTicketDisclose(Integer type, String workTicketId, String signImg) {
    public AjaxResult workTicketDisclose(String workTicketId, String signImg) {
        if (StringUtils.isEmpty(workTicketId)) {
            return AjaxResult.error("作业票ID不可为空！");
        }
        if (StringUtils.isEmpty(signImg)) {
            return AjaxResult.error("签字图片不可为空！");
        }
        WorkTicketBasicData workTicketBasicDataDB = workTicketBasicDataMapper.selectById(workTicketId);
        if (Objects.isNull(workTicketBasicDataDB)) {
            return AjaxResult.error("作业票不存在！");
        }

        Long workTicketDirectorId = workTicketBasicDataDB.getWorkTicketDirectorId();
        //APP用户类型：1内部，2承包商
        String appUserType = JWTUtil.getAppUserType();

        if (!"1".equals(appUserType)) {
            return AjaxResult.error("接受失败，请切换内部人员用户登录（1-负责人才可以操作）！");
        } else if (!workTicketDirectorId.toString().equals(JWTUtil.getPCUserId())) {
            return AjaxResult.error("接受失败，请切换内部人员用户登录（2-负责人才可以操作）！");
        }


        //签字处理
        WorkTicketBasicData workTicketBasicData = new WorkTicketBasicData();
        workTicketBasicData.setId(workTicketId);
        workTicketBasicData.setUpdateDefaultForApp();
//        workTicketBasicData.setWorkTicketDiscloseUserSignImg(workTicketBasicData1.getWorkTicketDiscloseUserSignImg());
//        workTicketBasicData.setWorkTicketAcceptUserSignImg(workTicketBasicData1.getWorkTicketAcceptUserSignImg());
        //安全交底人签字
//        if (type == 1) {
//            workTicketBasicData.setWorkTicketDiscloseUser(Long.parseLong(JWTUtil.getUserId()));
//            workTicketBasicData.setWorkTicketDiscloseUserSignImg(signImg);
//        }
        //接受交底人签字
//        else {
        workTicketBasicData.setWorkTicketAcceptUser(Long.parseLong(JWTUtil.getUserId()));
        workTicketBasicData.setWorkTicketAcceptUserSignImg(signImg);
//        }
        //接受交底人签字完成（作业负责人），进入会签状态
//        if (StringUtils.isNotEmpty(workTicketBasicData.getWorkTicketDiscloseUserSignImg())
//                && !StringUtils.isNotEmpty(workTicketBasicData.getWorkTicketAcceptUserSignImg())) {
        workTicketBasicData.setWorkTicketStatus(WorkTicketStatusEnum.COUNTERSIGN_v2.getValue());//COUNTERSIGN("会签中（已交底）","30"),
//        }
        int count = workTicketBasicDataMapper.updateById(workTicketBasicData);
//        handleWorkTicketOperateRecord(false, workTicketId, workTicketBasicData.getWorkTicketStatus(), false);
        handleWorkTicketOperateRecord(false, workTicketId, WorkTicketStatusEnum.COUNTERSIGN_v2.getValue(), false);
        return AjaxResult.success(count);
    }

    /**
     * 作业票会签
     *
     * @param workTicketId 作业票ID
     * @param signOptionId 签字项ID
     * @param signImg      签字图片
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult workSignOptionRun(String workTicketId, String signOptionId, String signImg) {
        if (StringUtils.isEmpty(workTicketId)) {
            return AjaxResult.error("作业票ID不可为空！");
        }
        if (StringUtils.isEmpty(signImg)) {
            return AjaxResult.error("签字图片不可为空！");
        }
        WorkTicketBasicData workTicketBasicData1 = workTicketBasicDataMapper.selectById(workTicketId);
        if (Objects.isNull(workTicketBasicData1)) {
            return AjaxResult.error("作业票不存在！");
        }
        WorkTicketSignOptionRun workTicketSignOptionRun = workTicketSignOptionRunMapper.selectById(signOptionId);
        if (Objects.isNull(workTicketSignOptionRun) || workTicketSignOptionRun.getIsDel().equals(DeletedEnum.INVALID.getValue())) {
            return AjaxResult.error("签字项不存在！");
        }
        //作业票签字类型：10人员、20岗位
        String workTicketSignType = workTicketSignOptionRun.getWorkTicketSignType();
        //签字人或签字岗位范围
        String workTicketSignUser = workTicketSignOptionRun.getWorkTicketSignUser();
        if (StringUtils.isEmpty(workTicketSignUser)) {
            return AjaxResult.error("签字人范围为空！");
        }
        String[] signUserOrPost = workTicketSignUser.split(",");
        //判断签字用户权限
        if (workTicketSignType.equals(WorkTicketSignOptionUserTypeEnum.USER.getValue())) {
            if (!Arrays.asList(signUserOrPost).contains(JWTUtil.getPCUserId())) {
                return AjaxResult.error("暂无权限！");
            }
        } else {
            //查询岗位信息
            List<Long> postIdList = sysPostMapper.selectPostListByUserId(Long.parseLong(JWTUtil.getPCUserId()));
            postIdList.retainAll(getSignUserList(signUserOrPost));//求交集
            if (CollectionUtils.isEmpty(postIdList)) {
                return AjaxResult.error("暂无权限！");
            }
        }
        //修改签字信息
        workTicketSignOptionRun.setWorkSignOptionUserId(Long.parseLong(JWTUtil.getUserId()));
        workTicketSignOptionRun.setWorkSignOptionUserImg(signImg);
        workTicketSignOptionRun.setUpdateDefaultForApp();
        int count = workTicketSignOptionRunMapper.updateById(workTicketSignOptionRun);
        if (count <= 0) {
            return AjaxResult.error("更新签字异常，请稍后重试！");
        }

        //判断是否最后一个签字
        LambdaQueryWrapper<WorkTicketSignOptionRun> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkTicketSignOptionRun::getWorkTicketId, workTicketId);
        queryWrapper.eq(WorkTicketSignOptionRun::getIsDel, DeletedEnum.VALID.getValue());
        List<WorkTicketSignOptionRun> workTicketSignOptionRuns = workTicketSignOptionRunMapper.selectList(queryWrapper);
        List<WorkTicketSignOptionRun> noSignOption = workTicketSignOptionRuns.stream().
                filter(workTicketSignOptionRun1 -> StringUtils.isEmpty(workTicketSignOptionRun1.getWorkSignOptionUserImg())).collect(Collectors.toList());

        //不是最后一个会签：继续插入审核中（会签中）
        if (!CollectionUtils.isEmpty(noSignOption)) {
            //添加记录
            handleWorkTicketOperateRecord(false, workTicketId, WorkTicketStatusEnum.COUNTERSIGN_v2.getValue(), false);
        }
        //是最后一个会签：插入作业中
        else {
            //添加记录
            handleWorkTicketOperateRecord(false, workTicketId, WorkTicketStatusEnum.OPERATION_v2.getValue(), false);

            //更新为作业中：最后一个会签
            WorkTicketBasicData workTicketBasicData = new WorkTicketBasicData();
            workTicketBasicData.setId(workTicketId);
            workTicketBasicData.setWorkTicketStatus(WorkTicketStatusEnum.OPERATION_v2.getValue());//最后一个会签，修改为作业中
            workTicketBasicData.setUpdateDefaultForApp();
            workTicketBasicDataMapper.updateById(workTicketBasicData);
        }

        return AjaxResult.success(count);
    }

    private List<Long> getSignUserList(String[] signUser) {
        if (signUser == null) {
            return Lists.newArrayList();
        }
        List<Long> signUserList = new ArrayList<>(signUser.length);
        for (String signUserId : signUser) {
            signUserList.add(Long.parseLong(signUserId));
        }
        return signUserList;
    }

    @Override
    public AjaxResult getWorkTicketOperateRecord(String workTicketId) {
        LambdaQueryWrapper<WorkTicketOperateRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkTicketOperateRecord::getWorkTicketId, workTicketId);
        queryWrapper.eq(WorkTicketOperateRecord::getIsDel, DeletedEnum.VALID.getValue());
//        queryWrapper.orderByDesc(WorkTicketOperateRecord::getOperateTime);//按操作时间倒叙
        queryWrapper.orderByDesc(WorkTicketOperateRecord::getCreateDate);//按操作时间倒叙
        List<WorkTicketOperateRecord> workTicketOperateRecords = workTicketOperateRecordMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(workTicketOperateRecords)) {
            List<WorkTicketOperateRecordDTO> workTicketOperateRecordDTOS = new ArrayList<>();
            for (int i = 0; i < workTicketOperateRecords.size(); i++) {

                WorkTicketOperateRecord record = workTicketOperateRecords.get(i);

                WorkTicketOperateRecordDTO workTicketOperateRecordDTO = new WorkTicketOperateRecordDTO();
                BeanUtils.copyProperties(record, workTicketOperateRecordDTO);


                //0-预约成功
                if (WorkTicketStatusEnum.CREATE.getValue().equals(record.getWorkTicketStatus())) {
                    workTicketOperateRecordDTO.setWorkTicketStatusDesc("预约成功");
                }

                //10-待交底：申请完成
                else if (WorkTicketStatusEnum.DISCLOSE_v2.getValue().equals(record.getWorkTicketStatus())) {
                    workTicketOperateRecordDTO.setWorkTicketStatusDesc(
                            record.getOperateUserId() != null ? "已交底" : "待交底"
                    );
                }
                //20-待接受：安全交底人签字完成
                else if (WorkTicketStatusEnum.ACCEPT_v2.getValue().equals(record.getWorkTicketStatus())) {
                    workTicketOperateRecordDTO.setWorkTicketStatusDesc(
                            record.getOperateUserId() != null ? "已接受" : "待接受");
                }

                //30-会签中：
                else if (WorkTicketStatusEnum.COUNTERSIGN_v2.getValue().equals(record.getWorkTicketStatus())) {
                    workTicketOperateRecordDTO.setWorkTicketStatusDesc(record.getOperateUserId() != null ? "已审核" : "审核中");
                    /*
                    //观察上一条
                    if (i > 0) {
                        WorkTicketOperateRecord next = workTicketOperateRecords.get(i - 1);
                        String workTicketStatus = next.getWorkTicketStatus();
                        if (WorkTicketStatusEnum.COUNTERSIGN_v2.getValue().equals(workTicketStatus)) {
                            workTicketOperateRecordDTO.setWorkTicketStatusDesc("审核中");
                        } else {
                            workTicketOperateRecordDTO.setWorkTicketStatusDesc("已审核");
                        }
                    }
                    //最后一条
                    else {
                        workTicketOperateRecordDTO.setWorkTicketStatusDesc("审核中");
                    }
                    */
                }
                //40-作业中：
                else if (WorkTicketStatusEnum.OPERATION_v2.getValue().equals(record.getWorkTicketStatus())) {
                    workTicketOperateRecordDTO.setWorkTicketStatusDesc(
                            record.getOperateUserId() != null ? "作业完成" : "作业中");
                }
                //50-已验收：
                else if (WorkTicketStatusEnum.APPROVED_v2.getValue().equals(record.getWorkTicketStatus())) {
                    workTicketOperateRecordDTO.setWorkTicketStatusDesc(
                            record.getOperateUserId() != null ? "已验收" : "作业中");
                } else {
                    workTicketOperateRecordDTO.setWorkTicketStatusDesc(
                            "其他：workTicketStatus=" + record.getWorkTicketStatus());
                }

//                if (WorkTicketStatusEnum.CREATE.getValue().equals(workTicketOperateRecord.getWorkTicketStatus())) {
//                    workTicketOperateRecordDTO.setWorkTicketStatusDesc("作业预约成功");
//                }
//                else if (WorkTicketStatusEnum.CHECK_PENDING.getValue().equals(workTicketOperateRecord.getWorkTicketStatus())) {
//                    workTicketOperateRecordDTO.setWorkTicketStatusDesc(
//                            workTicketOperateRecord.getOperateUserId() != null ? "审核完成" : "等待审核");
//                }
//                else if (WorkTicketStatusEnum.APPLICATION.getValue().equals(workTicketOperateRecord.getWorkTicketStatus())) {
//                    workTicketOperateRecordDTO.setWorkTicketStatusDesc(workTicketOperateRecord.getOperateUserId() != null ? "已措施确认" : "等待措施确认");
//                }
//
//                else if (WorkTicketStatusEnum.COUNTERSIGN.getValue().equals(workTicketOperateRecord.getWorkTicketStatus())) {
//                    workTicketOperateRecordDTO.setWorkTicketStatusDesc(workTicketOperateRecord.getOperateUserId() != null ? "已会签完成" : "会签中");
//                }
//                else if (WorkTicketStatusEnum.OPERATION.getValue().equals(workTicketOperateRecord.getWorkTicketStatus())) {
//                    workTicketOperateRecordDTO.setWorkTicketStatusDesc(workTicketOperateRecord.getOperateUserId() != null ? "作业完成等待验收" : "等待作业");
//                }
//                else if (WorkTicketStatusEnum.APPROVED.getValue().equals(workTicketOperateRecord.getWorkTicketStatus())) {
//                    workTicketOperateRecordDTO.setWorkTicketStatusDesc("已验收完成");
//                }
                workTicketOperateRecordDTO.setOperateUserName(workTicketOperateRecordDTO.getOperateUserName() != null ? workTicketOperateRecordDTO.getOperateUserName() : "");

                workTicketOperateRecordDTOS.add(workTicketOperateRecordDTO);
            }
            return AjaxResult.success(workTicketOperateRecordDTOS);
        }
        return AjaxResult.success();
    }

    /**
     * 作业票验收
     *
     * @param workTicketId
     * @param signImg
     * @return
     */
    @Override
    public AjaxResult acceptance(String workTicketId, String signImg) {
        WorkTicketBasicData workTicketBasicDataDB = workTicketBasicDataMapper.selectById(workTicketId);
        if (Objects.isNull(workTicketBasicDataDB)) {
            return AjaxResult.error("作业票不存在");
        }
        if (!workTicketBasicDataDB.getWorkTicketStatus().equals(WorkTicketStatusEnum.OPERATION_v2.getValue())) {
            return AjaxResult.error("作业票非作业中，不可验收！");
        }
        //判断是否作业负责人
        if (!workTicketBasicDataDB.getWorkTicketDirectorId().toString().equals(JWTUtil.getPCUserId())) {
            return AjaxResult.error("暂无验收权限！");
        }

        //判断是否作业负责人
        if (!workTicketBasicDataDB.getWorkTicketDirectorId().toString().equals(JWTUtil.getPCUserId())) {
            return AjaxResult.error("暂无审核权限，请切换作业负责人操作！");
        }


        WorkTicketBasicData workTicketBasicData = new WorkTicketBasicData();
        workTicketBasicData.setUpdateDefaultForApp();
        workTicketBasicData.setId(workTicketId);
        workTicketBasicData.setWorkTicketCheckUserSignImg(signImg);
        workTicketBasicData.setWorkTicketCheckUser(Long.parseLong(JWTUtil.getUserId()));
        workTicketBasicData.setWorkTicketStatus(WorkTicketStatusEnum.APPROVED_v2.getValue());//验收完成
//        handleWorkTicketOperateRecord(false, workTicketId, workTicketBasicData.getWorkTicketStatus(), false);
        int count = workTicketBasicDataMapper.updateById(workTicketBasicData);

        //添加记录
        handleWorkTicketOperateRecord(false, workTicketId, workTicketBasicData.getWorkTicketStatus(), false);

        return AjaxResult.success(count);
    }

    /**
     * PC首页统计-作业票统计
     *
     * @param companyCode
     * @return
     */
    @Override
    public List<WorkTicketStatisticsPCDTO> workTicketTypeStatistics(String companyCode) {
        List<WorkTicketStatisticsPCDTO> dataList = workTicketBasicDataMapper.workTicketTypeStatistics(companyCode);
        WorkTicketStatisticsPCDTO data = null;
        if (dataList == null) {
            dataList = new ArrayList<>();
            //作业票类型 10动火、20受限、30盲板抽堵、40高处、50吊装、60临时、70动土、80断路
            data = new WorkTicketStatisticsPCDTO();
            data.setWorkTicketType("10");
            data.setWorkTicketTypeName("动火");
            data.setWorkTicketCount(0);
            dataList.add(data);

            data = new WorkTicketStatisticsPCDTO();
            data.setWorkTicketType("20");
            data.setWorkTicketTypeName("受限");
            data.setWorkTicketCount(0);
            dataList.add(data);

            data = new WorkTicketStatisticsPCDTO();
            data.setWorkTicketType("30");
            data.setWorkTicketTypeName("盲板抽堵");
            data.setWorkTicketCount(0);
            dataList.add(data);

            data = new WorkTicketStatisticsPCDTO();
            data.setWorkTicketType("40");
            data.setWorkTicketTypeName("高处");
            data.setWorkTicketCount(0);
            dataList.add(data);

            data = new WorkTicketStatisticsPCDTO();
            data.setWorkTicketType("50");
            data.setWorkTicketTypeName("吊装");
            data.setWorkTicketCount(0);
            dataList.add(data);

            data = new WorkTicketStatisticsPCDTO();
            data.setWorkTicketType("60");
            data.setWorkTicketTypeName("临时");
            data.setWorkTicketCount(0);
            dataList.add(data);

            data = new WorkTicketStatisticsPCDTO();
            data.setWorkTicketType("70");
            data.setWorkTicketTypeName("动土");
            data.setWorkTicketCount(0);
            dataList.add(data);

            data = new WorkTicketStatisticsPCDTO();
            data.setWorkTicketType("80");
            data.setWorkTicketTypeName("断路");
            data.setWorkTicketCount(0);
            dataList.add(data);
        }
        return dataList;
    }

    /**
     * PC首页查询作业票列表
     *
     * @param workTicketBasicData
     * @return
     */
    @Override
    public List<WorkTicketBasicDataResultDTO> selectWorkTicketList(WorkTicketBasicDataDTO workTicketBasicData) {
        return workTicketBasicDataMapper.selectWorkTicketList(workTicketBasicData);
    }

    /**
     * PC首页-企业信息-生产区域-统计区域下作业分布列表
     *
     * @param companyCode
     * @return
     */
    @Override
    public List<WorkTicketAreaWorkStatisticsPCDTO> workTicketAreaWorkStatistics(String companyCode) {
        Date startTiem = DateUtils.getLastDay(0, 0, 0, 0, 0);
        Date endTime = DateUtils.getLastDay(0, 23, 59, 59, 999);
        return workTicketBasicDataMapper.workTicketAreaWorkStatistics(startTiem, endTime, companyCode);
    }

    /**
     * PC首页-企业信息-生产区域统计
     *
     * @param companyCode
     * @return
     */
    @Override
    public Integer workTicketAreaWorkCountStatistics(String companyCode) {
        Date startTiem = DateUtils.getLastDay(0, 0, 0, 0, 0);
        Date endTime = DateUtils.getLastDay(0, 23, 59, 59, 999);
        return workTicketBasicDataMapper.workTicketAreaWorkCountStatistics(startTiem, endTime, companyCode);
    }
}
