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.enums.WorkFlowEnum;
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.enums.BusinessTypeEnum;
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.BeanUtils;
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;
            }
        }
        List<String> codes = tzsServiceFeignClient.applicationFormCode(ApplicationFormTypeEnum.JY.getCode(), 1).getResult();
        model.setApplicationSeq(codes.get(0));
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        model.setPromoter(reginParams.getUserModel().getUserId());
        if (!isUpdate) {
            CompanyBo companyBo = commonserviceImpl.getReginParamsOfCurrentUser().getCompany();
            model.setUnitCode(companyBo.getCompanyCode());
            model.setUnitCodeName(companyBo.getCompanyName());
            model.setCreateUserId(reginParams.getUserModel().getUserId());
            this.createWithModel(model);
        }
        if (enableStartFlow) {
            model.setStatus(String.valueOf(FlowStatusEnum.TO_BE_PROCESSED.getCode()));
            model.setApplyTime(new Date());
            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());
                    // 创建代办
                    buildTask(model, workflowResultDto);
                }
            } else {
                // 存在流程，执行
                HashMap<String, Object> map = new HashMap<>();
                map.put("sequenceNbr",model.getSequenceNbr());
                map.put("op", "0");
                map.put("comments", "提交");
                JyjcOpeningApplication jyjcOpeningApplication = execueFlow(map);
                model.setNextTaskId(jyjcOpeningApplication.getNextTaskId());
//                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.setPromoter(reginParams.getUserModel().getUserId());
//                    // 更新代办
//                }

            }

        } else {
            // 只有第一次改为待提交
            if (entity == null) {
                model.setStatus(FlowStatusEnum.TO_BE_SUBMITTED.getCode() + "");
                // 暂存生成代办逻辑
                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);
                commonServiceImpl.buildTaskModel(list);
            }
        }
        model.setStatusName(FlowStatusEnum.TO_BE_PROCESSED.getName());
       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 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());
        }
        return result;
    }

//    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();
            jyjcOpeningApplicationModel.setResultType("input");
            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 JyjcOpeningApplication execueFlow(Map<String, Object> params) {
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        Long sequenceNbr = Long.parseLong(params.get("sequenceNbr") + "");
        String op = params.get("op").toString();
        JyjcOpeningApplication data = jyjcOpeningApplicationMapper.selectById(sequenceNbr);
        //组装信息
        TaskResultDTO dto = new TaskResultDTO();
        dto.setResultCode("approvalStatus");
        dto.setTaskId(data.getNextTaskId());
        dto.setComment(params.get("comments").toString());
        HashMap<String, Object> map = new HashMap<>();
        map.put("approvalStatus", op);
        if (String.valueOf(FlowStatusEnum.ROLLBACK.getCode()).equals(data.getStatus()) || String.valueOf(FlowStatusEnum.REJECTED.getCode()).equals(data.getStatus())) {
            map.put("approvalStatus", "提交");
        }
        dto.setVariable(map);
        ProcessTaskDTO complete = new ProcessTaskDTO();
        if ("0".equals(op)){
             complete = cmWorkflowService.complete(data.getNextTaskId(), dto);
        }else {
             complete = cmWorkflowService.reject(data.getNextTaskId(), dto);

        }

        ArrayList<ProcessTaskDTO> processTaskDTOS = new ArrayList<>();
        processTaskDTOS.add(complete);
        List<WorkflowResultDto> resultDto = commonServiceImpl.buildWorkFlowInfo(processTaskDTOS);
        if (!org.springframework.util.ObjectUtils.isEmpty(resultDto) && !org.springframework.util.ObjectUtils.isEmpty(resultDto.get(0))) {
            WorkflowResultDto workflowResultDto = resultDto.get(0);
            if (!ObjectUtils.isEmpty(workflowResultDto.getNextTaskId())){
                if ("1".equals(op)) {
                    // 驳回
                    data.setStatus(String.valueOf(FlowStatusEnum.REJECTED.getCode()));
                    data.setStatusName(String.valueOf(FlowStatusEnum.REJECTED.getName()));
                    data.setPromoter("");

                }else {
                    data.setStatus(String.valueOf(FlowStatusEnum.TO_BE_PROCESSED.getCode()));
                    data.setStatusName(String.valueOf(FlowStatusEnum.TO_BE_PROCESSED.getName()));
                    data.setPromoter(reginParams.getUserModel().getUserId());
                }
                // 更新代办
                updateTask(data, workflowResultDto, op);
                data.setNextTaskId(workflowResultDto.getNextTaskId());
            }else {

                // 流程结束
                data.setStatus(String.valueOf(FlowStatusEnum.TO_BE_FINISHED.getCode()));
                //更新办理日期
                data.setAcceptDate( new Date());
                // 更新代办
                HashMap<String, Object> taskParams = new HashMap<>();
                taskParams.put("relationId", data.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", data);
                commonServiceImpl.updateTaskModel(taskParams);
                data.setStatusName(FlowStatusEnum.TO_BE_FINISHED.getName());
            }
        }
        jyjcOpeningApplicationMapper.updateById(data);
        // 已完成 作废逻辑
        if (String.valueOf(FlowStatusEnum.TO_BE_FINISHED.getCode()).equals(data.getStatus())){
            doDiscard(data.getUnitCode(), data.getSequenceNbr());
        }
        return data;
    }



    /**
     * 撤回流程办理单
     */
    public JyjcOpeningApplication stopFlow(String sequenceNbr) {
        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()));
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(jyjcOpeningApplication));
        List<WorkflowResultDto> resultDto = commonServiceImpl.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.setStatusName(FlowStatusEnum.ROLLBACK.getName());
        }
        jsonObject.put("nextTaskId", jyjcOpeningApplication.getNextTaskId());
        jsonObject.put("taskType", BusinessTypeEnum.JY_OPENING_APPLICATION.getCode());
        jsonObject.put("flowStatus", FlowStatusEnum.ROLLBACK.getCode());
        jsonObject.put("flowStatusLabel", FlowStatusEnum.ROLLBACK.getName());
        // 撤回删除代办
        commonServiceImpl.rollbackTask(jyjcOpeningApplication.getWorkflowProstanceId(), jsonObject);
        // 更新数据
        jyjcOpeningApplicationMapper.updateById(jyjcOpeningApplication);
        return jyjcOpeningApplication;
    }

    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();

    }


    public void buildTask(JyjcOpeningApplicationModel model, WorkflowResultDto workflowResultDto) {
        ReginParams reginParams = commonserviceImpl.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);
        commonServiceImpl.buildTaskModel(list);
    }

    public 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 = commonServiceImpl.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());
            commonServiceImpl.buildTaskModel(Collections.singletonList(taskModelDto));
        } else {
            JyjcOpeningApplicationModel applicationModel = new JyjcOpeningApplicationModel();
            BeanUtil.copyProperties(model, applicationModel);
            buildTask(applicationModel, workflowResultDto);
        }

    }
}