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.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.controller.BaseController;
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.enums.BizTypeEnum;
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.*;
import com.yeejoin.amos.boot.module.jyjc.api.service.IJyjcOpeningApplicationService;
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.jyjc.biz.service.TaskModelServiceImpl;
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.component.feign.utils.FeignUtil;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.systemctl.model.TaskV2Model;
import com.yeejoin.amos.feign.workflow.Workflow;
import com.yeejoin.amos.feign.workflow.model.*;
import org.apache.commons.io.IOUtils;
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.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

import static com.alibaba.fastjson.JSON.parseArray;


/**
 * 服务实现类
 *
 * @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;
    @Value("classpath:/json/bizTypeInfo.json")
    private org.springframework.core.io.Resource bizTypeInfo;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private TzBaseUnitLicenceMapper unitLicenceMapper;
    @Autowired
    private TzBaseEnterpriseInfoMapper enterpriseInfoMapper;
    @Autowired
    private TzsUserInfoMapper userInfoMapper;
    @Autowired
    CommonserviceImpl commonservice;
    @Autowired
    private WorkflowHelper workflowHelper;
    @Autowired
    private WorkflowFeignClient workflowFeignClient;
    @Autowired
    CmWorkflowServiceImpl cmWorkflowService;
    @Autowired
    TaskModelServiceImpl commonServiceImpl;

    @Transactional(rollbackFor = {Exception.class, BaseException.class})
    public JyjcOpeningApplicationModel saveOrUpdateModel(JyjcOpeningApplicationModel model, Boolean enableStartFlow) {
        boolean isUpdate = false;
        String instanceId = null;
        JyjcOpeningApplication entity = null;
        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
                ActWorkflowBatchDTO actWorkflowBatchDTO = new ActWorkflowBatchDTO();
                ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
                ArrayList<ActWorkflowStartDTO> list = new ArrayList<>();
                dto.setProcessDefinitionKey(processDefinitionKey);
                dto.setBusinessKey("1");
                dto.setCompleteFirstTask(Boolean.TRUE);
                // 接受机构
//                    dto.setNextExecuteUserCompanyCode(jgUseRegistration.getReceiveCompanyCode());
                list.add(dto);
                actWorkflowBatchDTO.setProcess(list);
                List<ProcessTaskDTO> processTaskDTOS = cmWorkflowService.startBatch(actWorkflowBatchDTO);
                List<WorkflowResultDto> resultDto = commonServiceImpl.buildWorkFlowInfo(processTaskDTOS);
                if (!ObjectUtils.isEmpty(resultDto) && !ObjectUtils.isEmpty(resultDto.get(0))) {
                    WorkflowResultDto workflowResultDto = resultDto.get(0);
                    model.setWorkflowProstanceId(workflowResultDto.getInstanceId());
                    model.setNextExecuteIds(workflowResultDto.getNextExecutorRoleIds());
                    model.setNextTaskId(workflowResultDto.getNextTaskId());
                    model.setNextExecuteUserIds(workflowResultDto.getNextExecutorUserIds());
                }
            } else {
                // 存在流程，执行
                TaskResultDTO dto = new TaskResultDTO();
                dto.setResultCode("approvalStatus");
                dto.setTaskId(model.getNextTaskId());
                HashMap<String, Object> map = new HashMap<>();
                map.put("approvalStatus", "提交");
                dto.setVariable(map);
                ProcessTaskDTO complete = cmWorkflowService.complete(model.getNextTaskId(), dto);
                ArrayList<ProcessTaskDTO> processTaskDTOS = new ArrayList<>();
                processTaskDTOS.add(complete);
                List<WorkflowResultDto> resultDto = commonServiceImpl.buildWorkFlowInfo(processTaskDTOS);
                if (!ObjectUtils.isEmpty(resultDto) && !ObjectUtils.isEmpty(resultDto.get(0))) {
                    WorkflowResultDto workflowResult = resultDto.get(0);
                    model.setWorkflowProstanceId(workflowResult.getInstanceId());
                    model.setNextExecuteIds(workflowResult.getNextExecutorRoleIds());
                    model.setNextTaskId(workflowResult.getNextTaskId());
                    model.setNextExecuteUserIds(workflowResult.getNextExecutorUserIds());
                }
            }
            model.setStatus(FlowStatusEnum.TO_BE_PROCESSED.getCode() + "");
            model.setApplyTime(new Date());
        } else {
            // 只有第一次改为待提交
            if (entity == null) {
                model.setStatus(FlowStatusEnum.TO_BE_SUBMITTED.getCode() + "");
            }
        }
        if (!isUpdate) {
            CompanyBo companyBo = commonserviceImpl.getReginParamsOfCurrentUser().getCompany();
            model.setUnitCode(companyBo.getCompanyCode());
            model.setUnitCodeName(companyBo.getCompanyName());
            List<String> codes = tzsServiceFeignClient.applicationFormCode(ApplicationFormTypeEnum.JY.getCode(), 1).getResult();
            model.setApplicationSeq(codes.get(0));
            model.setCreateUserId(reginParams.getUserModel().getUserId());
            model = this.createWithModel(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(String.valueOf(BizTypeEnum.BUSINESS_OPEN.getCode()));
            // 业务主键
            dto.setRelationId(String.valueOf(model.getSequenceNbr()));
            dto.setNextExecuteUser("");
            list.add(dto);
            commonServiceImpl.buildTaskModel(list);
            return model;
        } else {
            return this.updateWithModel(model);
        }

    }

    @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())
                     .set("remark", "到期作废")
                     .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 dto) {
        ReginParams reginParams = commonserviceImpl.getReginParamsOfCurrentUser();
        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";
        }
        return jyjcOpeningApplicationMapper.selectJyjcOpeningApplicationList(page, dto, 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();
        }
        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);
        if (StringUtils.isBlank(jyjcOpeningApplicationModel.getWorkflowProstanceId())) {
            // 如果未开启流程则只查询未被删除的用户
            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)  {
//        // 重新开启工作流
//        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() + "";
                params.put("relationId",instanceId);
                params.put("taskStatus",FlowStatusEnum.TO_BE_FINISHED.getCode());
                params.put("taskStatusLabel",FlowStatusEnum.TO_BE_FINISHED.getName());
                TaskV2Model taskV2Model = commonservice.updateTaskModel(params);
                String json = null;
                try {
                    json = IOUtils.toString(bizTypeInfo.getInputStream(), java.lang.String.valueOf(StandardCharsets.UTF_8));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                List<Map> list = parseArray(json, Map.class);
                String url = null;
                for (Map map : list) {
                    if (map.get("type").equals("opening" )&& "edit".equals(map.get("pageType"))){
                        url = map.get("url").toString();
                    }
                }
                taskV2Model.setRoutePath(url);
                Map<String, Object> nextNodeInfo = workflowHelper.getNextWorkflowNode(instanceId);
                String roles = (String) nextNodeInfo.get("role");
                taskV2Model.setExecuteUserIds(roles);

                commonservice.buildTaskModel(BeanUtil.beanToMap(taskV2Model));
            } else {
                if ("流程结束".equals(taskName)) {
                    status = FlowStatusEnum.TO_BE_FINISHED.getCode() + "";
                    params.put("taskStatus",FlowStatusEnum.TO_BE_FINISHED.getCode());
                    params.put("taskStatusLabel",FlowStatusEnum.TO_BE_FINISHED.getName());
                    TaskV2Model taskV2Model = commonservice.updateTaskModel(params);
                } 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);
            commonservice.deleteTaskModel(jyjcOpeningApplication.getWorkflowProstanceId());
            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());
    }

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

    }
}