package com.ruoyi.project.listener.semsApprove;

import com.alibaba.fastjson.JSON;

import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.ruoyi.common.sendEmail.IMailService;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.SpringContextUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.project.sems.controller.TApproveController;
import com.ruoyi.project.sems.domain.*;
import com.ruoyi.project.sems.his.controller.*;
import com.ruoyi.project.sems.his.domain.*;
import com.ruoyi.project.sems.his.service.*;
import com.ruoyi.project.sems.his.service.impl.*;
import com.ruoyi.project.sems.service.*;
import com.ruoyi.project.sems.service.impl.TReportHiYlgdServiceImpl;
import com.ruoyi.project.system.service.ISysUserService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("specEndSucessListener")
public class SpecEndSucessListener implements Serializable, ExecutionListener {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    private static final long serialVersionUID = -3759054058055401826L;

    @Override
    public void notify(DelegateExecution delegateExecution) {
        String id = delegateExecution.getProcessInstanceBusinessKey();
        logger.info("delegateExecution--------------------------------" + delegateExecution);
        logger.info("审批id--------------------------------" + id);
        ITApproveService tApproveService = (ITApproveService) SpringContextUtils.getBean("tApproveService");
        ISysUserService sysUserService = (ISysUserService) SpringContextUtils.getBean("sysUserService");
        IMailService mailService = (IMailService) SpringContextUtils.getBean("mailService");
        ITSpecdevDtService tSpecdevDtService = (ITSpecdevDtService) SpringContextUtils.getBean("tSpecdevDtService");
        ITSpecdevDzsbService tSpecdevDzsbService = (ITSpecdevDzsbService) SpringContextUtils.getBean("tSpecdevDzsbService");
        ITSpecdevGlService tSpecdevGlService = (ITSpecdevGlService) SpringContextUtils.getBean("tSpecdevGlService");
        ITSpecdevYlgdService tSpecdevYlgdService = (ITSpecdevYlgdService) SpringContextUtils.getBean("tSpecdevYlgdService");
        ITSpecdevYlrqService tSpecdevYlrqService = (ITSpecdevYlrqService) SpringContextUtils.getBean("tSpecdevYlrqService");
        ITSpecdevCcService tSpecdevCcService = (ITSpecdevCcService) SpringContextUtils.getBean("tSpecdevCcService");

        ITSpechiYlrqService tSpechiYlrqService = (ITSpechiYlrqService) SpringContextUtils.getBean("tSpechiYlrqService");
        ITSpechiYlgdService tSpechiYlgdService = (ITSpechiYlgdService) SpringContextUtils.getBean("tSpechiYlgdService");
        ITSpechiGlService tSpechiGlService = (ITSpechiGlService) SpringContextUtils.getBean("tSpechiGlService");
        ITSpechiDzsbService tSpechiDzsbService = (ITSpechiDzsbService) SpringContextUtils.getBean("tSpechiDzsbService");
        ITSpechiDtService tSpechiDtService = (ITSpechiDtService) SpringContextUtils.getBean("tSpechiDtService");
        ITSpechiCcService tSpechiCcService = (ITSpechiCcService) SpringContextUtils.getBean("tSpechiCcService");

        TSpechiCcController tSpechiCcController = (TSpechiCcController) SpringContextUtils.getBean("tSpechiCcController");
        TSpechiDtController tSpechiDtController = (TSpechiDtController) SpringContextUtils.getBean("tSpechiDtController");
        TSpechiGlController tSpechiGlController = (TSpechiGlController) SpringContextUtils.getBean("tSpechiGlController");
        TSpechiDzsbController tSpechiDzsbController = (TSpechiDzsbController) SpringContextUtils.getBean("tSpechiDzsbController");
        TSpechiYlrqController tSpechiYlrqController = (TSpechiYlrqController) SpringContextUtils.getBean("tSpechiYlrqController");
        TSpechiYlgdController tSpechiYlgdController = (TSpechiYlgdController) SpringContextUtils.getBean("tSpechiYlgdController");
        TApproveController tApproveController = (TApproveController) SpringContextUtils.getBean("tApproveController");

        TApprove approveEntity = tApproveService.selectTApproveById(Long.parseLong(id)) ;
        logger.info("approveEntity:" + approveEntity);
        approveEntity.setStatus(1l);
        approveEntity.setEndtime(new Date());
        tApproveService.updateTApprove(approveEntity);
        String[] ids = approveEntity.getDevId().split(",");
        //获取操作日志参数
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        String userName =loginUser != null? loginUser.getUsername(): "";
        String operType = tApproveController.getOperType(Integer.parseInt(approveEntity.getApproveType().toString()));

        //申请中变更办理中
        switch (Integer.parseInt(approveEntity.getDevType().toString())) {
            case 1:
                for (String i : ids
                ) {
                    TSpecdevYlrq ylrqEntity = tSpecdevYlrqService.getById(i);

                    if (approveEntity.getApproveType() < 4) {
                        ylrqEntity.setStatus(approveEntity.getApproveType());
                    }
                    //新增改造记录，Hitype用于区分改造与修改0：改造， 1：修改
                    if (approveEntity.getApproveType() == 4) {
                        ylrqEntity.setApproveStatus(0l);
                        tSpecdevYlrqService.updateById(ylrqEntity);
                        ylrqEntity.setDevId(ylrqEntity.getId());
                        ylrqEntity.setHiType((long)0);
                        ylrqEntity.setCreatedate(new Date());
                        tSpechiYlrqService.insertTSpechiYlrqWithDev(ylrqEntity);
                    }else{
                        ylrqEntity.setApproveStatus(0l);
                        tSpecdevYlrqService.updateById(ylrqEntity);
                    }
                }
                new Thread(() -> {
                    tSpechiYlrqController.addOperLog(ids,userName,new Date() , operType + "批准" );
                },"特种设备操作日志").start();
                break;
            case 2:
                for (String i : ids
                ) {
                    TSpecdevYlgd ylgdEntity = tSpecdevYlgdService.getById(i);
                    if (approveEntity.getApproveType() < 4) {
                        ylgdEntity.setStatus(approveEntity.getApproveType());
                    }
                    //添加压力管道的改造记录 0:改造,1:修改
                    if (approveEntity.getApproveType() == 4) {
                        ylgdEntity.setApproveStatus(0l);
                        tSpecdevYlgdService.updateById(ylgdEntity);
                        ylgdEntity.setDevId(ylgdEntity.getId());
                        ylgdEntity.setHiType((long)0);
                        ylgdEntity.setCreatedate(new Date());
                        tSpechiYlgdService.insertTSpechiYlgdWithDev(ylgdEntity);
                    }else {
                        ylgdEntity.setApproveStatus(0l);
                        tSpecdevYlgdService.updateById(ylgdEntity);
                    }
                }
                new Thread(() -> {
                    tSpechiYlgdController.addOperLog(ids,userName,new Date() , operType + "批准" );
                },"特种设备操作日志").start();
                break;
            case 3:
                for (String i : ids
                ) {
                    TSpecdevDzsb dzsbEntity = tSpecdevDzsbService.getById(i);
                    if (approveEntity.getApproveType() < 4) {
                        dzsbEntity.setStatus(approveEntity.getApproveType());
                    }
                    if (approveEntity.getApproveType() == 4) {
                        dzsbEntity.setApproveStatus(0l);
                        tSpecdevDzsbService.updateById(dzsbEntity);
                        dzsbEntity.setDevId(dzsbEntity.getId());
                        dzsbEntity.setHiType((long)0);
                        dzsbEntity.setCreatedate(new Date());
                        tSpechiDzsbService.insertTSpechiDzsbWithDev(dzsbEntity);
                    }else {

                        dzsbEntity.setApproveStatus(0l);
                        tSpecdevDzsbService.updateById(dzsbEntity);
                    }
                }
                new Thread(() -> {
                    tSpechiDzsbController.addOperLog(ids,userName,new Date() , operType + "批准" );
                },"特种设备操作日志").start();
                break;
            case 4:
                for (String i : ids
                ) {
                    TSpecdevGl glEntity = tSpecdevGlService.getById(i);
                    if (approveEntity.getApproveType() < 4) {
                        glEntity.setStatus(approveEntity.getApproveType());
                    }
                    if (approveEntity.getApproveType() == 4) {
                        glEntity.setApproveStatus(0l);
                        tSpecdevGlService.updateById(glEntity);
                        glEntity.setDevId(glEntity.getId());
                        glEntity.setHiType((long)0);
                        glEntity.setCreatedate(new Date());
                        tSpechiGlService.insertTSpechiGlWithDev(glEntity);
                    }else {
                        glEntity.setApproveStatus(0l);
                        tSpecdevGlService.updateById(glEntity);
                    }
                }
                new Thread(() -> {
                    tSpechiGlController.addOperLog(ids,userName,new Date() , operType + "批准" );
                },"特种设备操作日志").start();
                break;
            case 5:
                for (String i : ids
                ) {
                    TSpecdevDt dtEntity = tSpecdevDtService.getById(i);
                    if (approveEntity.getApproveType() < 4) {
                        dtEntity.setStatus(approveEntity.getApproveType());
                    }
                    if (approveEntity.getApproveType() == 4) {
                        dtEntity.setApproveStatus(0l);
                        tSpecdevDtService.updateById(dtEntity);
                        dtEntity.setDevId(dtEntity.getId());
                        dtEntity.setHiType((long)0);
                        dtEntity.setCreatedate(new Date());
                        tSpechiDtService.insertTSpechiDtWithDev(dtEntity);
                    }else {
                        dtEntity.setApproveStatus(0l);
                        tSpecdevDtService.updateById(dtEntity);
                    }
                }
                new Thread(() -> {
                    tSpechiDtController.addOperLog(ids,userName,new Date() , operType + "批准" );
                },"特种设备操作日志").start();
                break;
            case 6:
                for (String i : ids
                ) {
                    TSpecdevCc ccEntity = tSpecdevCcService.getById(i);
                    if (approveEntity.getApproveType() < 4) {
                        ccEntity.setStatus(approveEntity.getApproveType());
                    }
                    if (approveEntity.getApproveType() == 4) {
                        ccEntity.setApproveStatus(0l);
                        tSpecdevCcService.updateById(ccEntity);
                        ccEntity.setDevId(ccEntity.getId());
                        ccEntity.setHiType((long)0);
                        ccEntity.setCreatedate(new Date());
                        tSpechiCcService.insertTSpechiCcWithDev(ccEntity);
                    }else {
                        ccEntity.setApproveStatus(0l);
                        tSpecdevCcService.updateById(ccEntity);
                    }
                }
                new Thread(() -> {
                    tSpechiCcController.addOperLog(ids,userName,new Date() , operType + "批准" );
                },"特种设备操作日志").start();
                break;
//            case 7:
//                for (String i : ids
//                ) {
//                    TOtherTankEntity tankEntityEntity = tOtherTankService.getById(i);
//                    if (approveEntity.getApproveType() < 4) {
//                        tankEntityEntity.setStatus(approveEntity.getApproveType());
//                    }
//                    tankEntityEntity.setApproveStatus(0);
//                    tOtherTankService.updateById(tankEntityEntity);
//                }
//                break;
        }
        //发送邮件
        try {
            String email = sysUserService.selectUserById(approveEntity.getUserId()).getEmail();
            String apNo = approveEntity.getApNo();
            logger.info("apNo:" + apNo);
            String username = sysUserService.selectUserById(approveEntity.getUserId()).getNickName();
            String usernameEN = PinyinHelper.convertToPinyinString(username, " ", PinyinFormat.WITHOUT_TONE);
            logger.info("email:" + email);
            logger.info("username:" + username);
            String devType = "";
            String devTypeEN = "";
            switch (Integer.parseInt(approveEntity.getDevType().toString())) {
                case 1:
                    devType = "压力容器";
                    devTypeEN = "Pressure Vessel";
                    break;
                case 2:
                    devType = "压力管道";
                    devTypeEN = "Pressure Pipeline";
                    break;
                case 3:
                    devType = "起重机械";
                    devTypeEN = "Lifting Equipment";
                    break;
                case 4:
                    devType = "锅炉";
                    devTypeEN = "Boiler";
                    break;
                case 5:
                    devType = "电梯";
                    devTypeEN = "Elevator";
                    break;
                case 6:
                    devType = "叉车";
                    devTypeEN = "Forklift";
                    break;
                case 7:
                    devType = "常压罐";
                    devTypeEN = "Tank";
                    break;
            }
            String approveType = "";
            String approveTypeEN = "";
            switch (Integer.parseInt(approveEntity.getApproveType().toString())) {
                case 1:
                    approveType = "启用";
                    approveTypeEN = "Start Usage";
                    break;
                case 2:
                    approveType = "停用";
                    approveTypeEN = "Stop Usage";
                    break;
                case 3:
                    approveType = "报废";
                    approveTypeEN = "Scrapped";
                    break;
                case 4:
                    approveType = "改造";
                    approveTypeEN = "Retrofit";
                    break;
                case 5:
                    approveType = "延期检验";
                    approveTypeEN = "Deferred Inspection";
                    break;
                case 6:
                    approveType = "超设计寿命变更";
                    approveTypeEN = "Change Beyond Design Life";
                    break;
                case -1:
                    approveType = "注销";
                    approveTypeEN = "Logout";
                    break;
            }
            //写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); \">Special Equipment Management System (SEMS)</font></th></tr>";
            //表html中间内容
            String prime = "";
            String center = "<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\">" +
                    "Dear usernameEN</font></font></h2>" +
                    "<p>您的审批已完成：<br>" +
                    "Your approval has been completed:<br>" +
                    "任务编号：<b>apNo</b><br>" +
                    "Task Number: <b>apNoEN</b><br>" +
                    "申请设备类型：<b>devType</b><br>" +
                    "Equipment Type: <b>devTypeEN</b><br>" +
                    "审批类型：<b>approveType</b><br>" +
                    "Application Category: <b>approveTypeEN</b><br>" +
                    "请登录<a href=\"https://cpms.basf-ypc.net.cn/cpms/index.html#/approve/pending\">特种设备信息管理系统</a>查看。<br>" +
                    "Please log in the <a href=\"https://cpms.basf-ypc.net.cn/cpms/index.html#/approve/pending\">SEMS</a> to handle it.</p>" +
                    "<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 SEMS, please do not reply</p>" +
                    "</div></div></div></td></tr>";
            String one = center.replaceFirst("username", username);
            String two = one.replaceFirst("usernameEN", usernameEN);
            String three = two.replaceFirst("devType", devType);
            String four = three.replaceFirst("apNo", apNo);
            String five = four.replaceFirst("apNoEN", apNo);
            String six = five.replaceFirst("devTypeEN", devTypeEN);
            String seven = six.replaceFirst("approveType", approveType);
            String eight = seven.replaceFirst("approveTypeEN", approveTypeEN);
            String result = eight.replaceFirst("date", String.valueOf(new Date()));
            prime = prime + result;
            //写html结尾内容
            String end = "</tbody></table></div></body></html>";
            //拼接html
            String html = start + prime + end;
            logger.info("html:" + html);
            mailService.sendHtmlMail(email, "特种设备：您有一个新的待办任务 SEMS:You have a new to-do task (" + apNo + ")", html);
        }catch (Exception e) {
            logger.error("邮件发送失败" + JSON.toJSONString(e));
        }
    }
}
