package com.testor.workflow.config;

import com.alibaba.fastjson.JSON;
import com.testor.module.messageNotice.service.TMsgNoticeService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 任务完成全局监听器
 *
 * 注： 如果要使用此全局消息通知 则初始的form表单需要以下字段：
 * bizKeyId、title、processStatus、
 * receiverObj、 receiverType
 *
 * by sj
 */
@Component
@Slf4j
public class GlobalCompleteListener  implements FlowableEventListener {

    @Autowired
    private TMsgNoticeService tMsgNoticeService;

    @Override
    public void onEvent(FlowableEvent flowableEvent) {
        System.out.println("flowableEvent：" +JSON.toJSONString(flowableEvent));
        FlowableEntityEventImpl flowableEntity = (FlowableEntityEventImpl) flowableEvent;

        ExecutionEntityImpl executionEntity = (ExecutionEntityImpl)flowableEntity.getEntity();
        System.out.println("executionEntity：" + JSON.toJSONString(executionEntity));
        String startUserId = executionEntity.getStartUserId();
        Map variablesMap = executionEntity.getVariables();
        String processStatus = variablesMap.get("processStatus").toString();
        if(!processStatus.equals("5")) { // 审批通过（最终审批通过）
            return;
        }
//        // 业务数据id
//        String business_id = variablesMap.get("bizKeyId").toString();
//        // 业务标题
//        String title = variablesMap.get("title").toString();
        // 获取业务类型
        String proDefId = flowableEntity.getProcessDefinitionId();
        String businessKey = proDefId.split(":")[0];

        // todo 调用消息通知 新增 的接口 创建 消息通知
        // 此处直接调用业务接口进行处理
        tMsgNoticeService.processPassMsgHandle(startUserId, businessKey, variablesMap);
    }

    @Override
    public boolean isFailOnException() {
        return false;
    }

    @Override
    public boolean isFireOnTransactionLifecycleEvent() {
        return false;
    }

    @Override
    public String getOnTransaction() {
        return null;
    }
}
