package com.ruoyi.framework.task;

import com.ruoyi.common.sendEmail.IMailService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.reliability.domain.TBamList;
import com.ruoyi.project.reliability.service.ITBamListService;
import com.ruoyi.project.system.domain.TAlarmPrincipal;
import com.ruoyi.project.system.domain.TAlarmhistory;
import com.ruoyi.project.system.domain.TAlarmtype;
import com.ruoyi.project.system.service.ITAlarmPrincipalService;
import com.ruoyi.project.system.service.ITAlarmhistoryService;
import com.ruoyi.project.system.service.ITAlarmtypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 定时任务故障管理跟踪预警
 *
 * @author ruoyi
 */
@Component
public class BamlistTask extends BaseController
{
    /**
     * 注入发送邮件的接口
     */
    @Autowired
    private IMailService mailService;

    /**
     * 注入报警类型的接口
     */
    @Autowired
    private ITAlarmtypeService alarmtypeService;

    /**
     * 注入报警管理负责人的接口
     */
    @Autowired
    private ITAlarmPrincipalService alarmPrincipalService;
    /**
     * 注入报警记录管理的接口
     */
    @Autowired
    private ITAlarmhistoryService alarmhistoryService;

    /**
     * 注入故障管理跟踪的接口
     */
    @Autowired
    private ITBamListService bamListService;

    /**
     * 计划完成时间预警
     */
    public void PlanTask()
    {
        List<TBamList> bamLists = bamListService.selectList(new TBamList());
        TAlarmtype alarmtype = alarmtypeService.selectTAlarmtypeById(Long.parseLong("1043"));
        //判断报警是否开启
        if (alarmtype.getIsOpen() == 1) {
            //三级预警设置时间
            Long firstLevel = Math.round(Double.POSITIVE_INFINITY);
            Long secondLevel = Math.round(Double.POSITIVE_INFINITY);
            Long thirdLevel = Math.round(Double.POSITIVE_INFINITY);
            if (alarmtype.getFirstlevel() != null) { firstLevel = alarmtype.getFirstlevel() * 24 * 3600 * 1000; }
            if (alarmtype.getSecondlevel() != null) { secondLevel = alarmtype.getSecondlevel() * 24 * 3600 * 1000; }
            if (alarmtype.getThirdlevel() != null) { thirdLevel = alarmtype.getThirdlevel() * 24 * 3600 * 1000; }
            TAlarmPrincipal alarmPrincipal = new TAlarmPrincipal();
            //预警类型对应负责人
            alarmPrincipal.setTypeId(Long.parseLong("1043"));
            List<TAlarmPrincipal> alarmPrincipals = alarmPrincipalService.selectList(alarmPrincipal);
            String firstwarningContent = "";
            String secondwarningContent = "";
            String thirdwarningContent = "";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (TBamList t : bamLists) {
                if (t.getPlancompdate() != null) {
                    long difference = t.getPlancompdate().getTime() - new Date().getTime();
                    if (difference <= firstLevel) {
                        if (alarmtype.getFirstlevel() != null) {
                            firstwarningContent = alarmLevelContent(firstwarningContent, t.getDescription(), t.getFailbrief(), sdf.format(t.getPlancompdate()));
                        }
                    }else if (difference <= secondLevel) {
                        if (alarmtype.getSecondlevel() != null) {
                            secondwarningContent = alarmLevelContent(secondwarningContent, t.getDescription(), t.getFailbrief(), sdf.format(t.getPlancompdate()));
                        }
                    }else if (difference <= thirdLevel) {
                        if (alarmtype.getThirdlevel() != null) {
                            thirdwarningContent = alarmLevelContent(thirdwarningContent, t.getDescription(), t.getFailbrief(), sdf.format(t.getPlancompdate()));
                        }
                    }
                }
            }
            levelSendEmail(firstwarningContent, secondwarningContent, thirdwarningContent, alarmPrincipals, "故障管理跟踪", "list", "（设备名称，故障简述，计划完成时间）", "1043");
        }
    }

    /**
     * 预警内容拼接
     */
    public String alarmLevelContent(String alarmContent, String fieleOne, String fieldSecond, String fieldThird)
    {
        if (alarmContent == "") {
            alarmContent = fieleOne + ", " + fieldSecond + ", " + fieldThird;
        }else {
            alarmContent = alarmContent + ";<br>" + fieleOne + ", " + fieldSecond + ", " + fieldThird;
        }
        return alarmContent;
    }

    /**
     * 分级预警
     */
    public void levelSendEmail(String content1, String content2, String content3, List<TAlarmPrincipal> alarmPrincipals, String alarmType, String alarmTypeEn, String contenFormat, String typeId)
    {
        if (content1 != "") {
            sendEmail(alarmPrincipals, alarmType, "1级预警", content1, alarmTypeEn, contenFormat, typeId);
        }
        if (content2 != "") {
            sendEmail(alarmPrincipals, alarmType, "2级预警", content2, alarmTypeEn, contenFormat, typeId);
        }
        if (content3 != "") {
            sendEmail(alarmPrincipals, alarmType, "3级预警", content3, alarmTypeEn, contenFormat, typeId);
        }
    }

    /**
     * 发送预警邮件
     */
    public void sendEmail(List<TAlarmPrincipal> alarmPrincipals, String alarmType, String warningLevel, String warningContent, String alarmTypeEn, String contenFormat, String typeId)
    {
        //写html开始内容
        String start = "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title></title></head><body><div style=\"background-color:#ECECEC; padding: 35px;\">" +
                "<table cellpadding=\"0\" align=\"center\"" +
                "style=\"width: 600px; margin: 0px auto; text-align: left; position: relative; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; font-size: 14px; font-family:微软雅黑, 黑体; line-height: 1.5; box-shadow: rgb(153, 153, 153) 0px 0px 5px; border-collapse: collapse; background-position: initial initial; background-repeat: initial initial;background:#fff;\">" +
                "<tbody><tr><th valign=\"middle\" style=\"height: 25px; line-height: 25px; padding: 15px 35px; border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: #42a3d3; background-color: #49bcff; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px;\">" +
                "<font face=\"微软雅黑\" size=\"5\" style=\"color: rgb(255, 255, 255); \">化工装置管理系统 </font><font face=\"微软雅黑\" size=\"3\" style=\"color: rgb(255, 255, 255); \">Chemical Plant Management System(CPMS)</font></th></tr>";
        //写html结尾内容
        String end = "</tbody></table></div></body></html>";
        String username = "";
        String email = "";
        for (TAlarmPrincipal a : alarmPrincipals) {
            username = a.getPrincipalName();
            email = a.getPrincipalEmail();
            //表html中间内容
            String prime = "";
            String firstcenter = "<tr><td><div style=\"padding:25px 35px 40px; background-color:#fff;\"><h2 style=\"margin: 5px 0px; \">" +
                    "<font color=\"#333333\" style=\"line-height: 20px; \"><font style=\"line-height: 22px; \" size=\"4\">" +
                    "亲爱的 username</font><br><font style=\"line-height: 22px; \" size=\"4\">" +
                    "<p>您有一条预警信息：<br>" +
                    "预警类型：<b>alarmType</b><br>" +
                    "预警等级：<b>warningLevel</b><br>" +
                    "预警内容contenFormat：<b>warningContent</b><br>" +
                    "请前往<a href=\"http://47.114.101.16:8080/cpms/index.html#/reliability/bam/alarmTypeEn\">alarmType</a>查看。<br>" +
                    "<p align=\"right\">date</p>" +
                    "<div style=\"width:700px;margin:0 auto;\">" +
                    "<div style=\"padding:10px 10px 0;border-top:1px solid #ccc;color:#747474;margin-bottom:20px;line-height:1.3em;font-size:12px;\">" +
                    "<p>此为系统邮件，请勿回复<br>This e-Mail is an automatic reminder sent by CPMS, please do not reply</p>" +
                    "</div></div></div></td></tr>";
            String one = firstcenter.replaceFirst("username", username);
            String two = one.replaceFirst("alarmType", alarmType);
            String three = two.replaceFirst("warningLevel", warningLevel);
            String four = three.replaceFirst("contenFormat", contenFormat);
            String five = four.replaceFirst("warningContent", warningContent);
            String six = five.replaceFirst("alarmTypeEn", alarmTypeEn);
            String seven = six.replaceFirst("alarmType", alarmType);
            String result = seven.replaceFirst("date", String.valueOf(new Date()));
            prime = prime + result;
            //拼接html
            String html = start + prime + end;
            mailService.sendHtmlMail(email, "CPMS：您有一条预警信息", html);
            String level = warningLevel.substring(0,1);
            insertHistory(a, level, warningContent, typeId, alarmType);
        }
    }

    /**
     * 预警记录管理新增
     */
    public void insertHistory(TAlarmPrincipal a, String warningLevel, String warningContent, String typeId, String alarmType) {
        //预警记录管理新增
        TAlarmhistory alarmhistory = new TAlarmhistory();
        alarmhistory.setPlantCode(a.getPlantCode());
        alarmhistory.setTableName(alarmType);
        alarmhistory.setStaffid(a.getStaffid());
        alarmhistory.setDeptId(a.getDeptId());
        alarmhistory.setTypeId(Long.parseLong(typeId));
        alarmhistory.setAlarmLevel(warningLevel);
        alarmhistory.setAlarmContent(StringUtils.remove(warningContent, "<br>"));
        String[] content = StringUtils.remove(warningContent, "<br>").split(";");
        if (content.length == 0) {
            alarmhistory.setAlarmNum(Long.parseLong(String.valueOf("1")));
        }else {
            alarmhistory.setAlarmNum(Long.parseLong(String.valueOf(content.length)));
        }
        alarmhistory.setSendTime(new Date());
        alarmhistoryService.insertTAlarmhistory(alarmhistory);
    }
}
