package cn.fateverse.workflow.process.listener;

import cn.fateverse.admin.entity.User;
import cn.fateverse.workflow.constant.ProcessConstant;
import cn.fateverse.workflow.entity.HistoricalOperation;
import cn.fateverse.workflow.entity.bpmn.UserInfo;
import cn.fateverse.workflow.enums.OperationStateEnums;
import cn.fateverse.workflow.mapper.HistoricalOperationMapper;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;

/**
 * 事件创建监听器
 *
 * @author Clay
 * @date 2023-02-24
 */
@Component
public class CreateStartEventListener implements ExecutionListener {

    private final HistoricalOperationMapper operationMapper;

    public CreateStartEventListener(HistoricalOperationMapper operationMapper) {
        this.operationMapper = operationMapper;
    }

    @Override
    public void notify(DelegateExecution execution) {
        User user = (User) execution.getVariables().get(ProcessConstant.START_USER_INFO);
        UserInfo userInfo = UserInfo.toUserInfo(user);
        userInfo.setState(OperationStateEnums.AGREE);
        HistoricalOperation operation = HistoricalOperation.toHistoricalOperation(execution, userInfo);
        operation.setState(OperationStateEnums.CREATE);
        operationMapper.insert(operation);
    }
}
