package com.njcn.process.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.config.GeneralInfo;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.oss.constant.OssPath;
import com.njcn.device.pms.api.DistributionMonitorClient;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.process.constant.Param;
import com.njcn.process.enums.AuditProcessEnum;
import com.njcn.process.enums.ThsFlowTypeEnum;
import com.njcn.process.mapper.FlowFormAssMapper;
import com.njcn.process.mapper.FlowableAssMapper;
import com.njcn.process.mapper.LoadTypeUserManageMapper;
import com.njcn.process.pojo.param.*;
import com.njcn.process.pojo.po.FlowFormAss;
import com.njcn.process.pojo.po.FlowableAss;
import com.njcn.process.pojo.po.RGeneralSurveyPlanPO;
import com.njcn.process.pojo.po.RLoadTypeUserManage;
import com.njcn.process.pojo.vo.LoadTypeRelationExcel;
import com.njcn.process.pojo.vo.LoadTypeUserExcel;
import com.njcn.process.pojo.vo.RLoadTypeUserManageVO;
import com.njcn.process.pojo.vo.flowable.FlowTaskVo;
import com.njcn.process.service.LoadTypeUserManageService;
import com.njcn.process.service.flowable.IFlowDefinitionService;
import com.njcn.process.service.flowable.IFlowInstanceService;
import com.njcn.process.service.flowable.IFlowTaskService;
import com.njcn.process.utils.FlowableUtils;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.api.UserFeignClient;
import com.njcn.user.pojo.dto.DeptDTO;
import com.njcn.user.pojo.dto.UserDTO;
import com.njcn.user.pojo.po.Dept;
import com.njcn.user.pojo.po.User;
import com.njcn.user.pojo.vo.PvTerminalTreeVO;
import com.njcn.web.utils.RequestUtil;
import com.njcn.web.utils.WebUtil;
import liquibase.pro.packaged.S;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.Null;
import org.flowable.task.api.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 干扰源用户管理
 *
 * @author qijian
 * @version 1.0.0
 * @createTime 2022/11/11 - 9:20
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class LoadTypeUserManageServiceImpl extends ServiceImpl<LoadTypeUserManageMapper,RLoadTypeUserManage> implements LoadTypeUserManageService {

    private final LoadTypeUserManageMapper loadTypeUserManageMapper;
    private final DicDataFeignClient dicDataFeignClient;
    private final DeptFeignClient deptFeignClient;

    private final UserFeignClient userFeignClient;

    private final FileStorageUtil fileStorageUtil;

    private final FlowFormAssMapper flowFormAssMapper;

    private final IFlowDefinitionService iFlowDefinitionService;

    private final IFlowInstanceService iFlowInstanceService;

    private final FlowableAssMapper flowableAssMapper;

    private final IFlowTaskService iFlowTaskService;

    /**
     * 干扰源用户分页查询
     *
     * @param loadTypeUserSearchParam
     * @return
     */
    @Override
    public Page<RLoadTypeUserManageVO> getLoadTypeUserList(LoadTypeUserSearchParam loadTypeUserSearchParam) {
        Page<RLoadTypeUserManageVO> page = new Page<>(loadTypeUserSearchParam.getPageNum(), loadTypeUserSearchParam.getPageSize());
        List<String> ids=deptFeignClient.getDepSonIdtByDeptId (loadTypeUserSearchParam.getOrgNo()).getData ( );
        Integer checkType = loadTypeUserSearchParam.getCheckType();
        Integer aStatus = null;
        //0表示不是审核信息 1标识审核信息

        String checkPerson = null;
        if(checkType==1){
            aStatus = AuditProcessEnum.WaitAudit.getStatus();
            checkPerson = RequestUtil.getUserIndex();
        }
        //干扰源用户信息录入
        Page<RLoadTypeUserManageVO> loadTypeUserPage = loadTypeUserManageMapper.getLoadTypeUserPage(page, loadTypeUserSearchParam,ids,aStatus,aStatus,checkPerson,checkPerson);

        //查询审核，创建用户信息
        List<String> personList = new ArrayList<>();
        loadTypeUserPage.getRecords().forEach(it->{
            if(StrUtil.isNotBlank(it.getACheckPerson())){
                personList.add(it.getACheckPerson());
            }
            if(StrUtil.isNotBlank(it.getICheckPerson())){
                personList.add(it.getICheckPerson());
            }
            if(StrUtil.isNotBlank(it.getCreateBy())){
                personList.add(it.getCreateBy());
            }
        });
        Map<String,User> userMap = new HashMap<>();
        if(CollectionUtil.isNotEmpty(personList)){
          List<User> userList =  userFeignClient.getUserByIdList(personList.stream().distinct().collect(Collectors.toList())).getData();
            userMap =  userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
        }
        List<PvTerminalTreeVO> dept = deptFeignClient.allDeptList().getData();
        Map<String, PvTerminalTreeVO> pvTerminalTreeVOMap = dept.stream().collect(Collectors.toMap(PvTerminalTreeVO::getId, pvTerminalTreeVO -> pvTerminalTreeVO));
        //部门处理：根据部门code取名称
        for(RLoadTypeUserManageVO rLoadTypeUserManageVO : loadTypeUserPage.getRecords()){
            if(StrUtil.isNotBlank(rLoadTypeUserManageVO.getACheckPerson())){
                rLoadTypeUserManageVO.setACheckPersonName(userMap.get(rLoadTypeUserManageVO.getACheckPerson()).getName());
            }
            if(StrUtil.isNotBlank(rLoadTypeUserManageVO.getICheckPerson())){
                rLoadTypeUserManageVO.setICheckPersonName(userMap.get(rLoadTypeUserManageVO.getICheckPerson()).getName());
            }
            if(StrUtil.isNotBlank(rLoadTypeUserManageVO.getCreateBy())){
                rLoadTypeUserManageVO.setCreateByName(userMap.get(rLoadTypeUserManageVO.getCreateBy()).getName());
            }
            rLoadTypeUserManageVO.setOrgName(pvTerminalTreeVOMap.get(rLoadTypeUserManageVO.getOrgNo()).getName()); //单位名称
        }
        //返回新的数据组
        return loadTypeUserPage;
    }

    /**
     * 根据id查询干扰源用户
     *
     * @param id
     * @return
     */
    @Override
    public RLoadTypeUserManageVO getLoadTypeUserById(String id) {
        RLoadTypeUserManage rLoadTypeUserManage = loadTypeUserManageMapper.selectById(id);
        RLoadTypeUserManageVO rLoadTypeUserManageVO = new RLoadTypeUserManageVO();
        BeanUtils.copyProperties(rLoadTypeUserManage, rLoadTypeUserManageVO);
        //文件
        if (rLoadTypeUserManageVO.getIFilePath() != null) {
            String iFile = fileStorageUtil.getFileUrl(rLoadTypeUserManageVO.getIFilePath());
            rLoadTypeUserManageVO.setIFile(iFile);
        }
        if (rLoadTypeUserManageVO.getAFilePath() != null) {
            String aFile = fileStorageUtil.getFileUrl(rLoadTypeUserManageVO.getAFilePath());
            rLoadTypeUserManageVO.setAFile(aFile);
        }

        rLoadTypeUserManageVO.setOrgName(deptFeignClient.getDeptById(rLoadTypeUserManage.getOrgNo()).getData().getName());

        return rLoadTypeUserManageVO;
    }

    /**
     * 新增干扰源用户
     *
     * @param loadTypeUserParam
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addLoadTypeUser(LoadTypeUserParam loadTypeUserParam) {
        //参数转换
        RLoadTypeUserManage rLoadTypeUserManage = new RLoadTypeUserManage();
        BeanUtils.copyProperties(loadTypeUserParam, rLoadTypeUserManage);

        //塞入建档时间
        Date date = DateUtil.parse(loadTypeUserParam.getRecordTime(), "yyyy-MM-dd HH:mm:ss");
        rLoadTypeUserManage.setRecordTime(date);
        rLoadTypeUserManage.setIStatus(AuditProcessEnum.New.getStatus());
        rLoadTypeUserManage.setId(IdUtil.simpleUUID());
        loadTypeUserManageMapper.insert(rLoadTypeUserManage);

        //绑定工作流
        //开始流程
        /*FlowFormAss flowFormAss = flowFormAssMapper.selectOne(new LambdaQueryWrapper<FlowFormAss>().eq(FlowFormAss::getFormId, 2));
        if (Objects.isNull(flowFormAss)) {
            throw new BusinessException("当前功能未绑定流程,请先绑定流程");
        }

        Map<String,Object> map = new HashMap<>();
        String processId = iFlowDefinitionService.startProcessInstanceById(flowFormAss.getDefinitionId(), rLoadTypeUserManage.getId(), map);
        Task task = iFlowTaskService.getTask(processId);
        FlowTaskVo flowTaskVo = new FlowTaskVo();
        flowTaskVo.setTaskId(task.getId());
        flowTaskVo.setInstanceId(processId);
        flowTaskVo.setComment(RequestUtil.getUserNickname() + "发起录入干扰源用户申请");
        iFlowTaskService.complete(flowTaskVo);*/
        return true;
    }

    /**
     * 上传干扰源用户入网报告
     *
     * @param loadTypeUserIUploadParam
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean uploadLoadTypeUserI(LoadTypeUserIUploadParam loadTypeUserIUploadParam) {
        //todo 修改用户信息，当用户信息为待审核状态。该信息不可修改
        Boolean aBoolean = checkStatus(loadTypeUserIUploadParam.getId(), 0);
        RLoadTypeUserManage rLoadTypeUserManage = new RLoadTypeUserManage();
        BeanUtils.copyProperties(loadTypeUserIUploadParam, rLoadTypeUserManage);
        MultipartFile multipartFile = loadTypeUserIUploadParam.getFile();
        //文件上传到Minio服务器，存入文件名
        if (Objects.nonNull(multipartFile)) {
            rLoadTypeUserManage.setIFilePath(fileStorageUtil.uploadMultipart(multipartFile,OssPath.LOAD_TYPE_USER));
            rLoadTypeUserManage.setIFilePathName(multipartFile.getOriginalFilename());
            rLoadTypeUserManage.setIUploadTime(new Date());
            rLoadTypeUserManage.setIIsFileUpload(rLoadTypeUserManage.getIFilePath()!=null?1:0);
        }
        loadTypeUserManageMapper.updateById(rLoadTypeUserManage);
        return true;
    }

    /**
     * 关联营销用户
     *
     * @param
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean linkUser(LoadTypeUserAssociateParam loadTypeUserAssociateParam) {
        RLoadTypeUserManage rLoadTypeUserManage = new RLoadTypeUserManage();
        //填入数据修改
        BeanUtils.copyProperties(loadTypeUserAssociateParam, rLoadTypeUserManage);
        loadTypeUserManageMapper.updateById(rLoadTypeUserManage);
        return true;
    }

    /**
     * 查询所有干扰源用户（与营销系统关联）
     *
     * @param loadTypeUserSearchParam
     * @return
     */
    @Override
    public Page<RLoadTypeUserManageVO> getLoadTypeRelationList(LoadTypeUserSearchParam loadTypeUserSearchParam) {
        Page<RLoadTypeUserManageVO> page = new Page<>(loadTypeUserSearchParam.getPageNum(), loadTypeUserSearchParam.getPageSize());
        List<String> ids=deptFeignClient.getDepSonIdtByDeptId (loadTypeUserSearchParam.getOrgNo()).getData ( );
        Integer checkType = loadTypeUserSearchParam.getCheckType();
        String aStatus = null;
        //0表示不是审核信息 1标识审核信息
        if(checkType==1){
            ids=ids.stream().filter(x->!x.contains(loadTypeUserSearchParam.getOrgNo())).collect(Collectors.toList());
            aStatus =   dicDataFeignClient.getDicDataByCode(DicDataEnum.FINISH.getCode()).getData().getId();
        }
        Page<RLoadTypeUserManageVO> loadTypeUserPage = loadTypeUserManageMapper.getLoadTypeRelationPage(page, loadTypeUserSearchParam,ids,aStatus);
        //部门处理：根据部门code取名称
        List<RLoadTypeUserManageVO> list = loadTypeUserPage.getRecords();
        List<PvTerminalTreeVO> dept = deptFeignClient.allDeptList().getData();
        Map<String, PvTerminalTreeVO> pvTerminalTreeVOMap = dept.stream().collect(Collectors.toMap(PvTerminalTreeVO::getId, pvTerminalTreeVO -> pvTerminalTreeVO));
        List<RLoadTypeUserManageVO> resultList = list.stream().map(item -> {
            RLoadTypeUserManageVO rLoadTypeUserManageVO = new RLoadTypeUserManageVO();
            BeanUtils.copyProperties(item, rLoadTypeUserManageVO);
            rLoadTypeUserManageVO.setOrgName(pvTerminalTreeVOMap.get(item.getOrgNo()).getName()); //单位名称
            return rLoadTypeUserManageVO;
        }).collect(Collectors.toList());

        //返回新的数据组
        return loadTypeUserPage.setRecords(resultList);
    }



    /**
     * 上传干扰源用户实测报告
     *
     * @param loadTypeUserAUploadParam
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean uploadLoadTypeUserA(LoadTypeUserAUploadParam loadTypeUserAUploadParam) {
        //todo 修改用户信息，当用户信息为待审核状态。该信息不可修改
        Boolean aBoolean = checkStatus(loadTypeUserAUploadParam.getId(), 1);
        RLoadTypeUserManage rLoadTypeUserManage = new RLoadTypeUserManage();
        BeanUtils.copyProperties(loadTypeUserAUploadParam, rLoadTypeUserManage);
        MultipartFile multipartFile = loadTypeUserAUploadParam.getFile();
        //文件上传到文件服务器，存入文件名
        if (Objects.nonNull(multipartFile)) {
            rLoadTypeUserManage.setAFilePath(fileStorageUtil.uploadMultipart(multipartFile,OssPath.LOAD_TYPE_USER));
            rLoadTypeUserManage.setAFilePathName(multipartFile.getOriginalFilename());
            rLoadTypeUserManage.setAUploadTime(new Date());
        }

        //提交：待审核/保存：新建
      /*  DictData dictData;
        if (Objects.equals(Param.LOAD_TYPE_USER_SUBMIT, loadTypeUserAUploadParam.getStatus())) {
            dictData = dicDataFeignClient.getDicDataByCode(DicDataEnum.AUDIT.getCode()).getData();
        } else {
            //是否是未通过，未通过则不修改状态
            if(aBoolean){
                dictData=null;
            }else{
                dictData = dicDataFeignClient.getDicDataByCode(DicDataEnum.NEWLY.getCode()).getData();
            }
        }
        if(!aBoolean){
            rLoadTypeUserManage.setAStatus(dictData.getId());
        }*/
        rLoadTypeUserManage.setAIsFileUpload(rLoadTypeUserManage.getAFilePath()!=null?1:0);
        loadTypeUserManageMapper.updateById(rLoadTypeUserManage);
        return true;
    }

    /**
     * 导出未建档干扰源用户管理信息
     *
     * @param list
     * @return
     */
    @Override
    public List<LoadTypeUserExcel> exportLoadTypeUserList(List<String> list) {
        //数据处理
        LambdaQueryWrapper<RLoadTypeUserManage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(RLoadTypeUserManage::getId, list);
        List<RLoadTypeUserManage> rLoadTypeUserManages = loadTypeUserManageMapper.selectList(queryWrapper);
        //1、部门数据
        List<PvTerminalTreeVO> dept = deptFeignClient.allDeptList().getData();
        Map<String, PvTerminalTreeVO> pvTerminalTreeVOMap = dept.stream().collect(Collectors.toMap(PvTerminalTreeVO::getId, pvTerminalTreeVO -> pvTerminalTreeVO));

        //2、取干扰源类型
        List<DictData> loadTypeList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.MONITORING_LABELS.getCode()).getData();
        Map<String, DictData> loadTypeMap = loadTypeList.stream().collect(Collectors.toMap(DictData::getId, dictData -> dictData));

        //3、取入网报告状态
        List<DictData> iStatusList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.ON_NETWORK_STATUS.getCode()).getData();
        Map<String, DictData> iStatusMap = iStatusList.stream().collect(Collectors.toMap(DictData::getId, dictData -> dictData));

        List<LoadTypeUserExcel> resultList = rLoadTypeUserManages.stream().map(item -> {
            LoadTypeUserExcel loadTypeUserExcel = new LoadTypeUserExcel();
            if (item.getUserName() != null) {
                loadTypeUserExcel.setUserName(item.getUserName());
            }
            if (item.getRecordTime() != null) {
                loadTypeUserExcel.setRecordTime(item.getRecordTime());
            }
            if (item.getAIsFileUpload() != null) {
                loadTypeUserExcel.setIIsFileUpload(item.getIIsFileUpload() == 0 ? "否" : "是"); //实测报告是否上传
            }
            if (item.getOrgNo() != null) {
                loadTypeUserExcel.setOrgName(pvTerminalTreeVOMap.get(item.getOrgNo()).getName()); //单位
            }
            if (item.getLoadType() != null) {
                loadTypeUserExcel.setLoadTypeName(loadTypeMap.get(item.getLoadType()).getName()); //入网报告状态
            }
            if (item.getIStatus() != null) {
                loadTypeUserExcel.setIStatusName(iStatusMap.get(item.getIStatus()).getName()); //入网报告状态
            }
            if (item.getAIsFileUpload() != null) {
                loadTypeUserExcel.setIIsFileUpload(item.getIIsFileUpload() == 0 ? "否" : "是"); //实测报告是否上传
            }
            return loadTypeUserExcel;
        }).collect(Collectors.toList());

        return resultList;
    }

    /**
     * 导出干扰源用户常态化管理信息
     *
     * @param list
     * @return
     */
    @Override
    public List<LoadTypeRelationExcel> exportLoadTypeRelationList(List<String> list) {
        //数据处理
        LambdaQueryWrapper<RLoadTypeUserManage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(RLoadTypeUserManage::getId, list);
        List<RLoadTypeUserManage> rLoadTypeUserManages = loadTypeUserManageMapper.selectList(queryWrapper);
        //1、部门数据
        List<PvTerminalTreeVO> dept = deptFeignClient.allDeptList().getData();
        Map<String, PvTerminalTreeVO> pvTerminalTreeVOMap = dept.stream().collect(Collectors.toMap(PvTerminalTreeVO::getId, pvTerminalTreeVO -> pvTerminalTreeVO));

        //2、取干扰源类型
        List<DictData> loadTypeList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.MONITORING_LABELS.getCode()).getData();
        Map<String, DictData> loadTypeMap = loadTypeList.stream().collect(Collectors.toMap(DictData::getId, dictData -> dictData));

        //3、取实测报告状态
        List<DictData> aStatusList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.ON_NETWORK_STATUS.getCode()).getData();
        Map<String, DictData> aStatusMap = aStatusList.stream().collect(Collectors.toMap(DictData::getId, dictData -> dictData));

        List<LoadTypeRelationExcel> resultList = rLoadTypeUserManages.stream().map(item -> {
            LoadTypeRelationExcel loadTypeRelationExcel = new LoadTypeRelationExcel();
            if (item.getOrgNo() != null) {
                loadTypeRelationExcel.setOrgName(pvTerminalTreeVOMap.get(item.getOrgNo()).getName());
            }
            if (item.getLoadType() != null) {
                loadTypeRelationExcel.setLoadTypeName(loadTypeMap.get(item.getLoadType()).getName());
            }
            if (item.getUserName() != null) {
                loadTypeRelationExcel.setUserName(item.getUserName());
            }
            if (item.getRelationUserName() != null) {
                loadTypeRelationExcel.setRelationUserName(item.getRelationUserName());
            }
            if (item.getAStatus() != null) {
                loadTypeRelationExcel.setAStatusName(aStatusMap.get(item.getIStatus()).getName());
            }
            return loadTypeRelationExcel;
        }).collect(Collectors.toList());

        return resultList;
    }

    /**
     * @param loadTypeUserCheckParam
     * @Description: 入网评估报告审核
     * @Param: [loadTypeUserCheckParam]
     * @return: java.lang.Boolean
     * @Author: clam
     * @Date: 2023/2/22
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Boolean checkLoadTypeUserI(LoadTypeUserCheckParam loadTypeUserCheckParam) {
        UpdateWrapper<RLoadTypeUserManage> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id", loadTypeUserCheckParam.getId());
        updateWrapper.set("i_check_comment", loadTypeUserCheckParam.getCheckComment());
        updateWrapper.set("i_status", Objects.equals("1", loadTypeUserCheckParam.getCheckResult()) ? AuditProcessEnum.AuditPass.getStatus() :AuditProcessEnum.AuditRefuse.getStatus());
        int i = loadTypeUserManageMapper.update(null, updateWrapper);

        //流程审核
        FlowableAss flowableAss = flowableAssMapper.selectOne(new LambdaQueryWrapper<FlowableAss>().eq(FlowableAss::getType, ThsFlowTypeEnum.rLoadTypeUser.getCode()).eq(FlowableAss::getThsIndex,loadTypeUserCheckParam.getId()));
        if(Objects.isNull(flowableAss)){
            throw new BusinessException("当前功能未绑定流程,请联系管理员处理");
        }
        FlowableUtils.dealAuditResult(flowableAss,loadTypeUserCheckParam.getCheckResult(),iFlowTaskService,loadTypeUserCheckParam.getCheckComment());
        return true;
    }

    /**
     * @param loadTypeUserCheckParam
     * @Description: 实测报告审核
     * @Param: [loadTypeUserCheckParam]
     * @return: java.lang.Boolean
     * @Author: clam
     * @Date: 2023/2/22
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Boolean checkLoadTypeUserA(LoadTypeUserCheckParam loadTypeUserCheckParam) {
        boolean result = true;
        UpdateWrapper<RLoadTypeUserManage> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id", loadTypeUserCheckParam.getId());
        updateWrapper.set("a_check_comment", loadTypeUserCheckParam.getCheckComment());
        updateWrapper.set("a_check_person", loadTypeUserCheckParam.getCheckPerson());

        DictData fail = dicDataFeignClient.getDicDataByCode(DicDataEnum.FAILED.getCode()).getData();
        DictData finish = dicDataFeignClient.getDicDataByCode(DicDataEnum.FINISH.getCode()).getData();

        updateWrapper.set("a_status", Objects.equals("1", loadTypeUserCheckParam.getCheckResult()) ? finish.getId() : fail.getId());
        int i = loadTypeUserManageMapper.update(null, updateWrapper);
        result = i == 1;
        return result;
    }

    @Override
    public Boolean delLoadTypeUserPlan(List<String> ids) {
        List<RLoadTypeUserManage> rLoadTypeUserManageList = this.lambdaQuery().in(RLoadTypeUserManage::getId,ids).list();
        long count = rLoadTypeUserManageList.stream().map(RLoadTypeUserManage::getIStatus).filter(item-> Objects.equals(item, AuditProcessEnum.WaitAudit.getStatus())||Objects.equals(item, AuditProcessEnum.Release.getStatus())).count();
        if(count>0){
            throw new BusinessException("非新建驳回状态条目无法删除");
        }
        this.removeByIds(ids);
        //删除同时删除报告
        for(RLoadTypeUserManage rLoadTypeUserManage : rLoadTypeUserManageList){
            if(Objects.equals(rLoadTypeUserManage.getAIsFileUpload(),1)){
                fileStorageUtil.getFileUrl(rLoadTypeUserManage.getIFilePath());
            }
            if(Objects.equals(rLoadTypeUserManage.getAIsFileUpload(),1)){
                fileStorageUtil.getFileUrl(rLoadTypeUserManage.getAFilePath());
            }
        }
        return true;
    }

    @Override
    public Boolean submitAuditUser(LoadTypeUserCheckParam loadTypeUserCheckParam) {
        String userId = RequestUtil.getUserIndex();
        List<String> ids = loadTypeUserCheckParam.getIds();

        Integer count = this.lambdaQuery().in(RLoadTypeUserManage::getId, ids).eq(RLoadTypeUserManage::getCreateBy, userId).count();
        if (count != ids.size()) {
            throw new BusinessException("只可以操作自己创建的计划!");
        }

        this.update(new LambdaUpdateWrapper<RLoadTypeUserManage>()
                .in(RLoadTypeUserManage::getId, ids)
                .set(RLoadTypeUserManage::getIStatus, AuditProcessEnum.WaitAudit.getStatus()).set(RLoadTypeUserManage::getICheckPerson, loadTypeUserCheckParam.getCheckPerson())
        );

        //绑定工作流
        Map<String, Object> map = new HashMap<>();
        //map.put("applyUser",userId);
        for (String planId : ids) {
            //需要判断那些流程已经启动,已经启动的则为驳回后的再次提交审核
            FlowableAss flowableAss = flowableAssMapper.selectOne(new LambdaQueryWrapper<FlowableAss>().eq(FlowableAss::getThsIndex, planId));
            if (Objects.nonNull(flowableAss)) {
                //不为空则认为是驳回后的重新发起
                Task task = iFlowTaskService.getTask(flowableAss.getExecIndex());
                FlowTaskVo flowTaskVo = new FlowTaskVo();
                flowTaskVo.setTaskId(task.getId());
                flowTaskVo.setAssignee(userId);
                flowTaskVo.setComment(RequestUtil.getUserNickname() + "重新发起新建干扰源用户申请");
                iFlowTaskService.complete(flowTaskVo);

                Task taskNext = iFlowTaskService.getTask(flowableAss.getExecIndex());
                FlowTaskVo flowTaskVoNext = new FlowTaskVo();
                flowTaskVoNext.setTaskId(taskNext.getId());
                flowTaskVoNext.setAssignee(loadTypeUserCheckParam.getCheckPerson());
                iFlowTaskService.toNextTaskUser(flowTaskVoNext);
            } else {
                //开始流程
                FlowFormAss flowFormAss = flowFormAssMapper.selectOne(new LambdaQueryWrapper<FlowFormAss>().eq(FlowFormAss::getFormId, 2));
                if (Objects.isNull(flowFormAss)) {
                    throw new BusinessException("当前功能未绑定流程,请先绑定流程");
                }

                String processId = iFlowDefinitionService.startProcessInstanceById(flowFormAss.getDefinitionId(), planId,ThsFlowTypeEnum.rLoadTypeUser.getCode(), map);
                Task task = iFlowTaskService.getTask(processId);
                FlowTaskVo flowTaskVo = new FlowTaskVo();
                flowTaskVo.setTaskId(task.getId());
                flowTaskVo.setInstanceId(processId);
                flowTaskVo.setComment(RequestUtil.getUserNickname() + "发起新建干扰源用户申请");
                iFlowTaskService.complete(flowTaskVo);

                Task taskReport = iFlowTaskService.getTask(processId);
                FlowTaskVo flowTaskVoReport = new FlowTaskVo();
                flowTaskVoReport.setTaskId(taskReport.getId());
                flowTaskVoReport.setAssignee(userId);
                flowTaskVoReport.setComment(RequestUtil.getUserNickname() + "填报了预测评估报告");
                iFlowTaskService.complete(flowTaskVoReport);

                Task taskNext = iFlowTaskService.getTask(processId);
                FlowTaskVo flowTaskVoNext = new FlowTaskVo();
                flowTaskVoNext.setTaskId(taskNext.getId());
                flowTaskVoNext.setAssignee(loadTypeUserCheckParam.getCheckPerson());
                iFlowTaskService.toNextTaskUser(flowTaskVoNext);
            }
        }
        return true;
    }

    /**
     * @Description: 干扰源用户报告状态，待审核无法修改信息
     * @param id
     * @param type
     * @Author: wr
     * @Date: 2024/1/30 10:44
     */
    private Boolean checkStatus(String id,Integer type){
        RLoadTypeUserManage rLoadTypeUserManage = loadTypeUserManageMapper.selectById(id);
        if(type==0){
            //入网评估
            Integer iStatus = rLoadTypeUserManage.getIStatus();
            if(Objects.equals(iStatus, AuditProcessEnum.WaitAudit.getStatus()) ||Objects.equals(iStatus, AuditProcessEnum.Release.getStatus()) ){
                throw new BusinessException(CommonResponseEnum.FAIL, "只有新建和未通过状态下，可修改信息");
            }
        }else if(type==1){
            //实测评估
            Integer aStatus = rLoadTypeUserManage.getAStatus();
            if(Objects.equals(aStatus, AuditProcessEnum.WaitAudit.getStatus()) ||Objects.equals(aStatus, AuditProcessEnum.Release.getStatus()) ){
                throw new BusinessException(CommonResponseEnum.FAIL, "只有新建和未通过状态下，可修改信息");
            }
        }
        return true;
    }




}
