package com.ankaibei.workFlow.common.flow.listener;

import cn.hutool.core.util.StrUtil;
import com.ankaibei.workFlow.common.core.object.GlobalThreadLocal;
import com.ankaibei.workFlow.common.core.util.ApplicationContextHolder;
import com.ankaibei.workFlow.common.flow.model.FlowWorkOrder;
import com.ankaibei.workFlow.common.flow.service.FlowWorkOrderService;
import com.ankaibei.workFlow.common.flow.constant.FlowTaskStatus;
import com.ankaibei.workFlow.common.flow.util.FlowCustomExtFactory;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;

/**
 * 流程实例监听器，在流程实例结束的时候，需要完成一些自定义的业务行为。如：
 * 1. 更新流程工单表的审批状态字段。
 * 2. 业务数据同步。
 *
 * @author Buzhanyi
 * @date 2022-09-25
 */
@Slf4j
public class FlowFinishedListener implements ExecutionListener {

    private final FlowWorkOrderService flowWorkOrderService =
            ApplicationContextHolder.getBean(FlowWorkOrderService.class);
    private final FlowCustomExtFactory flowCustomExtFactory =
            ApplicationContextHolder.getBean(FlowCustomExtFactory.class);

    @Override
    public void notify(DelegateExecution execution) {
        if (!StrUtil.equals("end", execution.getEventName())) {
            return;
        }
        boolean enabled = GlobalThreadLocal.setDataFilter(false);
        try {
            String processInstanceId = execution.getProcessInstanceId();
            FlowWorkOrder workOrder = flowWorkOrderService.getFlowWorkOrderByProcessInstanceId(processInstanceId);
            if (workOrder == null) {
                return;
            }
            int flowStatus = FlowTaskStatus.FINISHED;
            if (workOrder.getFlowStatus().equals(FlowTaskStatus.CANCELLED)
                    || workOrder.getFlowStatus().equals(FlowTaskStatus.STOPPED)) {
                flowStatus = workOrder.getFlowStatus();
            }
            flowWorkOrderService.updateFlowStatusByProcessInstanceId(processInstanceId, flowStatus);
            if (workOrder.getOnlineTableId() == null) {
                flowCustomExtFactory.getBusinessDataExtHelper().updateFlowStatus(workOrder);
            } else {
                flowCustomExtFactory.getOnlineBusinessDataExtHelper().updateFlowStatus(workOrder);
            }
            if (flowStatus == FlowTaskStatus.FINISHED) {
                flowCustomExtFactory.getBusinessDataExtHelper().triggerSync(workOrder);
            }
        } finally {
            GlobalThreadLocal.setDataFilter(enabled);
        }
    }
}
