package com.mortals.flowable.listener.global;

import com.alibaba.fastjson.JSON;
import com.mortals.framework.util.HttpUtil;
import com.mortals.xhx.common.code.PlatformTypeEnum;
import com.mortals.xhx.common.code.flowable.runtime.ProcessStatusEnum;
import com.mortals.xhx.common.pdu.flow.FlowTaskNotifyPdu;
import com.mortals.xhx.flowable.message.FlowMessageReq;
import com.mortals.xhx.module.platform.model.PlatformEntity;
import com.mortals.xhx.module.platform.model.PlatformListenerQuery;
import com.mortals.xhx.module.platform.model.PlatformQuery;
import com.mortals.xhx.module.platform.service.PlatformListenerService;
import com.mortals.xhx.module.platform.service.PlatformModelinfoService;
import com.mortals.xhx.module.platform.service.PlatformService;
import lombok.extern.apachecommons.CommonsLog;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.common.engine.impl.event.FlowableEntityEventImpl;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.identitylink.api.IdentityLink;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 任务创建全局监听
 *
 * @author: zxfei
 * @date: 2021/9/9 11:48
 */
@Component
@CommonsLog
public class GlobalTaskCreateListener extends AbstractFlowableEngineEventListener {

    public static String TaskCreate = "2";

    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;

    @Autowired
    private PlatformService platformService;
    @Autowired
    private PlatformListenerService platformListenerService;


    @Override
    protected void taskCreated(FlowableEngineEntityEvent event) {
        log.info("进入任务创建全局监听");


        List<String> userNameList = new ArrayList<>();
        FlowableEntityEventImpl flowableEntityEvent = (FlowableEntityEventImpl) event;

        TaskEntity taskEntity = (TaskEntity) (flowableEntityEvent).getEntity();

        if (!ObjectUtils.isEmpty(taskEntity.getParentTaskId())) {
            log.info("当前任务为子任务");
            return;
        }

        String taskId = taskEntity.getId();

        String scopeType = taskEntity.getScopeType();
        log.info(String.format("任务类型:%s", scopeType));
        String scopeId = taskEntity.getScopeId();


        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(taskEntity.getProcessInstanceId()).singleResult();

        if (historicProcessInstance == null) {
            log.info("historicProcessInstance is null!");
            return;
        }

        List<IdentityLink> idList = taskService.getIdentityLinksForTask(taskId);
        if (CollectionUtils.isEmpty(idList)) {
            log.info("idList is null!");

        }

        log.info("idList:" + JSON.toJSONString(idList));

        // 获取接收人，区分审核人，候选组，并行等  todo
        idList.forEach(identityLink -> {
            if (StringUtils.isNotBlank(identityLink.getUserId())) {
                userNameList.add(identityLink.getUserId());
            }
        });

        //发送消息或者http回调
        PlatformEntity modelinfoEntity = platformService.selectOne(new PlatformQuery().platformSn(taskEntity.getTenantId()), null);
        if (ObjectUtils.isEmpty(modelinfoEntity)) {
            log.info("平台用户为空，sn:" + taskEntity.getTenantId());
            return;
        }

        //校验当前平台用户是否订阅了流程终结消息
        Set<String> collect = platformListenerService.find(new PlatformListenerQuery().platformId(modelinfoEntity.getId())).stream().map(item -> item.getTypeCode()).collect(Collectors.toSet());

        if (!collect.contains(TaskCreate)) {
            log.info("当前平台用户未订阅任务创建通知，sn:" + modelinfoEntity.getPlatformSn());
            return;
        }

        //手动终止撤销的不触发通知消息
        if (!ObjectUtils.isEmpty(modelinfoEntity)) {
            if (PlatformTypeEnum.HTTP.getValue() == modelinfoEntity.getType()) {
                //http
                FlowMessageReq flowMessageReq = new FlowMessageReq();
                flowMessageReq.setPlatformSn(taskEntity.getTenantId());
                flowMessageReq.setType(Integer.parseInt(TaskCreate));
                flowMessageReq.setTaskId(taskEntity.getId());
                flowMessageReq.setBusinessKey(historicProcessInstance.getBusinessKey());
                flowMessageReq.setProcessInstanceId(taskEntity.getProcessInstanceId());
                flowMessageReq.setAssigneeList(userNameList);
                flowMessageReq.setFormName(historicProcessInstance.getName());

                doPostMessage(modelinfoEntity.getCallbackUrl(), flowMessageReq);

            } else if (PlatformTypeEnum.JMS.getValue() == modelinfoEntity.getType()) {
                //todo
            }
        }
    }

    private void doPostMessage(String url, FlowMessageReq flowMessageReq) {
        String ret = "";
        try {
            log.info(String.format("发送请求,url:%s,body:%s", url, JSON.toJSONString(flowMessageReq)));
            HashMap<String, String> header = new HashMap<>();
            header.put("Content-Type", "application/json");
            ret = HttpUtil.doPost(url, header, JSON.toJSONString(flowMessageReq));
            log.info("收到响应:" + ret);
        } catch (Exception e) {
            log.error("回调异常", e);
//            try {
//                Thread.sleep(10000);
//            } catch (InterruptedException interruptedException) {
//                interruptedException.printStackTrace();
//            }
//            doPostMessage(url,flowMessageReq);
        }
    }


    @Override
    protected void taskCompleted(FlowableEngineEntityEvent event) {

        super.taskCompleted(event);
    }
}
