package com.testor.workflow.config;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.testor.module.notice.model.domain.TSysOrg;
import com.testor.module.notice.service.TSysOrgService;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.workflow.apis.identitylink.model.domain.ActRuIdentitylink;
import com.tongtech.tfw.workflow.apis.identitylink.service.ActRuIdentitylinkService;
import com.tongtech.tfw.workflow.apis.instance.controller.ProcessInstanceController;
import com.tongtech.tfw.workflow.apis.instance.model.dto.ProcessInsVarRequest;
import com.tongtech.tfw.workflow.apis.task.model.domain.ActRuTask;
import com.tongtech.tfw.workflow.apis.task.service.ActRuTaskService;
import com.tongtech.tfw.workflow.service.TfwTaskService;
import com.tongtech.tfw.workflow.service.dto.ProcessInsStartResult;
import com.tongtech.tfw.workflow.service.dto.TaskServiceResult;
import lombok.val;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.flowable.engine.HistoryService;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.flowable.variable.api.history.HistoricVariableInstanceQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Aspect  // 使用@Aspect注解声明一个切面
@Component
public class ProcessInsStartAspect {

    @Autowired
    private TfwTaskService tfwTaskService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private TSysOrgService orgService;

    @Autowired
    private ActRuTaskService actRuTaskService;

    @Autowired
    private ActRuIdentitylinkService actRuIdentitylinkService;

    @Autowired
    private ProcessInstanceController processInstanceController;



//    @Pointcut("execution(* com.tongtech.tfw.workflow.service.TfwProcessInsService.startProcessInsByKey(..))")
//    public void addCandidateGroupsPointCut() {
//    }

    /**
     * 启动流程后 创建任务 后 修改 任务执行人
     * @param joinPoint
     * @param methodResult
     */
    @AfterReturning(value = "execution(* com.tongtech.tfw.workflow.service.TfwProcessInsService.startProcessInsByKey(..))",
            returning = "methodResult")
    public void afterStart(JoinPoint joinPoint, Object methodResult) {

        System.out.println("ProcessInsStartAspect afterReturning()启动流程创建任务后执行！！！！！");

        try {
            System.out.println("请求返回内容为：" + methodResult.toString());
            ProcessInsStartResult startResult = (ProcessInsStartResult)methodResult;
            String processInsId = startResult.getCode();

            if(StrUtil.isBlank(processInsId)) {
              return;
            }
            String orgPath = findExecutorOrg(processInsId);
            if(orgPath == null) {
                return;
            }
            String[] arrOrgPath = orgPath.split(",");
            int arrOrgPathSize = arrOrgPath.length;

            LambdaQueryWrapper<ActRuTask> actRuTaskQueryWrapper = new LambdaQueryWrapper<>();
            actRuTaskQueryWrapper.eq(ActRuTask::getProcInstId, processInsId);
            ActRuTask task = actRuTaskService.getOne(actRuTaskQueryWrapper);
            if(task == null) {
                return;
            }

            LambdaQueryWrapper<ActRuIdentitylink> identitylinkQueryWrapper = new LambdaQueryWrapper<>();
            identitylinkQueryWrapper.eq(ActRuIdentitylink::getTaskId, task.getId())
            .eq(ActRuIdentitylink::getType, "candidate");
            List<ActRuIdentitylink> ruIdentitylinkList = actRuIdentitylinkService.list(identitylinkQueryWrapper);
            if(ruIdentitylinkList == null || ruIdentitylinkList.size() == 0) {
                return;
            }

            //判断执行流程是否为隐患台账
            actRuTaskQueryWrapper.like(ActRuTask::getProcDefId, "hiddenDangerReport");
            ActRuTask actRuTask = actRuTaskService.getOne(actRuTaskQueryWrapper);
            //如果是隐患台账
            if(actRuTask != null) {
                ProcessInsVarRequest processInsVarRequest = new ProcessInsVarRequest();
                processInsVarRequest.setProcessInstanceId(processInsId);
                Map<String, Object> data = processInstanceController.processInsVars(processInsVarRequest).getData();
                String orgId = data.get("orgId").toString();
                for (ActRuIdentitylink identitylink : ruIdentitylinkList) {
                    String group = identitylink.getGroupId();
                    if (StrUtil.isBlank(group) || group.indexOf("-") < 0) {
                        continue;
                    }
                    String[] arrStr = group.split("-");
                    String newGroup = orgId+"-"+arrStr[1];
                    identitylink.setGroupId(newGroup);
                    actRuIdentitylinkService.updateById(identitylink);
                }
            }else {
                int size = ruIdentitylinkList.size();
                //判断长度是否等于1 如果大于1是多候选组，多候选组newGroup的机构id要为启动者的机构id
                if (size == 1) {
                    for (ActRuIdentitylink identitylink : ruIdentitylinkList) {
                        String group = identitylink.getGroupId();
                        if (StrUtil.isBlank(group) || group.indexOf("-") < 0) {
                            continue;
                        }
                        String[] arrStr = group.split("-");
                        String level = arrStr[0];
                        String newGroup = null;
                        int index = Integer.parseInt(level); // 将 level 转换为整型
                        //如果机构层大于角色层级
                        if (arrOrgPathSize > index) {
                            newGroup = arrOrgPath[index] + "-" + arrStr[1];
                        }
                        //如果不大于 类似于北良公司在第三层，实际性质是基层粮库
                        else {
                            //取最后一位层级
                            newGroup = arrOrgPath[arrOrgPathSize - 1] + "-" + arrStr[1];
                        }
                        identitylink.setGroupId(newGroup);
                        actRuIdentitylinkService.updateById(identitylink);
                    }
                }else {
                    ProcessInsVarRequest processInsVarRequest = new ProcessInsVarRequest();
                    processInsVarRequest.setProcessInstanceId(processInsId);
                    Map<String, Object> data = processInstanceController.processInsVars(processInsVarRequest).getData();
                    String orgId = data.get("executorOrgId").toString();
                    for (ActRuIdentitylink identitylink : ruIdentitylinkList) {
                        String group = identitylink.getGroupId();
                        if (StrUtil.isBlank(group) || group.indexOf("-") < 0) {
                            continue;
                        }
                        String[] arrStr = group.split("-");
                        String newGroup = orgId+"-"+arrStr[1];
                        identitylink.setGroupId(newGroup);
                        actRuIdentitylinkService.updateById(identitylink);
                    }
                }
            }


        }catch (Throwable e) {
            e.printStackTrace();
        }

    }

    /**
     * 完成当前任务后 创建下级任务 后 修改 任务执行人
     * @param joinPoint
     * @param methodResult
     */
    @AfterReturning(value = "execution(* com.tongtech.tfw.workflow.service.TfwTaskService.completeTask(..))",
            returning = "methodResult")
    public void afterComplete(JoinPoint joinPoint, Object methodResult) {

        System.out.println("ProcessInsStartAspect afterComplete()当前任务完成创建下级任务后执行！！！！！");

        try {
            System.out.println("请求返回内容为：" + methodResult.toString());
            TaskServiceResult startResult = (TaskServiceResult)methodResult;
            String hisTaskId = startResult.getResult();
            HistoricTaskInstance activityInstanceList =
                    historyService
                            .createHistoricTaskInstanceQuery()
                            .taskId(hisTaskId)
                            .singleResult();
            String processInsId= activityInstanceList.getProcessInstanceId();
            if(StrUtil.isBlank(processInsId)) {
                return;
            }

            LambdaQueryWrapper<ActRuTask> actRuTaskQueryWrapper = new LambdaQueryWrapper<>();
            actRuTaskQueryWrapper.eq(ActRuTask::getProcInstId, processInsId);
            ActRuTask task = actRuTaskService.getOne(actRuTaskQueryWrapper);
            if(task == null) {
                return;
            }

            String orgPath = findExecutorOrg(processInsId);
            if(orgPath == null) {
                return;
            }
            String[] arrOrgPath = orgPath.split(",");
            int arrOrgPathSize = arrOrgPath.length;

            LambdaQueryWrapper<ActRuIdentitylink> identitylinkQueryWrapper = new LambdaQueryWrapper<>();
            identitylinkQueryWrapper.eq(ActRuIdentitylink::getTaskId, task.getId())
                    .eq(ActRuIdentitylink::getType, "candidate");
            List<ActRuIdentitylink> ruIdentitylinkList = actRuIdentitylinkService.list(identitylinkQueryWrapper);
            if(ruIdentitylinkList == null || ruIdentitylinkList.size() == 0) {
                return;
            }

            for(ActRuIdentitylink identitylink : ruIdentitylinkList) {
                String group = identitylink.getGroupId();
                if(StrUtil.isBlank(group) || group.indexOf("-") < 0) {
                    continue;
                }
                String[] arrStr = group.split("-");
                String level = arrStr[0];
                String newGroup = null;
                int index = Integer.parseInt(level); // 将 level 转换为整型
                if (arrOrgPathSize > index) {
                    newGroup = arrOrgPath[index] + "-" + arrStr[1];
                }else {
                    //取最后一位层级
                    newGroup = arrOrgPath[arrOrgPathSize -1] + "-" + arrStr[1];
                }
                identitylink.setGroupId(newGroup);
                actRuIdentitylinkService.updateById(identitylink);
            }


        }catch (Throwable e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取 单据提交者 所属单位的全路径
     * @param processInstanceId
     * @return
     */
    public String findExecutorOrg(String processInstanceId) {
        if (StringHelper.isNotBlank(processInstanceId)) {
            HistoricVariableInstanceQuery historicVariableInstanceQuery =
                    historyService
                            .createHistoricVariableInstanceQuery()
                            .processInstanceId(processInstanceId);
            List<HistoricVariableInstance> hisVarList = historicVariableInstanceQuery.list();
            Map<String, Object> params = new HashMap<>();
            for (HistoricVariableInstance historicVariableInstance : hisVarList) {
                if(!StrUtil.isBlank(historicVariableInstance.getTaskId())) {
                    continue;
                }
                if (!"executorOrgId".equals(historicVariableInstance.getVariableName())) {
                    continue;
                }
                String executorOrgId = historicVariableInstance.getValue().toString();
                TSysOrg org = orgService.getById(executorOrgId);
                if (org == null) {
                    return null;
                }
                String orgPath = org.getParentIds() + "," + org.getOrgId();
                return orgPath;
            }

            return null;
        }
        return null;
    }

}


