package com.testor.workflow.config;


import cn.hutool.core.util.StrUtil;
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.idm.api.User;
import org.flowable.ui.common.model.RemoteUser;
import org.flowable.ui.common.security.DefaultPrivileges;
import org.flowable.ui.common.security.SecurityUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

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

//    public final String userPointCut = "execution(* org.flowable.ui.modeler.serviceapi.ModelService.createModel(..))&& args(modelRepresentation, json, user)";
//    @Before(value=userPointCut,argNames="modelRepresentation, json, user")
//    public void runBefore(ModelRepresentation modelRepresentation, String json, User user){
//        System.out.println("ModelsResourceAspect runBefore()执行前执行了！！！！！");
//            if(user == null) {
//                user = new RemoteUser();
//            }
//            user.setId("admin22");
//            user.setDisplayName("Administrator22");
//    }


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

    @Around("saveModelPointCut()")
    public Object runBefore(ProceedingJoinPoint  joinPoint){
      //  System.out.println("ModelResourceAspect runBefore()执行前执行了！！！！！");

        try {
            User currentUser = SecurityUtils.getCurrentUserObject();
            if(currentUser == null || StrUtil.isBlank(currentUser.getId())) {
                RemoteUser user = new RemoteUser();
                user.setId("admin");
                user.setDisplayName("Administrator");
                user.setFirstName("Administrator");
                user.setLastName("Administrator");
                user.setEmail("admin@flowable.com");
                user.setPassword("123456");
                List<String> pris = new ArrayList<>();
                pris.add(DefaultPrivileges.ACCESS_MODELER);
                pris.add(DefaultPrivileges.ACCESS_IDM);
                pris.add(DefaultPrivileges.ACCESS_ADMIN);
                pris.add(DefaultPrivileges.ACCESS_TASK);
                pris.add(DefaultPrivileges.ACCESS_REST_API);
                user.setPrivileges(pris);

                SecurityUtils.assumeUser(user);
            }
                 Object result = joinPoint.proceed();
            return result;
        }catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }
}


