package com.ruoyi.project.listener.apply.valve;

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.SpringContextUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.apply.domain.TApplyOfflinevalve;
import com.ruoyi.project.apply.service.ITApplyOfflinevalveService;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysUserService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.task.IdentityLink;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("nextTaskListener")
public class NextTaskListener implements Serializable, TaskListener {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void notify(DelegateTask delegateTask) {
        String businessKey = delegateTask.getExecution().getProcessInstanceBusinessKey();
        ITApplyOfflinevalveService tApplyOfflinevalveService = (ITApplyOfflinevalveService) SpringContextUtils.getBean("tApplyOfflinevalveService");
        TApplyOfflinevalve tApplyOfflinevalve = tApplyOfflinevalveService.selectTApplyOfflinevalveById(Long.valueOf(businessKey));
        logger.info("==========================businessKey:" + businessKey);
        logger.info("==========================tApplyOfflinevalve:" + tApplyOfflinevalve);
        ISysUserService sysUserService = (ISysUserService) SpringContextUtils.getBean("sysUserService");
        IMailService mailService = (IMailService) SpringContextUtils.getBean("mailService");
        String assignee = delegateTask.getAssignee();
        List<String> userIds = new ArrayList<>();
        if (StringUtils.isEmpty(assignee)) {
            for (IdentityLink candidate : delegateTask.getCandidates()) {
                userIds.add(candidate.getUserId());
            }
        } else {
            userIds.add(assignee);
        }
        StringBuilder to = new StringBuilder();
        for (String userId : userIds) {
            //发送邮件
            try {
                SysUser sysUser = sysUserService.selectUserById(Long.parseLong(userId));
                String email = sysUser.getEmail();
                String apNo = tApplyOfflinevalve.getApNo();
                logger.info("apNo:" + apNo);
                String username = sysUser.getNickName();
                to.append(username).append(" ");
                String loginName = sysUser.getUserName();
                String usernameEN = PinyinHelper.convertToPinyinString(username, " ", PinyinFormat.WITHOUT_TONE);
                logger.info("email:" + email);
                logger.info("username:" + username);
                //写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); \">Safety valve offline/cut-out application</font></th></tr>";
                //表html中间内容
                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(loginName)</font><br><font style=\"line-height: 22px; \" size=\"4\">" +
                        "Dear usernameEN(loginName)</font></font></h2>" +
                        "<p>您有一个新的待办任务：<br>" +
                        "You have a new to-do task:<br>" +
                        "任务名：<b>安全阀离线/切出申请审批</b><br>" +
                        "Task Name: <b>Approval of safety valve offline/cut-out application</b><br>" +
                        "任务编号：<b>apNo</b><br>" +
                        "Task Number: <b>apNoEN</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\">My To-do</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 CPMS, 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.replace("loginName", loginName);
                String four = three.replaceFirst("apNo", apNo);
                String five = four.replaceFirst("apNoEN", apNo);
                String result = five.replaceFirst("date", String.valueOf(new Date()));
                //写html结尾内容
                String end = "</tbody></table></div></body></html>";
                //拼接html
                String html = start + result + end;
                logger.info("html:" + html);
                mailService.sendHtmlMail(email, "安全阀离线/切出申请：您有一个新的待办任务 Safety valve offline/cut-out application:You have a new to-do task (" + apNo + ")", html);
            } catch (Exception e) {
                logger.error("邮件发送失败" + JSON.toJSONString(e));
            }
        }
        logger.info("====================================本次通过邮件发送给：" + to);
    }
}
