package net.ferrum.workflow.listener;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.ferrum.common.exception.ServiceException;
import net.ferrum.flowable.utils.TaskUtils;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.List;

/**
 * 流程节点携带参数记录监听类
 *
 * @author 26554
 * @version 1.0.0
 * @since 2025/2/26
 */

@Slf4j
@Component("variablePublishListener")
@RequiredArgsConstructor
public class VariablePublishListener implements ExecutionListener {

    private final TaskService taskService;

    @Override
    public void notify(DelegateExecution delegateExecution) {
        TaskQuery taskQuery = taskService.createTaskQuery()
            .active()
            .includeProcessVariables()
            .includeCaseVariables()
            .includeTaskLocalVariables()
            .taskCandidateOrAssigned(TaskUtils.getUserId())
            .taskCandidateGroupIn(TaskUtils.getCandidateGroup())
            .processDefinitionId(delegateExecution.getProcessDefinitionId())
            .processInstanceBusinessKey(delegateExecution.getProcessInstanceBusinessKey())
            ;
            //.orderByTaskCreateTime();
            //.desc();
        System.out.println("userid =" + TaskUtils.getUserId());
        System.out.println("getCandidateGroup =" + TaskUtils.getCandidateGroup());
        System.out.println("getProcessDefinitionId =" + delegateExecution.getProcessDefinitionId());

        long n = taskQuery.count();
        List<Task> taskQueryList = taskQuery.list();

        Task task = taskQuery.singleResult();
        if (task == null) {
            throw new ServiceException("任务没找到");
        }
        Field[] fields = delegateExecution.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                log.info("delegateExecution当前[{}]属性值为[{}]", field.getName(), field.get(delegateExecution));
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
        Field[] fields1 = task.getClass().getDeclaredFields();
        for (Field field : fields1) {
            field.setAccessible(true);
            try {
                log.info("task当前[{}]属性值为[{}]", field.getName(), field.get(task));
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
