package org.springblade.flow.engine.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.FlowNode;
import org.flowable.bpmn.model.Process;
import org.flowable.engine.*;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.history.HistoricProcessInstanceQuery;
import org.flowable.engine.impl.bpmn.behavior.ReceiveTaskActivityBehavior;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.task.api.history.HistoricTaskInstanceQuery;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.springblade.flow.base.UserInfo;
import org.springblade.flow.base.util.*;
import org.springblade.flow.database.model.DataSourceUtil;
import org.springblade.flow.database.source.impl.DbOracle;
import org.springblade.flow.database.util.DbTypeUtil;
import org.springblade.flow.engine.assembly.GlobalExPropertyDTO;
import org.springblade.flow.engine.assembly.UserTaskExPropertyDTO;
import org.springblade.flow.engine.assembly.prop.UserTaskBasicPropDTO;
import org.springblade.flow.engine.custom.behavior.impl.CustomCallActivityActivityBehavior;
import org.springblade.flow.engine.custom.cmd.execution.GetRootExecutionEntityCmd;
import org.springblade.flow.engine.custom.cmd.multi.SimpleUserTaskSignCmd;
import org.springblade.flow.engine.custom.constants.BasicActivitiConstants;
import org.springblade.flow.engine.custom.constants.GlobalProcessVariableConstants;
import org.springblade.flow.engine.custom.variables.entity.FormDataInfo;
import org.springblade.flow.engine.entity.*;
import org.springblade.flow.engine.enums.*;
import org.springblade.flow.engine.mapper.FlowTaskMapper;
import org.springblade.flow.engine.model.flowlaunch.FlowLaunchListVO;
import org.springblade.flow.engine.model.flowtask.CounterSignModel;
import org.springblade.flow.engine.model.flowtask.FlowTaskWaitListModel;
import org.springblade.flow.engine.model.flowtask.PaginationFlowTask;
import org.springblade.flow.engine.service.*;
import org.springblade.flow.engine.util.SortType;
import org.springblade.flow.exception.WorkFlowException;
import org.springblade.flow.permission.entity.UserRelationEntity;
import org.springblade.flow.permission.service.UserRelationService;
import org.springblade.flow.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import static org.springblade.flow.base.util.BpmnModelUtils.*;
import static org.springblade.flow.engine.custom.constants.BasicActivitiConstants.exActivitiPrefixURL;
import static org.springblade.flow.engine.custom.constants.BasicActivitiConstants.extensionAttributeName;
import static org.springblade.flow.engine.custom.constants.GlobalProcessVariableConstants.*;
import static org.springblade.flow.engine.custom.constants.TaskVariableConstants.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 流程任务
 *
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date 2019年9月27日 上午9:18
 */
@Slf4j
@Service
@SuppressWarnings("all")
public class FlowTaskServiceImpl extends ServiceImpl<FlowTaskMapper, FlowTaskEntity> implements FlowTaskService {

    @Autowired
    private UserProvider userProvider;
    @Autowired
    private UserRelationService userRelationService;
    @Autowired
    private FlowDelegateService flowDelegateService;
    @Autowired
    private FlowTaskNodeService flowTaskNodeService;
    @Autowired
    private FlowTaskOperatorService flowTaskOperatorService;
    @Autowired
    private FlowTaskOperatorRecordService flowTaskOperatorRecordService;
    @Autowired
    private FlowTaskCirculateService flowTaskCirculateService;
    @Autowired
    private DataSourceUtil dataSourceUtil;
    @Resource
    private UserRelationService userRelationApi;
    @Autowired
    private FlowDataUtil flowDataUtil;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private HistoryService historyService;
    @Resource
    private ActivitiUtils activitiUtils;
    @Resource
    private RepositoryService repositoryService;
    @Resource
    private TaskService taskService;
    @Resource
    private ActivitiDataBaseUtils activitiDataBaseUtils;
    @Resource
    private ManagementService managementService;
    @Resource
    private FlowTaskNotificationService flowTaskNotificationService;


    @Override
    public List<FlowTaskEntity> getMonitorList(PaginationFlowTask paginationFlowTask) {

        HistoricProcessInstanceQuery historicProcessInstanceQuery = historyService.createHistoricProcessInstanceQuery();
        //发起人是自己
        historicProcessInstanceQuery.variableValueEquals(APPLY_USER_ID,userProvider.getUserId());
        //草稿状态不显示
        historicProcessInstanceQuery.variableValueNotEquals(PROCESS_STATUS,FlowTaskStatusEnum.Draft.getCode());
        //关键词 也即流程标题
        if(StringUtils.isNotBlank(paginationFlowTask.getKeyword())){
            historicProcessInstanceQuery.variableValueEquals(GlobalProcessVariableConstants.BUSINESS_TITLE,"%"+paginationFlowTask.getKeyword()+"%");
        }
        //所属分类
        if(StringUtils.isNotBlank(paginationFlowTask.getFlowCategory())){
            historicProcessInstanceQuery.processDefinitionCategory(paginationFlowTask.getFlowCategory());
        }
        //所属流程
        if(StringUtils.isNotBlank(paginationFlowTask.getFlowId())){
            historicProcessInstanceQuery.processDefinitionName(paginationFlowTask.getFlowId());
        }
        //时间范围开始
        if(StringUtils.isNotBlank(paginationFlowTask.getStartTime())){

            historicProcessInstanceQuery.startedAfter(DateUtils.parseDate(paginationFlowTask.getStartTime()));
        }
        //时间范围结束
        if(StringUtils.isNotBlank(paginationFlowTask.getEndTime())){
            historicProcessInstanceQuery.startedBefore(DateUtils.parseDate(paginationFlowTask.getEndTime()));
        }
        //发起人员
        if(StringUtils.isNotBlank(paginationFlowTask.getCreatorUserId())){
//            historicProcessInstanceQuery.startedBefore(DateUtils.parseDate(paginationFlowTask.getEndTime()));
            historicProcessInstanceQuery.variableValueEquals(APPLY_USER_ID,paginationFlowTask.getCreatorUserId());
        }
        //可以再连带条件

        //排序
        if(SortType.ASC.equals(paginationFlowTask.getSort().toLowerCase())){
            historicProcessInstanceQuery.orderByProcessInstanceStartTime().asc();
        }
        else{
            historicProcessInstanceQuery.orderByProcessInstanceStartTime().desc();
        }
        Integer currentPage = Integer.valueOf(paginationFlowTask.getCurrentPage() + "");
        Integer pageSize = Integer.valueOf(paginationFlowTask.getPageSize() + "");
        long count = historicProcessInstanceQuery.count();


        //分页查询
        List<HistoricProcessInstance> historicProcessInstances = historicProcessInstanceQuery
                .includeProcessVariables()
                .listPage((currentPage - 1) * pageSize, pageSize);

        List<FlowTaskEntity> flowTaskEntityList = new ArrayList<>();
        for (HistoricProcessInstance historicProcessInstance : historicProcessInstances) {
            Process process = getBpmnModelMainProcess(historicProcessInstance.getProcessDefinitionId());
            String property = getAttributeValueByTaskDefinitionKey(process, "", "global");
            ProcessDefinitionEntity processDefinitionEntity = activitiUtils.getProcessDefinitionEntityById(historicProcessInstance.getProcessDefinitionId());
//            Object property = processDefinitionEntity.getProperty(BasicActivitiConstants.extensionAttributeName);
            GlobalExPropertyDTO exPropertyDTO = JSONObject.parseObject(property, new TypeReference<GlobalExPropertyDTO>() {});
            FlowTaskEntity flowTaskEntity = new FlowTaskEntity();
            Map<String, Object> processVariables = historicProcessInstance.getProcessVariables();
            flowTaskEntity.setId(historicProcessInstance.getId());
            flowTaskEntity.setProcessId(historicProcessInstance.getBusinessKey());
            flowTaskEntity.setEnCode(MapUtil.getStr(processVariables,GlobalProcessVariableConstants.BILL_CODE));
            flowTaskEntity.setFullName(MapUtil.getStr(processVariables, BUSINESS_TITLE));
            flowTaskEntity.setFlowUrgent(MapUtil.getInt(processVariables, GlobalProcessVariableConstants.FLOW_URGENT));
            flowTaskEntity.setFlowId(MapUtil.getStr(processVariables, GlobalProcessVariableConstants.FLOW_ENGINE_ID));
            flowTaskEntity.setFlowCode(processDefinitionEntity.getKey().replace(BasicActivitiConstants.activitiPrefix,""));
            flowTaskEntity.setFlowName(processDefinitionEntity.getName());
            flowTaskEntity.setFlowType(exPropertyDTO.getFlowType());
            flowTaskEntity.setCreatorUserId(MapUtil.getStr(processVariables,APPLY_USER_ID));
            flowTaskEntity.setCreatorUserName(MapUtil.getStr(processVariables,APPLY_USER_NAME));
            flowTaskEntity.setFlowFormType(exPropertyDTO.getFlowFormType()+"");
            flowTaskEntity.setFlowCategory(MapUtil.getStr(processVariables,GlobalProcessVariableConstants.PROCESS_CATEGORY));
            flowTaskEntity.setFlowForm(exPropertyDTO.getFormData());
            FormDataInfo formDataInfo = MapUtil.get(processVariables, FORM_INFO_JSON, FormDataInfo.class);
            if(formDataInfo!=null){
                flowTaskEntity.setFlowFormContentJson(formDataInfo.getFormDataJson());
            }
            flowTaskEntity.setFlowTemplateJson(exPropertyDTO.getFlowTemplateJson());
            flowTaskEntity.setFlowVersion(exPropertyDTO.getFlowVersion());
            flowTaskEntity.setCreatorTime(historicProcessInstance.getStartTime());
            flowTaskEntity.setStartTime(historicProcessInstance.getStartTime());
            flowTaskEntity.setEndTime(historicProcessInstance.getEndTime());
            flowTaskEntity.setStatus(MapUtil.getInt(processVariables,GlobalProcessVariableConstants.PROCESS_STATUS));
            Boolean endFlag=historicProcessInstance.getEndTime()==null;
            if(endFlag){
                flowTaskEntity.setCompletion(50);
            }
            else{
                flowTaskEntity.setCompletion(100);
            }
            flowTaskEntity.setEnabledMark(1);
            if(historicProcessInstance.getEndTime()==null){
                List<String> activeActivityIds = runtimeService.getActiveActivityIds(historicProcessInstance.getId());
                HashSet<String> setActiveActivityIds = new HashSet<>(activeActivityIds);
                flowTaskEntity.setThisStepId(String.join(",", setActiveActivityIds));
                List<FlowElement> activities = getFlowElementsWithOutSequenceFlow(process);
                List<String> activityNames= new ArrayList<>();
                for (String setActiveActivityId : setActiveActivityIds) {
                    FlowNode flowNode = getFlowNodeById(process, setActiveActivityId);
                    activityNames.add(flowNode.getName());
                }
                flowTaskEntity.setThisStep(String.join(",", activityNames));
            }
            flowTaskEntityList.add(flowTaskEntity);
        }

        return paginationFlowTask.setData(flowTaskEntityList, count);
    }

    @Override
    public List<FlowLaunchListVO> getLaunchList(PaginationFlowTask paginationFlowTask) {

        HistoricProcessInstanceQuery historicProcessInstanceQuery = historyService.createHistoricProcessInstanceQuery();
        //发起人是自己
//        historicProcessInstanceQuery.startedBy(userInfo.getUserId()); //调用活动无法所以不能使用
        historicProcessInstanceQuery.variableValueEquals(APPLY_USER_ID,userProvider.getUserId());
        //未被删除的
//        historicProcessInstanceQuery.notDeleted();

        //关键词 也即流程标题
        if(StringUtils.isNotBlank(paginationFlowTask.getKeyword())){
            historicProcessInstanceQuery.variableValueLikeIgnoreCase(GlobalProcessVariableConstants.BUSINESS_TITLE,"%"+paginationFlowTask.getKeyword()+"%");
        }

        //所属分类
        if(StringUtils.isNotBlank(paginationFlowTask.getFlowCategory())){
            historicProcessInstanceQuery.processDefinitionCategory(paginationFlowTask.getFlowCategory());
        }
        //所属流程
        if(StringUtils.isNotBlank(paginationFlowTask.getFlowId())){
            historicProcessInstanceQuery.variableValueEquals(FLOW_ENGINE_ID,paginationFlowTask.getFlowId());
        }
        //时间范围开始
        if(StringUtils.isNotBlank(paginationFlowTask.getStartTime())){

            Date date=new Date(Long.valueOf(paginationFlowTask.getStartTime()));
            historicProcessInstanceQuery.startedAfter(date);
        }
        //时间范围结束
        if(StringUtils.isNotBlank(paginationFlowTask.getEndTime())){
            Date date=new Date(Long.valueOf(paginationFlowTask.getEndTime()));
            historicProcessInstanceQuery.startedBefore(date);
        }

        //可以再连带条件

        //排序
        if("asc".equals(paginationFlowTask.getSort().toLowerCase())){
            historicProcessInstanceQuery.orderByProcessInstanceStartTime().asc();
        }
        else{
            historicProcessInstanceQuery.orderByProcessInstanceStartTime().desc();
        }

        Integer currentPage = Integer.valueOf(paginationFlowTask.getCurrentPage() + "");
        Integer pageSize = Integer.valueOf(paginationFlowTask.getPageSize() + "");
        long count = historicProcessInstanceQuery.count();
        historicProcessInstanceQuery.orderByProcessInstanceStartTime().desc(); //发起时间倒序排序
        //分页查询
        List<HistoricProcessInstance> historicProcessInstances = historicProcessInstanceQuery
                .includeProcessVariables()
                .listPage((currentPage - 1) * pageSize, pageSize);

        List<FlowLaunchListVO> listVO = new LinkedList<>();
        for (HistoricProcessInstance historicProcessInstance : historicProcessInstances) {
            FlowLaunchListVO flowLaunchListVO = new FlowLaunchListVO();
            String processDefinitionId = historicProcessInstance.getProcessDefinitionId();
            Process process = getBpmnModelMainProcess(processDefinitionId);
            ProcessDefinitionEntity processDefinitionEntity = activitiUtils.getProcessDefinitionEntityById(processDefinitionId);
            Map<String, Object> processVariables = historicProcessInstance.getProcessVariables();
            flowLaunchListVO.setEnCode(MapUtil.getStr(processVariables,GlobalProcessVariableConstants.BILL_CODE));
            flowLaunchListVO.setCreatorUserId(userProvider.getUserId());
            flowLaunchListVO.setCreatorTime(historicProcessInstance.getStartTime().getTime());
            String currentActivityId="";
            if(historicProcessInstance.getEndTime()==null){ //流程实例还没有结束
                List<HistoricActivityInstance> historicActivityInstances = historyService.createHistoricActivityInstanceQuery().processInstanceId(historicProcessInstance.getId())
                        .unfinished()
                        .listPage(0, 2);
                if(historicActivityInstances==null || historicActivityInstances.isEmpty()){
                    flowLaunchListVO.setThisStep("流程已挂起");
                }
                else{
                    HistoricActivityInstance historicActivityInstance = historicActivityInstances.get(0);
                    flowLaunchListVO.setThisStep(historicActivityInstance.getActivityName());
                    currentActivityId=historicActivityInstance.getActivityId();
                }
            }
            else{
                flowLaunchListVO.setThisStep("流程已结束");
            }
            flowLaunchListVO.setFlowCategory(MapUtil.getStr(processVariables,GlobalProcessVariableConstants.PROCESS_CATEGORY));
            flowLaunchListVO.setFullName(historicProcessInstance.getName());
            flowLaunchListVO.setFlowName(historicProcessInstance.getProcessDefinitionName());
            flowLaunchListVO.setStatus(MapUtil.getInt(processVariables, GlobalProcessVariableConstants.PROCESS_STATUS));
            flowLaunchListVO.setStartTime(flowLaunchListVO.getCreatorTime());
            flowLaunchListVO.setId(historicProcessInstance.getBusinessKey()  );
            Date endTime = historicProcessInstance.getEndTime();
            Boolean endTimeFlag=endTime==null?false:true;
            flowLaunchListVO.setEndTime(endTime==null?null:endTime.getTime());
            if(endTimeFlag){
                flowLaunchListVO.setCompletion(FlowRecordEnum.end.getCode());
            }
            else{
                if(StringUtils.isNotBlank(currentActivityId)){
                    FlowNode activity = getFlowNodeById(process, currentActivityId);
                    if(activity.getBehavior() instanceof ReceiveTaskActivityBehavior){
                        flowLaunchListVO.setCompletion(50);
                    }
                    else if(activity.getBehavior() instanceof CustomCallActivityActivityBehavior){
                        flowLaunchListVO.setCompletion(50);
                    }
                    else{
                        String property = activity.getAttributeValue(exActivitiPrefixURL, extensionAttributeName);
                        UserTaskExPropertyDTO userTaskExPropertyDTO=JSONObject.parseObject(property, new TypeReference<UserTaskExPropertyDTO>() {} );
                        UserTaskBasicPropDTO userTaskBasicPropDTO = userTaskExPropertyDTO.getUserTaskBasicPropDTO();

//                flowLaunchListVO.setCompletion(Integer.valueOf(activityExPropertyDTO.getProgress()));
                        String progress = userTaskBasicPropDTO.getProgress();
                        flowLaunchListVO.setCompletion(progress==null?0:Integer.valueOf(progress));
                    }
                }
                else{
                    flowLaunchListVO.setCompletion(50);
                }
            }


            flowLaunchListVO.setFlowCode(historicProcessInstance.getProcessDefinitionKey().replace(BasicActivitiConstants.activitiPrefix,""));
            flowLaunchListVO.setFlowId(MapUtil.getStr(processVariables,FLOW_ENGINE_ID));
            String property = getAttributeValueByTaskDefinitionKey(process, "", "global");
            GlobalExPropertyDTO activityExPropertyDTO = JSONObject.parseObject(property, new TypeReference<GlobalExPropertyDTO>() {} );
            flowLaunchListVO.setDescription(flowLaunchListVO.getDescription());
            flowLaunchListVO.setFormType(activityExPropertyDTO.getFormType());
            flowLaunchListVO.setFormData(activityExPropertyDTO.getFormData());

            listVO.add(flowLaunchListVO);
        }
        return listVO;
    }

    @Override
    public List<FlowTaskEntity> getWaitList(PaginationFlowTask paginationFlowTask) {
        String userId = userProvider.getUserId();

        TaskQuery taskQuery = taskService.createTaskQuery().taskCandidateOrAssigned(userId)
                .includeProcessVariables()
                .active()
                .processVariableValueNotEquals(PROCESS_STATUS,FlowTaskStatusEnum.Draft.getCode());
        String keyword = paginationFlowTask.getKeyword();
        String startTime = paginationFlowTask.getStartTime();
        String endTime = paginationFlowTask.getEndTime();
        String flowId = paginationFlowTask.getFlowId();
        String flowCategory = paginationFlowTask.getFlowCategory();
        String creatorUserId = paginationFlowTask.getCreatorUserId();

        if(StringUtils.isNotBlank(keyword)){
            taskQuery.processVariableValueLike(BUSINESS_TITLE,"%"+keyword+"%");
        }
        if(StringUtils.isNotBlank(startTime)){
            long startTimeL = Long.parseLong(startTime);
            Date date = new Date(startTimeL);
            taskQuery.taskCreatedAfter(date);
        }
        if(StringUtils.isNotBlank(endTime)){
            long endTimeL = Long.parseLong(startTime);
            Date end= new Date(endTimeL);
            taskQuery.taskCreatedBefore(end);
        }
        //所属流程
        if(StringUtils.isNotBlank(flowId)){
            taskQuery.processVariableValueEquals(FLOW_ENGINE_ID,flowId);
        }
        //所属分类
        if(StringUtils.isNotBlank(flowCategory)){
            taskQuery.processVariableValueEquals(PROCESS_CATEGORY,flowCategory);
        }
        //发起人
        if(StringUtils.isNotBlank(creatorUserId)){
            taskQuery.processVariableValueEquals(APPLY_USER_ID,creatorUserId);
        }
        //

        //排序
        if (SortType.DESC.equals(paginationFlowTask.getSort().toLowerCase())) {
            taskQuery.orderByTaskCreateTime().desc();
        } else {
            taskQuery.orderByTaskCreateTime().asc();
        }
        long count = taskQuery.count();
        //按照任务优先级排序
        taskQuery.orderByTaskPriority().desc();
        Integer currentPage = Integer.valueOf(paginationFlowTask.getCurrentPage() + "");
        Integer pageSize = Integer.valueOf(paginationFlowTask.getPageSize() + "");
        List<Task> taskList = taskQuery.listPage((currentPage - 1) * pageSize, pageSize);
        Map<String, Date> collect=null;
        if(CollUtil.isNotEmpty(taskList)&& taskList.size()>0){
            Set<String> processInstanceIds = taskList.stream().map(Task::getProcessInstanceId).collect(Collectors.toSet());
            List<ProcessInstance> list = runtimeService.createProcessInstanceQuery().processInstanceIds(processInstanceIds).list();
            collect = list.stream().collect(Collectors.toMap(ProcessInstance::getId, ProcessInstance::getStartTime));
        }

        List<FlowTaskEntity> result = new LinkedList<>();
        for (Task task : taskList) {

            ProcessDefinitionEntity processDefinitionEntity = activitiUtils.getProcessDefinitionEntityById(task.getProcessDefinitionId());
            Process process = getBpmnModelMainProcess(processDefinitionEntity.getId());
            String property = getAttributeValueByTaskDefinitionKey(process, "", "global");
            GlobalExPropertyDTO globalExPropertyDTO = JSONObject.parseObject(property.toString(), new TypeReference<GlobalExPropertyDTO>() {
            });

            FlowNode flowNode = getFlowNodeById(process, task.getTaskDefinitionKey());
            String taskProperty = flowNode.getAttributeValue(BasicActivitiConstants.exActivitiPrefixURL, BasicActivitiConstants.extensionAttributeName);
            UserTaskExPropertyDTO taskExPropertyDTO = JSONObject.parseObject(taskProperty.toString(), new TypeReference<UserTaskExPropertyDTO>() {
            });

            List<String> activeActivityIds = runtimeService.getActiveActivityIds(task.getProcessInstanceId());
            HashSet<String> setActiveActivityIds = new HashSet<>(activeActivityIds);
            FlowTaskEntity flowTaskEntity = new FlowTaskEntity();
            Map<String, Object> processVariables = task.getProcessVariables();
            flowTaskEntity.setId(task.getId());
            flowTaskEntity.setProcessId(task.getFormKey());
            flowTaskEntity.setEnCode(MapUtil.getStr(processVariables,GlobalProcessVariableConstants.BILL_CODE));
            flowTaskEntity.setFullName(MapUtil.getStr(processVariables, BUSINESS_TITLE));
            flowTaskEntity.setFlowUrgent(MapUtil.getInt(processVariables, GlobalProcessVariableConstants.FLOW_URGENT));
            flowTaskEntity.setFlowId(MapUtil.getStr(processVariables, GlobalProcessVariableConstants.FLOW_ENGINE_ID));
            flowTaskEntity.setFlowCode(processDefinitionEntity.getKey().replace(BasicActivitiConstants.activitiPrefix,""));
            flowTaskEntity.setFlowName(processDefinitionEntity.getName());
            flowTaskEntity.setFlowType(globalExPropertyDTO.getFlowType());
            flowTaskEntity.setFlowCategory(MapUtil.getStr(processVariables,GlobalProcessVariableConstants.PROCESS_CATEGORY));
            flowTaskEntity.setFlowForm(globalExPropertyDTO.getFormData());
            FormDataInfo formDataInfo = MapUtil.get(processVariables, FORM_INFO_JSON, FormDataInfo.class);
            flowTaskEntity.setFlowFormContentJson(formDataInfo.getFormDataJson());
            flowTaskEntity.setFlowTemplateJson(globalExPropertyDTO.getFlowTemplateJson());
            flowTaskEntity.setFlowVersion(globalExPropertyDTO.getFlowVersion());
            flowTaskEntity.setCreatorTime(task.getCreateTime());
            flowTaskEntity.setCreatorUserId(MapUtil.getStr(processVariables, APPLY_USER_ID));
            flowTaskEntity.setCreatorUserName(MapUtil.getStr(processVariables,APPLY_USER_NAME));
            flowTaskEntity.setFlowFormType(globalExPropertyDTO.getFlowFormType()+"");
            flowTaskEntity.setClaimTime(task.getClaimTime());
            flowTaskEntity.setDueDate(task.getDueDate());
            flowTaskEntity.setCurrentNodeName(task.getName());
            flowTaskEntity.setStartTime(MapUtil.get(collect,task.getProcessInstanceId(),Date.class));
            flowTaskEntity.setEndTime(null);
            flowTaskEntity.setStatus(MapUtil.getInt(processVariables,GlobalProcessVariableConstants.PROCESS_STATUS));
            String progress = taskExPropertyDTO.getUserTaskBasicPropDTO().getProgress();
            if(StringUtils.isNotBlank(progress)){
                flowTaskEntity.setCompletion(Integer.valueOf(progress));
            }
            else{
                flowTaskEntity.setCompletion(50);
            }
            flowTaskEntity.setEnabledMark(1);
            flowTaskEntity.setThisStepId(String.join(",", setActiveActivityIds));
            List<FlowElement> activities = getFlowElementsWithOutSequenceFlow(process);
            List<String> activityNames= new ArrayList<>();
            for (String setActiveActivityId : setActiveActivityIds) {
                FlowNode activity = getFlowNodeById(process, setActiveActivityId);
                activityNames.add(activity.getName());
            }
            flowTaskEntity.setThisStep(String.join(",", activityNames));

            Object o = processVariables.get(NOTIFICATION_FLAG);
            if(o!=null){
                flowTaskEntity.setNoticeFlag(true);
                QueryWrapper<FlowTaskNotificationEntity> queryWrapper=new QueryWrapper<>();
                queryWrapper.lambda().eq(FlowTaskNotificationEntity::getProcessInstanceId,task.getProcessInstanceId());
                List<FlowTaskNotificationEntity> list = flowTaskNotificationService.list(queryWrapper);
                flowTaskEntity.setFlowTaskNotificationEntityList(list);
            }
            result.add(flowTaskEntity);
        }
        //返回数据
        return paginationFlowTask.setData(PageUtil.getListPage((int) paginationFlowTask.getCurrentPage(), (int) paginationFlowTask.getPageSize(), result), count);
    }

    @Override
    public List<FlowTaskEntity> getTrialList(PaginationFlowTask paginationFlowTask) {
        String userId = userProvider.getUserId();
        HistoricTaskInstanceQuery historicTaskInstanceQuery = historyService.createHistoricTaskInstanceQuery()
                .taskAssignee(userId)
                .processVariableValueNotEquals(PROCESS_STATUS,FlowTaskStatusEnum.Draft.getCode())
                .finished().includeProcessVariables();
        String keyword = paginationFlowTask.getKeyword();
        String startTime = paginationFlowTask.getStartTime();
        String endTime = paginationFlowTask.getEndTime();
        String flowId = paginationFlowTask.getFlowId();
        String flowCategory = paginationFlowTask.getFlowCategory();
        String creatorUserId = paginationFlowTask.getCreatorUserId();
        if(StringUtils.isNotBlank(keyword)){
            historicTaskInstanceQuery.processVariableValueLike(BUSINESS_TITLE,"%"+keyword+"%");
        }
        if(StringUtils.isNotBlank(startTime)){
            long startTimeL = Long.parseLong(startTime);
            Date date = new Date(startTimeL);
            historicTaskInstanceQuery.taskCreatedAfter(date);
        }
        if(StringUtils.isNotBlank(endTime)){
            long endTimeL = Long.parseLong(startTime);
            Date end= new Date(endTimeL);
            historicTaskInstanceQuery.taskCreatedBefore(end);
        }
        //所属流程
        if(StringUtils.isNotBlank(flowId)){
            historicTaskInstanceQuery.processVariableValueEquals(FLOW_ENGINE_ID,flowId);
        }
        //所属分类
        if(StringUtils.isNotBlank(flowCategory)){
            historicTaskInstanceQuery.processVariableValueEquals(PROCESS_CATEGORY,flowCategory);
        }
        //发起人
        if(StringUtils.isNotBlank(creatorUserId)){
            historicTaskInstanceQuery.processVariableValueEquals(APPLY_USER_ID,creatorUserId);
        }
        //

        //排序
        if (SortType.DESC.equals(paginationFlowTask.getSort().toLowerCase())) {
            historicTaskInstanceQuery.orderByHistoricTaskInstanceEndTime().desc();
        } else {
            historicTaskInstanceQuery.orderByHistoricTaskInstanceEndTime().asc();
        }
        long count = historicTaskInstanceQuery.count();

        //
        historicTaskInstanceQuery.orderByTaskCreateTime().desc();


        Integer currentPage = Integer.valueOf(paginationFlowTask.getCurrentPage() + "");
        Integer pageSize = Integer.valueOf(paginationFlowTask.getPageSize() + "");
        List<HistoricTaskInstance> historicTaskInstances = historicTaskInstanceQuery.listPage((currentPage - 1) * pageSize, pageSize);

        Map<String, HistoricProcessInstance> collect=new HashMap<>();
        if(CollUtil.isNotEmpty(historicTaskInstances)&& historicTaskInstances.size()>0){
            Set<String> processInstanceIds = historicTaskInstances.stream().map(HistoricTaskInstance::getProcessInstanceId).collect(Collectors.toSet());
            List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery().processInstanceIds(processInstanceIds).list();
            for (HistoricProcessInstance historicProcessInstance : list) {
                collect.put(historicProcessInstance.getId(),historicProcessInstance);
            }
        }

        List<FlowTaskEntity> result = new LinkedList<>();
        for (HistoricTaskInstance historicTaskInstance : historicTaskInstances) {
            HistoricProcessInstance historicProcessInstance = MapUtil.get(collect, historicTaskInstance.getProcessInstanceId(), HistoricProcessInstance.class);
            ProcessDefinitionEntity processDefinitionEntity = activitiUtils.getProcessDefinitionEntityById(historicTaskInstance.getProcessDefinitionId());
            Process process = getBpmnModelMainProcess(processDefinitionEntity.getId());
            String property = getAttributeValueByTaskDefinitionKey(process, "", "global");
            GlobalExPropertyDTO exPropertyDTO = JSONObject.parseObject(property.toString(), new TypeReference<GlobalExPropertyDTO>() {
            });

            FlowNode flowNode = getFlowNodeById(process, historicTaskInstance.getTaskDefinitionKey());
            String taskProperty = flowNode.getAttributeValue(BasicActivitiConstants.exActivitiPrefixURL, BasicActivitiConstants.extensionAttributeName);
            UserTaskExPropertyDTO taskExPropertyDTO = JSONObject.parseObject(taskProperty.toString(), new TypeReference<UserTaskExPropertyDTO>() {
            });
            FlowTaskEntity flowTaskEntity = new FlowTaskEntity();
            List<String> activeActivityIds = null;
//            try{
            activeActivityIds=runtimeService.getActiveActivityIds(historicTaskInstance.getProcessInstanceId());
//            }catch (FlowableObjectNotFoundException e){
            if(activeActivityIds.isEmpty()){
                activeActivityIds= CollectionUtil.newArrayList("已结束");
            }
//            }
            if(!activeActivityIds.contains("已结束")){
                HashSet<String> setActiveActivityIds = new HashSet<>(activeActivityIds);
                flowTaskEntity.setThisStepId(String.join(",", setActiveActivityIds));
                List<String> activityNames= new ArrayList<>();
                for (String setActiveActivityId : setActiveActivityIds) {
                    FlowNode activity = getFlowNodeById(process, setActiveActivityId);
                    activityNames.add(activity.getName());
                }
                flowTaskEntity.setThisStep(String.join(",", activityNames));
            }
            Map<String, Object> processVariables = historicTaskInstance.getProcessVariables();
            flowTaskEntity.setId(historicTaskInstance.getId());
            flowTaskEntity.setProcessId(historicTaskInstance.getFormKey());
            flowTaskEntity.setEnCode(MapUtil.getStr(processVariables,GlobalProcessVariableConstants.BILL_CODE));
            flowTaskEntity.setFullName(MapUtil.getStr(processVariables, BUSINESS_TITLE));
            flowTaskEntity.setFlowUrgent(MapUtil.getInt(processVariables, GlobalProcessVariableConstants.FLOW_URGENT));
            flowTaskEntity.setFlowId(MapUtil.getStr(processVariables, GlobalProcessVariableConstants.FLOW_ENGINE_ID));
            flowTaskEntity.setFlowCode(processDefinitionEntity.getKey().replace(BasicActivitiConstants.activitiPrefix,""));
            flowTaskEntity.setFlowName(processDefinitionEntity.getName());
            flowTaskEntity.setFlowType(exPropertyDTO.getFlowType());
            flowTaskEntity.setFlowCategory(MapUtil.getStr(processVariables,GlobalProcessVariableConstants.PROCESS_CATEGORY));
            flowTaskEntity.setFlowForm(exPropertyDTO.getFormData());
            FormDataInfo formDataInfo = MapUtil.get(processVariables, FORM_INFO_JSON, FormDataInfo.class);
            if(formDataInfo!=null){
                flowTaskEntity.setFlowFormContentJson(formDataInfo.getFormDataJson());
            }
            flowTaskEntity.setFlowTemplateJson(exPropertyDTO.getFlowTemplateJson());
            flowTaskEntity.setFlowVersion(exPropertyDTO.getFlowVersion());
            flowTaskEntity.setCreatorTime(historicTaskInstance.getCreateTime());
            flowTaskEntity.setStartTime(historicProcessInstance.getStartTime());
            flowTaskEntity.setEndTime(historicTaskInstance.getEndTime());
            flowTaskEntity.setCreatorUserName(MapUtil.getStr(processVariables,APPLY_USER_NAME));
            flowTaskEntity.setFlowFormType(exPropertyDTO.getFlowFormType()+"");
            flowTaskEntity.setClaimTime(historicTaskInstance.getClaimTime());
//            flowTaskEntity.setDueDate(historicTaskInstance.getDueDate());
            if(historicProcessInstance.getEndTime()!=null){
                flowTaskEntity.setCompletion(100);
                flowTaskEntity.setCurrentNodeName("流程已结束");
            }
            else{
                String progress = taskExPropertyDTO.getUserTaskBasicPropDTO().getProgress();
                if(StringUtils.isNotBlank(progress)){
                    flowTaskEntity.setCompletion(Integer.valueOf(progress));
                }
                else{
                    flowTaskEntity.setCompletion(50);
                }
                flowTaskEntity.setCurrentNodeName(process.getFlowElement(activeActivityIds.get(0)).getName());
            }
            Integer anInt = MapUtil.getInt(processVariables, TASK_STATE);
            flowTaskEntity.setStatus(anInt==null?1:anInt);
            flowTaskEntity.setEnabledMark(1);
            result.add(flowTaskEntity);
        }


        return paginationFlowTask.setData(PageUtil.getListPage((int) paginationFlowTask.getCurrentPage(), (int) paginationFlowTask.getPageSize(), result), count);
    }

    @Override
    public List<FlowTaskEntity> getTrialList() {
        String userId = userProvider.getUserId();
        Map<String, Object> queryParam = new HashMap<>(16);
        StringBuilder dbSql = new StringBuilder();
        queryParam.put("handleId", userId);
        queryParam.put("sql", dbSql.toString());
        List<FlowTaskEntity> data = this.baseMapper.getTrialList(queryParam);
        return data;
    }

    @Override
    public List<FlowTaskEntity> getWaitList() {
        String userId = userProvider.getUserId();
        StringBuilder dbSql = new StringBuilder();
        //查询自己的待办
        dbSql.append(" AND (");
        dbSql.append("o.F_HandleId = '" + userId + "' ");
        //委托审核
        List<FlowDelegateEntity> flowDelegateList = flowDelegateService.getUser(userId);
        if (flowDelegateList.size() > 0) {
            dbSql.append(" OR ");
            for (int i = 0; i < flowDelegateList.size(); i++) {
                FlowDelegateEntity delegateEntity = flowDelegateList.get(i);
                //委托的人
                dbSql.append(" o.F_HandleId = '" + delegateEntity.getCreatorUserId() + "' ");
                if (flowDelegateList.size() - 1 > i) {
                    dbSql.append(" OR ");
                }
            }
            dbSql.append(")");
        } else {
            dbSql.append(")");
        }
        List<FlowTaskWaitListModel> data = this.baseMapper.getWaitList(dbSql.toString());
        //返回数据
        List<FlowTaskEntity> result = JsonUtil.getJsonToList(data, FlowTaskEntity.class);
        return result;
    }

    @Override
    public List<FlowTaskEntity> getAllWaitList() {
        StringBuilder dbSql = new StringBuilder();
        List<FlowTaskWaitListModel> data = this.baseMapper.getWaitList(dbSql.toString());
        List<FlowTaskEntity> result = JsonUtil.getJsonToList(data, FlowTaskEntity.class);
        return result;
    }

    @Override
    public List<FlowTaskEntity> getCirculateList(PaginationFlowTask paginationFlowTask) {
        LambdaQueryWrapper<FlowTaskCirculateEntity> queryWrapper = new LambdaQueryWrapper();
        String userId = userProvider.getUserId();
        queryWrapper.eq(FlowTaskCirculateEntity::getObjectId,userId);
        if(StringUtils.isNotBlank(paginationFlowTask.getKeyword())){
            queryWrapper.like(FlowTaskCirculateEntity::getEnCode,paginationFlowTask.getKeyword())
                    .or()
                    .like(FlowTaskCirculateEntity::getFullName,paginationFlowTask.getKeyword());
        }
        //日期范围
        String startTime = paginationFlowTask.getStartTime();
        String endTime = paginationFlowTask.getEndTime();
        if (!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
            Date startDate=new Date(Long.parseLong(startTime));
            Date endDate=new Date(Long.parseLong(endTime));
            queryWrapper.between(FlowTaskCirculateEntity::getCreatorTime,startDate,endDate);
        }
        String flowId = paginationFlowTask.getFlowId();
        if(StringUtils.isNotBlank(flowId)){
            queryWrapper.eq(FlowTaskCirculateEntity::getFlowId,flowId);
        }
        String flowCategory = paginationFlowTask.getFlowCategory();
        if(StringUtils.isNotBlank(flowCategory)){
            queryWrapper.eq(FlowTaskCirculateEntity::getFlowCategory,flowCategory);
        }

        String creatorUserId = paginationFlowTask.getCreatorUserId();
        if(StringUtils.isNotBlank(creatorUserId)){
            queryWrapper.eq(FlowTaskCirculateEntity::getCreateUserId,creatorUserId);
        }


        //排序
        if (SortType.DESC.equals(paginationFlowTask.getSort().toLowerCase())) {
            queryWrapper.orderByDesc(FlowTaskCirculateEntity::getUpdateTime);
        } else {
            queryWrapper.orderByAsc(FlowTaskCirculateEntity::getUpdateTime);
        }
        int count = flowTaskCirculateService.count(queryWrapper);
        List<FlowTaskCirculateEntity> data = flowTaskCirculateService.list(queryWrapper);
        Map<String,HistoricProcessInstance> processInstanceMap=new HashMap<>();
        if(CollUtil.isNotEmpty(data) && data.size()>0){
            Set<String> collect = data.stream().map(FlowTaskCirculateEntity::getTaskId).collect(Collectors.toSet());
            List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery().processInstanceIds(collect).includeProcessVariables().list();
            for (HistoricProcessInstance historicProcessInstance : list) {
                processInstanceMap.put(historicProcessInstance.getId(),historicProcessInstance);
            }
        }

        List<FlowTaskEntity> flowTaskEntityList= new ArrayList<>();
        for (FlowTaskCirculateEntity flowTaskCirculateEntity : data) {
            HistoricProcessInstance historicProcessInstance = processInstanceMap.get(flowTaskCirculateEntity.getTaskId());
            ProcessDefinitionEntity processDefinitionEntity = activitiUtils.getProcessDefinitionEntityById(historicProcessInstance.getProcessDefinitionId());
            Process process = getBpmnModelMainProcess(processDefinitionEntity.getId());
            String property = getAttributeValueByTaskDefinitionKey(process, "", "global");
            GlobalExPropertyDTO exPropertyDTO = JSONObject.parseObject(property.toString(), new TypeReference<GlobalExPropertyDTO>() {
            });
            FlowTaskEntity flowTaskEntity = new FlowTaskEntity();
            List<String> activeActivityIds =new ArrayList<>();
            if(historicProcessInstance.getEndTime()!=null){
                activeActivityIds.add("已结束");
                flowTaskEntity.setEndTime(historicProcessInstance.getEndTime());
                flowTaskEntity.setCurrentNodeName("流程已结束");
                flowTaskEntity.setCompletion(100);
                flowTaskEntity.setThisStep("已结束");
            }
            else{
                activeActivityIds = runtimeService.getActiveActivityIds(historicProcessInstance.getId());
                flowTaskEntity.setCompletion(50);
                flowTaskEntity.setCurrentNodeName(process.getFlowElement(activeActivityIds.get(0)).getName());
                List<String> activityNames= new ArrayList<>();
                for (String setActiveActivityId : CollUtil.distinct(activeActivityIds)) {
                    FlowNode activity = getFlowNodeById(process, setActiveActivityId);
                    activityNames.add(activity.getName());
                }
            }
            HashSet<String> setActiveActivityIds = new HashSet<>(activeActivityIds);
            Map<String, Object> processVariables = historicProcessInstance.getProcessVariables();
            flowTaskEntity.setId(historicProcessInstance.getId());
            flowTaskEntity.setProcessId(historicProcessInstance.getBusinessKey());
            flowTaskEntity.setEnCode(MapUtil.getStr(processVariables,GlobalProcessVariableConstants.BILL_CODE));
            flowTaskEntity.setFullName(MapUtil.getStr(processVariables, BUSINESS_TITLE));
            flowTaskEntity.setFlowUrgent(MapUtil.getInt(processVariables, GlobalProcessVariableConstants.FLOW_URGENT));
            flowTaskEntity.setFlowId(MapUtil.getStr(processVariables, GlobalProcessVariableConstants.FLOW_ENGINE_ID));
            flowTaskEntity.setFlowCode(processDefinitionEntity.getKey().replace(BasicActivitiConstants.activitiPrefix,""));
            flowTaskEntity.setFlowName(processDefinitionEntity.getName());
            flowTaskEntity.setFlowType(exPropertyDTO.getFlowType());
            flowTaskEntity.setFlowCategory(MapUtil.getStr(processVariables,GlobalProcessVariableConstants.PROCESS_CATEGORY));
            flowTaskEntity.setFlowForm(exPropertyDTO.getFormData());
            FormDataInfo formDataInfo = MapUtil.get(processVariables, FORM_INFO_JSON, FormDataInfo.class);
            flowTaskEntity.setFlowFormContentJson(formDataInfo.getFormDataJson());
            flowTaskEntity.setFlowTemplateJson(exPropertyDTO.getFlowTemplateJson());
            flowTaskEntity.setFlowVersion(exPropertyDTO.getFlowVersion());
            flowTaskEntity.setCreatorTime(flowTaskCirculateEntity.getCreatorTime());
            flowTaskEntity.setStartTime(historicProcessInstance.getStartTime());
            flowTaskEntity.setCreatorUserName(MapUtil.getStr(processVariables,APPLY_USER_NAME));
            flowTaskEntity.setFlowFormType(exPropertyDTO.getFlowFormType()+"");
            flowTaskEntity.setStatus(MapUtil.getInt(processVariables,GlobalProcessVariableConstants.PROCESS_STATUS));
            flowTaskEntity.setEnabledMark(1);
            flowTaskEntity.setThisStepId(String.join(",", setActiveActivityIds));
            List<FlowElement> activities = getFlowElementsWithOutSequenceFlow(process);
            flowTaskEntityList.add(flowTaskEntity);

        }
        return paginationFlowTask.setData(PageUtil.getListPage((int) paginationFlowTask.getCurrentPage(), (int) paginationFlowTask.getPageSize(), flowTaskEntityList), count);
    }

    @Override
    public FlowTaskEntity getInfo(String id) throws WorkFlowException {
        QueryWrapper<FlowTaskEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().and(
                t -> t.eq(FlowTaskEntity::getId, id)
                        .or().eq(FlowTaskEntity::getProcessId, id)
        );
        FlowTaskEntity entity = this.getOne(queryWrapper);
        if (entity == null) {
            throw new WorkFlowException("未找到流程任务");
        }
        return entity;
    }

    @Override
    public FlowTaskEntity getInfoSubmit(String id) {
        QueryWrapper<FlowTaskEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().and(
                t -> t.eq(FlowTaskEntity::getId, id)
                        .or().eq(FlowTaskEntity::getProcessId, id)
        );
        return this.getOne(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String processInstanceId,Boolean flag) throws WorkFlowException {
//        if (!checkStatus(entity.getStatus())) {
//            throw new WorkFlowException("当前流程正在运行不能删除");
//        }
//        else {
//            this.removeById(entity.getId());
            if(flag){
                historyService.deleteHistoricProcessInstance(processInstanceId);
            }
            else{
                runtimeService.deleteProcessInstance(processInstanceId,"在我发起页面执行删除操作");
                historyService.deleteHistoricProcessInstance(processInstanceId);
            }
//            QueryWrapper<FlowTaskNodeEntity> node = new QueryWrapper<>();
//            node.lambda().eq(FlowTaskNodeEntity::getTaskId, entity.getId());
//            flowTaskNodeService.remove(node);
            QueryWrapper<FlowTaskOperatorEntity> operator = new QueryWrapper<>();
            operator.lambda().eq(FlowTaskOperatorEntity::getTaskId, processInstanceId);
            flowTaskOperatorService.remove(operator);
            QueryWrapper<FlowTaskOperatorRecordEntity> record = new QueryWrapper<>();
            record.lambda().eq(FlowTaskOperatorRecordEntity::getTaskId, processInstanceId);
            flowTaskOperatorRecordService.remove(record);
            QueryWrapper<FlowTaskCirculateEntity> circulate = new QueryWrapper<>();
            circulate.lambda().eq(FlowTaskCirculateEntity::getTaskId, processInstanceId);
            flowTaskCirculateService.remove(circulate);
//        }
    }

    @Override
    public void deleteChild(FlowTaskEntity entity) {
        this.removeById(entity.getId());
        QueryWrapper<FlowTaskNodeEntity> node = new QueryWrapper<>();
        node.lambda().eq(FlowTaskNodeEntity::getTaskId, entity.getId());
        flowTaskNodeService.remove(node);
        QueryWrapper<FlowTaskOperatorEntity> operator = new QueryWrapper<>();
        operator.lambda().eq(FlowTaskOperatorEntity::getTaskId, entity.getId());
        flowTaskOperatorService.remove(operator);
        QueryWrapper<FlowTaskOperatorRecordEntity> record = new QueryWrapper<>();
        record.lambda().eq(FlowTaskOperatorRecordEntity::getTaskId, entity.getId());
        flowTaskOperatorRecordService.remove(record);
        QueryWrapper<FlowTaskCirculateEntity> circulate = new QueryWrapper<>();
        circulate.lambda().eq(FlowTaskCirculateEntity::getTaskId, entity.getId());
        flowTaskCirculateService.remove(circulate);
    }

    @Override
    public void delete(String[] ids) throws WorkFlowException {
        if (ids.length > 0) {
            for (String id : ids) {
                long count = runtimeService.createProcessInstanceQuery().processInstanceId(id).count();
                if(count>0){
                    runtimeService.deleteProcessInstance(id,"流程监控页面批量删除");
                    historyService.deleteHistoricProcessInstance(id);
                }
                else{
                    historyService.deleteHistoricProcessInstance(id);
                }
            }
            QueryWrapper<FlowTaskOperatorEntity> operator = new QueryWrapper<>();
            operator.lambda().in(FlowTaskOperatorEntity::getTaskId, ids);
            flowTaskOperatorService.remove(operator);
            QueryWrapper<FlowTaskOperatorRecordEntity> record = new QueryWrapper<>();
            record.lambda().in(FlowTaskOperatorRecordEntity::getTaskId, ids);
            flowTaskOperatorRecordService.remove(record);
            QueryWrapper<FlowTaskCirculateEntity> circulate = new QueryWrapper<>();
            circulate.lambda().in(FlowTaskCirculateEntity::getTaskId, ids);
            flowTaskCirculateService.remove(circulate);
        }
    }

    @Override
    public List<FlowTaskEntity> getTaskList(String id) {
        QueryWrapper<FlowTaskEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(FlowTaskEntity::getFlowId, id);
        return this.list(queryWrapper);
    }

    @Override
    public List<FlowTaskEntity> getOrderStaList(List<String> id) {
        List<FlowTaskEntity> list = new ArrayList<>();
        if (id.size() > 0) {
            QueryWrapper<FlowTaskEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(FlowTaskEntity::getId, id);
            list = this.list(queryWrapper);
        }
        return list;
    }

    @Override
    public List<FlowTaskEntity> getChildList(String id) {
        QueryWrapper<FlowTaskEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(FlowTaskEntity::getParentId, id);
        return this.list(queryWrapper);
    }

    @Override
    public void counterSign(CounterSignModel counterSignModel) {
        Boolean multiInstanceFlag = counterSignModel.getMultiInstanceFlag();
        String operator = counterSignModel.getOperator();
        String taskId = counterSignModel.getTaskId();
        List<String> candidateUsers = counterSignModel.getCandidateUsers();
        String user = counterSignModel.getUser();
        if(multiInstanceFlag==false){
            managementService.executeCommand(new SimpleUserTaskSignCmd(taskId,candidateUsers,operator));
        }
        else{
            String executionId = counterSignModel.getExecutionId();
            String taskDefinitionKey = counterSignModel.getTaskDefinitionKey();
            ExecutionEntity executionEntity = managementService.executeCommand(new GetRootExecutionEntityCmd(executionId, taskDefinitionKey));
            if("add".equals(operator)){
                Map<String,Object> variableMap= new HashMap<>();
                variableMap.put("assignee",counterSignModel.getUser());
                runtimeService.addMultiInstanceExecution(taskDefinitionKey,executionEntity.getId(),variableMap);
            }
            else{
                runtimeService.deleteMultiInstanceExecution(counterSignModel.getExecutionId(),true);
            }
        }
    }

    /**
     * 验证有效状态
     *
     * @param status 状态编码
     * @return
     */
    private boolean checkStatus(int status) {
        if (status == FlowTaskStatusEnum.Draft.getCode() || status == FlowTaskStatusEnum.Reject.getCode() || status == FlowTaskStatusEnum.Revoke.getCode()) {
            return true;
        } else {
            return false;
        }
    }

}
