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.TContingencyPlanContent;
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 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 StartContingencyPlan implements TaskListener {
    private final TEmergencyWorkingUserService tEmergencyWorkingUserService;
    private final TContingencyPlanContentService tContingencyPlanContentService;
    private final TMsgNoticeService tMsgNoticeService;
    private final TEmergencyRehearsalService tEmergencyRehearsalService;
    private static final Logger logger = LoggerFactory.getLogger(SafeTaskListener.class);
    public StartContingencyPlan() {
        this.tMsgNoticeService = SpringBeanFactory.getBean(TMsgNoticeService.class);
        this.tEmergencyRehearsalService =SpringBeanFactory.getBean(TEmergencyRehearsalService.class);
        this.tContingencyPlanContentService =SpringBeanFactory.getBean(TContingencyPlanContentService.class);
        this.tEmergencyWorkingUserService =SpringBeanFactory.getBean(TEmergencyWorkingUserService.class);
    }





    @Override
    public void notify(DelegateTask delegateTask) {
        logger.info("=============启动应急预案==============");
        Map<String, Object> variablesLocal = delegateTask.getVariablesLocal();
        // 对应业务值
        String bizKeyId = String.valueOf(variablesLocal.get("bizKeyId"));

        TEmergencyRehearsal evaluate = tEmergencyRehearsalService.getById(bizKeyId);

        Map<String , String > timeLine = (Map<String, String>) variablesLocal.get("timeLine");

        // 预案名称
        String planName = timeLine.get("planName");

        // 预案id
        String planId = timeLine.get("planId");

        List<TContingencyPlanContent> list = tContingencyPlanContentService.list(new QueryWrapper<TContingencyPlanContent>().eq(TContingencyPlanContent.PLAN_ID, planId)
                .ne(TContingencyPlanContent.STATUS, BizConstants.STATUS_DELETE)
        );
        // 应急措施
        String specific = "";
        if (list.size() > 0) {
            for (TContingencyPlanContent tContingencyPlanContent : list) {
                String specificWork = tContingencyPlanContent.getSpecificWork();
                specific += "[" + specificWork + "] ";
            }
        }

        // 获取应急工作小组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());
        // 模拟事件XXX（模拟事件名称）于X年X月X日X时X分X秒启动XXX（启动应急预案名称），请您及时采取XXX应急措施（预案中各小组【应急工作组及工作内容】中的应急措施））。
        String simulationEventName = evaluate.getSimulationEventName();
        String time = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒").format(new Date());
        String msg = "模拟事件" + simulationEventName + "于" + time + "启动" + planName + ",请您及时采取" + specific + "应急措施";
        // 发送消息
        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);
    }
}
