package com.testor.module.safe.handler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.testor.common.constant.StatusEnum;
import com.testor.common.util.DateUtil;
import com.testor.common.util.cron.CheckFrequencyEnum;
import com.testor.common.util.cron.FrequencyUtil;
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.model.domain.TSafeHazardOrg;
import com.testor.module.safe.service.TSafeHazardOrgService;
import com.testor.xxl.job.task.response.ReturnT;
import com.testor.xxl.job.task.util.CronUtil;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * TODO xxl job handler
 *
 * @author L
 * @version 1.0
 * @date 2022-08-25 11:00
 */
@Component
public class SafeHandler {

    private static final Logger logger = LoggerFactory.getLogger(SafeHandler.class);

    @Autowired
    private TMsgNoticeService tMsgNoticeService;

    @Autowired
    private TSafeHazardOrgService tSafeHazardOrgService;

    @Resource
    private FrequencyUtil frequencyUtil;


    /**
     * 发送单次消息
     */
    @XxlJob("hiddenRectificationSingle")
    public void hiddenRectificationSingle() {
        String params = XxlJobHelper.getJobParam();

        // 字典编码
        String bizKey = "hiddenDangerReport";
        // 字典值
        String templateType = "overdueNotice";
        MsgTemplateVO msgTemplateVO = new MsgTemplateVO();

        // 根据业务id获取隐患
        TSafeHazardOrg tSafeHazardOrg = tSafeHazardOrgService.getOne(new QueryWrapper<TSafeHazardOrg>().eq("id", params).eq("status", StatusEnum.USE.getCode()));
        if (ObjectHelper.isEmpty(tSafeHazardOrg)) {
            // 隐患为空 不发送
            return;
        }

        // 隐患名称
        String name = tSafeHazardOrg.getName();
        // 整改时间
        LocalDateTime rectifyDate = DateUtil.dateToLocalDateTime(tSafeHazardOrg.getRectifyDate());

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String timeStr = formatter.format(rectifyDate.atZone(ZoneId.systemDefault()));


        List<String> userIdList = new ArrayList<>();
        // 整改人
        String rectifyPeople = tSafeHazardOrg.getRectifyPeople();
        userIdList.add(rectifyPeople);

        msgTemplateVO.setTemplateTypeName("逾期通知");
        msgTemplateVO.setTemplateType(templateType);
        msgTemplateVO.setTemplateContent("您的整改工单任务 [" + name + "] 于 [" + timeStr + "] 逾期，请尽快处理。");

        List<TMsgNotice> tMsgNotices = tMsgNoticeService.generateMsgNotice(bizKey, tSafeHazardOrg.getId(), userIdList, msgTemplateVO);

        tMsgNoticeService.saveBatch(tMsgNotices);

    }

    /**
     * 创建前 x 时间点，轮询发送消息
     */
    @XxlJob("createHiddenRectification")
    public void createHiddenRectification() {
        String params = XxlJobHelper.getJobParam();

        JSONObject jsonParams = JSONObject.parseObject(params);

        String id = jsonParams.getString("id");
        // 任务频次 CheckFrequencyEnum 对应枚举
        String frequencyKey = jsonParams.getString("frequencyKey");

        String dayCode = CheckFrequencyEnum.day.getCode();
        String hourCode = CheckFrequencyEnum.hour.getCode();

        String taskCronStr = "";
        if (dayCode.equals(frequencyKey)) {
            // 每日
            taskCronStr = CronUtil.generateCronByEveryDay("00:00:00");
        } else if (hourCode.equals(frequencyKey)) {
            // 每时
            taskCronStr = CronUtil.generateCronByEveryHour(0, 0);
        }

        ReturnT hiddenRectificationPolling = frequencyUtil.createTaskJobResult(id, taskCronStr, "隐患上报-隐患整改-"+id+"-polling", "hiddenRectificationPolling");


    }

    /**
     * 轮询发送消息
     */
    @XxlJob("hiddenRectificationPolling")
    public void hiddenRectificationPolling() {
        String params = XxlJobHelper.getJobParam();
        logger.info("请求了:{}", params);

        // 字典编码
        String bizKey = "hiddenDangerReport";
        // 字典值
        String templateType = "overdueReminder";

        // 根据业务id获取隐患
        TSafeHazardOrg tSafeHazardOrg = tSafeHazardOrgService.getOne(new QueryWrapper<TSafeHazardOrg>().eq("id", params).eq("status", StatusEnum.USE.getCode()));
        if (ObjectHelper.isEmpty(tSafeHazardOrg)) {
            // 隐患为空 不发送
            return;
        }
        // 隐患名称
        String name = tSafeHazardOrg.getName();
        // 整改时间
        LocalDateTime rectifyDate = DateUtil.dateToLocalDateTime(tSafeHazardOrg.getRectifyDate());
        LocalDateTime now = LocalDateTime.now();
        int compareTo = rectifyDate.compareTo(now);

        // 判断整改时间是否超时
        if (0 > compareTo) {
            // 未超时 计算剩余时间
            Duration duration = Duration.between(rectifyDate, now);
            long toHours = duration.toHours();

            List<String> userIdList = new ArrayList<>();
            // 整改人
            String rectifyPeople = tSafeHazardOrg.getRectifyPeople();
            userIdList.add(rectifyPeople);

            MsgTemplateVO msgTemplateVO = new MsgTemplateVO();
            msgTemplateVO.setTemplateTypeName("逾期提醒");
            msgTemplateVO.setTemplateType(templateType);
            msgTemplateVO.setTemplateContent("您的整改工单任务 [" + name + "] 将在 ["+ toHours +"]个小时后逾期，请尽快处理。");


            List<TMsgNotice> tMsgNotices = tMsgNoticeService.generateMsgNotice(bizKey, tSafeHazardOrg.getId(), userIdList, msgTemplateVO);
            System.err.println(JSONArray.toJSONString(tMsgNotices));
            tMsgNoticeService.saveBatch(tMsgNotices);
        } else {
            // 超时  不发送  做任务删除处理
            return;
        }
    }
}
