package com.ruoyi.framework.task.byx;

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.document.domain.TPlantproglist;
import com.ruoyi.project.ehs.domain.TEnvironapproval;
import com.ruoyi.project.ehs.domain.TFireapproval;
import com.ruoyi.project.ehs.domain.TSafetyapproval;
import com.ruoyi.project.ehs.service.ITEnvironapprovalService;
import com.ruoyi.project.ehs.service.ITFireapprovalService;
import com.ruoyi.project.ehs.service.ITSafetyapprovalService;
import com.ruoyi.project.system.domain.SysUser;
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.mapper.SysUserMapper;
import com.ruoyi.project.system.service.ISysUserService;
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 javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 定时任务批文管理预警
 *
 * @author ruoyi
 */
@Component
public class ApprovalBYXTask extends BaseController {
    /**
     * 注入发送邮件的接口
     */
    @Autowired
    private IMailService mailService;
    @Autowired
    private RuoYiConfig ruoyiConfig;
    /**
     * 注入报警类型的接口
     */
    @Autowired
    private ITAlarmtypeService alarmtypeService;

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

    /**
     * 注入安全批文清单的接口
     */
    @Autowired
    private ITSafetyapprovalService safetyapprovalService;

    /**
     * 注入消防批文清单的接口
     */
    @Autowired
    private ITFireapprovalService fireapprovalService;

    /**
     * 注入环保批文清单的接口
     */
    @Autowired
    private ITEnvironapprovalService environapprovalService;
    //注入用户接口
    @Autowired
    private ISysUserService sysUserService;

    @Resource
    private SysUserMapper userMapper;
    private static Long AlarmtypeId = 1200l;

    /**
     * 下次回顾日期预警
     */
    public void NextTask(Long deptId) {
        TSafetyapproval safeParam = new TSafetyapproval();
        safeParam.setDeptId(deptId);
        List<TSafetyapproval> safetyapprovals = safetyapprovalService.selectList(safeParam);
        TFireapproval FireParam = new TFireapproval();
        List<TFireapproval> fireapprovals = fireapprovalService.selectList(FireParam);
        TEnvironapproval EnvironParam = new TEnvironapproval();
        List<TEnvironapproval> environapprovals = environapprovalService.selectList(EnvironParam);
        TAlarmtype alarmtype = alarmtypeService.selectTAlarmtypeById(AlarmtypeId);
        HashSet<String> safetyOwners = new HashSet<>(); //责任人集合
        for (TSafetyapproval t : safetyapprovals
        ) {
            if (StringUtils.isNotEmpty(t.getReviewer())) {
                safetyOwners.add(t.getReviewer());
            }
        }
        HashSet<String> fireOwners = new HashSet<>(); //责任人集合
        for (TFireapproval t : fireapprovals
        ) {
            if (StringUtils.isNotEmpty(t.getReviewer())) {
                fireOwners.add(t.getReviewer());
            }
        }
        HashSet<String> environOwners = new HashSet<>(); //责任人集合
        for (TEnvironapproval t : environapprovals
        ) {
            if (StringUtils.isNotEmpty(t.getReviewer())) {
                environOwners.add(t.getReviewer());
            }
        }
        //判断报警是否开启
        if (alarmtype.getIsOpen() == 1) {
            //三级预警设置时间
            Long firstLevel = alarmtype.getFirstlevel() * 24 * 3600 * 1000;
            Long secondLevel = alarmtype.getSecondlevel() * 24 * 3600 * 1000;
            Long thirdLevel = alarmtype.getThirdlevel() * 24 * 3600 * 1000;
            TAlarmPrincipal alarmPrincipal = new TAlarmPrincipal();
            //预警类型对应负责人
            alarmPrincipal.setTypeId(AlarmtypeId);
            alarmPrincipal.setDeptId(deptId);
            List<TAlarmPrincipal> alarmPrincipals = alarmPrincipalService.selectList(alarmPrincipal);
            String firstwarningContent = "";
            String secondwarningContent = "";
            String thirdwarningContent = "";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (TAlarmPrincipal t : alarmPrincipals) {
                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<SysUser> safetyUserList = new ArrayList();
            //查询用户表赋值邮箱
            for (String t : safetyOwners) {
                SysUser param = new SysUser();
                param.setStaffId(t);
                param.setDeptId(deptId);
                SysUser user = this.userMapper.selectUserSingle(param);
                if (user != null) {
                    safetyUserList.add(user);
                }
            }
            for (SysUser o : safetyUserList) {
                TSafetyapproval param = new TSafetyapproval();
                param.setDeptId(deptId);
                param.setReviewer(o.getStaffId());
                List<TSafetyapproval> safetyapprovalList = safetyapprovalService.selectList(param);
                for (TSafetyapproval t : safetyapprovalList) {
                    if (t.getNextreviewdate() != null) {
                        long safetyDifference = t.getNextreviewdate().getTime() - new Date().getTime();
                        if (safetyDifference <= firstLevel) {
                            if (alarmtype.getFirstlevel() != null) {
                                firstwarningContent = alarmLevelContent(firstwarningContent, t.getCertno(), t.getApprovalname(), sdf.format(t.getNextreviewdate()));
                            }
                        } else if (safetyDifference <= secondLevel) {
                            if (alarmtype.getSecondlevel() != null) {
                                secondwarningContent = alarmLevelContent(secondwarningContent, t.getCertno(), t.getApprovalname(), sdf.format(t.getNextreviewdate()));
                            }
                        } else if (safetyDifference <= thirdLevel) {
                            if (alarmtype.getThirdlevel() != null) {
                                thirdwarningContent = alarmLevelContent(thirdwarningContent, t.getCertno(), t.getApprovalname(), sdf.format(t.getNextreviewdate()));
                            }
                        }
                    }
                }
                levelSendEmail(firstwarningContent, secondwarningContent, thirdwarningContent, alarmPrincipals, "安全批文清单", "safetyapproval", "（证书编号，批文名称，下次回顾日期）", AlarmtypeId.toString(), o);
            }
            firstwarningContent = "";
            secondwarningContent = "";
            thirdwarningContent = "";
            List<SysUser> fireUserList = new ArrayList();
            //查询用户表赋值邮箱
            for (String t : fireOwners) {
                SysUser param = new SysUser();
                param.setStaffId(t);
                param.setDeptId(deptId);
                SysUser user = this.userMapper.selectUserSingle(param);
                if (user != null) {
                    fireUserList.add(user);
                }
            }
            for (SysUser o : fireUserList) {
                TFireapproval param = new TFireapproval();
                param.setDeptId(deptId);
                param.setReviewer(o.getStaffId());
                List<TFireapproval> fireapprovalList = fireapprovalService.selectList(param);
                for (TFireapproval t : fireapprovalList) {
                    if (t.getNextreviewdate() != null) {
                        long fireDifference = t.getNextreviewdate().getTime() - new Date().getTime();
                        if (fireDifference <= firstLevel) {
                            if (alarmtype.getFirstlevel() != null) {
                                firstwarningContent = alarmLevelContent(firstwarningContent, t.getFileno(), t.getApprovalname(), sdf.format(t.getNextreviewdate()));
                            }
                        } else if (fireDifference <= secondLevel) {
                            if (alarmtype.getSecondlevel() != null) {
                                secondwarningContent = alarmLevelContent(secondwarningContent, t.getFileno(), t.getApprovalname(), sdf.format(t.getNextreviewdate()));
                            }
                        } else if (fireDifference <= thirdLevel) {
                            if (alarmtype.getThirdlevel() != null) {
                                thirdwarningContent = alarmLevelContent(thirdwarningContent, t.getFileno(), t.getApprovalname(), sdf.format(t.getNextreviewdate()));
                            }
                        }
                    }
                }
                levelSendEmail(firstwarningContent, secondwarningContent, thirdwarningContent, alarmPrincipals, "消防批文清单", "fireapproval", "（文件编号，批文名称，下次回顾日期）", AlarmtypeId.toString(), o);
            }
            firstwarningContent = "";
            secondwarningContent = "";
            thirdwarningContent = "";
            List<SysUser> environUserList = new ArrayList();
            //查询用户表赋值邮箱
            for (String t : environOwners) {
                SysUser param = new SysUser();
                param.setStaffId(t);
                param.setDeptId(deptId);
                SysUser user = this.userMapper.selectUserSingle(param);
                if (user != null) {
                    environUserList.add(user);
                }
            }
            for (SysUser o : environUserList) {
                TEnvironapproval param = new TEnvironapproval();
                param.setDeptId(deptId);
                param.setReviewer(o.getStaffId());
                List<TEnvironapproval> environapprovalList = environapprovalService.selectList(param);
                for (TEnvironapproval t : environapprovalList) {
                    if (t.getNextreviewdate() != null) {
                        long EnvironDifference = t.getNextreviewdate().getTime() - new Date().getTime();
                        if (EnvironDifference <= firstLevel) {
                            if (alarmtype.getFirstlevel() != null) {
                                firstwarningContent = alarmLevelContent(firstwarningContent, t.getCertno(), t.getApprovalname(), sdf.format(t.getNextreviewdate()));
                            }
                        } else if (EnvironDifference <= secondLevel) {
                            if (alarmtype.getSecondlevel() != null) {
                                secondwarningContent = alarmLevelContent(secondwarningContent, t.getCertno(), t.getApprovalname(), sdf.format(t.getNextreviewdate()));
                            }
                        } else if (EnvironDifference <= thirdLevel) {
                            if (alarmtype.getThirdlevel() != null) {
                                thirdwarningContent = alarmLevelContent(thirdwarningContent, t.getCertno(), t.getApprovalname(), sdf.format(t.getNextreviewdate()));
                            }
                        }
                    }
                }
                levelSendEmail(firstwarningContent, secondwarningContent, thirdwarningContent, alarmPrincipals, "环保批文清单", "environapproval", "（证书编号，批文名称，下次回顾日期）", AlarmtypeId.toString() , o);
            }
        }
        this.ValidityTask(deptId);
    }

    /**
     * 证书有效期
     */
    public void ValidityTask(Long deptId) {
        TSafetyapproval safeParam = new TSafetyapproval();
        safeParam.setDeptId(deptId);
        List<TSafetyapproval> safetyapprovals = safetyapprovalService.selectList(safeParam);
        TFireapproval FireParam = new TFireapproval();
        List<TFireapproval> fireapprovals = fireapprovalService.selectList(FireParam);
        TEnvironapproval EnvironParam = new TEnvironapproval();
        List<TEnvironapproval> environapprovals = environapprovalService.selectList(EnvironParam);
        TAlarmtype alarmtype = alarmtypeService.selectTAlarmtypeById(AlarmtypeId);
        HashSet<String> safetyOwners = new HashSet<>(); //责任人集合
        for (TSafetyapproval t : safetyapprovals
        ) {
            if (StringUtils.isNotEmpty(t.getReviewer())) {
                safetyOwners.add(t.getReviewer());
            }
        }
        HashSet<String> fireOwners = new HashSet<>(); //责任人集合
        for (TFireapproval t : fireapprovals
        ) {
            if (StringUtils.isNotEmpty(t.getReviewer())) {
                fireOwners.add(t.getReviewer());
            }
        }
        HashSet<String> environOwners = new HashSet<>(); //责任人集合
        for (TEnvironapproval t : environapprovals
        ) {
            if (StringUtils.isNotEmpty(t.getReviewer())) {
                environOwners.add(t.getReviewer());
            }
        }
        //判断报警是否开启
        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(AlarmtypeId);
            alarmPrincipal.setDeptId(deptId);
            List<TAlarmPrincipal> alarmPrincipals = alarmPrincipalService.selectList(alarmPrincipal);
            String firstwarningContent = "";
            String secondwarningContent = "";
            String thirdwarningContent = "";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (TAlarmPrincipal t : alarmPrincipals) {
                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<SysUser> safetyUserList = new ArrayList();
            //查询用户表赋值邮箱
            for (String t : safetyOwners) {
                SysUser param = new SysUser();
                param.setStaffId(t);
                param.setDeptId(deptId);
                SysUser user = this.userMapper.selectUserSingle(param);
                if (user != null) {
                    safetyUserList.add(user);
                }
            }
            for (SysUser o : safetyUserList) {
                TSafetyapproval param = new TSafetyapproval();
                param.setDeptId(deptId);
                param.setReviewer(o.getStaffId());
                List<TSafetyapproval> safetyapprovalList = safetyapprovalService.selectList(param);
                for (TSafetyapproval t : safetyapprovalList) {
                    if (t.getValidityAfter() != null) {
                        long safetyDifference = t.getValidityAfter().getTime() - new Date().getTime();
                        if (safetyDifference <= firstLevel) {
                            if (alarmtype.getFirstlevel() != null) {
                                firstwarningContent = alarmLevelContent(firstwarningContent, t.getCertno(), t.getApprovalname(), sdf.format(t.getValidityAfter()));
                            }
                        } else if (safetyDifference <= secondLevel) {
                            if (alarmtype.getSecondlevel() != null) {
                                secondwarningContent = alarmLevelContent(secondwarningContent, t.getCertno(), t.getApprovalname(), sdf.format(t.getValidityAfter()));
                            }
                        } else if (safetyDifference <= thirdLevel) {
                            if (alarmtype.getThirdlevel() != null) {
                                thirdwarningContent = alarmLevelContent(thirdwarningContent, t.getCertno(), t.getApprovalname(), sdf.format(t.getValidityAfter()));
                            }
                        }
                    }
                }
                levelSendEmail(firstwarningContent, secondwarningContent, thirdwarningContent, alarmPrincipals, "安全批文清单", "safetyapproval", "（证书编号，批文名称，证书有效期）", AlarmtypeId.toString(),o);
            }
            firstwarningContent = "";
            secondwarningContent = "";
            thirdwarningContent = "";
            List<SysUser> environUserList = new ArrayList();
            //查询用户表赋值邮箱
            for (String t : environOwners) {
                SysUser param = new SysUser();
                param.setStaffId(t);
                param.setDeptId(deptId);
                SysUser user = this.userMapper.selectUserSingle(param);
                if (user != null) {
                    environUserList.add(user);
                }
            }
            for (SysUser o : environUserList) {
                TEnvironapproval param = new TEnvironapproval();
                param.setDeptId(deptId);
                param.setReviewer(o.getStaffId());
                List<TEnvironapproval> environapprovalList = environapprovalService.selectList(param);
            for (TEnvironapproval t : environapprovalList) {
                if (t.getValidity() != null) {
                    long EnvironDifference = t.getValidityAfter().getTime() - new Date().getTime();
                    if (EnvironDifference <= firstLevel) {
                        if (alarmtype.getFirstlevel() != null) {
                            firstwarningContent = alarmLevelContent(firstwarningContent, t.getCertno(), t.getApprovalname(), sdf.format(t.getValidityAfter()));
                        }
                    } else if (EnvironDifference <= secondLevel) {
                        if (alarmtype.getSecondlevel() != null) {
                            secondwarningContent = alarmLevelContent(secondwarningContent, t.getCertno(), t.getApprovalname(), sdf.format(t.getValidityAfter()));
                        }
                    } else if (EnvironDifference <= thirdLevel) {
                        if (alarmtype.getThirdlevel() != null) {
                            thirdwarningContent = alarmLevelContent(thirdwarningContent, t.getCertno(), t.getApprovalname(), sdf.format(t.getValidityAfter()));
                        }
                    }
                }
            }
            levelSendEmail(firstwarningContent, secondwarningContent, thirdwarningContent, alarmPrincipals, "环保批文清单", "environapproval", "（证书编号，批文名称，证书有效期）", AlarmtypeId.toString(),o);
        }}
    }

    /**
     * 预警内容拼接
     */
    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>  alarmPrincipal, String alarmType, String alarmTypeEn, String contenFormat, String typeId, SysUser user) {
        if (content1 != "") {
            sendEmail(alarmPrincipal, alarmType, "1级预警", content1, alarmTypeEn, contenFormat, typeId, user);
        }
        if (content2 != "") {
            sendEmail(alarmPrincipal, alarmType, "2级预警", content2, alarmTypeEn, contenFormat, typeId, user);
        }
        if (content3 != "") {
            sendEmail(alarmPrincipal, alarmType, "3级预警", content3, alarmTypeEn, contenFormat, typeId, user);
        }
    }

    /**
     * 发送预警邮件
     */
    public void sendEmail(List<TAlarmPrincipal> alarmPrincipal, String alarmType, String warningLevel, String warningContent, String alarmTypeEn, String contenFormat, String typeId, SysUser user) {
        //写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 = "";
        username = user.getNickName();
        email = user.getEmail();
        String[] emailCc = alarmPrincipal.stream()
                .map(TAlarmPrincipal::getPrincipalEmail)
                .filter(Objects::nonNull)
                .toArray(String[]::new);
        //表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=\"requestJumpPath/ehs/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 + "?reviewer=" + user.getStaffId());
        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;
        mailService.sendHtmlMail(email, "CPMS：您有一条预警信息", html,emailCc);
//        mailService.sendHtmlMail("735032128@qq.com", "CPMS：您有一条预警信息", html, "ly@seashoreept.com");
        String level = warningLevel.substring(0, 1);
        insertHistory(alarmPrincipal.get(0), 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);
    }
}
