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.ehs.domain.*;
import com.ruoyi.project.ehs.service.*;
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.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 定时任务消防应急设施预警
 *
 * @author ruoyi
 */
@Component
public class FireTask extends BaseController
{
    /**
     * 注入发送邮件的接口
     */
    @Autowired
    private IMailService mailService;

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

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

    /**
     * 注入报警记录管理的接口
     */
    @Autowired
    private ITAlarmhistoryService alarmhistoryService;

    /**
     * 注入灭火器的接口
     */
    @Autowired
    private ITFireextinguisherService fireextinguisherService;

    /**
     * 注入洗眼器的接口
     */
    @Autowired
    private ITEyewasherService eyewasherService;

    /**
     * 注入消防水带箱的接口
     */
    @Autowired
    private ITFirehoseService firehoseService;

    /**
     * 注入消防栓的接口
     */
    @Autowired
    private ITFirehydrantService firehydrantService;

    /**
     * 注入高压消防炮的接口
     */
    @Autowired
    private ITHighpresfireService highpresfireService;

    /**
     * 注入自动喷淋系统的接口
     */
    @Autowired
    private ITAutosprinklerService autosprinklerService;

    /**
     * 注入消防竖管的接口
     */
    @Autowired
    private ITFirestandpipeService firestandpipeService;

    /**
     * 灭火器5号预警，20号预警
     */
    public void FiveTask() throws ParseException {
        List<TFireextinguisher> fireextinguishers = fireextinguisherService.selectList(new TFireextinguisher());
        TAlarmtype alarmtype = alarmtypeService.selectTAlarmtypeById(Long.parseLong("1020"));
        //判断报警是否开启
        if (alarmtype.getIsOpen() == 1) {
            //查询预警负责人
            TAlarmPrincipal alarmPrincipal = new TAlarmPrincipal();
            alarmPrincipal.setTypeId(Long.parseLong("1020"));
            List<TAlarmPrincipal> alarmPrincipals = alarmPrincipalService.selectList(alarmPrincipal);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String warningContent = "";
            for (TFireextinguisher f : fireextinguishers) {
                if (f.getUpinspectdate() != null) {
                    long difference = f.getUpinspectdate().getTime() - sdf.parse(sdf.format(new Date())).getTime();
                    if (difference <= 10 * 24 * 3600 * 1000) {
                        warningContent = alarmLevelContent(warningContent, f.getLocation(), f.getNumb(), sdf.format(f.getUpinspectdate()));
                    }
                }
            }
            levelSendEmail("", warningContent, "", alarmPrincipals, "灭火器", "fireextinguisher", "（设备位置，设备编号，检查日期/上旬）", "1020");
        }
    }

    /**
     * 灭火器10号预警，25号预警
     */
    public void TenTask() throws ParseException
    {
        List<TFireextinguisher> fireextinguishers = fireextinguisherService.selectList(new TFireextinguisher());
        TAlarmtype alarmtype = alarmtypeService.selectTAlarmtypeById(Long.parseLong("1020"));
        //判断报警是否开启
        if (alarmtype.getIsOpen() == 1) {
            //查询预警负责人
            TAlarmPrincipal alarmPrincipal = new TAlarmPrincipal();
            alarmPrincipal.setTypeId(Long.parseLong("1020"));
            List<TAlarmPrincipal> alarmPrincipals = alarmPrincipalService.selectList(alarmPrincipal);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String warningContent = "";
            for (TFireextinguisher f : fireextinguishers) {
                if (f.getUpinspectdate() != null) {
                    long difference = f.getUpinspectdate().getTime() - sdf.parse(sdf.format(new Date())).getTime();
                    if (difference <= 5 * 24 * 3600 * 1000) {
                        warningContent = alarmLevelContent(warningContent, f.getLocation(), f.getNumb(), sdf.format(f.getUpinspectdate()));
                    }
                }
            }
            levelSendEmail(warningContent, "", "", alarmPrincipals, "灭火器", "fireextinguisher", "（设备位置，设备编号，检查日期/上旬）", "1020");
        }
    }

    /**
     * 其他消防设施预警（默认设定15号二级（10天））
     */
    public void OtherFirstTask() throws ParseException
    {
        Long differ = Long.parseLong(String.valueOf(10 * 24 * 3600 * 1000));
        otherFire("15", differ);
    }

    /**
     * 其他消防设施预警（默认设定20号为一级（5天））
     */
    public void OtherSecondTask() throws ParseException {
        Long differ = Long.parseLong(String.valueOf(5 * 24 * 3600 * 1000));
        otherFire("20", differ);
    }

    /**
     * 其他消防设施预警
     */
    public void otherFire(String level, Long differ) throws ParseException
    {
        TAlarmtype alarmtype = alarmtypeService.selectTAlarmtypeById(Long.parseLong("1020"));
        //判断报警是否开启
        if (alarmtype.getIsOpen() == 1) {
            //预警类型对应负责人
            TAlarmPrincipal alarmPrincipal = new TAlarmPrincipal();
            alarmPrincipal.setTypeId(Long.parseLong("1020"));
            List<TAlarmPrincipal> alarmPrincipals = alarmPrincipalService.selectList(alarmPrincipal);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //洗眼器
            List<TEyewasher> eyewashers = eyewasherService.selectList(new TEyewasher());
            String warningContent = "";
            for (TEyewasher e : eyewashers) {
                if (e.getInspectdate() != null) {
                    long difference = e.getInspectdate().getTime() - sdf.parse(sdf.format(new Date())).getTime();
                    if (difference <= differ) {
                        warningContent = alarmLevelContent(warningContent, e.getArea(), e.getPosition(), sdf.format(e.getInspectdate()));
                    }
                }
            }
            if (level == "15") {
                levelSendEmail("", warningContent, "", alarmPrincipals, "洗眼器", "eyewasher", "（区域，位置，检查日期）", "1020");
            }else if (level == "20") {
                levelSendEmail(warningContent, "", "", alarmPrincipals, "洗眼器", "eyewasher", "（区域，位置，检查日期）", "1020");
            }

            //消防水带箱
            List<TFirehose> firehoses = firehoseService.selectList(new TFirehose());
            warningContent = "";
            for (TFirehose f : firehoses) {
                if (f.getInspectdate() != null) {
                    long difference = f.getInspectdate().getTime() - sdf.parse(sdf.format(new Date())).getTime();
                    if (difference <= differ) {
                        warningContent = alarmLevelContent(warningContent, f.getPosition(), f.getInspector(), sdf.format(f.getInspectdate()));
                    }
                }
            }
            if (level == "15") {
                levelSendEmail("", warningContent, "", alarmPrincipals, "消防水带箱", "firehose", "（位置，检查人，检查日期）", "1020");
            }else if (level == "20") {
                levelSendEmail(warningContent, "", "", alarmPrincipals, "消防水带箱", "firehose", "（位置，检查人，检查日期）", "1020");
            }


            //消防栓
            List<TFirehydrant> firehydrants = firehydrantService.selectList(new TFirehydrant());
            warningContent = "";
            for (TFirehydrant f : firehydrants) {
                if (f.getInspectdate() != null) {
                    long difference = f.getInspectdate().getTime() - sdf.parse(sdf.format(new Date())).getTime();
                    if (difference <= differ) {
                        warningContent = alarmLevelContent(warningContent, f.getArea(), f.getPosition(), sdf.format(f.getInspectdate()));
                    }
                }
            }
            if (level == "15") {
                levelSendEmail("", warningContent, "", alarmPrincipals, "消防栓", "firehydrant", "（区域，位置，检查日期）", "1020");
            }else if (level == "20") {
                levelSendEmail(warningContent, "", "", alarmPrincipals, "消防栓", "firehydrant", "（区域，位置，检查日期）", "1020");
            }

            //高压消防炮
            List<THighpresfire> highpresfires = highpresfireService.selectList(new THighpresfire());
            warningContent = "";
            for (THighpresfire f : highpresfires) {
                if (f.getInspectdate() != null) {
                    long difference = f.getInspectdate().getTime() - sdf.parse(sdf.format(new Date())).getTime();
                    if (difference <= differ) {
                        warningContent = alarmLevelContent(warningContent, f.getArea(), f.getPosition(), sdf.format(f.getInspectdate()));
                    }
                }
            }
            if (level == "15") {
                levelSendEmail("", warningContent, "", alarmPrincipals, "高压消防炮", "highpresfire", "（区域，位置，检查日期）", "1020");
            }else if (level == "20") {
                levelSendEmail(warningContent, "", "", alarmPrincipals, "高压消防炮", "highpresfire", "（区域，位置，检查日期）", "1020");
            }

            //自动喷淋系统
            List<TAutosprinkler> autosprinklers = autosprinklerService.selectList(new TAutosprinkler());
            warningContent = "";
            for (TAutosprinkler a : autosprinklers) {
                if (a.getInspectdate() != null) {
                    long difference = a.getInspectdate().getTime() - sdf.parse(sdf.format(new Date())).getTime();
                    if (difference <= differ) {
                        warningContent = alarmLevelContent(warningContent, a.getLocation(), a.getChkcontents(), sdf.format(a.getInspectdate()));
                    }
                }
            }
            if (level == "15") {
                levelSendEmail("", warningContent, "", alarmPrincipals, "自动喷淋系统", "autosprinkler", "（部位，检查内容，检查日期）", "1020");
            }else if (level == "20") {
                levelSendEmail(warningContent, "", "", alarmPrincipals, "自动喷淋系统", "autosprinkler", "（部位，检查内容，检查日期）", "1020");
            }

            //消防竖管
            List<TFirestandpipe> firestandpipes = firestandpipeService.selectList(new TFirestandpipe());
            warningContent = "";
            for (TFirestandpipe f : firestandpipes) {
                if (f.getInspectdate() != null) {
                    long difference = f.getInspectdate().getTime() - sdf.parse(sdf.format(new Date())).getTime();
                    if (difference <= differ) {
                        warningContent = alarmLevelContent(warningContent, f.getName(), f.getPosition(), sdf.format(f.getInspectdate()));
                    }
                }
            }
            if (level == "15") {
                levelSendEmail("", warningContent, "", alarmPrincipals, "消防竖管", "firestandpipe", "（名称，位置，检查日期）", "1020");
            }else if (level == "20") {
                levelSendEmail(warningContent, "", "", alarmPrincipals, "消防竖管", "firestandpipe", "（名称，位置，检查日期）", "1020");
            }
        }
    }

    /**
     * 预警内容拼接
     */
    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#/ehs/fire/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);
    }
}
