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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.service.IDataDictionaryService;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
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.model.InstanceRuntimeData;
import com.yeejoin.amos.boot.module.jyjc.api.model.TaskModelDto;
import com.yeejoin.amos.boot.module.jyjc.api.model.WorkflowResultDto;
import com.yeejoin.amos.boot.module.jyjc.biz.service.impl.CmWorkflowServiceImpl;
import com.yeejoin.amos.boot.module.jyjc.biz.service.impl.CommonServiceImpl;
import com.yeejoin.amos.boot.module.jyjc.biz.util.JsonUtils;
import com.yeejoin.amos.boot.module.ymt.api.enums.FlowStatusEnum;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.TaskV2Model;
import com.yeejoin.amos.feign.workflow.model.ActTaskDTO;
import com.yeejoin.amos.feign.workflow.model.FlowTaskVo;
import com.yeejoin.amos.feign.workflow.model.ProcessTaskDTO;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service
public class TaskModelServiceImpl {
    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    CommonServiceImpl commonService;

    @Autowired
    IDataDictionaryService iDataDictionaryService;

    @Value("classpath:/json/bizTypeInfo.json")
    private Resource urlInfo;

    @Autowired
    CmWorkflowServiceImpl cmWorkflowService;

    @Autowired
    JyjcBaseMapper jyjcBaseMapper;

    @Autowired
    RedissonClient redissonClient;


    public void deleteTaskModel(String id) {
        List<TaskV2Model> result = Systemctl.taskV2Client.selectListByRelationId(id).getResult();
        if (result.size() > 0) {
            List<Long> idList = result.stream().map(TaskV2Model::getSequenceNbr).collect(Collectors.toList());
            String ids = idList.stream().map(Object::toString).collect(Collectors.joining(","));
            Systemctl.taskV2Client.delete(ids);
        }
    }


    /**
     * 待办新增接口
     **/
    public void buildTaskModel(List<TaskModelDto> list) {
        List<TaskV2Model> taskV2Models = new ArrayList<>();
        for (TaskModelDto obj : list) {
            //判断是否是暂存 新增若无下一节点执行人即为暂存
            boolean flag = StringUtils.isEmpty(obj.getNextExecuteUser()) ? true : false;
            if (flag) {
                List<TaskV2Model> result = Systemctl.taskV2Client.selectListByRelationId(obj.getRelationId()).getResult();
                if (CollectionUtil.isNotEmpty(result) && result.size() > 0) {
                    TaskV2Model taskV2Model = result.get(0);
                    taskV2Model.setTaskContent(obj.getTaskContent());
                    Systemctl.taskV2Client.update(taskV2Model, taskV2Model.getSequenceNbr());
                    break;
                }
            }
            ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
            TaskV2Model model = new TaskV2Model();
            BeanUtil.copyProperties(obj, model);
            String urlParams = "";
            try {
                urlParams = "&" + toQueryParams(obj.getModel());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            List<Map> urlList = JsonUtils.getResourceList(urlInfo);
            for (Map map : urlList) {
                //获取暂存的可编辑页面url
                if (flag && map.get("type").equals(obj.getTaskType())
                        && map.get("pageType").equals("draft")) {
                    model.setRoutePath(map.get("url").toString() + urlParams);
                    break;
                }
                //其他逻辑均按详情页面获取
                else if (map.get("type").equals(obj.getTaskType())
                        && map.get("pageType").equals(null == obj.getPageType() ? "look" : obj.getPageType())) {
                    model.setRoutePath(map.get("url").toString().replace("{roleIds}", obj.getNextExecuteUser()) + urlParams + "&nextExecuteUserIds=" + model.getExecuteUserIds());
                    break;
                }
            }
            //是true则为暂存 除公共部分统一处理
            if (flag) {
                model.setFlowStatus(FlowStatusEnum.TO_BE_SUBMITTED.getCode());
                model.setFlowStatusLabel(FlowStatusEnum.TO_BE_SUBMITTED.getName());
                model.setStartUserId(RequestContext.getExeUserId());
                model.setStartUser(reginParams.getUserModel().getRealName());
                model.setStartUserCompanyName(reginParams.getCompany().getCompanyName());
                model.setStartDate(new Date());
                model.setExecuteUserIds(RequestContext.getExeUserId());
                model.setFlowCreateDate(new Date());
                model.setTaskStatus(FlowStatusEnum.TO_BE_SUBMITTED.getCode());
                model.setTaskTitle("有一条待提交的草稿");
                model.setTaskName(BizTypeEnum.getNameByNum(obj.getTaskType()));
                model.setTaskTypeLabel(BizTypeEnum.getNameByCode(obj.getTaskType()));
                //     model.setTaskContent("【申请单号:"+obj.getTaskCode()+"】待提交");
            } else {
                model.setTaskStatus(0);
                model.setTaskTitle(obj.getStartUser() + "发起了" + obj.getTaskName());
            }
            model.setFlowInstanceId(model.getRelationId());
            model.setTaskSource("workFlow");
            model.setExtras(JSON.toJSONString(obj.getModel()));
            model.setCreateDate(new Date());
            model.setRecUserId(RequestContext.getExeUserId());
            model.setAgencyCode(RequestContext.getAgencyCode());
            taskV2Models.add(model);

        }
        Systemctl.taskV2Client.batchAdd(taskV2Models);
    }


    public void updateTaskContentById(Map<String, Object> params) {
        List<TaskV2Model> result = Systemctl.taskV2Client.selectListByRelationId(params.get("relationId").toString()).getResult();
        List<TaskV2Model> collect = result.stream().sorted((r1, r2) -> r2.getSequenceNbr().compareTo(r1.getSequenceNbr())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(collect)) {
            collect.get(0).setTaskContent(params.getOrDefault("taskContent", "").toString());
            Systemctl.taskV2Client.update(collect.get(0), collect.get(0).getSequenceNbr());
        }
    }

    /**
     * 待办编辑接口
     * 参数
     * taskStatus
     * taskStatusLabel 操作名称  6614驳回 6616已完成 6612待受理
     * flowStatusLabel  任务状态枚举code
     * 流程实例id  instanceId
     * flowCode 任务id
     **/
    public TaskV2Model updateTaskModel(Map<String, Object> params) {
        String exeUserId = RequestContext.getExeUserId();
        List<TaskV2Model> result = Systemctl.taskV2Client.selectListByRelationId(params.get("relationId").toString()).getResult();
        List<TaskV2Model> collect = result.stream().sorted((r1, r2) -> r2.getSequenceNbr().compareTo(r1.getSequenceNbr())).collect(Collectors.toList());

        if (collect == null || collect.size() == 0) {
            return null;
        }
        collect.get(0).setFlowStatus(Integer.valueOf(params.get("flowStatus").toString()));
        collect.get(0).setFlowStatusLabel(params.get("flowStatusLabel").toString());
        collect.get(0).setTaskStatus(Integer.valueOf(params.get("taskStatus").toString()));
        collect.get(0).setTaskStatusLabel(params.get("taskStatusLabel").toString());
        collect.get(0).setEndUserId(exeUserId);
        collect.get(0).setEndDate(new Date());

//        String[] roleIds = model.getRoutePath().split("roleIds=");
//        String[] userIds = roleIds[1].split("&userId");
//        String url = roleIds[0]+"roleIds="+"55555"+"&userId"+ userIds[1];
//        String tarUrl = url.replaceFirst("&executeUserIds=", "");
//        tarUrl+"&executeUserIds="
        // model.setRoutePath( roleIds[0]+"roleIds="+"55555"+"&userId"+userIds[1]);
        //当流程完成时将所有待办状态统一修改为已完成
        if (collect.get(0).getFlowStatusLabel().equals(FlowStatusEnum.TO_BE_FINISHED.getName())) {
            String urlParams = "";
            try {
                urlParams = "&" + toQueryParams(params.get("model"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            List<Map> urlList = JsonUtils.getResourceList(urlInfo);
            for (Map map : urlList) {
                if (map.get("type").equals(collect.get(0).getTaskType()) && map.get("pageType").equals("look")) {
                    urlParams = map.get("url").toString().replace("{roleIds}", "") + urlParams + "&nextExecuteUserIds=";
                    break;
                }
            }
            collect.get(0).setRoutePath(urlParams);
            for (TaskV2Model taskV2Model : collect) {
                taskV2Model.setTaskStatusLabel((FlowStatusEnum.TO_BE_FINISHED.getName()));
                taskV2Model.setTaskStatus(FlowStatusEnum.TO_BE_FINISHED.getCode());
                taskV2Model.setFlowStatusLabel((FlowStatusEnum.TO_BE_FINISHED.getName()));
                taskV2Model.setFlowStatus(FlowStatusEnum.TO_BE_FINISHED.getCode());
            }
            Systemctl.taskV2Client.batchUpdate(collect);
        } else {
            collect.get(0).setRoutePath(collect.get(0).getRoutePath().replace("roleIds=", "roleIds=55555&fq="));
            Systemctl.taskV2Client.update(collect.get(0), collect.get(0).getSequenceNbr());
        }
        //修改model并返回 用于组装新待办
        collect.get(0).setEndUserId(null);
        collect.get(0).setTaskStatus(null);
        collect.get(0).setEndDate(null);
        collect.get(0).setSequenceNbr(null);
        collect.get(0).setCreateDate(new Date());
        collect.get(0).setStartDate(new Date());
        return collect.get(0);
    }

    /**
     * 待办 撤回
     *
     * @param id  工作流实例id
     * @param obj 自己的实体：taskType为BusinessTypeEnum code；nextExecuteUser
     */
    public void rollbackTask(String id, JSONObject obj) {
        this.removeNoUsedKey(obj);
        List<TaskV2Model> result = Systemctl.taskV2Client.selectListByRelationId(id).getResult();
        List<TaskV2Model> list = result.stream().sorted((r1, r2) -> r2.getSequenceNbr().compareTo(r1.getSequenceNbr())).collect(Collectors.toList());
        TaskV2Model model = list.get(0);
        Systemctl.taskV2Client.delete(String.valueOf(model.getSequenceNbr()));

        String urlParams = "";
        urlParams = "&" + toQueryParams2(obj);
        List<Map> urlList = JsonUtils.getResourceList(urlInfo);

        if (list.size() > 1) {
            TaskV2Model lastTaskModel = list.get(1);
            lastTaskModel.setEndUserId(null);
            lastTaskModel.setEndDate(null);
            lastTaskModel.setTaskStatus(0);
            lastTaskModel.setTaskStatusLabel("待处理");
            lastTaskModel.setFlowCode(obj.get("nextTaskId").toString());
            if (obj.get("flowStatus") != null) {
                lastTaskModel.setFlowStatus(Integer.valueOf(obj.get("flowStatus").toString()));
            }
            if (obj.get("flowStatusLabel") != null) {
                lastTaskModel.setFlowStatusLabel(obj.get("flowStatusLabel").toString());
            }

            for (Map map : urlList) {
                if (map.get("type").equals(obj.get("taskType")) && map.get("pageType").equals(obj.getOrDefault("pageType", "edit"))) {
                    lastTaskModel.setRoutePath(map.get("url").toString().replace("{roleIds}", obj.get("nextExecuteUser").toString()) + urlParams);
                    break;
                }
            }
            Systemctl.taskV2Client.update(lastTaskModel, lastTaskModel.getSequenceNbr());
        } else if (list.size() == 1) {
            model.setExecuteUserIds(model.getStartUserId());
            model.setTaskStatusLabel("重新提交");
            model.setTaskStatus(FlowStatusEnum.TO_SUBMITTED.getCode());
            model.setSequenceNbr(null);
            if (obj.get("flowStatus") != null) {
                model.setFlowStatus(Integer.valueOf(obj.get("flowStatus").toString()));
            }
            if (obj.get("flowStatusLabel") != null) {
                model.setFlowStatusLabel(obj.get("flowStatusLabel").toString());
            }
            for (Map map : urlList) {
                if (map.get("type").equals(obj.get("taskType")) && map.get("pageType").equals("edit")) {
                    model.setRoutePath(map.get("url").toString().replace("{roleIds}", obj.get("nextExecuteUser").toString()) + urlParams);
                    break;
                }
            }
            Systemctl.taskV2Client.create(model);
        }
    }

    public void removeNoUsedKey(JSONObject obj) {
        obj.remove("applicationRemark");
        obj.remove("planData");
        obj.remove("inspectionChargePerson");
        obj.remove("inspectionChargePersonName");
        obj.remove("inspectionChargePhone");
        obj.remove("recUserId");
        obj.remove("recDate");
        obj.remove("applicationDate");
        obj.remove("acceptDate");
        obj.remove("superviseOrgName");
        obj.remove("dockingUnitCode");
        obj.remove("address");
        obj.remove("detectionRegion");
        obj.remove("expiryDate");
        obj.remove("applyTime");
        obj.remove("expiryDate");
    }

    private static String toQueryParams2(JSONObject jsonObject) {
        StringBuilder sb = new StringBuilder();
        Set<String> keys = jsonObject.keySet();
        keys.forEach(key -> {
            Object value = jsonObject.get(key);
            if (sb.length() > 0) {
                sb.append('&');
            }
            try {
                if (value != null && !"".equals(value)) {
                    sb.append(URLEncoder.encode(key, "UTF-8"))
                            .append('=')
                            .append(URLEncoder.encode(value.toString(), "UTF-8"));
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        });
        return sb.toString();
    }


    public <T> String toQueryParams(T obj) throws UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder();

        for (Class<?> clazz = obj.getClass(); !clazz.equals(Object.class); clazz = clazz.getSuperclass()) {
            Field[] fields = clazz.getDeclaredFields();

            for (Field field : fields) {
                if (!Modifier.isStatic(field.getModifiers())) {
                    field.setAccessible(true);

                    try {
                        Object value = field.get(obj);

                        if (value != null && !"".equals(value)) {
                            String encodedValue = URLEncoder.encode(value.toString(), "UTF-8");
                            sb.append(field.getName()).append('=').append(encodedValue).append('&');
                        }
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }

        return sb.length() > 0 ? sb.substring(0, sb.length() - 1) : "";
    }


    /**
     * 根据工作流返回信息，组装业务需要的数据
     *
     * @param processTaskDTOS 工作流返回信息
     * @return 组装后的信息
     */
    public List<WorkflowResultDto> buildWorkFlowInfo(List<ProcessTaskDTO> processTaskDTOS) {
        List<WorkflowResultDto> workflowResultDtoList = new ArrayList<>();
        processTaskDTOS.forEach(item -> {
            WorkflowResultDto workflowResultDto = new WorkflowResultDto();
            if (!ObjectUtils.isEmpty(item.getProcessInstance())) {
                workflowResultDto.setInstanceId(item.getProcessInstance().getId());
            }
            if (!ObjectUtils.isEmpty(item.getTask())) {
                workflowResultDto.setTaskName(item.getTask().getName());
            }
            if (!ObjectUtils.isEmpty(item.getCandidateGroups())) {
                workflowResultDto.setExecutorRoleIds(String.join(",", item.getCandidateGroups()));
            }
            if (!ObjectUtils.isEmpty(item.getStartUser())) {
                workflowResultDto.setStartUserId(item.getStartUser().getUserId());
                workflowResultDto.setStartUserName(item.getStartUser().getRealName());
            }
            if (!ObjectUtils.isEmpty(item.getExecutor())) {
                workflowResultDto.setExecutorId(item.getExecutor().getUserId());
                workflowResultDto.setExecutorName(item.getExecutor().getRealName());
            }
            if (!CollectionUtils.isEmpty(item.getNextTask())) {
                ActTaskDTO actTaskDTO = item.getNextTask().get(0);
                workflowResultDto.setNextTaskId(actTaskDTO.getId());
                workflowResultDto.setNextTaskCode(actTaskDTO.getKey());
                workflowResultDto.setNextTaskName(actTaskDTO.getName());
                List<String> nextGroups = item.getNextCandidateGroups().get(actTaskDTO.getId());
                String join = String.join(",", nextGroups);
                workflowResultDto.setNextExecutorRoleIds(join);
                List<String> nextUserIds = item.getNextTaskExecutor().get(actTaskDTO.getId()).stream().map(AgencyUserModel::getUserId).collect(Collectors.toList());
                String nextUserIdsString = String.join(",", nextUserIds);
                workflowResultDto.setNextExecutorUserIds(nextUserIdsString);
            }
            workflowResultDtoList.add(workflowResultDto);
        });
        return workflowResultDtoList;
    }

    public Object transfer(Map<String, Object> map) {
        if (ObjectUtils.isEmpty(map.get("nextTaskId")) || map.get("nextTaskId") == null) {
            throw new BadRequest("nextTaskId不能为空");
        }
        if (ObjectUtils.isEmpty(map.get("instanceId")) || map.get("instanceId") == null) {
            throw new BadRequest("instanceId不能为空");
        }
        String taskId = map.get("nextTaskId").toString();
        String instanceId = map.get("instanceId").toString();
        String lockKey = CommonServiceImpl.buildJcExecuteLockKey(instanceId);
        RLock lock = redissonClient.getLock(lockKey);
        try {
            boolean isLocked = lock.tryLock(0, 180, TimeUnit.SECONDS);
            // 解决并发问题：多个人同时操作一个流程（并发执行通过、驳回、撤回）
            if (!isLocked) {
                throw new BadRequest("当前流程已经被执行！请重新打开页面查看并执行！");
            }
            // 流程执行时，状态及权限校验
            commonService.checkForExecuteFlow(taskId, instanceId);
            String tableName = map.get("tableName").toString();
            String assignee = map.get("assignee").toString();

            FlowTaskVo flowTaskVo = new FlowTaskVo();
            flowTaskVo.setTaskId(taskId);
            flowTaskVo.setAssignee(assignee);
            ProcessTaskDTO processTaskDTO = cmWorkflowService.assign(flowTaskVo);
            //修改待办
            List<TaskV2Model> result = Systemctl.taskV2Client.selectListByRelationId(instanceId).getResult();
            List<TaskV2Model> collect = result.stream().sorted((r1, r2) -> r2.getSequenceNbr().compareTo(r1.getSequenceNbr())).collect(Collectors.toList());
            if (collect.size() == 0) {
                return null;
            }
            TaskV2Model taskV2Model = collect.get(0);
            taskV2Model.setExecuteUserIds(RequestContext.getExeUserId());
            taskV2Model.setTaskStatus(FlowStatusEnum.TO_BE_TRANSFER.getCode());
            taskV2Model.setTaskStatusLabel(FlowStatusEnum.TO_BE_TRANSFER.getName());
            taskV2Model.setEndUserId(RequestContext.getExeUserId());
            taskV2Model.setEndDate(new Date());
            String routhPath = taskV2Model.getRoutePath().replace("nextExecuteUserIds", "executeUserId") + "&nextExecuteUserIds=" + assignee;
            taskV2Model.setRoutePath(routhPath);
            Systemctl.taskV2Client.update(taskV2Model, taskV2Model.getSequenceNbr());
            //创建新待办
            taskV2Model.setExecuteUserIds(assignee);
            String nextTaskId = processTaskDTO.getNextTask().get(0).getId();
            taskV2Model.setFlowCode(nextTaskId);
            String routhPath1 = routhPath.replace("nextTaskId", "nextTask") + "&nextTaskId=" + nextTaskId;
            taskV2Model.setCreateDate(new Date());
            taskV2Model.setRoutePath(routhPath1);
            taskV2Model.setTaskStatus(0);
            taskV2Model.setTaskStatusLabel(FlowStatusEnum.TO_BE_PROCESSED.getName());
            taskV2Model.setEndUserId(null);
            taskV2Model.setEndDate(null);
            taskV2Model.setSequenceNbr(null);
            Systemctl.taskV2Client.create(taskV2Model);

            String key = map.get("key").toString();
            String id = jyjcBaseMapper.selectBusinessData(tableName, instanceId, key);
            id = ObjectUtils.isEmpty(id) ? assignee : id + "," + assignee;
            //修改业务数据
            jyjcBaseMapper.updateBusinessData(tableName, assignee, id, instanceId, nextTaskId, key);
            // 更新流程中的流程数据
            commonService.saveExecuteFlowData2Redis(instanceId, this.buildInstanceRuntimeData(assignee, "", nextTaskId));
            return Boolean.TRUE;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
        return Boolean.FALSE;
    }


    public Object transfer2(Map<String, Object> map) {
        if (ObjectUtils.isEmpty(map.get("nextTaskId")) || map.get("nextTaskId") == null) {
            throw new BadRequest("nextTaskId不能为空");
        }
        if (ObjectUtils.isEmpty(map.get("instanceId")) || map.get("instanceId") == null) {
            throw new BadRequest("instanceId不能为空");
        }
        String inspectUnitCode = map.get("transferOrg").toString();
        CompanyModel companyModel = jyjcBaseMapper.selectOneCompanyByCode(inspectUnitCode);
        String taskId = map.get("nextTaskId").toString();
        String instanceId = map.get("instanceId").toString();
        String lockKey = CommonServiceImpl.buildJcExecuteLockKey(instanceId);
        RLock lock = redissonClient.getLock(lockKey);
        try {
            boolean isLocked = lock.tryLock(0, 180, TimeUnit.SECONDS);
            // 解决并发问题：多个人同时操作一个流程（并发执行通过、驳回、撤回）
            if (!isLocked) {
                throw new BadRequest("当前流程已经被执行！请重新打开页面查看并执行！");
            }
            // 流程执行时，状态及权限校验
            commonService.checkForExecuteFlow(taskId, instanceId);
            String tableName = map.get("tableName").toString();
            String assignee = map.get("assignee").toString();

            FlowTaskVo flowTaskVo = new FlowTaskVo();
            flowTaskVo.setTaskId(taskId);
            flowTaskVo.setAssignee(assignee);
            ProcessTaskDTO processTaskDTO = cmWorkflowService.assign(flowTaskVo);
            //修改待办
            List<TaskV2Model> result = Systemctl.taskV2Client.selectListByRelationId(instanceId).getResult();
            List<TaskV2Model> collect = result.stream().sorted((r1, r2) -> r2.getSequenceNbr().compareTo(r1.getSequenceNbr())).collect(Collectors.toList());
            if (collect.size() == 0) {
                return null;
            }
            TaskV2Model taskV2Model = collect.get(0);
            taskV2Model.setExecuteUserIds(RequestContext.getExeUserId());
            taskV2Model.setTaskStatus(FlowStatusEnum.TO_BE_TRANSFER.getCode());
            taskV2Model.setTaskStatusLabel(FlowStatusEnum.TO_BE_TRANSFER.getName());
            taskV2Model.setEndUserId(RequestContext.getExeUserId());
            taskV2Model.setEndDate(new Date());
            String routhPath = taskV2Model.getRoutePath().replace("nextExecuteUserIds", "executeUserId") + "&nextExecuteUserIds=" + assignee;
            taskV2Model.setRoutePath(routhPath);
            Systemctl.taskV2Client.update(taskV2Model, taskV2Model.getSequenceNbr());
            //创建新待办
            taskV2Model.setExecuteUserIds(assignee);
            String nextTaskId = processTaskDTO.getNextTask().get(0).getId();
            taskV2Model.setFlowCode(nextTaskId);
            String routhPath1 = routhPath.replace("nextTaskId", "nextTask") + "&nextTaskId=" + nextTaskId;
            taskV2Model.setCreateDate(new Date());
            taskV2Model.setRoutePath(routhPath1);
            taskV2Model.setTaskStatus(0);
            taskV2Model.setTaskStatusLabel(FlowStatusEnum.TO_BE_PROCESSED.getName());
            taskV2Model.setEndUserId(null);
            taskV2Model.setEndDate(null);
            taskV2Model.setSequenceNbr(null);
            Systemctl.taskV2Client.create(taskV2Model);

            String key = map.get("key").toString();
            String id = jyjcBaseMapper.selectBusinessData(tableName, instanceId, key);
            id = ObjectUtils.isEmpty(id) ? assignee : id + "," + assignee;
            //修改业务数据
            jyjcBaseMapper.updateBusinessDataWithCompany(tableName, assignee, id, instanceId, nextTaskId, key, inspectUnitCode, companyModel.getCompanyName());
            // 更新流程中的流程数据
            commonService.saveExecuteFlowData2Redis(instanceId, this.buildInstanceRuntimeData(assignee, "", nextTaskId));
            return Boolean.TRUE;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
        return Boolean.FALSE;
    }

    public InstanceRuntimeData buildInstanceRuntimeData(String executeUserIds, String promoter, String nextTaskId) {
        return InstanceRuntimeData.builder()
                .nextExecuteUserIds(executeUserIds)
                .promoter(promoter)
                .nextTaskId(nextTaskId)
                .build();
    }

}
