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

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.UpdateWrapper;
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.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.dto.AttachmentDto;
import com.yeejoin.amos.boot.module.jyjc.api.entity.JyjcOpeningApplication;
import com.yeejoin.amos.boot.module.jyjc.api.mapper.JyjcBaseMapper;
import com.yeejoin.amos.boot.module.jyjc.api.mapper.JyjcOpeningApplicationMapper;
import com.yeejoin.amos.boot.module.jyjc.api.model.JyjcGeographicModel;
import com.yeejoin.amos.boot.module.jyjc.api.model.JyjcOpeningApplicationRequstDto;
import com.yeejoin.amos.boot.module.jyjc.api.service.IJyjcOpeningApplicationService;
import com.yeejoin.amos.boot.module.jyjc.api.model.JyjcOpeningApplicationModel;
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.feign.WorkflowFeignClient;
import com.yeejoin.amos.boot.module.ymt.api.dto.TzBaseUnitLicenceDto;
import com.yeejoin.amos.boot.module.ymt.api.dto.TzsUserInfoDto;
import com.yeejoin.amos.boot.module.ymt.api.entity.TzBaseEnterpriseInfo;
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.TzBaseEnterpriseInfoMapper;
import com.yeejoin.amos.boot.module.ymt.api.mapper.TzBaseUnitLicenceMapper;
import com.yeejoin.amos.boot.module.ymt.api.mapper.TzsUserInfoMapper;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.workflow.Workflow;
import com.yeejoin.amos.feign.workflow.model.ActWorkflowStartDTO;
import com.yeejoin.amos.feign.workflow.model.AjaxResult;
import com.yeejoin.amos.feign.workflow.model.TaskResultDTO;
import org.apache.commons.lang3.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.annotation.Resource;
import java.util.*;
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
    CommonserviceImpl commonserviceImpl;
    @Autowired
    private TzsServiceFeignClient tzsServiceFeignClient;
    @Autowired
    JyjcOpeningApplicationMapper jyjcOpeningApplicationMapper;

    @Resource(type = JyjcBaseMapper.class)
    private JyjcBaseMapper baseMapper;

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

    @Value("${jyjc.user-post:6615}")
    private String jyjcUserPost;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private TzBaseUnitLicenceMapper unitLicenceMapper;
    @Autowired
    private TzBaseEnterpriseInfoMapper enterpriseInfoMapper;
    @Autowired
    private TzsUserInfoMapper userInfoMapper;

    @Autowired
    private WorkflowHelper workflowHelper;
    @Autowired
    private WorkflowFeignClient workflowFeignClient;

    @Transactional(rollbackFor = {Exception.class, BaseException.class})
    public JyjcOpeningApplicationModel saveOrUpdateModel(JyjcOpeningApplicationModel model, Boolean enableStartFlow) {
        boolean isUpdate = false;
        String instanceId = null;
        JyjcOpeningApplication entity = null;
        try {
            if (model.getSequenceNbr() != null) {
                entity = jyjcOpeningApplicationMapper.selectById(model.getSequenceNbr());
                if (entity != null) {
                    instanceId = entity.getWorkflowProstanceId();
                    isUpdate = true;
                }
            }
            ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
            if (enableStartFlow) {
                if (StringUtils.isBlank(instanceId)) {
                    // 未开启过工作流则进行开启 startProcess
                    instanceId = startFlow("1");
                }
                model.setStatus(FlowStatusEnum.TO_BE_PROCESSED.getCode() + "");
                // model.setStatusName(FlowStatusEnum.TO_BE_PROCESSED.getName());
                model.setApplyTime(new Date());
                model.setWorkflowProstanceId(instanceId);
                // 默认自动执行第一步
                execueFlowNoBusiness(MapBuilder.<String, Object>create().put("op", "0").put("instanceId", instanceId).put("comments", "").build());
                // 查询下节点任务
                Map<String, Object> nextNodeInfo = workflowHelper.getNextWorkflowNode(instanceId);
                String role = (String) nextNodeInfo.get("role");
                model.setNextExecuteIds(role);
                model.setPromoter(reginParams.getUserModel().getUserId());
                if (!org.springframework.util.ObjectUtils.isEmpty(model.getWorkflowRole())) {
                    model.setWorkflowRole(model.getWorkflowRole() + "," + role);
                } else {
                    model.setWorkflowRole(role);
                }
            } else {
                // 只有第一次改为待提交
                if (entity == null) {
                    model.setStatus(FlowStatusEnum.TO_BE_SUBMITTED.getCode() + "");
                    // model.setStatusName(FlowStatusEnum.TO_BE_SUBMITTED.getName());
                }
            }
            if (!isUpdate) {
                CompanyBo companyBo = commonserviceImpl.getReginParamsOfCurrentUser().getCompany();
                model.setUnitCode(companyBo.getCompanyCode());
                model.setUnitCodeName(companyBo.getCompanyName());
                // ResponseModel<Map<String, Object>> result = tzsServiceFeignClient.applicationFormCode(ApplicationFormTypeEnum.JY.getCode(), 1);
                List<String> codes = tzsServiceFeignClient.applicationFormCode(ApplicationFormTypeEnum.JY.getCode(), 1).getResult();

                //List<String> codes = createCodeService.createApplicationFormCode(ApplicationFormTypeEnum.JY.getCode(), 1);
                model.setApplicationSeq(codes.get(0));
                model.setCreateUserId(reginParams.getUserModel().getUserId());
                model = this.createWithModel(model);
                return model;
            } else {
                return this.updateWithModel(model);
            }
        } catch (Exception e) {
            log.error("saveModel: model={} error", model, e);
            throw new BaseException(e.getMessage());
        }
    }

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

    public void updateModelByInstanceId(Long sequenceNbr, String instanceId, String status, String role, Boolean rollBack) {
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        LambdaQueryWrapper<JyjcOpeningApplication> lambda = new QueryWrapper<JyjcOpeningApplication>().lambda();
        lambda.eq(JyjcOpeningApplication::getSequenceNbr, sequenceNbr);
        JyjcOpeningApplication entity = this.getBaseMapper().selectOne(lambda);
        // JyjcOpeningApplication entity = this.lambdaQuery().eq(JyjcOpeningApplication::getWorkflowProstanceId, instanceId).one();
        if (entity == null) {
            return;
        }
        // JSONObject taskJson = getTask(instanceId);
        // if (taskJson == null) {
        //     log.warn("流程=>{}查询不到或已结束", instanceId);
        //     return;
        // }
        // entity.setWorkflowRole(getWorkflowRoleGroups(taskJson));
        // entity.setWorkflowActiveKey(taskJson.getString("taskDefinitionKey"));

        entity.setNextExecuteIds(role);
        entity.setPromoter(reginParams.getUserModel().getUserId());
        if (!org.springframework.util.ObjectUtils.isEmpty(entity.getWorkflowRole())) {
            entity.setWorkflowRole(entity.getWorkflowRole() + "," + role);
        } else {
            entity.setWorkflowRole(role);
        }
        entity.setStatus(status);
        // entity.setStatusName(FlowStatusEnum.getNameByType(Long.parseLong(status)));
        // region 更新其他的数据为已作废
        if (String.valueOf(FlowStatusEnum.TO_BE_FINISHED.getCode()).equals(status)) {
            doDiscard(entity.getUnitCode(), entity.getSequenceNbr());
            entity.setAcceptDate(new Date());
        }
        // endregion
        this.updateById(entity);
        if (rollBack) {
            this.getBaseMapper().updatePromoter(entity.getSequenceNbr());
        }
    }

    /**
     * 完成的时候废弃其他已完成的申请单
     *
     *
     * @param unitCode unitCode
     * @param sequenceNbr sequenceNbr
     * @return {@link  Boolean}
     * @author yangyang
     * @throws
     * @date 2023/12/22 09:23
     */
    public Boolean doDiscard(String unitCode, Long sequenceNbr) {
        if (StringUtils.isBlank(unitCode) || sequenceNbr == null) {
            return false;
        }
        List<Long> ids = this.lambdaQuery().select(JyjcOpeningApplication::getSequenceNbr)
                             .eq(JyjcOpeningApplication::getUnitCode, unitCode)
                             .eq(JyjcOpeningApplication::getStatus, FlowStatusEnum.TO_BE_FINISHED.getCode())
                             .list().stream().filter(o -> o.getSequenceNbr().compareTo(sequenceNbr) != 0)
                             .map(JyjcOpeningApplication::getSequenceNbr).collect(Collectors.toList());
        if (ValidationUtil.isEmpty(ids)) {
            return false;
        }
        UpdateWrapper<JyjcOpeningApplication> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("status", FlowStatusEnum.TO_BE_DISCARD.getCode()).set("status_name", FlowStatusEnum.TO_BE_DISCARD.getName()).in("SEQUENCE_NBR", ids);
        return 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 Page<JyjcOpeningApplicationModel> queryForJyjcOpeningApplicationPage(Page<JyjcOpeningApplicationModel> page) {
        return this.queryForPage(page, null, false);
    }

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

    public Page<JyjcOpeningApplicationModel> queryForJyjcOpeningApplicationPage(Page<JyjcOpeningApplication> page, JyjcOpeningApplicationRequstDto jyjcOpeningApplicationRequstDto) {
        String applyStartTime = "";
        String applyEndTime = "";
        if (ObjectUtils.isNotEmpty(jyjcOpeningApplicationRequstDto.getApplyTime())) {
            String date = jyjcOpeningApplicationRequstDto.getApplyTime();
            applyStartTime = date + " 00:00:00";
            applyEndTime = date + " 23:59:59";
        }
        // 设置为监管端
        jyjcOpeningApplicationRequstDto.setType("supervision");
        return jyjcOpeningApplicationMapper.selectJyjcOpeningApplicationList(page, jyjcOpeningApplicationRequstDto, applyStartTime, applyEndTime);
    }

    public Page<JyjcOpeningApplicationModel> querypageForCompany(Page<JyjcOpeningApplication> page, JyjcOpeningApplicationRequstDto jyjcOpeningApplicationRequstDto) {
        //根据申请单中的单位信息对于列表数据进行过滤
        CompanyBo companyBo = commonserviceImpl.getReginParamsOfCurrentUser().getCompany();
//        if (companyBo.getLevel().equals("company")) {
            jyjcOpeningApplicationRequstDto.setUnitCode(companyBo.getCompanyCode());
//        }

        String applyStartTime = "";
        String applyEndTime = "";
        if (ObjectUtils.isNotEmpty(jyjcOpeningApplicationRequstDto.getApplyTime())) {
            String date = jyjcOpeningApplicationRequstDto.getApplyTime();
            applyStartTime = date + " 00:00:00";
            applyEndTime = date + " 23:59:59";
        }
        jyjcOpeningApplicationRequstDto.setType("enterprise");
        return jyjcOpeningApplicationMapper.selectJyjcOpeningApplicationList(page, jyjcOpeningApplicationRequstDto, applyStartTime, applyEndTime);
    }


    /**
     * 获取详情跳转
     *
     * @param
     * @return {@link }
     * @throws
     * @author yangyang
     */
    public JyjcOpeningApplicationModel queryDetail(Long sequenceNbr) {
        ReginParams reginParams = commonserviceImpl.getReginParamsOfCurrentUser();
        if (ValidationUtil.isEmpty(reginParams.getCompany())) {
            throw new RuntimeException("未指定人员归属单位信息");
        }
        String unitCode;
        JyjcOpeningApplicationModel jyjcOpeningApplicationModel;
        if (null != sequenceNbr) {
            jyjcOpeningApplicationModel = this.queryBySeq(sequenceNbr);
            unitCode = jyjcOpeningApplicationModel.getUnitCode();
        } else {
            jyjcOpeningApplicationModel = new JyjcOpeningApplicationModel();
            unitCode = reginParams.getCompany().getCompanyCode();
        }
        // unitCode = "91611103MAC4Q1EG7B"; // 测试用，之后务必删除！！！
        QueryWrapper enterpriseInfoQueryWrapper = new QueryWrapper<>();
        enterpriseInfoQueryWrapper.eq("use_code", 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())) {
                List<Map<String, String>> dicts = baseMapper.selectDataDictionaryList(Arrays.asList(baseUnitLicenceEntity.getIndustrySupervisor()));
                if (!ValidationUtil.isEmpty(dicts)) {
                    jyjcOpeningApplicationModel.setIndustrySupervisor(dicts.get(0).get("name"));
                } else {
                    jyjcOpeningApplicationModel.setIndustrySupervisor(baseUnitLicenceEntity.getIndustrySupervisor());
                }
            }
            // {  "latitude": "34.311788",  "longitude": "108.948721"}
            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));
            }
        }
        // QueryWrapper unitLicenceQueryWrapper = new QueryWrapper<>();
        // unitLicenceQueryWrapper.eq("unit_code", unitCode);
        // unitLicenceQueryWrapper.eq("licence_type", LicenceTypeEnum.JYJC.getCode());
        // List<TzBaseUnitLicenceDto> baseUnitLicences = Bean.toModels(unitLicenceMapper.selectList(unitLicenceQueryWrapper), TzBaseUnitLicenceDto.class );
        //
        List<TzBaseUnitLicenceDto> baseUnitLicences = baseMapper.selectBaseUnitLicenceList(MapBuilder.<String, Object>create().put("unitCode", unitCode).put("licenceType", "jyjc").build());
        jyjcOpeningApplicationModel.setBaseUnitLicences(baseUnitLicences);
        // 获取检验人员信息
        QueryWrapper userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("unit_code", unitCode);
        userInfoQueryWrapper.eq("is_delete", false);
        List<TzsUserInfo> userInfos = userInfoMapper.selectList(userInfoQueryWrapper);
        if (!ValidationUtil.isEmpty(userInfos)) {
            // List<String> codes = userInfos.stream()
            //                            .map(o -> o.getPost() != null ? JSON.parseArray(o.getPost(), String.class) : null)
            //                            .filter(Objects::nonNull)
            //                            .collect(Collectors.toList())
            //                            .stream().flatMap(o -> o.stream()).distinct().collect(Collectors.toList());
            // List<Map<String, String>> dicts = baseMapper.selectDataDictionaryList(codes);
            List<TzsUserInfoDto> userInfoDtos = userInfos.stream().map(o -> {
                TzsUserInfoDto dto = new TzsUserInfoDto();
                Bean.toModel(o, dto);
                // 字段不要了
                // if (o.getPost() != null) {
                //    List<String> temps = JSON.parseArray(o.getPost(), String.class);
                //    String postName = temps.stream().map(m -> dicts.stream().filter(dict -> dict.get("code").equals(m)).findFirst().map(n -> n.get("name")).orElse("")).collect(Collectors.joining(","));
                //    dto.setPostName(postName);
                // }
                return dto;
            }).filter(o -> o.getPost() != null && o.getPost().contains(jyjcUserPost)).collect(Collectors.toList());
            jyjcOpeningApplicationModel.setUserInfos(userInfoDtos);
        }
        return jyjcOpeningApplicationModel;
    }

    public String startFlow(String businessKey) throws Exception {
        // 重新开启工作流
        ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
        dto.setProcessDefinitionKey(processDefinitionKey);
        dto.setBusinessKey(StringUtils.defaultString(businessKey, "1"));
        // dto.setCompleteFirstTask(true);
        // FeignClientResult ajaxResult = Workflow.taskV2Client.startByVariable(dto);
        //
        // if (log.isDebugEnabled()) {
        //     log.debug("开启工作流结果：{}", ajaxResult);
        // }
        // if (ajaxResult == null || 200 != ajaxResult.getStatus()) {
        //     throw new BaseException("开启工作流错误");
        // }
        // return ((Map) ajaxResult.getResult()).get("id").toString();
        // V1
        AjaxResult ajaxResult = Workflow.taskClient.startByVariable(dto);
        if (log.isDebugEnabled()) {
            log.debug("开启工作流结果：{}", ajaxResult);
        }
        if (ajaxResult == null || (ajaxResult.get(AjaxResult.CODE_TAG) != null && !"200".equals(ajaxResult.get(AjaxResult.CODE_TAG).toString()))) {
            throw new BaseException("开启工作流错误");
        }
        return ((Map) ajaxResult.get("data")).get("id").toString();
    }


    /**
     * 接收/驳回通知检验单
     */
    public void execueFlowNoBusiness(Map<String, Object> params) {
        String op = params.get("op").toString();
        String instanceId = params.get("instanceId").toString();
        String comments = params.get("comments").toString();
        try {
            AjaxResult ajaxResult = Workflow.taskClient.getTaskNoAuth(instanceId);
            JSONObject dataObject = JSON.parseObject(JSON.toJSONString(ajaxResult.get("data")));
            String taskId = dataObject.getString("id");
            //组装信息
            TaskResultDTO dto = new TaskResultDTO();
//            dto.setResult(op);
            dto.setResultCode("approvalStatus");
            dto.setTaskId(taskId);
            HashMap<String, Object> varibalble = new HashMap<>();
            varibalble.put("approvalStatus", op);
            dto.setVariable(varibalble);
            dto.setComment(comments);
            //执行流程
            Workflow.taskClient.completeByTask(taskId, dto);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("execueFlow error:{}", e);
        }
    }


    /**
     * 接收/驳回通知检验单
     */
    public void execueFlow(Map<String, Object> params) {
        String role = "";
        String taskName = "流程结束";
        Long sequenceNbr = Long.parseLong(params.get("sequenceNbr") + "");
        String op = params.get("op").toString();
        String instanceId = params.get("instanceId").toString();
        String comments = params.get("comments").toString();
        try {
            AjaxResult ajaxResult = Workflow.taskClient.getTaskNoAuth(instanceId);
            JSONObject dataObject = JSON.parseObject(JSON.toJSONString(ajaxResult.get("data")));
            if (!ValidationUtil.isEmpty(dataObject)) {
                String taskId = dataObject.getString("id");
                //组装信息
                TaskResultDTO dto = new TaskResultDTO();
                dto.setResultCode("approvalStatus");
                dto.setTaskId(taskId);
                HashMap<String, Object> varibalble = new HashMap<>();
                varibalble.put("approvalStatus", op);
                dto.setVariable(varibalble);
                dto.setComment(comments);
                //执行流程
                Workflow.taskClient.completeByTask(taskId, dto);
                // 查询下节点任务
                Map<String, Object> nextNodeInfo = workflowHelper.getNextWorkflowNode(instanceId);
                if ("0".equals(op) && ObjectUtils.isNotEmpty(params.get("originalDataId"))) {
                    String originalDataId = params.get("originalDataId").toString();
                    JyjcOpeningApplication jyjcOpeningApplication = jyjcOpeningApplicationMapper.selectById(originalDataId);
                    List<String> detectionRegion = (List<String>) params.get("detectionRegion");
//                String detectionRegionName =  params.get("detectionRegionName").toString();
                    if(!detectionRegion.isEmpty()){
                        jyjcOpeningApplication.setDetectionRegion(detectionRegion);
                    }
//                jyjcOpeningApplication.setDetectionRegionName(detectionRegionName);
//                     if(ObjectUtils.isEmpty(jyjcOpeningApplication.getAcceptDate())){
//                         jyjcOpeningApplication.setAcceptDate(new Date());
//                     }
                    jyjcOpeningApplicationMapper.updateById(jyjcOpeningApplication);
                }
                role = (String) nextNodeInfo.get("role");
                taskName = (String) nextNodeInfo.get("taskName");
            }
            String status;
            if ("1".equals(op)) {
                // 如果是回退, 则业务状态改为驳回
                status = FlowStatusEnum.REJECTED.getCode() + "";
            } else {
                if ("流程结束".equals(taskName)) {
                    status = FlowStatusEnum.TO_BE_FINISHED.getCode() + "";
                } else {
                    status = FlowStatusEnum.TO_BE_PROCESSED.getCode() + "";
                }
            }
            Boolean rollBack = "1".equals(op) ? true : false;
            updateModelByInstanceId(sequenceNbr, instanceId, status, role, rollBack);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("execueFlow error:{}", e);
        }
    }



    /**
     * 撤回流程办理单
     */
    public JSONObject stopFlow(String sequenceNbr) {
        JSONObject jsonObject= new JSONObject();
        JyjcOpeningApplication jyjcOpeningApplication = jyjcOpeningApplicationMapper.selectById(sequenceNbr);
        try {
            //撤回流程
             jsonObject = workflowFeignClient.rollBack(jyjcOpeningApplication.getWorkflowProstanceId());
            if (ObjectUtils.isEmpty(jsonObject)) {

            }
            Map<String, Object> nextNodeInfo = workflowHelper.getNextWorkflowNode(jyjcOpeningApplication.getWorkflowProstanceId());
            String role = (String) nextNodeInfo.get("role");
            Long id = Long.parseLong(sequenceNbr);
            updateModelByInstanceId(id, jyjcOpeningApplication.getWorkflowProstanceId(), FlowStatusEnum.ROLLBACK.getCode() + "", role, true);
        } catch (Exception e) {
            throw  new BadRequest("撤回流程失败，请联系管理员！");
        }
        return jsonObject;
    }

    private String getWorkflowStatus(JSONObject dataObject) {
        return !ValidationUtil.isEmpty(dataObject) && !ValidationUtil.isEmpty(dataObject.get("status")) ? String.valueOf(dataObject.get("status")) : "";
    }

    private String getWorkflowRoleGroups(JSONObject dataObject) {
        JSONArray executorArray = dataObject.getJSONObject("nodeInfo").getJSONArray("executor");
        if (!ValidationUtil.isEmpty(executorArray)) {
            return executorArray.stream().map(json -> Optional.ofNullable(((LinkedHashMap) json).get("groupId")).orElse("").toString()).collect(Collectors.joining(","));
        }
        return null;
    }

    private JSONObject getTask(String instanceId) {
        AjaxResult ajaxResult = Workflow.taskClient.getTaskNoAuth(instanceId);
        JSONObject dataObject = JSON.parseObject(JSON.toJSONString(ajaxResult.get("data")));
        String taskId = dataObject.getString("id");// 工作流ID
        FeignClientResult<JSONObject> nodeInfo = workflowFeignClient.getNodeInfotoken(RequestContext.getAppKey(), RequestContext.getProduct(), RequestContext.getToken(), taskId);
        dataObject.put("nodeInfo", nodeInfo.getResult());
        return dataObject;
    }

    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<TzBaseEnterpriseInfo> getInspectionUnitList() {
        List<TzBaseEnterpriseInfo> tzBaseEnterpriseInfos = enterpriseInfoMapper.getInspectionUnitList(CommonserviceImpl.UNIT_TYPE);
        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());
    }
}