package com.ruoyi.framework.task.sems.measure;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.sendEmail.IMailService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.sems.domain.TMeasureThickness;
import com.ruoyi.project.sems.service.ITMeasureThicknessService;
import com.ruoyi.project.system.domain.*;
import com.ruoyi.project.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 特种设备预警标识定时任务
 */

@Component("measureThicknessEstTask")
public class MeasureThicknessEstTask extends BaseController {
    //注入发送邮件的接口
    @Autowired
    private IMailService mailService;
    //注入特种设备预警接口
    @Autowired
    private ITAlarmtypeService tAlarmtypeService;
    //注入预警管理负责人接口
    @Autowired
    private ITAlarmPrincipalService tAlarmPrincipalService;
    //注入用户接口
    @Autowired
    private ISysUserService sysUserService;
    //注入报警记录管理的接口
    @Autowired
    private ITAlarmhistoryService alarmhistoryService;
    @Autowired
    private ISysPlantService sysPlantService;
    @Autowired
    private ITMeasureThicknessService measureThicknessService;
    //系统基础配置
    @Autowired
    private RuoYiConfig ruoyiConfig;

    private final String stAlarmType = "定点测厚-预估剩余寿命小于1年";
    private final String estAlarmType = "定点测厚-预估剩余寿命小于5年";
    private final String glUrlSuffix = "sems/thickness";

    private final Long alarmtype = 1080L;//特种设备预警ID

    private final String contentFormat = "（装置名称，单元，单位内编号，侧厚部位）";

    /**
     * 检查预警标识状态
     * 3天检查一次
     */
    public void checkWarnFlag() {
        //获取动态处理预警级别
        TAlarmtype tAlarmtype = this.tAlarmtypeService.selectTAlarmtypeById(this.alarmtype);
        if (tAlarmtype.getIsOpen() == 0) {
            logger.info("特种设备预警标识定时任务未启用");
            return;
        }

        //获取需要发送邮件的人员信息
        TAlarmPrincipal tAlarmPrincipal = new TAlarmPrincipal();
        tAlarmPrincipal.setTypeId(this.alarmtype);
        List<TAlarmPrincipal> userList = this.tAlarmPrincipalService.selectList(tAlarmPrincipal);
        for (TAlarmPrincipal t : userList) {
            SysUser user = this.sysUserService.selectUserByStaffId(t.getStaffid());
            if (user != null) {
                logger.info("发送人"+user.getNickName() + "--发送邮箱：" + user.getEmail());
                t.setPrincipalName(user.getNickName());
                t.setPrincipalEmail(user.getEmail());
            }
        }
        List<TMeasureThickness> stList = new ArrayList<>();
        List<TMeasureThickness> estList = new ArrayList<>();
        //
        for (TAlarmPrincipal o : userList) {
            //根据装置权限获取数据
            List<SysPlant> plantList = sysPlantService.selectSysPlantByDeptId(o.getDeptId());
            logger.info("部门id"+o.getDeptId() + "--部门：" + plantList.toString());
            List<String> plants = new ArrayList<>();
            for (SysPlant s : plantList
            ) {
                plants.add(s.getName());
            }
            List<TMeasureThickness> list = this.measureThicknessService.list(new QueryWrapper<TMeasureThickness>()
                    .eq("del_flag", 0).eq("is_send" , 0)
                    .in("plant_code", plants)
            );
            for (TMeasureThickness tMeasureThickness : list) {
                if (tMeasureThickness.getEstRemain() != null) {
                    if (new BigDecimal(tMeasureThickness.getEstRemain()).compareTo(new BigDecimal("1")) <= 0) { //寿命小于1年
                        stList.add(tMeasureThickness);
                    }
                }
                if (tMeasureThickness.getEstRemain() != null) {
                    if (new BigDecimal(tMeasureThickness.getEstRemain()).compareTo(new BigDecimal("5")) <= 0) { //寿命小于5年
                        estList.add(tMeasureThickness);
                    }
                }
            }
            sendEmailBySt(stList , o );
            sendEmailByEst(estList , o );
        }
        // 标记 已发送邮件
        List<TMeasureThickness> sendList = this.measureThicknessService.list(new QueryWrapper<TMeasureThickness>()
                .eq("del_flag", 0)
        );
        for (TMeasureThickness t: sendList
             ) {
            t.setIsSend(1);
//            this.measureThicknessService.updateTMeasureThickness(t);
        }
    }


    private void sendEmailBySt(List<TMeasureThickness> stList, TAlarmPrincipal o) {
        String str = "";
        for (TMeasureThickness t : stList) {
            str += "<br>" + t.getPlantCode() + "，" + t.getUnitCode() + "，" + t.getTagno() + "，" + t.getPosition();
        }
        if (stList.size() > 0) {
            this.sendEmail(o.getPrincipalName(), o.getPrincipalEmail(), this.stAlarmType, "0",
                    this.contentFormat, str, this.glUrlSuffix);
            insertHistory(o, "0", str, this.alarmtype + "", this.stAlarmType);
        }
    }

    private void sendEmailByEst(List<TMeasureThickness> estList, TAlarmPrincipal o) {
        String str = "";
        for (TMeasureThickness t : estList) {
            str += "<br>" + t.getPlantCode() + "，" + t.getUnitCode() + "，" + t.getTagno() + "，" + t.getPosition();
        }
        if (estList.size() > 0) {
            this.sendEmail(o.getPrincipalName(), o.getPrincipalEmail(), this.estAlarmType, "0",
                    this.contentFormat, str, this.glUrlSuffix);
            insertHistory(o, "0", str, this.alarmtype + "", this.estAlarmType);
        }
    }

    /**
     * 特种设备预警-邮件发送
     *
     * @param username       负责人姓名
     * @param email          负责人邮箱
     * @param alarmType      预警类型
     * @param warningLevel   预警等级
     * @param contenFormat   预警内容
     * @param warningContent 预警内容详细
     * @param urlSuffix      链接跳转对应路径
     */
    private void sendEmail(String username, String email, String alarmType, String warningLevel, String contenFormat, String warningContent, String urlSuffix) {
        //写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>";
        //表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>" +
                "预警内容contenFormat：<b>warningContent</b><br>" +
                "请前往<a href=\"requestJumpPath/urlSuffix\">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("urlSuffix", urlSuffix);
        String seven = six.replaceFirst("alarmType", alarmType);
        String eight = seven.replace("requestJumpPath", this.ruoyiConfig.getRequestJumpPath());
        String result = eight.replaceFirst("date", String.valueOf(new Date()));
        prime = prime + result;
        //拼接html
        String html = start + prime + end;
        this.mailService.sendHtmlMail(email, "CPMS：您有一条预警信息", html);
    }

    /**
     * 预警记录管理新增
     */
    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);
    }
}
