package com.ruoyi.project.plant.controller;

import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.sendEmail.IMailService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.interceptor.annotation.RepeatSubmit;
import com.ruoyi.project.plant.domain.*;
import com.ruoyi.project.plant.mapper.TMtOpextrackMapper;
import com.ruoyi.project.plant.mapper.TMtPersonMapper;
import com.ruoyi.project.plant.service.*;
import com.ruoyi.project.production.domain.TMonthplan;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 装置会议Controller
 *
 * @author ruoyi
 * @date 2020-12-30
 */
@RestController
@RequestMapping("/plant/meeting")
public class TMtMeetingController extends BaseController {
    @Autowired
    private ITMtMeetingService tMtMeetingService;
    @Autowired
    private ITMtActionlistService tMtActionlistService;
    @Autowired
    private ITMtEhsopenitemService tMtEhsopenitemService;
    @Autowired
    private ITMtKeymaintenanceService tMtKeymaintenanceService;
    @Autowired
    private ITMtMessageattentionService tMtMessageattentionService;
    @Autowired
    private ITMtRiskreminderService tMtRiskreminderService;
    @Autowired
    private ITMtInterlockService tMtInterlockService;
    @Resource
    private TMtOpextrackMapper tMtOpextrackMapper;
    @Autowired
    private ITMtPersonService tMtPersonService;
    @Autowired
    private IMailService mailService;
    @Resource
    private TMtPersonMapper tMtPersonMapper;
    @Autowired
    private ISysUserService sysUserService;
    //系统基础配置
    @Autowired
    private RuoYiConfig ruoyiConfig;

    /**
     * 查询装置会议列表
     */
    @PreAuthorize("@ss.hasPermi('plant:meeting:list')")
    @GetMapping("/list")
    public TableDataInfo list(TMtMeeting tMtMeeting) {
        startPage();
        List<TMtMeeting> list = tMtMeetingService.selectTMtMeetingList(tMtMeeting);
        return getDataTable(list);
    }

    /**
     * 导出装置会议列表
     */
    @PreAuthorize("@ss.hasPermi('plant:meeting:export')")
    @Log(title = "装置会议", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TMtMeeting tMtMeeting) {
        List<TMtMeeting> list = tMtMeetingService.selectTMtMeetingList(tMtMeeting);
        ExcelUtil<TMtMeeting> util = new ExcelUtil<TMtMeeting>(TMtMeeting.class);
        return util.exportExcel(list, "meeting");
    }

    /**
     * 获取装置会议详细信息
     */
    @PreAuthorize("@ss.hasPermi('plant:meeting:list')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tMtMeetingService.selectTMtMeetingById(id));
    }

    /**
     * 获取装置会议详细信息
     */
    @PreAuthorize("@ss.hasPermi('plant:meeting:list')")
    @GetMapping("/last")
    public AjaxResult getLast(TMtMeeting tMtMeeting) {
        TMtMeeting t = tMtMeetingService.selectTMtMeetingLast(tMtMeeting);
        t.setId(null);
        t.setEmailStatus(null);
        return AjaxResult.success(t);
    }

    /**
     * 新增装置会议
     */
    @PreAuthorize("@ss.hasPermi('plant:meeting:edit')")
    @Log(title = "装置会议", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping
    public AjaxResult add(@RequestBody TMtMeeting tMtMeeting) {
        tMtMeetingService.insertTMtMeeting(tMtMeeting);
        String url = getReport(null, tMtMeeting.getId());
        tMtMeeting.setWordUrl(url);
        tMtMeetingService.updateTMtMeeting(tMtMeeting);
        return AjaxResult.success();
    }

    /**
     * 修改装置会议
     */
    @PreAuthorize("@ss.hasPermi('plant:meeting:edit')")
    @Log(title = "装置会议", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping
    public AjaxResult edit(@RequestBody TMtMeeting tMtMeeting) {
        tMtMeetingService.updateTMtMeeting(tMtMeeting);
        String url = getReport(null, tMtMeeting.getId());
        tMtMeeting.setWordUrl(url);
        tMtMeetingService.updateTMtMeeting(tMtMeeting);
        return AjaxResult.success();
    }

    /**
     * 删除装置会议
     */
    @PreAuthorize("@ss.hasPermi('plant:meeting:remove')")
    @Log(title = "装置会议", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tMtMeetingService.deleteTMtMeetingByIds(ids));
    }

    /**
     * 生成报告
     */
//    @RequestMapping(value = "/meetingReport", produces = "application/json;charset=utf-8")
//    @ResponseBody
    public String getReport(Long year, Long meetingId) {
        logger.info("meetingId:" + meetingId);
        String tempUrl = "";
        tempUrl = "static/word/meeting.docx"; // 模板文件
        // 保存结果文
        InputStream is = null;
        try {
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(tempUrl);
            XWPFDocument doc = new XWPFDocument(is);
            // 替换word模板数据
            replaceAll(doc, year, meetingId);

//            response.setContentType("application/octet-stream");// 下载,默认就是下载
//            response.setCharacterEncoding("UTF-8");
//            response.setHeader("Content-Disposition",
//                    "attachment;fileName=" + URLEncoder.encode("meetingReport" + ".docx", "UTF-8"));


            // 生成word的路径
            String fileDir = RuoYiConfig.getProfile() + "/" + "plant/meeting";
            // 生成word的文件名称
            TMtMeeting tMtMeeting = tMtMeetingService.selectTMtMeetingById(meetingId);
            String fileName = DateUtils.parseDateToStr("YYYY-MM-dd", tMtMeeting.getMeetingDate()) +"weekMeeting" + meetingId + ".docx";
            String filePath = fileDir + "/" + fileName;
            File dir = new File(fileDir);
            if (!dir.exists()) {
                logger.info("目录不存在，创建文件夹{}!", fileDir);
                dir.mkdirs();
            }
            FileOutputStream out = new FileOutputStream(filePath);
            doc.write(out);
            out.close();
            String pathFileName = FileUploadUtils.getPathFileName(RuoYiConfig.getFilePath("/" + "plant/meeting"), fileName);
            logger.info("pathFileName::::::::" + pathFileName);
            return pathFileName;
            // 刷新缓冲
//            response.flushBuffer();
//            OutputStream ouputStream = response.getOutputStream();
//            doc.write(ouputStream);
//            ouputStream.flush();
//            ouputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * @Description: 替换段落和表格
     */
    private void replaceAll(XWPFDocument doc, Long year, Long meetingId) throws Exception {
        TMonthplan tMonthplan = new TMonthplan();
        tMonthplan.setYear(2020l);
        doParagraphs(doc, meetingId);// 处理段落文字数据，包括文字和表格、图片
    }


    /**
     * 处理段落文字数据，包括文字和表格、图片
     *
     * @param doc 一个文档包含多个段落，一个段落包含多个Runs，一个Runs包含多个Run，Run是文档的最小单元
     */
    private void doParagraphs(XWPFDocument doc, Long meetingId) {
        // 文本数据
        Calendar cal = Calendar.getInstance();
        Map<String, String> textMap = new HashMap<String, String>();
        //
        TMtOpextrack tMtOpextrack = new TMtOpextrack();
        tMtOpextrack.setMeetingId(meetingId);
        List<TMtOpextrack> opextrackList = tMtOpextrackMapper.selectTMtOpextrackList(tMtOpextrack);
        if (opextrackList !=null && opextrackList.size()>0) { // opextrack为空的情况
            tMtOpextrack = opextrackList.get(0);
            textMap.put("{{items}}", "        " + String.valueOf(tMtOpextrack.getTotalitem()));
            textMap.put("{{ongoing}}", "        " + String.valueOf(tMtOpextrack.getOngoing()));
            textMap.put("{{finished}}", "        " + String.valueOf(tMtOpextrack.getFinished()));
            textMap.put("{{benefit}}", "                   " + String.valueOf(tMtOpextrack.getBenefit()));
            textMap.put("{{opxyear}} Estimated Benefit (RMB)", String.valueOf(tMtOpextrack.getYear()) + " Estimated Benefit (RMB)");
        }else {
            textMap.put("{{items}}", "        " );
            textMap.put("{{ongoing}}", "        " );
            textMap.put("{{finished}}", "        " );
            textMap.put("{{benefit}}", "                   " );
            textMap.put("{{opxyear}} Estimated Benefit (RMB)", " Estimated Benefit (RMB)");
        }

        TMtMeeting tMtMeeting = tMtMeetingService.selectTMtMeetingById(meetingId);
        textMap.put("{{mtDate}}", DateUtils.parseDateToStr("yyyy/MM/dd", tMtMeeting.getMeetingDate()));
        textMap.put("{{mtVenue}}", String.valueOf(tMtMeeting.getVenue()));
        textMap.put("{{mtNo}}", tMtMeeting.getMeetingNo());
        textMap.put("{{mtRecorder}}", tMtMeeting.getRecorder());
        /** ----------------------------处理段落------------------------------------ **/
        List<XWPFParagraph> paragraphList = doc.getParagraphs();
        if (paragraphList != null && paragraphList.size() > 0) {
            for (XWPFParagraph paragraph : paragraphList) {
                List<XWPFRun> runs = paragraph.getRuns();
                for (XWPFRun run : runs) {
                    String text = run.getText(0);
                    logger.info("text======" + text);
                    if (text != null) {
                        // 替换文本信息
                        String tempText = text;
                        String key = tempText.replaceAll("\\{\\{", "").replaceAll("}}", "");
                        if (!StringUtils.isEmpty(textMap.get(key))) {
                            run.setText(textMap.get(key), 0);
                        }

                        /**
                         * ----------------------------替换表格数据
                         * ------------------------------------
                         **/
                        doJLParagraphs(doc, paragraph, run, tempText, meetingId);// 处理段落文字数据，包括文字和表格、图片
                    }
                }
            }
        }
        //
        /**
         * 替换表格中指定的文字
         */
        Iterator<XWPFTable> itTable = doc.getTablesIterator();
        int i = 1;
        while (itTable.hasNext()) {
            XWPFTable table = (XWPFTable) itTable.next();
            changeTableMessage(textMap, table, false, null, i);
            i++;
        }

    }

    private void changeTableMessage(Map<String, String> textMap, XWPFTable table, boolean isBold, Integer fontSize, int num) {
        int count = table.getNumberOfRows();//获取table的行数
        for (int i = 0; i < count; i++) {
            XWPFTableRow row = table.getRow(i);
            List<XWPFTableCell> cells = row.getTableCells();
            for (XWPFTableCell cell : cells) {//遍历每行的值并进行替换
                logger.info(cell.getText() + ":::::");
                for (Map.Entry<String, String> e : textMap.entrySet()) {
                    if (cell.getText().equals(e.getKey())) {
                        XWPFParagraph newPara = new XWPFParagraph(cell.getCTTc().addNewP(), cell);
                        XWPFRun r1 = newPara.createRun();
                        if (num == 1) {
                            r1.setFontSize(10);
                            r1.setTextPosition(10);
                            r1.setBold(true);
                        } else if (num == 2) {
                            r1.setFontSize(13);
                            r1.setTextPosition(10);
                        }
                        r1.setText(e.getValue());
                        cell.removeParagraph(0);
                        cell.setParagraph(newPara);
                    }
                }
            }
        }
    }

    /**
     * 处理段落文字--经理
     *
     * @param doc
     * @throws InvalidFormatException
     * @throws FileNotFoundException
     * @throws IOException
     */
    public void doJLParagraphs(XWPFDocument doc, XWPFParagraph paragraph, XWPFRun run, String text, Long meetingId) {
        // 执行表
        if (text.contains("${table1}")) {
            tMtActionlistService.dealActionlist(doc, paragraph, run, meetingId);
        }
        // EHS开项追踪
        if (text.contains("${table2}")) {
            tMtEhsopenitemService.dealEhsopenitemlist(doc, paragraph, run, meetingId);
        }
        // 信息提醒
        if (text.contains("${table3}")) {
            tMtMessageattentionService.dealMessageattentionlist(doc, paragraph, run, meetingId);
        }
        // 信息提醒
        if (text.contains("${table4}")) {
            tMtRiskreminderService.dealRiskreminder(doc, paragraph, run, meetingId);
        }
        // 信息提醒
        if (text.contains("${table5}")) {
            tMtInterlockService.dealInterlock(doc, paragraph, run, meetingId);
        }
        // 下周关键维修工作
        if (text.contains("${table7}")) {
            tMtKeymaintenanceService.dealKeymaintenancelist(doc, paragraph, run, meetingId);
        }
        // yihuizhe
        if (text.contains("${table8}")) {
            tMtPersonService.dealPerson1(doc, paragraph, run, meetingId);
        }
        // cc
        if (text.contains("${table9}")) {
            tMtPersonService.dealPerson2(doc, paragraph, run, meetingId);
        }
    }

    /**
     * 发送会议邮件
     */
    @PreAuthorize("@ss.hasPermi('plant:dailyMeeting:edit')")
    @Log(title = "发送周会议邮件", businessType = BusinessType.OTHER)
    @RepeatSubmit
    @GetMapping("/sendMail")
    public AjaxResult sendMail(TMtMeeting tMtMeeting) {
        TMtMeeting mtMeeting = tMtMeetingService.selectTMtMeetingById(tMtMeeting.getId());
        try {
            //写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 = "";

//        email = "735032128@qq.com";
            //表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\">" +
                    "亲爱的 CPMS用户</font><br><font style=\"line-height: 22px; \" size=\"4\">" +
                    "<p>您有一条新的周会议：<br>" +
                    "会议日期：<b>meetingDate</b><br>" +
                    "请前往<a href=\"requestJumpPath/plant/meeting/meeting\">周历史会议</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 pattern = "yyyy年MM月dd日"; // 定义日期格式化模板

            SimpleDateFormat dateFormat = new SimpleDateFormat(pattern); // 创建日期格式化器

            String formattedDate = dateFormat.format(mtMeeting.getMeetingDate()); // 将日期转换为字符串

            String one = firstcenter.replaceFirst("meetingDate", formattedDate);
            String two = one.replace("requestJumpPath", this.ruoyiConfig.getRequestJumpPath());
            String result = two.replaceFirst("date", dateFormat.format(new Date()));
            prime = prime + result;
            //拼接html
            String html = start + prime + end;

            // 需要转换的文件路径
            String filePath = RuoYiConfig.getProfile() + mtMeeting.getWordUrl().replace("/profile", "");

            //发送人和抄送人
            String[] email = {"735032128@qq.com", "1213269375@qq.com"};
            String[] emailCc = {"ly@seashoreept.com", "ly735032128@gmail.com"};

            ArrayList<String> emailList = new ArrayList<>();
            ArrayList<String> emailCcList = new ArrayList<>();

            //邮件发送人
            TMtPerson tMtPerson = new TMtPerson();
            tMtPerson.setMeetingId(mtMeeting.getId());
            tMtPerson.setIsCc(0l);
            List<TMtPerson> personList = tMtPersonMapper.selectTMtPersonList(tMtPerson);
            for (TMtPerson t : personList
            ) {
                SysUser user = sysUserService.selectUserByStaffId(t.getStaffid());
                if (user != null && StringUtils.isNotEmpty(user.getEmail())) {
                    emailList.add(user.getEmail());
                }
            }

            //邮件抄送人
            tMtPerson.setIsCc(1l);
            List<TMtPerson> personCcList = tMtPersonMapper.selectTMtPersonList(tMtPerson);
            for (TMtPerson t : personCcList
            ) {
                SysUser user = sysUserService.selectUserByStaffId(t.getStaffid());
                if (user != null && StringUtils.isNotEmpty(user.getEmail())) {
                    emailCcList.add(user.getEmail());
                }
            }

            email = emailList.toArray(new String[emailList.size()]);
            emailCc = emailCcList.toArray(new String[emailCcList.size()]);
            logger.info("发送人：" + JSON.toJSONString(email));
            logger.info("抄送人：" + JSON.toJSONString(emailCc));

            mailService.sendAttachmentsMail(email, "周会议：您有一条" + formattedDate + "装置周会议信息", html, emailCc, filePath);
            tMtMeeting.setEmailStatus(1);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("e", e);
            tMtMeeting.setEmailStatus(-1);
            return AjaxResult.error("发送失败");
        } finally {
            tMtMeetingService.updateTMtMeeting(tMtMeeting);
        }
    }


}
