package com.testor.workflow.config;

import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.workflow.apis.definition.model.dto.ProcessDefStartParam;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

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

    @Resource
    private SysOrgService orgService;

    @Pointcut("execution(* com.tongtech.tfw.workflow.apis.definition.controller.ProcessDefinitionController.startProcessIns(..))")
    public void addTreeLevelPointCut() {
    }

    // 用户所属层级 '3' 粮库 ； '2' 区域公司 ； '1' 总部，默认路径；
    // private String treeLevel;

    /**
     * 启动流程后 创建任务 后 修改 任务执行人
     * @param joinPoint
     */
    @Before("addTreeLevelPointCut()")
    public void runBefore(JoinPoint joinPoint) {

        System.out.println("ProcessInsStartAspect runBefore()启动流程前执行！！！！！");

        try {
            UserInfo curUser = ContextUtils.getLoginUser();
            SysOrg sysOrg = orgService.getById(curUser.getOrgId());
            Object[] args = joinPoint.getArgs();
            for (Object arg : args) {
                if (arg instanceof ProcessDefStartParam){
                    ProcessDefStartParam processDefStartParam = (ProcessDefStartParam) arg;
                    Map variables = processDefStartParam.getVariables();
                    variables.put("treeLevel", sysOrg.getTreeLevel().toString());
                    processDefStartParam.setVariables(variables);
                }
            }

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

    }
}


