package com.testor.module.emergency.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.testor.common.util.SpringBeanFactory;
import com.testor.module.emergency.model.domain.TEmergencyRehearsal;
import com.testor.module.emergency.model.domain.TEmergencyWorkingUser;
import com.testor.module.emergency.model.vo.TContingencyPlanContentVO;
import com.testor.module.emergency.service.TContingencyPlanContentService;
import com.testor.module.emergency.service.TEmergencyRehearsalService;
import com.testor.module.emergency.service.TEmergencyWorkingUserService;
import com.testor.module.messageNotice.model.domain.TMsgNotice;
import com.testor.module.messageNotice.model.vo.MsgTemplateVO;
import com.testor.module.messageNotice.service.TMsgNoticeService;
import com.testor.module.safe.task.SafeTaskListener;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.workflow.apis.task.controller.WfTaskController;
import com.tongtech.tfw.workflow.apis.task.model.dto.HisTasksRequest;
import com.tongtech.tfw.workflow.apis.task.model.dto.HisTasksResponse;
import org.apache.commons.collections.CollectionUtils;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.task.service.delegate.DelegateTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


public class DispositionOver implements TaskListener {
    private final TMsgNoticeService tMsgNoticeService;
    private final TEmergencyWorkingUserService tEmergencyWorkingUserService;
    private final WfTaskController wfTaskController;
    private final TContingencyPlanContentService tContingencyPlanContentService;
    private final TEmergencyRehearsalService tEmergencyRehearsalService;
    private static final Logger logger = LoggerFactory.getLogger(SafeTaskListener.class);
    public DispositionOver() {
        this.tMsgNoticeService = SpringBeanFactory.getBean(TMsgNoticeService.class);
        this.tEmergencyRehearsalService =SpringBeanFactory.getBean(TEmergencyRehearsalService.class);
        this.wfTaskController =SpringBeanFactory.getBean(WfTaskController.class);
        this.tContingencyPlanContentService =SpringBeanFactory.getBean(TContingencyPlanContentService.class);
        this.tEmergencyWorkingUserService =SpringBeanFactory.getBean(TEmergencyWorkingUserService.class);
    }





    @Override
    public void notify(DelegateTask delegateTask) {
        logger.info("=============处置结束============");
        //模拟事件XXX（模拟事件名称）于X年X月X日X时X分X秒处置结束。

        // 标记从升级预案直接关闭
        String owner = delegateTask.getOwner();

        Map<String, Object> variablesLocal = delegateTask.getVariablesLocal();
        // 对应业务值
        String bizKeyId = String.valueOf(variablesLocal.get("bizKeyId"));

        // 流程状态
        String processStatus = String.valueOf(variablesLocal.get("processStatus"));

        if ("4".equals(processStatus)) {
            // 流程实例id
//        String processId = evaluate.getProcessId();
            String processDefinitionId = delegateTask.getProcessInstanceId();

            // 获取业务数据
            TEmergencyRehearsal evaluate = tEmergencyRehearsalService.getOne(new QueryWrapper<TEmergencyRehearsal>().eq("process_id", processDefinitionId));
//        TEmergencyRehearsal evaluate = tEmergencyRehearsalService.getById(bizKeyId);

            // 获取历史节点
            HisTasksRequest hisTasksRequest = new HisTasksRequest();
            hisTasksRequest.setProcessInstanceId(processDefinitionId);
            List<HisTasksResponse> data = wfTaskController.getHistoryByInstanceId(hisTasksRequest).getData().getData();
            HisTasksResponse hisTasksResponse = data.get(data.size() - 4);
            if ("OVER".equals(owner)) {
                hisTasksResponse = data.get(data.size() - 2);
            }
            Map<String, Object> vars = hisTasksResponse.getVars();
            Map<String , String > timeLine = (Map<String, String>) vars.get("timeLine");
            String planId = timeLine.get("planId");
            if (StringHelper.isNotEmpty(planId)) {
                List<String> userIdList = getUserList(planId);
                // 事件上报人
                userIdList.add(evaluate.getCreateBy());
                // 模拟事件名称
                String simulationEventName = evaluate.getSimulationEventName();
                String time = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒").format(new Date());
                String msg = simulationEventName + "于"+time+"处置结束";
                // 发送消息
                MsgTemplateVO msgTemplateVO = new MsgTemplateVO();
                msgTemplateVO.setTemplateContent(msg);
                msgTemplateVO.setTemplateType("notice");
                msgTemplateVO.setTemplateTypeName("通知");
                String bizKey = "emergency_rehearsa";
                List<TMsgNotice> tMsgNotices = tMsgNoticeService.generateMsgNotice(bizKey, bizKeyId, userIdList, msgTemplateVO);
                tMsgNoticeService.saveBatch(tMsgNotices);
            }
        }

    }

    /**
     * 获取最后一次升级应急预案中的人员
     * @param planId
     * @return
     */
    private List<String> getUserList(String planId) {
        // 获取应急工作小组id
        List<TContingencyPlanContentVO> planContent = tContingencyPlanContentService.getList(planId);
        List<String> collect = planContent.stream().map(TContingencyPlanContentVO::getSmallId).distinct().collect(Collectors.toList());
        // 根据应急工作小组获取人员
        List<String> userIdList = tEmergencyWorkingUserService.list(new QueryWrapper<TEmergencyWorkingUser>().ne(TEmergencyWorkingUser.STATUS, BizConstants.STATUS_DELETE)
                .in(CollectionUtils.isNotEmpty(collect)&&collect.size()>0,TEmergencyWorkingUser.GROUP_ID, collect)
        ).stream().map(TEmergencyWorkingUser::getUserId).distinct().collect(Collectors.toList());
        return userIdList;
    }
}
