package com.ruoyi.project.listener.invoiceApprove;

import com.alibaba.fastjson.JSON;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.data.Texts;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.ruoyi.common.sendEmail.IMailService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SpringContextUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.invoice.controller.TInvoiceBookingworkticketController;
import com.ruoyi.project.invoice.domain.TApproveReserveInvoice;
import com.ruoyi.project.invoice.domain.TInvoiceBookingworkticket;
import com.ruoyi.project.invoice.domain.TInvoiceWorkcontent;
import com.ruoyi.project.invoice.service.ITApproveReserveInvoiceService;
import com.ruoyi.project.invoice.service.ITInvoiceBookingworkticketService;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysDictTypeService;
import com.ruoyi.project.system.service.ISysUserService;
import io.jsonwebtoken.lang.Assert;
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.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

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


    @Override
    public void notify(DelegateExecution delegateExecution) {
        String id = delegateExecution.getProcessInstanceBusinessKey();
        logger.info("delegateExecution--------------------------------" + delegateExecution);
        logger.info("审批id--------------------------------" + id);
        ITApproveReserveInvoiceService tApproveReserveInvoiceService = (ITApproveReserveInvoiceService) SpringContextUtils.getBean("tApproveReserveInvoiceService");
        ITInvoiceBookingworkticketService tInvoiceBookingworkticketService = (ITInvoiceBookingworkticketService) SpringContextUtils.getBean("tInvoiceBookingworkticketService");
        TInvoiceBookingworkticketController bookingworkticketController = (TInvoiceBookingworkticketController) SpringContextUtils.getBean("tInvoiceBookingworkticketController");

        ISysUserService sysUserService = (ISysUserService) SpringContextUtils.getBean("sysUserService");
        IMailService mailService = (IMailService) SpringContextUtils.getBean("mailService");
        TApproveReserveInvoice approveEntity = tApproveReserveInvoiceService.selectTApproveReserveInvoiceById(Long.parseLong(id)) ;
        approveEntity.setStatus(1L);
        approveEntity.setEnddate(new Date());
        // 修改申请状态
        TInvoiceBookingworkticket invoiceBook = tInvoiceBookingworkticketService.selectBookingworkticketById(Long.valueOf(approveEntity.getInvoiceId()));
        invoiceBook.setStatus(3L);
        tInvoiceBookingworkticketService.updateById(invoiceBook);
        //发送邮件
        try {
            String email = sysUserService.selectUserById(approveEntity.getUserId()).getEmail();
            String apNo = approveEntity.getApNo();
            logger.info("apNo:" + apNo);
            SysUser sysUser = sysUserService.selectUserById(approveEntity.getUserId());
            String username = sysUser.getNickName();
            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); \">Reserve Invoice</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(loginName)</font><br><font style=\"line-height: 22px; \" size=\"4\">" +
                    "Dear usernameEN(loginName)</font></font></h2>" +
                    "<p><font style=\"line-height: 22px; \" size=\"5\"><b>您的审批已完成<br>" +
                    "Your approval has been completed</b></font><br>" +
                    "任务名：<b>预约开票审批流程</b><br>" +
                    "Task Name: <b>Approval process of booking invoicing</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\">InvoiceApprove</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()));
            prime = prime + result;
            //写html结尾内容
            String end = "</tbody></table></div></body></html>";
            //拼接html
            String html = start + prime + end;
            logger.info("html:" + html);
            mailService.sendHtmlMail(email, "预约开票：您的申请已完成审批 Reserve Invoice:Your application has been approved (" + apNo + ")", html);
        }catch (Exception e) {
            logger.error("邮件发送失败" + JSON.toJSONString(e));
        }
        //生成预约票
        String url= null;
        try {
            url = bookingworkticketController.PreView(Long.parseLong(approveEntity.getInvoiceId()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //找到主记录
        TInvoiceBookingworkticket tInvoiceBookingworkticket=tInvoiceBookingworkticketService.selectBookingworkticketById(Long.parseLong(approveEntity.getInvoiceId()));
        tInvoiceBookingworkticket.setFilename(url);
        tInvoiceBookingworkticketService.updateTInvoiceBookingworkticket(tInvoiceBookingworkticket);
        tApproveReserveInvoiceService.updateTApproveReserveInvoice(approveEntity);
    }

    /**
     *
     * @param id   生成文件名
     * @return
     * @throws IOException
     */
    public String PreView(Long id) throws IOException {
        ITInvoiceBookingworkticketService tInvoiceBookingworkticketService = (ITInvoiceBookingworkticketService) SpringContextUtils.getBean("tInvoiceBookingworkticketService");
        //根据ID查询并生成
        TInvoiceBookingworkticket tInvoiceBookingworkticket= tInvoiceBookingworkticketService.selectBookingworkticketById(id);
        String url = this.createBookingworkticketWord(tInvoiceBookingworkticket);
        return url;
    }

    /**
     * 生成word
     */
    public String createBookingworkticketWord(TInvoiceBookingworkticket invoiceBookingworkticket) throws IOException {
        //生成word
        //渲染文本
        Map<String, Object> params = getWordData(invoiceBookingworkticket);
        // 模板路径
        String templatePath = "static/word/invoice/book.docx";
        // 生成word的路径
        String fileDir = RuoYiConfig.getProfile() + "/"+ "ticketWord";
        // 生成word的文件名称
        // 承包商+联系人+当前时间
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm"));
        String fileName = invoiceBookingworkticket.getWorkUnit()+invoiceBookingworkticket.getContact() +time+".docx";
        String wordPath = this.createWord(templatePath, fileDir, fileName, params);

        return wordPath;
    };


    /**
     * 获取word数据
     */
    public Map<String, Object> getWordData (TInvoiceBookingworkticket ticket){
        Map<String, Object> params = new HashMap<>();
        ITApproveReserveInvoiceService tApproveReserveInvoiceService = (ITApproveReserveInvoiceService) SpringContextUtils.getBean("tApproveReserveInvoiceService");
        ISysUserService sysUserService = (ISysUserService) SpringContextUtils.getBean("sysUserService");
        ISysDictTypeService iSysDictTypeService = (ISysDictTypeService) SpringContextUtils.getBean("sysDictTypeService");
        ITInvoiceBookingworkticketService tInvoiceBookingworkticketService = (ITInvoiceBookingworkticketService) SpringContextUtils.getBean("tInvoiceBookingworkticketService");
        List<TInvoiceWorkcontent> tInvoiceWorkcontentList= tInvoiceBookingworkticketService.selectTInvoiceWorkcontentBybookingticketId(ticket.getId());
        //字典查询
        List<SysDictData> book_work_type = iSysDictTypeService.selectDictDataByType("book_work_type");
        List<SysDictData> book_user_unit = iSysDictTypeService.selectDictDataByType("book_user_unit");
        List<SysDictData> book_risk_level = iSysDictTypeService.selectDictDataByType("book_risk_level");
        //构造模板的value
        StringBuilder content=new StringBuilder();
        StringBuilder contentUserUnit=new StringBuilder();
        StringBuilder contentUserWorkType=new StringBuilder();
        StringBuilder contentTicket=new StringBuilder();
        String ct=new String();
        String cuw=new String();
        //关联的申请流程
        TApproveReserveInvoice tApproveReserveInvoice= tApproveReserveInvoiceService.selectTApproveReserveInvoiceByinvoiceId(ticket.getId().toString());
        for(int i =0;i<tInvoiceWorkcontentList.size();i++){
            TInvoiceWorkcontent tInvoiceWorkcontent=tInvoiceWorkcontentList.get(i);
            //不为空的字段进行拼接
            if(tInvoiceWorkcontent.getRiskLevel()!=null){
                for (SysDictData p : book_risk_level) {
                    if (tInvoiceWorkcontent.getRiskLevel().toString().equals(p.getDictValue())) {
                        content.append(ticket.getWorkArea()+","+tInvoiceWorkcontent.getWorkDescription());//装置名称
                    }
                }
            }
            params.put("content"+i, Texts.of(content.toString()).fontSize(10).bold().create());
            //用户单位
            if(ticket.getUserUnit()!=null){
                for (SysDictData p : book_user_unit) {
                    if (ticket.getUserUnit().toString().equals(p.getDictValue())) {
                        contentUserUnit.append(p.getDictLabel());//用户单位
                    }
                }
                if(!params.containsKey("userUnit")){
                    params.put("userUnit", Texts.of(contentUserUnit.toString()).fontSize(10).bold().create());
                }
            }
            //用户主管
            if(ticket.getUserMg()!=null){
                SysUser sysUser =sysUserService.selectUserById(ticket.getUserMg());
                if(!params.containsKey("userMg")){
                    if(sysUser.getSignUrl()!=null){
                        params.put("userMg", Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(100, 40).create());
                    }
                }
                if(!params.containsKey("userNumber")){
                    params.put("userNumber", Texts.of(sysUser.getPhonenumber()).fontSize(10).bold().create());
                }
            }
            //承包商
            if(ticket.getWorkUnit()!=null) {
                if (!params.containsKey("workUnit")) {
                    params.put("workUnit", Texts.of(ticket.getWorkUnit()).fontSize(10).bold().create());
                }
            }
            //申请人签名
            if(tApproveReserveInvoice.getUserId()!=null) {
                if (!params.containsKey("userName")) {
                    SysUser sysUser = sysUserService.selectUserById(tApproveReserveInvoice.getUserId());
                    if(sysUser.getSignUrl()!=null){
                        params.put("userName",Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(100, 40).create());
                    }
                }
            }
            //联系电话
            if(tApproveReserveInvoice.getUserId()!=null) {
                SysUser sysUser = sysUserService.selectUserById(tApproveReserveInvoice.getUserId());
                String dName= sysUser.getPhonenumber();
                //如果没有添加过  找到用户所属的部门添加进去
                if (!params.containsKey("conUnit")) {
                    params.put("conUnit",Texts.of(dName).fontSize(10).bold().create());
                }
            }
            //作业类型 遍历查找 追加到该条作业内容
            if(tInvoiceWorkcontent.getWorkType()!=null){
                //先将字符串 分割数组 再转成集合 防止出现 1，11这种情况判断不清
                String newStr=tInvoiceWorkcontent.getWorkType()+",";
                String[] wtArr=newStr.split(",");
                List<String> contentlist = Arrays.asList(wtArr);
                for (SysDictData p : book_work_type) {
                    for (String t : contentlist)
                        if (t.equals(p.getDictValue())) {
                            contentUserWorkType.append(","+p.getDictLabel());//作业类型
                        }
                }
                if(contentUserWorkType.toString().startsWith(",")){
                    cuw=contentUserWorkType.substring(1);
                }
                params.put("workType"+i, Texts.of(cuw).fontSize(10).bold().create());

            }
            //作业开始时间
            if(ticket.getWorkStartTime()!=null){
                params.put("workStartTime",Texts.of(DateUtils.dateTime(ticket.getWorkStartTime())).fontSize(10).bold().create());
            }
            //作业结束时间
            if(ticket.getWorkEndTime()!=null){
                params.put("workEndTime",Texts.of(DateUtils.dateTime(ticket.getWorkEndTime())).fontSize(10).bold().create());
            }
            //关联票号  有几个许可证 就追加几个
            if(ticket!=null){
                if(!StringUtils.isEmpty(tInvoiceWorkcontent.getWhgzxkzh())){
                    contentTicket.append(tInvoiceWorkcontent.getWhgzxkzh());
                }
                if(!StringUtils.isEmpty(tInvoiceWorkcontent.getDhzyxkzh())){
                    contentTicket.append(","+tInvoiceWorkcontent.getDhzyxkzh());
                }
                if(!StringUtils.isEmpty(tInvoiceWorkcontent.getXzkjxkzh())){
                    contentTicket.append(","+tInvoiceWorkcontent.getXzkjxkzh());
                }
                if(!StringUtils.isEmpty(tInvoiceWorkcontent.getMbzyxkzh())){
                    contentTicket.append(","+tInvoiceWorkcontent.getMbzyxkzh());
                }
                if(!StringUtils.isEmpty(tInvoiceWorkcontent.getGczyxkzh())){
                    contentTicket.append(","+tInvoiceWorkcontent.getGczyxkzh());
                }
                if(contentTicket.toString().startsWith(",")){
                    ct=contentTicket.substring(1);
                }else {
                    ct=contentTicket.toString();
                }
                params.put("associated"+i, Texts.of(ct).fontSize(10).bold().create());
            }

            //申请单编号  字体红色
            if (!params.containsKey("application")) {
                params.put("application", Texts.of(DateUtils.dateTimeNow()).fontSize(10).color("FF0000").bold().create());
            }
            //暂定的批准日期
            if(tApproveReserveInvoice.getEnddate()!=null) {
                if (!params.containsKey("applyDate")) {
                    params.put("applyDate", Texts.of(DateUtils.dateTime(tApproveReserveInvoice.getEnddate())).fontSize(10).bold().create());
                }
            }
            //装置批准人
            if(tApproveReserveInvoice.getDevSupId()!=null) {
                if (!params.containsKey("zzUser")) {
                    SysUser sysUser = sysUserService.selectUserById(tApproveReserveInvoice.getDevSupId());
                    if(sysUser.getSignUrl()!=null){
                        params.put("zzUser",Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(100, 40).create());
                    }
                }
                //装置批准人的电话
                if (!params.containsKey("zjNumber")) {
                    SysUser sysUser = sysUserService.selectUserById(tApproveReserveInvoice.getDevSupId());
                    if(sysUser.getPhonenumber()!=null){
                        params.put("zjNumber", Texts.of(sysUser.getPhonenumber()).fontSize(10).bold().create());
                    }
                }
            }
            //装置工程师  如果涉及
            if(tApproveReserveInvoice.getDevEngineerId()!=null) {
                if (!params.containsKey("zjgcs")) {
                    SysUser sysUser = sysUserService.selectUserById(tApproveReserveInvoice.getDevEngineerId());
                    if(sysUser.getSignUrl()!=null){
                        params.put("zjgcs",Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(100, 40).create());
                    }
                }
                //批准日期
                if (!params.containsKey("DateOne")) {
                    if(tApproveReserveInvoice.getEnddate()!=null) {
                        params.put("DateOne", Texts.of(DateUtils.dateTime(tApproveReserveInvoice.getEnddate())).fontSize(10).bold().create());
                    }
                }
            }
            //装置经理(副)  如果涉及
            if(tApproveReserveInvoice.getManagerconId()!=null) {
                if (!params.containsKey("zzjl")) {
                    SysUser sysUser = sysUserService.selectUserById(tApproveReserveInvoice.getManagerconId());
                    if(sysUser.getSignUrl()!=null){
                        params.put("zzjl",Pictures.ofLocal(fileName(sysUser.getSignUrl())).size(100, 40).create());
                    }
                }
                if (!params.containsKey("DateTwo")) {
                    if(tApproveReserveInvoice.getEnddate()!=null) {
                        params.put("DateTwo", Texts.of(DateUtils.dateTime(tApproveReserveInvoice.getEnddate())).fontSize(10).bold().create());
                    }
                }

            }
            content.delete(0, content.length());
            contentUserWorkType.delete(0, contentUserWorkType.length());
            contentTicket.delete(0, contentUserWorkType.length());
        }
        // 渲染文本
        return params;
    };

    /**
     * @param templatePath word模板文件路径
     * @param fileDir      生成的文件存放地址
     * @param fileName     生成的文件名
     * @param paramMap     参数集合
     * @return 返回word生成的路径
     */
    public String createWord(String templatePath, String fileDir, String fileName, Map<String, Object> paramMap) throws IOException {
        Assert.notNull(templatePath, "word模板文件路径不能为空");
        Assert.notNull(fileDir, "生成的文件存放地址不能为空");
        Assert.notNull(fileName, "生成的文件名不能为空");
        File dir = new File(fileDir);
        if (!dir.exists()) {
            logger.info("目录不存在，创建文件夹{}!", fileDir);
            dir.mkdirs();
        }else{

        }
        String filePath = fileDir +"/"+ fileName;
        logger.info("目录{}!", filePath);
        // 读取模板渲染参数
        InputStream is = getClass().getClassLoader().getResourceAsStream(templatePath);
        XWPFTemplate template = XWPFTemplate.compile(is).render(paramMap);
        try {
            // 将模板参数写入路径
            template.writeToFile(filePath);
            template.close();
        } catch (Exception e) {
            logger.error("生成word异常{}", e.getMessage());
            e.printStackTrace();
        }
        String pathFileName = FileUploadUtils.getPathFileName(RuoYiConfig.getFilePath("/"+ "ticketWord"), fileName);
        return pathFileName;
    }

    /**
     *
     * @param
     * @return  映射签名的文件名
     * @throws IOException
     */
    public String fileName(String filepath) {
        String newFilePath=filepath.replace("/profile","");
        String pathName=RuoYiConfig.getProfile()+newFilePath;
        return pathName;
    }
}
