package com.testor.workflow.config;

import com.alibaba.fastjson.JSON;
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.service.TfwTaskService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.flowable.engine.HistoryService;
import org.flowable.task.api.Task;
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.*;

/**
 * 此切面方法暂时无用（IdentityLinkService 未加入spring容器中进行管理）
 */
@Aspect  // 使用@Aspect注解声明一个切面
@Component
public class IdentityLinkServiceAspect {

    @Autowired
    private TfwTaskService tfwTaskService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private TSysOrgService orgService;

    @Pointcut("execution(* org.flowable.identitylink.service.IdentityLinkService.addCandidateGroups(..))")
    public void addCandidateGroupsPointCut() {
    }

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

    @Pointcut("execution(* org.flowable.ui.modeler.rest.app.ModelResource.getModel(..))")
    public void addCandidateGroupsPointCut3() {
    }

//    @Before("addCandidateGroupsPointCut2()")
//    public void beforeDo() {
//        String ss = "dddd";
//        System.out.println("IdentityLinkService beforeDo()执行前执行了！！！！！"+ss);
//
//    }

    @Around("addCandidateGroupsPointCut()")
    public Object runAround(ProceedingJoinPoint  joinPoint){
        System.out.println("IdentityLinkService addCandidateGroups()执行前执行了！！！！！");

        try {
            Object[] args = joinPoint.getArgs();
            if(args == null || args.length == 0) {
                Object result = joinPoint.proceed(args);
                return result;
            }
            String taskId = (String)args[0];
            Task task = tfwTaskService.getRuTask(taskId);
            String orgPath = findExecutorOrg(task.getProcessInstanceId(), task.getExecutionId());
            if(orgPath == null) {
                Object result = joinPoint.proceed(args);
                return result;
            }
            String[] arrOrgPath = orgPath.split(",");
            int arrOrgPathSize = arrOrgPath.length;

            Collection<String> candidateGroups = (Collection<String>)args[1];
            for(String group : candidateGroups) {
                if(group.indexOf("-") < 0) {
                    continue;
                }
                String[] arrStr = group.split("-");
                String level = arrStr[0];
                String newGroup = null;
                if("1".equals(level) && arrOrgPathSize > 0) { // 总部
                    newGroup = arrOrgPath[1]+"-"+arrStr[1];
                } else if("2".equals(level) && arrOrgPathSize > 1) { // 区域分公司
                    newGroup = arrOrgPath[2]+"-"+arrStr[1];
                } else if("3".equals(level) && arrOrgPathSize > 2) {  // 粮库
                    newGroup = arrOrgPath[3]+"-"+arrStr[1];
                } else {
                    newGroup = "32cdbb3a278944f1a83ca40dbcc93c0a"+arrStr[1];
                }

                group = newGroup;
            }

            System.out.println("替换参数： "+ JSON.toJSONString(candidateGroups));
            Object result = joinPoint.proceed(args);
            return result;
        }catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取 单据提交者 所属单位的全路径
     * @param processInstanceId
     * @param executionId
     * @return
     */
    public String findExecutorOrg(String processInstanceId, String executionId) {
        if (StringHelper.isNotBlank(processInstanceId)) {
            HistoricVariableInstanceQuery historicVariableInstanceQuery =
                    historyService
                            .createHistoricVariableInstanceQuery()
                            .processInstanceId(processInstanceId);
            if (StringHelper.isNotEmpty(executionId)) {
                historicVariableInstanceQuery.executionId(executionId);
            }

            List<HistoricVariableInstance> hisVarList = historicVariableInstanceQuery.list();
            Map<String, Object> params = new HashMap<>();
            for (HistoricVariableInstance historicVariableInstance : hisVarList) {
                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;
    }

}


