package com.yeejoin.amos.boot.module.jyjc.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapBuilder;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.CompanyBo;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.dao.mapper.DataDictionaryMapper;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.module.common.api.dto.AttachmentDto;
import com.yeejoin.amos.boot.module.jyjc.api.dto.InspectionCompanyPublicityDto;
import com.yeejoin.amos.boot.module.jyjc.api.entity.JyjcOpeningApplication;
import com.yeejoin.amos.boot.module.jyjc.api.enums.BizTypeEnum;
import com.yeejoin.amos.boot.module.jyjc.api.enums.BusinessTypeEnum;
import com.yeejoin.amos.boot.module.jyjc.api.enums.OpenBizTypeEnum;
import com.yeejoin.amos.boot.module.jyjc.api.mapper.JyjcOpeningApplicationMapper;
import com.yeejoin.amos.boot.module.jyjc.api.model.*;
import com.yeejoin.amos.boot.module.jyjc.api.service.IJyjcOpeningApplicationService;
import com.yeejoin.amos.boot.module.jyjc.biz.action.RuleActionHandler;
import com.yeejoin.amos.boot.module.jyjc.biz.config.BaseException;
import com.yeejoin.amos.boot.module.jyjc.biz.feign.TzsServiceFeignClient;
import com.yeejoin.amos.boot.module.jyjc.biz.service.TaskModelServiceImpl;
import com.yeejoin.amos.boot.module.ymt.api.dto.TzBaseEnterpriseInfoDto;
import com.yeejoin.amos.boot.module.ymt.api.dto.TzBaseUnitLicenceDto;
import com.yeejoin.amos.boot.module.ymt.api.entity.BaseUnitLicence;
import com.yeejoin.amos.boot.module.ymt.api.entity.TzBaseEnterpriseInfo;
import com.yeejoin.amos.boot.module.ymt.api.entity.TzBaseUnitLicence;
import com.yeejoin.amos.boot.module.ymt.api.entity.TzsUserInfo;
import com.yeejoin.amos.boot.module.ymt.api.enums.ApplicationFormTypeEnum;
import com.yeejoin.amos.boot.module.ymt.api.enums.FlowStatusEnum;
import com.yeejoin.amos.boot.module.ymt.api.mapper.BaseUnitLicenceMapper;
import com.yeejoin.amos.boot.module.ymt.api.mapper.TzBaseEnterpriseInfoMapper;
import com.yeejoin.amos.boot.module.ymt.api.mapper.TzsUserInfoMapper;
import com.yeejoin.amos.boot.module.ymt.api.vo.TzsUserInfoVo;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import com.yeejoin.amos.feign.systemctl.model.TaskV2Model;
import com.yeejoin.amos.feign.workflow.model.ActWorkflowBatchDTO;
import com.yeejoin.amos.feign.workflow.model.ActWorkflowStartDTO;
import com.yeejoin.amos.feign.workflow.model.ProcessTaskDTO;
import com.yeejoin.amos.feign.workflow.model.TaskResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * 服务实现类
 *
 * @author system_generator
 * @date 2023-12-13
 */
@Service
@Slf4j
public class JyjcOpeningApplicationServiceImpl extends BaseService<JyjcOpeningApplicationModel, JyjcOpeningApplication, JyjcOpeningApplicationMapper> implements IJyjcOpeningApplicationService {

    @Autowired
    private TzsServiceFeignClient tzsServiceFeignClient;
    @Autowired
    JyjcOpeningApplicationMapper jyjcOpeningApplicationMapper;


    @Value("${process-definition-key.jyjc.openapplication:}")
    private String processDefinitionKey;

    @Value("${jy.user-post:66151}")
    private String jyUserPost;

    @Value("${jy.cert.type.code:1233-1}")
    private String jyCertTypeCode;

    @Value("${jc.user-post:66152}")
    private String jcUserPost;

    @Value("${jc.cert.type.code:1233-2}")
    private String jcCertTypeCode;

    @Value("classpath:/json/bizTypeInfo.json")
    private org.springframework.core.io.Resource bizTypeInfo;


    @Autowired
    private TzBaseEnterpriseInfoMapper enterpriseInfoMapper;

    @Autowired
    BaseUnitLicenceMapper baseUnitLicenceMapper;

    @Autowired
    private TzsUserInfoMapper userInfoMapper;

    @Autowired
    CommonServiceImpl commonService;

    @Autowired
    CmWorkflowServiceImpl cmWorkflowService;

    @Autowired
    TaskModelServiceImpl taskModelService;

    @Autowired
    DataDictionaryMapper dataDictionaryMapper;

    @Autowired
    RuleActionHandler ruleActionHandler;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    private RuleCommonServiceImpl ruleCommonService;

    @Autowired
    private TzBaseEnterpriseInfoMapper tzBaseEnterpriseInfoMapper;

    private static Map<String, DictionarieValueModel> permissionLevelMap;

    private static List<DictionarieValueModel> permissionItemList;

    private final static String INDUSTRY_SUPERVISOR_DICT_TYPE = "HYZGBM";

    /**
     * 人员级别字典KEY
     */
    private final static String RYJB_JYJC_DICT_KEY = "RYJB_JYJC";

    /**
     * 所有人员资质检验检测项目key
     */
    private final static String ZZXM_JYJC_DICT_KEY = "ZZXM_JYJC_ALL";

    /**
     * 编辑、工作台暂存逻辑
     *
     * @param model 对象
     * @return JyjcOpeningApplicationModel
     */
    @Transactional(rollbackFor = {Exception.class, BaseException.class})
    public JyjcOpeningApplicationModel saveOrUpdate(JyjcOpeningApplicationModel model) {
        if (model.getSequenceNbr() != null) {
            // 编辑逻辑
            return this.updateWithModel(model);
        } else {
            // 工作台暂存（新增）逻辑
            // 1.创建开通申请
            List<String> codes = tzsServiceFeignClient.applicationFormCode(ApplicationFormTypeEnum.JY.getCode(), 1).getResult();
            model.setApplicationSeq(codes.get(0));
            CompanyBo companyBo = commonService.getReginParamsOfCurrentUser().getCompany();
            model.setUnitCode(companyBo.getCompanyCode());
            model.setUnitCodeName(companyBo.getCompanyName());
            model.setCreateUserId(RequestContext.getExeUserId());
            model.setStatus(FlowStatusEnum.TO_BE_SUBMITTED.getCode() + "");
            model.setStatusName(FlowStatusEnum.TO_BE_SUBMITTED.getName());
            this.createWithModel(model);
            // 2.创建待办
            createDraftTask(model);
        }
        model.setStatusName(FlowStatusEnum.getNameByType(Long.parseLong((model.getStatus()))));
        return this.updateWithModel(model);
    }

    /**
     * 提交、保存并提交逻辑
     *
     * @param model 对象
     * @return JyjcOpeningApplicationModel
     */
    @Transactional(rollbackFor = {Exception.class, BaseException.class})
    public JyjcOpeningApplicationModel submitApplication(JyjcOpeningApplicationModel model) {
        String instanceId = model.getWorkflowProstanceId();
        this.setDefaultFieldValue(model);
        if (StringUtils.isBlank(instanceId)) {
            // 未开启过工作流则进行开启 startProcess
            ActWorkflowBatchDTO actWorkflowBatchDTO = new ActWorkflowBatchDTO();
            ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
            ArrayList<ActWorkflowStartDTO> list = new ArrayList<>();
            dto.setProcessDefinitionKey(processDefinitionKey);
            dto.setBusinessKey("1");
            dto.setCompleteFirstTask(Boolean.TRUE);
            // 接受机构
            list.add(dto);
            actWorkflowBatchDTO.setProcess(list);
            List<ProcessTaskDTO> processTaskDTOS = cmWorkflowService.startBatch(actWorkflowBatchDTO);
            List<WorkflowResultDto> resultDto = taskModelService.buildWorkFlowInfo(processTaskDTOS);
            WorkflowResultDto workflowResultDto = resultDto.get(0);
            model.setStatus(String.valueOf(FlowStatusEnum.TO_BE_PROCESSED.getCode()));
            model.setStatusName(String.valueOf(FlowStatusEnum.TO_BE_PROCESSED.getName()));
            model.setPromoter(RequestContext.getExeUserId());
            model.setWorkflowProstanceId(workflowResultDto.getInstanceId());
            model.setNextExecuteIds(workflowResultDto.getNextExecutorRoleIds());
            model.setNextTaskId(workflowResultDto.getNextTaskId());
            model.setNextExecuteUserIds(workflowResultDto.getNextExecutorUserIds());
            // 首次提交时删除暂存的待办
            this.deleteDraftTask(model);
            saveModel(model);
            // 创建代办
            buildTask(model, workflowResultDto);
            // 缓存流程数据
            commonService.saveExecuteFlowData2Redis(workflowResultDto.getInstanceId(), this.buildInstanceRuntimeData(model));
            return model;
        } else {
            // 首次提交时删除暂存的待办
            this.deleteDraftTask(model);
            // 存在流程，执行
            executeOneStep(model);
            saveModel(model);
            return model;
        }
    }

    private void deleteDraftTask(JyjcOpeningApplicationModel model) {
        if (model.getSequenceNbr() != null) {
            taskModelService.deleteTaskModel(model.getSequenceNbr() + "");
        }
    }

    private void setDefaultFieldValue(JyjcOpeningApplicationModel model) {
        CompanyBo companyBo = commonService.getReginParamsOfCurrentUser().getCompany();
        model.setApplyTime(new Date());
        model.setUnitCode(companyBo.getCompanyCode());
        model.setUnitCodeName(companyBo.getCompanyName());
        if (model.getSequenceNbr() == null) {
            model.setCreateUserId(RequestContext.getExeUserId());
            List<String> codes = tzsServiceFeignClient.applicationFormCode(ApplicationFormTypeEnum.JY.getCode(), 1).getResult();
            model.setApplicationSeq(codes.get(0));
        }
    }

    private JyjcOpeningApplicationModel saveModel(JyjcOpeningApplicationModel model) {
        if (model.getSequenceNbr() == null) {
            return this.createWithModel(model);
        } else {
            return this.updateWithModel(model);
        }
    }

    private void createDraftTask(JyjcOpeningApplicationModel model) {
        ArrayList<TaskModelDto> list = new ArrayList<>();
        TaskModelDto dto = new TaskModelDto();
        TaskMessageDto taskMessageDto = new TaskMessageDto();
        BeanUtil.copyProperties(model, taskMessageDto);
        // 数据参数
        dto.setModel(taskMessageDto);
        // 摘要
        dto.setTaskContent(String.format("检验检测业务开通办理，【申请单号：%s】", model.getApplicationSeq()));
        // 申请单号
        dto.setTaskCode(model.getApplicationSeq());
        // 业务类型
        dto.setTaskType(BusinessTypeEnum.JY_OPENING_APPLICATION.getCode());
        // 业务主键
        dto.setRelationId(String.valueOf(model.getSequenceNbr()));
        dto.setNextExecuteUser("");
        list.add(dto);
        taskModelService.buildTaskModel(list);
    }

    @Transactional(rollbackFor = {Exception.class, BaseException.class})
    public JyjcOpeningApplicationModel resubmit(JyjcOpeningApplicationModel model) {
        model.setStatus(FlowStatusEnum.TO_BE_PROCESSED.getCode() + "");
        model = this.updateWithModel(model);
        executeFlow(MapBuilder.<String, Object>create()
                .put("op", "0")
                .put("instanceId", model.getWorkflowProstanceId())
                .put("comments", "")
                .put("nextTaskId", model.getNextTaskId())
                .build());
        return model;
    }


    /**
     * 完成的时候废弃其他已完成的申请单
     *
     * @param unitCode    unitCode
     * @param sequenceNbr sequenceNbr
     * @param openBizType 按照单位及开通业务类型进进行作废
     * @throws
     * @author yangyang
     * @date 2023/12/22 09:23
     */
    private void doDiscard(String unitCode, Long sequenceNbr, String openBizType) {
        List<Long> ids = this.lambdaQuery().select(JyjcOpeningApplication::getSequenceNbr)
                .eq(JyjcOpeningApplication::getUnitCode, unitCode)
                .eq(JyjcOpeningApplication::getOpenBizType, openBizType)
                .ne(JyjcOpeningApplication::getSequenceNbr, sequenceNbr)
                .eq(JyjcOpeningApplication::getStatus, FlowStatusEnum.TO_BE_FINISHED.getCode())
                .list().stream().filter(o -> !o.getSequenceNbr().equals(sequenceNbr))
                .map(JyjcOpeningApplication::getSequenceNbr).collect(Collectors.toList());
        if (ValidationUtil.isEmpty(ids)) {
            return;
        }
        LambdaUpdateWrapper<JyjcOpeningApplication> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(JyjcOpeningApplication::getStatus, FlowStatusEnum.TO_BE_DISCARD.getCode())
                .set(JyjcOpeningApplication::getStatusName, FlowStatusEnum.TO_BE_DISCARD.getName())
                .set(JyjcOpeningApplication::getRemark, "新开通申请生效，原有开通申请自动作废")
                .in(org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity::getSequenceNbr, ids);
        this.update(updateWrapper);
    }

    public Boolean doDiscard(Long sequenceNbr, String remark) {
        if (sequenceNbr == null) {
            throw new BadRequest("sequenceNbr不能为空！");
        }
        JyjcOpeningApplication jyjcOpeningApplication = jyjcOpeningApplicationMapper.selectById(sequenceNbr);
        if (jyjcOpeningApplication == null) {
            return false;
        }
        if (!String.valueOf(FlowStatusEnum.TO_BE_FINISHED.getCode()).equals(jyjcOpeningApplication.getStatus())) {
            throw new BadRequest("只有已完成的申请单才可以作废！");
        }
        UpdateWrapper<JyjcOpeningApplication> updateWrapper = new UpdateWrapper<>();
        updateWrapper
                .set("status", FlowStatusEnum.TO_BE_DISCARD.getCode())
                .set("status_name", FlowStatusEnum.TO_BE_DISCARD.getName())
                .set("remark", remark)
                .eq("SEQUENCE_NBR", sequenceNbr);
        return this.update(updateWrapper);
    }


    /**
     * 列表查询 示例
     */
    public List<JyjcOpeningApplicationModel> queryForJyjcOpeningApplicationList() {
        return this.queryForList("", false);
    }

    public Page<JyjcOpeningApplicationModel> queryForJyjcOpeningApplicationPage(Page<JyjcOpeningApplication> page, JyjcOpeningApplicationRequstDto dto) {
        ReginParams reginParams = commonService.getReginParamsOfCurrentUser();
        String currentUserId = reginParams.getUserModel().getUserId();
        String level = reginParams.getCompany().getLevel();
        if (BaseController.COMPANY_TYPE_COMPANY.equals(level)) {
            dto.setType("enterprise");
            dto.setUnitCode(reginParams.getCompany().getCompanyCode());
        } else {
            dto.setType("supervision");
        }
        String applyStartTime = "";
        String applyEndTime = "";
        if (ObjectUtils.isNotEmpty(dto.getApplyTime())) {
            String date = dto.getApplyTime();
            applyStartTime = date + " 00:00:00";
            applyEndTime = date + " 23:59:59";
        }
        Page<JyjcOpeningApplicationModel> result = jyjcOpeningApplicationMapper.selectJyjcOpeningApplicationList(page, dto, applyStartTime, currentUserId, applyEndTime);
        for (JyjcOpeningApplicationModel record : result.getRecords()) {
            record.setIdentityType(dto.getType());
            record.setOpenBizTypeName(this.getOpenBizTypeName(record.getOpenBizType()));
        }
        return result;
    }


    private String getOpenBizTypeName(String openBizType) {
        return Optional.ofNullable(OpenBizTypeEnum.getOneByCode(openBizType))
                .map(OpenBizTypeEnum::getName)
                .orElse("");
    }


    /**
     * 获取详情跳转
     *
     * @param
     * @return {@link }
     * @throws
     * @author yangyang
     */
    public JyjcOpeningApplicationModel queryDetail(Long sequenceNbr) {
        ReginParams reginParams = commonService.getReginParamsOfCurrentUser();
        if (ValidationUtil.isEmpty(reginParams.getCompany())) {
            throw new RuntimeException("未指定人员归属单位信息");
        }
        String unitCode;
        JyjcOpeningApplicationModel jyjcOpeningApplicationModel;
        if (null != sequenceNbr) {
            jyjcOpeningApplicationModel = this.queryBySeq(sequenceNbr);
            unitCode = jyjcOpeningApplicationModel.getUnitCode();
            // 设置检验、检测资质信息
            setBaseUnitLicences(unitCode, jyjcOpeningApplicationModel, true);
            // 设置检验、检测人员信息
            setJYJCUserList(unitCode, jyjcOpeningApplicationModel, true, jyjcOpeningApplicationModel.getOpenBizType());
        } else {
            jyjcOpeningApplicationModel = new JyjcOpeningApplicationModel();
            jyjcOpeningApplicationModel.setResultType("input");
            jyjcOpeningApplicationModel.setOpenBizType(OpenBizTypeEnum.JY.getCode());
            unitCode = reginParams.getCompany().getCompanyCode();
            jyjcOpeningApplicationModel.setUnitCodeName(reginParams.getCompany().getCompanyName());
            jyjcOpeningApplicationModel.setUnitCode(unitCode);
            // 设置检测资质信息，前端需要按照开通的业务类型自行过滤，全部数据
            setBaseUnitLicences(unitCode, jyjcOpeningApplicationModel, false);
            // 设置业务有效期的默认值与yjcOpeningApplicationModel.setOpenBizType(OpenBizTypeEnum.JY.getCode())对应
            setDefaultExpiryDate(jyjcOpeningApplicationModel);
        }
        // 设置企业信息
        setBaseEnterpriseInfo(unitCode, jyjcOpeningApplicationModel);
        return jyjcOpeningApplicationModel;
    }

    private void setBaseEnterpriseInfo(String unitCode, JyjcOpeningApplicationModel jyjcOpeningApplicationModel) {
        LambdaQueryWrapper<TzBaseEnterpriseInfo> enterpriseInfoQueryWrapper = new LambdaQueryWrapper<>();
        enterpriseInfoQueryWrapper.eq(TzBaseEnterpriseInfo::getUseCode, unitCode);
        TzBaseEnterpriseInfo baseUnitLicenceEntity = enterpriseInfoMapper.selectOne(enterpriseInfoQueryWrapper);
        // 获取企业资质
        if (baseUnitLicenceEntity != null) {
            jyjcOpeningApplicationModel.setUseContact(baseUnitLicenceEntity.getUseContact());
            jyjcOpeningApplicationModel.setContactPhone(baseUnitLicenceEntity.getContactPhone());
            jyjcOpeningApplicationModel.setUnitAddress(baseUnitLicenceEntity.getAddress());
            if (StringUtils.isNotBlank(baseUnitLicenceEntity.getIndustrySupervisor())) {
                DataDictionary dict = dataDictionaryMapper.getByCode(baseUnitLicenceEntity.getIndustrySupervisor(), INDUSTRY_SUPERVISOR_DICT_TYPE);
                if (dict != null) {
                    jyjcOpeningApplicationModel.setIndustrySupervisor(dict.getName());
                } else {
                    jyjcOpeningApplicationModel.setIndustrySupervisor(baseUnitLicenceEntity.getIndustrySupervisor());
                }
            }
            jyjcOpeningApplicationModel.setGeographic(JyjcGeographicModel.builder().latitude(baseUnitLicenceEntity.getLatitude()).longitude(baseUnitLicenceEntity.getLongitude()).build());
            jyjcOpeningApplicationModel.setLongitude(baseUnitLicenceEntity.getLongitude());
            jyjcOpeningApplicationModel.setLatitude(baseUnitLicenceEntity.getLatitude());
            if (ObjectUtils.isNotEmpty(baseUnitLicenceEntity.getUnitBusinessLicense())) {
                jyjcOpeningApplicationModel.setUnitBusinessLicense(JSONArray.parseArray(baseUnitLicenceEntity.getUnitBusinessLicense(), AttachmentDto.class));
            }
        }
    }

    private void setDefaultExpiryDate(JyjcOpeningApplicationModel jyjcOpeningApplicationModel) {
        Optional<TzBaseUnitLicenceDto> op = jyjcOpeningApplicationModel.getBaseUnitLicences().stream().filter(l -> l.getCertTypeCode().equals(jyjcOpeningApplicationModel.getOpenBizType())).min(Comparator.comparing(TzBaseUnitLicenceDto::getExpiryDate));
        op.ifPresent(licenceDto -> jyjcOpeningApplicationModel.setExpiryDate(licenceDto.getExpiryDate()));
    }

    private void setBaseUnitLicences(String unitCode, JyjcOpeningApplicationModel jyjcOpeningApplicationModel, boolean isNeedFilter) {
        List<BaseUnitLicence> baseUnitLicences = baseUnitLicenceMapper.selectList(new LambdaQueryWrapper<BaseUnitLicence>()
                .eq(BaseUnitLicence::getUnitCode, unitCode)
                .gt(BaseUnitLicence::getExpiryDate , new Date())
                .in(BaseUnitLicence::getCertTypeCode, Arrays.asList(jyCertTypeCode, jcCertTypeCode)));
        List<TzBaseUnitLicenceDto> licences = baseUnitLicences.stream().map(l -> {
            TzBaseUnitLicenceDto licenceDto = new TzBaseUnitLicenceDto();
            BeanUtil.copyProperties(l, licenceDto);
            licenceDto.setCertTypeCode(this.castCode2Str(l.getCertTypeCode()));
            return licenceDto;
        }).collect(Collectors.toList());
        if (isNeedFilter) {
            licences = licences.stream().filter(u -> u.getCertTypeCode().equals(jyjcOpeningApplicationModel.getOpenBizType())).collect(Collectors.toList());
            jyjcOpeningApplicationModel.setBaseUnitLicences(licences);
        } else {
            jyjcOpeningApplicationModel.setBaseUnitLicences(licences);
        }
    }

    private String castCode2Str(String certTypeCode) {
        // 新注册逻辑，逻辑在1处维护，便于代码维护【jy、jc对应前端的业务类型】
        if (jcCertTypeCode.equals(certTypeCode)) {
            // 检测类型资质
            return "jc";
        }
        if (jyCertTypeCode.equals(certTypeCode)) {
            // 检验类型资质
            return "jy";
        }
        // 之前老数据逻辑，逻辑在1处维护，便于代码维护【jy、jc对应前端的业务类型】
        return "";
    }

    private void setJYJCUserList(String unitCode, JyjcOpeningApplicationModel jyjcOpeningApplicationModel, boolean isNeedFilter, String openBizType) {
        LambdaQueryWrapper<TzsUserInfo> userInfoQueryWrapper = new LambdaQueryWrapper<>();
        userInfoQueryWrapper.eq(TzsUserInfo::getUnitCode, unitCode);
        userInfoQueryWrapper.eq(BaseEntity::getIsDelete, false);
        this.castPersonType2Post(userInfoQueryWrapper, openBizType);
        List<TzsUserInfo> userInfos = userInfoMapper.selectList(userInfoQueryWrapper);
        if (!ValidationUtil.isEmpty(userInfos)) {
            List<TzsUserInfoVo> tzsUserInfoVos = userInfos.stream().map(userInfo -> {
                TzsUserInfoVo vo = new TzsUserInfoVo();
                BeanUtils.copyProperties(userInfo, vo, "identification", "profile", "permissionItem", "appointDoc");
                if (!ObjectUtils.isEmpty(userInfo.getPermissionData())) {
                    this.setPermissionInfo(vo, userInfo, openBizType);
                }
                if (!ObjectUtils.isEmpty(userInfo.getPost())) {
                    vo.setPost(JSON.parseArray(userInfo.getPost()));
                }
                if (!ObjectUtils.isEmpty(userInfo.getAppointDoc())) {
                    vo.setAppointDoc(JSON.parseArray(userInfo.getAppointDoc()));
                }
                return vo;
            }).filter(o -> o.getPost() != null && (o.getPost().contains(jyUserPost) || o.getPost().contains(jcUserPost))).peek(u -> {
                // 设置岗位类型，逻辑在1端处理，便于代码维护，前端直接使用即可【jy、jc对应前端的业务类型】
                if (u.getPost().contains(jyUserPost) && u.getPost().contains(jcUserPost)) {
                    // 即时检验又是检测人员
                    u.setStrPost("jy,jc");
                }
                if (u.getPost().contains(jyUserPost) && !u.getPost().contains(jcUserPost)) {
                    // 检验人员
                    u.setStrPost("jy");
                }
                if (!u.getPost().contains(jyUserPost) && u.getPost().contains(jcUserPost)) {
                    // 检测人员
                    u.setStrPost("jc");
                }
            }).collect(Collectors.toList());
            if (isNeedFilter) {
                tzsUserInfoVos = tzsUserInfoVos.stream().filter(u -> u.getStrPost().contains(jyjcOpeningApplicationModel.getOpenBizType())).collect(Collectors.toList());
                jyjcOpeningApplicationModel.setUserInfos(tzsUserInfoVos);
            } else {
                jyjcOpeningApplicationModel.setUserInfos(tzsUserInfoVos);
            }
        }
    }

    private void castPersonType2Post(LambdaQueryWrapper<TzsUserInfo> userInfoQueryWrapper, String personType) {
        if (personType.equals(OpenBizTypeEnum.JY.getCode())) {
            userInfoQueryWrapper.like(TzsUserInfo::getPost, jyUserPost);
        }
        if (personType.equals(OpenBizTypeEnum.JC.getCode())) {
            userInfoQueryWrapper.like(TzsUserInfo::getPost, jcUserPost);
        }
    }

    public List<TzsUserInfoVo> getUserListByUnitCodeAndPost(String unitCode, String personType) {
        LambdaQueryWrapper<TzsUserInfo> userInfoQueryWrapper = new LambdaQueryWrapper<>();
        userInfoQueryWrapper.eq(TzsUserInfo::getUnitCode, unitCode);
        this.castPersonType2Post(userInfoQueryWrapper, personType);
        userInfoQueryWrapper.eq(BaseEntity::getIsDelete, false);
        List<TzsUserInfo> userInfos = userInfoMapper.selectList(userInfoQueryWrapper);
        return userInfos.stream().map(userInfo -> {
            TzsUserInfoVo vo = new TzsUserInfoVo();
            BeanUtils.copyProperties(userInfo, vo, "identification", "profile", "permissionItem", "appointDoc");
            if (!ObjectUtils.isEmpty(userInfo.getPermissionData())) {
                this.setPermissionInfo(vo, userInfo, personType);
            }
            if (!ObjectUtils.isEmpty(userInfo.getPost())) {
                vo.setPost(JSON.parseArray(userInfo.getPost()));
            }
            if (!ObjectUtils.isEmpty(userInfo.getAppointDoc())) {
                vo.setAppointDoc(JSON.parseArray(userInfo.getAppointDoc()));
            }
            return vo;
        }).collect(Collectors.toList());
    }

    private void setPermissionInfo(TzsUserInfoVo vo, TzsUserInfo userInfo, String personType) {
        String post = "";
        if (personType.equals(OpenBizTypeEnum.JY.getCode())) {
            post = jyUserPost;
        }
        if (personType.equals(OpenBizTypeEnum.JC.getCode())) {
            post = jcUserPost;
        }
        JSONObject allPermissionData = JSON.parseObject(userInfo.getPermissionData());
        JSONArray postPermissionData = allPermissionData.getJSONArray(this.buildPermissionKey(post));
        if (postPermissionData != null && postPermissionData.size() > 0) {
            JSONObject jsonObject = postPermissionData.getJSONObject(0);
            vo.setPermissionItem(jsonObject.getJSONArray("permissionItem"));
            vo.setPermissionItemName(this.castItemCode2Name(jsonObject.getJSONArray("permissionItem")));
            vo.setPermissionLevelName(this.getDictNameByCode(jsonObject.getString("permissionLevel")));
        }
    }

    private String buildPermissionKey(String post) {
        return String.format("%s%s", "permissionData", post);
    }

    private String castItemCode2Name(JSONArray permissionItem) {
        if (permissionItemList == null) {
            FeignClientResult<List<DictionarieValueModel>> itemDicts = Systemctl.dictionarieClient.dictValues(ZZXM_JYJC_DICT_KEY);
            permissionItemList = itemDicts.getResult();
        }
        return permissionItemList.stream().filter(i -> permissionItem.contains(i.getDictDataKey())).map(this::buildItemWithCode).collect(Collectors.joining(","));
    }

    private String buildItemWithCode(DictionarieValueModel d) {
        return String.format("%s[%s]", d.getDictDataValue(), d.getDictDataKey());
    }

    private String getDictNameByCode(String permissionLevel) {
        if (StringUtils.isEmpty(permissionLevel)) {
            return "";
        }
        if (permissionLevelMap == null) {
            FeignClientResult<List<DictionarieValueModel>> levelDicts = Systemctl.dictionarieClient.dictValues(RYJB_JYJC_DICT_KEY);
            permissionLevelMap = levelDicts.getResult().stream().collect(Collectors.toMap(DictionarieValueModel::getDictDataKey, Function.identity(), (k1, k2) -> k2));
        }
        return Optional.ofNullable(permissionLevelMap.get(permissionLevel).getDictDataValue()).orElse("");
    }


    /**
     * 接收/驳回通知检验单
     */
    @Transactional(rollbackFor = Exception.class)
    public JyjcOpeningApplication executeFlow(Map<String, Object> params) {
        String instanceId = params.get("instanceId").toString();
        String nextTaskId = params.get("nextTaskId").toString();
        String lockKey = CommonServiceImpl.buildJcExecuteLockKey(instanceId);
        RLock lock = redissonClient.getLock(lockKey);
        try {
            boolean isLocked = lock.tryLock(0, 180, TimeUnit.SECONDS);
            // 解决并发问题：多个人同时操作一个流程（并发执行通过、驳回、撤回）
            if (!isLocked) {
                throw new BadRequest("当前流程已经被执行！请重新打开页面查看并执行！");
            }
            // 流程执行时，状态及权限校验
            commonService.checkForExecuteFlow(nextTaskId, instanceId);
            Long sequenceNbr = Long.parseLong(params.get("sequenceNbr") + "");
            String op = params.get("op").toString();
            JyjcOpeningApplication jyjcOpeningApplication = jyjcOpeningApplicationMapper.selectById(sequenceNbr);
            //组装信息
            TaskResultDTO dto = new TaskResultDTO();
            dto.setResultCode("approvalStatus");
            dto.setTaskId(jyjcOpeningApplication.getNextTaskId());
            dto.setComment(params.get("comments").toString());
            HashMap<String, Object> map = new HashMap<>();
            map.put("approvalStatus", op);
            if (String.valueOf(FlowStatusEnum.ROLLBACK.getCode()).equals(jyjcOpeningApplication.getStatus()) || String.valueOf(FlowStatusEnum.REJECTED.getCode()).equals(jyjcOpeningApplication.getStatus())) {
                map.put("approvalStatus", "提交");
            }
            dto.setVariable(map);
            ProcessTaskDTO complete = new ProcessTaskDTO();
            if ("0".equals(op)) {
                complete = cmWorkflowService.complete(jyjcOpeningApplication.getNextTaskId(), dto);
            } else {
                complete = cmWorkflowService.reject(jyjcOpeningApplication.getNextTaskId(), dto);

            }
            ArrayList<ProcessTaskDTO> processTaskDTOS = new ArrayList<>();
            processTaskDTOS.add(complete);
            List<WorkflowResultDto> resultDto = taskModelService.buildWorkFlowInfo(processTaskDTOS);
            WorkflowResultDto workflowResultDto = resultDto.get(0);
            if (!ObjectUtils.isEmpty(workflowResultDto.getNextTaskId())) {
                if ("1".equals(op)) {
                    // 驳回
                    jyjcOpeningApplication.setStatus(String.valueOf(FlowStatusEnum.REJECTED.getCode()));
                    jyjcOpeningApplication.setStatusName(String.valueOf(FlowStatusEnum.REJECTED.getName()));
                    jyjcOpeningApplication.setPromoter("");
                } else {
                    // 提交
                    jyjcOpeningApplication.setStatus(String.valueOf(FlowStatusEnum.TO_BE_PROCESSED.getCode()));
                    jyjcOpeningApplication.setStatusName(String.valueOf(FlowStatusEnum.TO_BE_PROCESSED.getName()));
                    jyjcOpeningApplication.setPromoter(RequestContext.getExeUserId());
                }
                jyjcOpeningApplication.setNextTaskId(workflowResultDto.getNextTaskId());
                jyjcOpeningApplication.setNextExecuteUserIds(workflowResultDto.getNextExecutorUserIds());
                // 更新代办
                updateTask(jyjcOpeningApplication, workflowResultDto, op);
            } else {
                // 流程结束
                jyjcOpeningApplication.setStatus(String.valueOf(FlowStatusEnum.TO_BE_FINISHED.getCode()));
                //更新办理日期
                jyjcOpeningApplication.setAcceptDate(new Date());
                // 更新代办
                HashMap<String, Object> taskParams = new HashMap<>();
                taskParams.put("relationId", jyjcOpeningApplication.getWorkflowProstanceId());
                taskParams.put("flowStatus", FlowStatusEnum.TO_BE_FINISHED.getCode());
                taskParams.put("flowStatusLabel", FlowStatusEnum.TO_BE_FINISHED.getName());
                taskParams.put("taskStatus", FlowStatusEnum.TO_BE_FINISHED.getCode());
                taskParams.put("taskStatusLabel", FlowStatusEnum.TO_BE_FINISHED.getName());
                taskParams.put("model", jyjcOpeningApplication);
                taskModelService.updateTaskModel(taskParams);
                List<String> detectionRegion = (List<String>)params.get("detectionRegion");
                jyjcOpeningApplication.setDetectionRegion(detectionRegion);
                jyjcOpeningApplication.setPromoter("");
                jyjcOpeningApplication.setNextTaskId("");
                jyjcOpeningApplication.setNextExecuteUserIds("");
                jyjcOpeningApplication.setStatusName(FlowStatusEnum.TO_BE_FINISHED.getName());
            }
            jyjcOpeningApplicationMapper.updateById(jyjcOpeningApplication);
            // 已完成 作废逻辑
            if (String.valueOf(FlowStatusEnum.TO_BE_FINISHED.getCode()).equals(jyjcOpeningApplication.getStatus())) {
                doDiscard(jyjcOpeningApplication.getUnitCode(), jyjcOpeningApplication.getSequenceNbr(), jyjcOpeningApplication.getOpenBizType());
            }
            // 更新流程中的流程数据
            commonService.saveExecuteFlowData2Redis(jyjcOpeningApplication.getWorkflowProstanceId(), this.buildInstanceRuntimeData(jyjcOpeningApplication));
            return jyjcOpeningApplication;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
        return null;
    }


    private void executeOneStep(JyjcOpeningApplicationModel openingApplication) {
        String instanceId = openingApplication.getWorkflowProstanceId();
        String nextTaskId = openingApplication.getNextTaskId();
        String lockKey = CommonServiceImpl.buildJcExecuteLockKey(instanceId);
        RLock lock = redissonClient.getLock(lockKey);
        try {
            boolean isLocked = lock.tryLock(0, 180, TimeUnit.SECONDS);
            // 解决并发问题：多个人同时操作一个流程（并发执行通过、驳回、撤回）
            if (!isLocked) {
                throw new BadRequest("当前流程已经被执行！请重新打开页面查看并执行！");
            }
            // 流程执行时，状态及权限校验
            commonService.checkForExecuteFlow(nextTaskId, instanceId);
            // 组装信息执行工作流
            TaskResultDTO dto = new TaskResultDTO();
            dto.setResultCode("approvalStatus");
            dto.setTaskId(nextTaskId);
            HashMap<String, Object> map = new HashMap<>();
            map.put("approvalStatus", "提交");
            dto.setVariable(map);
            ProcessTaskDTO complete = cmWorkflowService.complete(nextTaskId, dto);
            ArrayList<ProcessTaskDTO> processTaskDTOS = new ArrayList<>();
            processTaskDTOS.add(complete);
            List<WorkflowResultDto> resultDto = taskModelService.buildWorkFlowInfo(processTaskDTOS);
            WorkflowResultDto workflowResultDto = resultDto.get(0);
            // 更新业务信息
            openingApplication.setStatus(String.valueOf(FlowStatusEnum.TO_BE_PROCESSED.getCode()));
            openingApplication.setStatusName(String.valueOf(FlowStatusEnum.TO_BE_PROCESSED.getName()));
            openingApplication.setPromoter(RequestContext.getExeUserId());
            openingApplication.setNextTaskId(workflowResultDto.getNextTaskId());
            openingApplication.setNextExecuteUserIds(workflowResultDto.getNextExecutorUserIds());
            // 更新代办
            JyjcOpeningApplication jyjcOpeningApplicationEntry = new JyjcOpeningApplication();
            BeanUtil.copyProperties(openingApplication, jyjcOpeningApplicationEntry);
            updateTask(jyjcOpeningApplicationEntry, workflowResultDto, "0");
            // 更新流程中的流程数据
            commonService.saveExecuteFlowData2Redis(instanceId, this.buildInstanceRuntimeData(jyjcOpeningApplicationEntry));
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }


    /**
     * 撤回流程办理单
     */
    public JyjcOpeningApplication stopFlow(String sequenceNbr, String instanceId, String nextTaskId) {
        String lockKey = CommonServiceImpl.buildJcExecuteLockKey(instanceId);
        RLock lock = redissonClient.getLock(lockKey);
        try {
            boolean isLocked = lock.tryLock(0, 180, TimeUnit.SECONDS);
            // 解决并发问题：多个人同时操作一个流程（并发执行通过、驳回、撤回）
            if (!isLocked) {
                throw new BadRequest("当前流程已经被执行！请重新打开页面查看并执行！");
            }
            // 流程执行时，状态及权限校验
            commonService.checkForRevocationFlow(nextTaskId, instanceId);
            JyjcOpeningApplication jyjcOpeningApplication = jyjcOpeningApplicationMapper.selectById(sequenceNbr);
            //撤回流程
            ProcessTaskDTO processTaskDTO = cmWorkflowService.rollBack(jyjcOpeningApplication.getWorkflowProstanceId());
            ArrayList<ProcessTaskDTO> processTaskDTOS = new ArrayList<>();
            processTaskDTOS.add(processTaskDTO);
            jyjcOpeningApplication.setStatus(String.valueOf(FlowStatusEnum.ROLLBACK.getCode()));
            jyjcOpeningApplication.setStatusName(FlowStatusEnum.ROLLBACK.getName());
            jyjcOpeningApplication.setPromoter("");
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(jyjcOpeningApplication));
            List<WorkflowResultDto> resultDto = taskModelService.buildWorkFlowInfo(processTaskDTOS);
            if (!ObjectUtils.isEmpty(resultDto) && !ObjectUtils.isEmpty(resultDto.get(0))) {
                WorkflowResultDto workflowResultDto = resultDto.get(0);
                jsonObject.put("nextExecuteUser", workflowResultDto.getNextExecutorRoleIds());
                jyjcOpeningApplication.setNextTaskId(workflowResultDto.getNextTaskId());
                jyjcOpeningApplication.setNextExecuteUserIds(workflowResultDto.getNextExecutorUserIds());
            }
            jsonObject.put("nextTaskId", jyjcOpeningApplication.getNextTaskId());
            jsonObject.put("nextExecuteUserIds", jyjcOpeningApplication.getNextExecuteUserIds());
            jsonObject.put("taskType", BusinessTypeEnum.JY_OPENING_APPLICATION.getCode());
            jsonObject.put("flowStatus", FlowStatusEnum.ROLLBACK.getCode());
            jsonObject.put("flowStatusLabel", FlowStatusEnum.ROLLBACK.getName());
            // 撤回删除代办
            taskModelService.rollbackTask(jyjcOpeningApplication.getWorkflowProstanceId(), jsonObject);
            // 更新数据
            jyjcOpeningApplicationMapper.updateById(jyjcOpeningApplication);
            // 缓存下一个任务id,再任务进行时，用来校验数据，不再进行数据库查询
            commonService.saveExecuteFlowData2Redis(instanceId, this.buildInstanceRuntimeData(jyjcOpeningApplication));
            return jyjcOpeningApplication;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
        return null;
    }

    private InstanceRuntimeData buildInstanceRuntimeData(JyjcOpeningApplicationModel jyjcOpeningApplication) {
        return InstanceRuntimeData.builder()
                .nextExecuteUserIds(jyjcOpeningApplication.getNextExecuteUserIds())
                .promoter(jyjcOpeningApplication.getPromoter())
                .nextTaskId(jyjcOpeningApplication.getNextTaskId())
                .build();
    }

    private InstanceRuntimeData buildInstanceRuntimeData(JyjcOpeningApplication jyjcOpeningApplication) {
        return InstanceRuntimeData.builder()
                .nextExecuteUserIds(jyjcOpeningApplication.getNextExecuteUserIds())
                .promoter(jyjcOpeningApplication.getPromoter())
                .nextTaskId(jyjcOpeningApplication.getNextTaskId())
                .build();
    }


    public List<Map<String, Object>> selectForFlowStatusList() {
        return Arrays.stream(FlowStatusEnum.values()).map(this::mapPointTypeToMap).collect(Collectors.toList());
    }

    private Map<String, Object> mapPointTypeToMap(FlowStatusEnum e) {
        Map<String, Object> record = new HashMap<>();
        record.put("key", e.getCode());
        record.put("label", e.getName());
        return record;
    }

    public Boolean deleteBatchByIds(List<Long> ids) {
        List<JyjcOpeningApplication> jyjcOpeningApplicationList = jyjcOpeningApplicationMapper.selectList(new QueryWrapper<JyjcOpeningApplication>()
                .in("sequence_nbr"));
        List<String> status = Arrays.asList(String.valueOf(FlowStatusEnum.TO_BE_PROCESSED.getCode()), String.valueOf(FlowStatusEnum.TO_BE_FINISHED.getCode()));
        jyjcOpeningApplicationList = jyjcOpeningApplicationList.stream().filter(jyjcOpeningApplication -> status.contains(jyjcOpeningApplication.getStatus())).collect(Collectors.toList());
        if (jyjcOpeningApplicationList.isEmpty()) {
            throw new BadRequest("除撤回跟驳回的流程之外其余流程不可删除，请核对数据后重新提交！");
        }
        deleteBatchByIds(ids);
        return true;
    }

    public List<TzBaseEnterpriseInfoDto> getInspectionUnitList() {
        List<TzBaseEnterpriseInfoDto> tzBaseEnterpriseInfos = enterpriseInfoMapper.getInspectionUnitList(null);
        if (ValidationUtil.isEmpty(tzBaseEnterpriseInfos)) {
            return Collections.EMPTY_LIST;
        }
        List<String> unitCodes = this.lambdaQuery().select(JyjcOpeningApplication::getUnitCode).list().stream().map(JyjcOpeningApplication::getUnitCode).collect(Collectors.toList());
        // 根据开通机构过滤
        return tzBaseEnterpriseInfos.stream().filter(o -> StringUtils.isNotBlank(o.getUseCode()) && unitCodes.contains(o.getUseCode())).collect(Collectors.toList());
    }

    public List<Long> selectOverdueData() {
        return jyjcOpeningApplicationMapper.selectOverdueData();

    }


    private void buildTask(JyjcOpeningApplicationModel model, WorkflowResultDto workflowResultDto) {
        ReginParams reginParams = commonService.getReginParamsOfCurrentUser();
        // 代办消息
        ArrayList<TaskModelDto> list = new ArrayList<>();
        TaskModelDto dto = new TaskModelDto();
        dto.setTaskType(BusinessTypeEnum.JY_OPENING_APPLICATION.getCode());
        dto.setTaskTypeLabel(BizTypeEnum.BUSINESS_OPEN.getName());
        dto.setFlowCreateDate(model.getRecDate());
        dto.setTaskName(workflowResultDto.getNextTaskName());
        dto.setTaskCode(workflowResultDto.getNextTaskCode());
        dto.setTaskContent(String.format("检验检测业务开通办理，【申请单号：%s】", model.getApplicationSeq()));
        dto.setRelationId(workflowResultDto.getInstanceId());
        dto.setExecuteUserIds(workflowResultDto.getNextExecutorUserIds());
        dto.setTaskStatus(FlowStatusEnum.TO_BE_PROCESSED.getCode());
        dto.setTaskStatusLabel(FlowStatusEnum.TO_BE_PROCESSED.getName());
        dto.setFlowStatus(FlowStatusEnum.TO_BE_PROCESSED.getCode());
        dto.setFlowStatusLabel(FlowStatusEnum.TO_BE_PROCESSED.getName());
        dto.setStartUserId(reginParams.getUserModel().getUserId());
        dto.setStartUser(reginParams.getUserModel().getRealName());
        dto.setStartUserCompanyName(reginParams.getCompany().getCompanyName());
        dto.setStartDate(new Date());
        model.setWorkflowProstanceId(workflowResultDto.getInstanceId());
        model.setNextExecuteIds(workflowResultDto.getNextExecutorRoleIds());
        JyjcOpeningApplicationModel urlParms = new JyjcOpeningApplicationModel();
        BeanUtil.copyProperties(model, urlParms, "unitCode", "unitAddress", "unitCodeName", "detectionRegion", "detectionRegionName", "applicationSeq", "resultType", "expiryDate", "acceptDate", "remark", "applyTime", "baseUnitLicences", "userInfos", "useContact", "contactPhone", "industrySupervisor", "longitude", "latitude", "geographic", "unitBusinessLicense");
        dto.setModel(urlParms);
        dto.setNextExecuteUser(workflowResultDto.getNextExecutorRoleIds());
        dto.setPageType("look");
        list.add(dto);
        taskModelService.buildTaskModel(list);
    }

    private void updateTask(JyjcOpeningApplication model, WorkflowResultDto workflowResultDto, String op) {
        // 更新代办状态
        HashMap<String, Object> params = new HashMap<>();
        params.put("relationId", model.getWorkflowProstanceId());
        params.put("flowStatus", model.getStatus());
        params.put("flowStatusLabel", model.getStatus());
        params.put("taskStatus", model.getStatus());
        params.put("taskStatusLabel", model.getStatus());
        TaskV2Model taskV2Model = taskModelService.updateTaskModel(params);
        // 创建新的代办
        if (!ObjectUtils.isEmpty(taskV2Model)) {
            TaskModelDto taskModelDto = new TaskModelDto();
            BeanUtils.copyProperties(taskV2Model, taskModelDto);
            JyjcOpeningApplication urlParms = new JyjcOpeningApplication();
            BeanUtil.copyProperties(model, urlParms, "unitCode", "unitAddress", "unitCodeName", "detectionRegion", "detectionRegionName", "applicationSeq", "resultType", "expiryDate", "acceptDate", "remark", "applyTime", "baseUnitLicences", "userInfos", "useContact", "contactPhone", "industrySupervisor", "longitude", "latitude", "geographic", "unitBusinessLicense");
            taskModelDto.setModel(urlParms);
            taskModelDto.setTaskName(workflowResultDto.getNextTaskName());
            taskModelDto.setExecuteUserIds(workflowResultDto.getNextExecutorUserIds());
            if ("0".equals(op)) {
                taskModelDto.setTaskStatusLabel(FlowStatusEnum.TO_BE_PROCESSED.getName());
                taskModelDto.setTaskStatus(FlowStatusEnum.TO_BE_PROCESSED.getCode());
                taskModelDto.setFlowStatus(FlowStatusEnum.TO_BE_PROCESSED.getCode());
                taskModelDto.setFlowStatusLabel(FlowStatusEnum.TO_BE_PROCESSED.getName());
            } else {
                taskModelDto.setTaskStatusLabel(FlowStatusEnum.REJECTED.getName());
                taskModelDto.setTaskStatus(FlowStatusEnum.REJECTED.getCode());
                taskModelDto.setFlowStatus(FlowStatusEnum.REJECTED.getCode());
                taskModelDto.setFlowStatusLabel(FlowStatusEnum.REJECTED.getName());
                taskModelDto.setPageType("edit");
            }

            taskModelDto.setNextExecuteUser(workflowResultDto.getNextExecutorRoleIds());
            taskModelService.buildTaskModel(Collections.singletonList(taskModelDto));
        } else {
            JyjcOpeningApplicationModel applicationModel = new JyjcOpeningApplicationModel();
            BeanUtil.copyProperties(model, applicationModel);
            buildTask(applicationModel, workflowResultDto);
        }
    }

    @Override
    public List<TzBaseEnterpriseInfoDto> getUnitListByRecord(String record) {
        return this.getInspectionUnitList(new ArrayList<>(), true, record, OpenBizTypeEnum.JC.getCode());
    }

    private List<TzBaseEnterpriseInfoDto> getInspectionUnitList(List<TzBaseUnitLicence> unitLicenceList, Boolean isMatchArea, String record, String openBizType) {
        // 是否进行属地过滤
        String areaCode = isMatchArea ? ruleCommonService.getArea(record) : "";
        // 所有符合单位的code
        Set<String> unitCodes = unitLicenceList.stream().map(TzBaseUnitLicence::getUnitCode).collect(Collectors.toSet());
        List<TzBaseEnterpriseInfoDto> matchEnterpriseInfos = new ArrayList<>();
        // 按照资质 + areaCode，进行设备单位的筛选
        if (unitCodes.size() > 0) {
            matchEnterpriseInfos = tzBaseEnterpriseInfoMapper.getInspectionUnitListByCode(new ArrayList<>(unitCodes), areaCode, openBizType);
        }
        if (matchEnterpriseInfos.isEmpty()) {
            log.info("按照资质、区域未匹配到对应的单位、按照地市未匹配到单位，将返回全部单位");
            return tzBaseEnterpriseInfoMapper.getInspectionUnitListByCode(null, null, openBizType);
        }
        return matchEnterpriseInfos;
    }

    /**
     * 缓存当前正在流程中的实例的流程数据
     */
    public void initFlowData2Redis() {
        LambdaQueryWrapper<JyjcOpeningApplication> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(JyjcOpeningApplication::getStatus, FlowStatusEnum.TO_BE_FINISHED.getCode());
        queryWrapper.ne(JyjcOpeningApplication::getStatus, FlowStatusEnum.TO_BE_DISCARD.getCode());
        queryWrapper.isNotNull(JyjcOpeningApplication::getWorkflowProstanceId);
        queryWrapper.select(JyjcOpeningApplication::getWorkflowProstanceId, JyjcOpeningApplication::getNextTaskId, JyjcOpeningApplication::getPromoter, JyjcOpeningApplication::getNextExecuteUserIds);
        List<JyjcOpeningApplication> openingApplicationListInFlowing = this.list(queryWrapper);
        openingApplicationListInFlowing.forEach(inspectionApplication -> {
            commonService.saveExecuteFlowData2Redis(inspectionApplication.getWorkflowProstanceId(), this.buildInstanceRuntimeData(inspectionApplication));
        });
    }

    public List<InspectionCompanyPublicityDto> queryInspectionOrgListForBiz() {
        // 查询所有已经业务开通的检验检测机构，已机构为维度进行证的合并处理
        List<InspectionCompanyPublicityDto> inspectionCompanyPublicityDtos =  this.getBaseMapper().queryInspectionOrgListForBiz();
        // 枚举转换
        inspectionCompanyPublicityDtos.forEach(c->{
            c.setDetectionRegion(this.castRegionCode2Name(c.getDetectionRegion()));
            c.setApprovalInfo(this.breakNewLineForApprovalInfo(c.getApprovalInfo()));
            c.setOpenBizType(this.castOpenBizTypeCode2Name(c.getOpenBizType()));
        });
        return inspectionCompanyPublicityDtos;
    }

    private String castRegionCode2Name(String detectionRegion) {
        return "";
    }

    private String breakNewLineForApprovalInfo(String approvalInfo) {
        String[] approvalArray = approvalInfo.split("#");
        StringBuilder stringBuilder = new StringBuilder();
        return "";
    }

    private String castOpenBizTypeCode2Name(String openBizType) {
        return OpenBizTypeEnum.getOneByCode(openBizType).getName();
    }
}