package com.ruoyi.project.plant.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.data.Texts;
import com.deepoove.poi.plugin.table.LoopColumnTableRenderPolicy;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.deepoove.poi.policy.RenderPolicy;
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.TMtdEmail;
import com.ruoyi.project.plant.domain.TMtdItem;
import com.ruoyi.project.plant.mapper.TMtdDailyMapper;
import com.ruoyi.project.plant.mapper.TMtdItemMapper;
import com.ruoyi.project.plant.service.ITMtdEmailService;
import com.ruoyi.project.production.controller.TPrdRecordController;
import com.ruoyi.project.sems.safecheck.domain.TSpecWeekcheck;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.system.service.ISysUserService;
import io.jsonwebtoken.lang.Assert;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.plant.domain.TMtdDaily;
import com.ruoyi.project.plant.service.ITMtdDailyService;
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;

/**
 * 调度会议Controller
 *
 * @author ssy
 * @date 2023-11-14
 */
@RestController
@RequestMapping("/plant/dailyMeeting")
public class TMtdDailyController extends BaseController {
    @Autowired
    private ITMtdDailyService tMtdDailyService;
    @Resource
    private TMtdItemMapper tMtdItemMapper;
    @Autowired
    private IMailService mailService;
    //系统基础配置
    @Autowired
    private RuoYiConfig ruoyiConfig;
    @Resource
    private SysUserMapper sysUserMapper;
    @Autowired
    private ITMtdEmailService tMtdEmailService;
    @Autowired
    private ISysUserService sysUserService;
    @Resource
    private TMtdDailyMapper tMtdDailyMapper;
    @Autowired
    private TPrdRecordController tPrdRecordController;

    /**
     * 查询调度会议列表
     */
    @PreAuthorize("@ss.hasPermi('plant:dailyMeeting:list')")
    @GetMapping("/list")
    public TableDataInfo list(TMtdDaily tMtdDaily) {
        startPage();
        List<TMtdDaily> list = tMtdDailyService.selectTMtdDailyList(tMtdDaily);
        return getDataTable(list);
    }


    /**
     * 导出调度会议列表
     */
    @PreAuthorize("@ss.hasPermi('plant:dailyMeeting:export')")
    @Log(title = "调度会议", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TMtdDaily tMtdDaily) {
        List<TMtdDaily> list = tMtdDailyService.selectTMtdDailyList(tMtdDaily);
        ExcelUtil<TMtdDaily> util = new ExcelUtil<TMtdDaily>(TMtdDaily.class);
        return util.exportExcel(list, "dailyMeeting");
    }

    /**
     * 获取调度会议详细信息
     */
    @PreAuthorize("@ss.hasPermi('plant:dailyMeeting:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {

        TMtdDaily tMtdDaily = tMtdDailyService.selectTMtdDailyById(id);
        //获取item列表
        TMtdItem item = new TMtdItem();
        item.setDailyId(id);
        item.setItemType(0);
        List<TMtdItem> item0 = tMtdItemMapper.selectTMtdItemList(item);

        tMtdDaily.setItems0(item0);

        item.setItemType(1);
        List<TMtdItem> item1 = tMtdItemMapper.selectTMtdItemList(item);
        tMtdDaily.setItems1(item1);

        item.setItemType(2);
        List<TMtdItem> item2 = tMtdItemMapper.selectTMtdItemList(item);
        tMtdDaily.setItems2(item2);

        item.setItemType(3);
        List<TMtdItem> item3 = tMtdItemMapper.selectTMtdItemList(item);
        tMtdDaily.setItems3(item3);

        item.setItemType(4);
        List<TMtdItem> item4 = tMtdItemMapper.selectTMtdItemList(item);
        tMtdDaily.setItems4(item4);

        item.setItemType(5);
        List<TMtdItem> item5 = tMtdItemMapper.selectTMtdItemList(item);
        tMtdDaily.setItems5(item5);

        return AjaxResult.success(tMtdDaily);
    }

    /**
     * 获取调度会议详细信息
     */
    @GetMapping(value = "/last")
    public AjaxResult getLast(TMtdDaily mtdDaily) {

        TMtdDaily tMtdDaily = tMtdDailyMapper.selectTMtdDailyLast(mtdDaily);
        //获取item列表
        TMtdItem item = new TMtdItem();
        item.setDailyId(tMtdDaily.getId());
        item.setItemType(0);
        List<TMtdItem> item0 = tMtdItemMapper.selectTMtdItemList(item);

        tMtdDaily.setItems0(item0);

        item.setItemType(1);
        List<TMtdItem> item1 = tMtdItemMapper.selectTMtdItemList(item);
        tMtdDaily.setItems1(item1);

        item.setItemType(2);
        List<TMtdItem> item2 = tMtdItemMapper.selectTMtdItemList(item);
        tMtdDaily.setItems2(item2);

        item.setItemType(3);
        List<TMtdItem> item3 = tMtdItemMapper.selectTMtdItemList(item);
        tMtdDaily.setItems3(item3);

        item.setItemType(4);
        List<TMtdItem> item4 = tMtdItemMapper.selectTMtdItemList(item);
        tMtdDaily.setItems4(item4);

        item.setItemType(5);
        List<TMtdItem> item5 = tMtdItemMapper.selectTMtdItemList(item);
        tMtdDaily.setItems5(item5);
        tMtdDaily.setId(null);
        tMtdDaily.setEmailStatus(null);
        return AjaxResult.success(tMtdDaily);
    }

    /**
     * 新增调度会议
     */
    @PreAuthorize("@ss.hasPermi('plant:dailyMeeting:add')")
    @Log(title = "调度会议", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping
    public AjaxResult add(@RequestBody TMtdDaily tMtdDaily) throws IOException {
        logger.info(JSON.toJSONString(tMtdDaily));
        tMtdDailyService.insertTMtdDaily(tMtdDaily);
        String url = PreView(tMtdDaily.getId());
        tMtdDaily.setWordUrl(url);

        new Thread(() -> {
            tPrdRecordController.syncMeeting(tMtdDaily.getId());
        },"同步生产记录").start();

        return toAjax(tMtdDailyService.updateTMtdDaily(tMtdDaily));
    }

    /**
     * 修改调度会议
     */
    @PreAuthorize("@ss.hasPermi('plant:dailyMeeting:edit')")
    @Log(title = "调度会议", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping
    public AjaxResult edit(@RequestBody TMtdDaily tMtdDaily) throws IOException {
        logger.info(JSON.toJSONString(tMtdDaily));
        tMtdDailyService.updateTMtdDaily(tMtdDaily);
        String url = PreView(tMtdDaily.getId());
        tMtdDaily.setWordUrl(url);
        new Thread(() -> {
            tPrdRecordController.syncMeeting(tMtdDaily.getId());
        },"同步生产记录").start();
        return toAjax(tMtdDailyService.updateTMtdDaily(tMtdDaily));
    }

    /**
     * 删除调度会议
     */
    @PreAuthorize("@ss.hasPermi('plant:dailyMeeting:remove')")
    @Log(title = "调度会议", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tMtdDailyService.deleteTMtdDailyByIds(ids));
    }

    /**
     * 发送调度会议邮件
     */
    @PreAuthorize("@ss.hasPermi('plant:dailyMeeting:edit')")
    @Log(title = "发送调度会议邮件", businessType = BusinessType.OTHER)
    @RepeatSubmit
    @GetMapping("/sendMail")
    public AjaxResult sendMail(TMtdDaily tMtdDaily) {
        TMtdDaily daily = tMtdDailyService.selectTMtdDailyById(tMtdDaily.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/detail/dailyId\">会议详情</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(daily.getMeetingDate()); // 将日期转换为字符串

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

            // 需要转换的文件路径
            String filePath = RuoYiConfig.getProfile() + daily.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<>();

            List<TMtdEmail> list = tMtdEmailService.selectTMtdEmailList(new TMtdEmail());
            for (TMtdEmail t : list
            ) {
                SysUser user = sysUserService.selectUserByStaffId(t.getStaffid());
                if (user != null && StringUtils.isNotEmpty(user.getEmail())) {
                    if (t.getType() == 1) {
                        emailList.add(user.getEmail());
                    }
                    if (t.getType() == 2 && StringUtils.isNotEmpty(user.getEmail())) {
                        emailCcList.add(user.getEmail());
                    }
                }
            }
            email = emailList.toArray(new String[emailList.size()]);
            emailCc = emailCcList.toArray(new String[emailCcList.size()]);
            logger.info("发送人：" + email.toString());
            logger.info("抄送人：" + emailCc.toString());
            logger.info("文件地址：" + filePath);

            mailService.sendAttachmentsMail(email, "调度会：您有一条" + formattedDate + "装置调度会议信息", html, emailCc, filePath);
            daily.setEmailStatus(1);
            return AjaxResult.success();
        } catch (Exception e) {
            daily.setEmailStatus(-1);
            logger.error("e" , e);
            return AjaxResult.error("邮件发送失败");
        }finally {
            tMtdDailyMapper.updateTMtdDaily(daily);
        }
    }


    /**
     * @param id 生成文件名
     * @return
     * @throws IOException
     */
    public String PreView(Long id) throws IOException {
        //根据ID查询并生成
        TMtdDaily tMtdDaily = tMtdDailyService.selectTMtdDailyById(id);
        //获取item列表
        TMtdItem item = new TMtdItem();
        item.setDailyId(id);
        item.setItemType(0);
        List<TMtdItem> item0 = tMtdItemMapper.selectTMtdItemList(item);
        tMtdDaily.setItems0(item0);

        item.setItemType(1);
        List<TMtdItem> item1 = tMtdItemMapper.selectTMtdItemList(item);
        tMtdDaily.setItems1(getItemAndName(item1, "1", tMtdDaily));

        item.setItemType(2);
        List<TMtdItem> item2 = tMtdItemMapper.selectTMtdItemList(item);
        tMtdDaily.setItems2(getItemAndName(item2, "2", tMtdDaily));

        item.setItemType(3);
        List<TMtdItem> item3 = tMtdItemMapper.selectTMtdItemList(item);
        tMtdDaily.setItems3(getItemAndName(item3, "3", tMtdDaily));

        item.setItemType(4);
        List<TMtdItem> item4 = tMtdItemMapper.selectTMtdItemList(item);
        tMtdDaily.setItems4(getItemAndName(item4, "4", tMtdDaily));

        item.setItemType(5);
        List<TMtdItem> item5 = tMtdItemMapper.selectTMtdItemList(item);
        tMtdDaily.setItems5(getItemAndName(item5, "5", tMtdDaily));
        String url = this.createcheck(tMtdDaily);
        return url;
    }

    private List<TMtdItem> getItemAndName(List<TMtdItem> items, String itemNum, TMtdDaily tMtdDaily) {
        int num = 1;
        if (itemNum.equals("1")) {
            num = 3;
        }
        for (TMtdItem t : items
        ) {
            t.setItem(itemNum + "." + num);
//            if (StringUtils.isNotEmpty(t.getActionby())){
//                SysUser sysUser = sysUserMapper.selectUserByStaffId(t.getActionby());
//                t.setActionName(sysUser.getNickName());
//            }
            t.setActionName(t.getActionby());
            if (tMtdDaily.getMeetingDate() != null) {
                t.setBeginTime(DateUtils.parseDateToStr("MM-dd", tMtdDaily.getMeetingDate()));
            }
            num++;
        }
        return items;
    }

    /**
     * 生成wordt
     */
    public String createcheck(TMtdDaily tMtdDaily) throws IOException {
        //生成word
        //渲染文本
        Map<String, Object> params = getWordData(tMtdDaily);
        // 模板路径
        String templatePath = "static/word/plant/dailymeeting.docx";
        // 生成word的路径
        String fileDir = RuoYiConfig.getProfile() + "/" + "plant/dailymeeting";
        // 生成word的文件名称
        String fileName = DateUtils.parseDateToStr("YYYY-MM-dd", tMtdDaily.getMeetingDate()) + "Coordinating " + tMtdDaily.getId() + ".docx";
        String wordPath = this.createWord(templatePath, fileDir, fileName, params);
        return wordPath;
    }

    /**
     * 获取word数据
     */
    public Map<String, Object> getWordData(TMtdDaily tMtdDaily) {
        Map<String, Object> params = new HashMap<>();
        if (tMtdDaily.getMeetingDate() != null) {
            params.put("meetingDate", DateUtils.parseDateToStr("YYYY-MM-dd", tMtdDaily.getMeetingDate()));
            params.put("reDate", DateUtils.parseDateToStr("MM-dd", tMtdDaily.getMeetingDate()));
        }

        params.put("venue", tMtdDaily.getVenue());
        params.put("safetyTopic", tMtdDaily.getSafetyTopic());
        params.put("optMode", tMtdDaily.getOptMode());
        params.put("optItem", tMtdDaily.getOptItem());
        params.put("split", tMtdDaily.getSplit());
        params.put("pgu", tMtdDaily.getPgu());
        params.put("aeu", tMtdDaily.getAeu());

//        logger.info("tMtdDaily.getRecorder()" + tMtdDaily.getRecorder());
//        if (StringUtils.isNotEmpty(tMtdDaily.getRecorder())) {
//            SysUser recorder = sysUserMapper.selectUserByStaffId(tMtdDaily.getRecorder());
//            params.put("recorder", recorder.getNickName());
//        }
        params.put("recorder", tMtdDaily.getRecorder());


        params.put("cracker", tMtdDaily.getAttendCracker());
        params.put("ctm", tMtdDaily.getAttendCtm());
        params.put("cta", tMtdDaily.getAttendCta());
        params.put("lab", tMtdDaily.getAttendLab());

        params.put("item1", tMtdDaily.getItems1());
        params.put("item2", tMtdDaily.getItems2());
        params.put("item3", tMtdDaily.getItems3());
        params.put("item4", tMtdDaily.getItems4());
        params.put("item5", tMtdDaily.getItems5());
        // 渲染文本
        return params;
    }

    private String getUserName(String str) {
        String names = "";
        if (str == null) return "";
        String[] arr = str.split(",");
        for (int i = 0; i < arr.length; i++) {
            SysUser user = sysUserMapper.selectUserByStaffId(arr[i]);
            names = names + user.getNickName() + ",";
        }
        return names;
    }

    ;

    /**
     * @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();
        }
        fileName = fileName.replaceAll("/", "_"); //替换文件中敏感字段
        logger.info("目录文件{}!", fileName);
        String filePath = fileDir + "/" + fileName;
        logger.info("目录{}!", filePath);
        // 读取模板渲染参数
        InputStream is = getClass().getClassLoader().getResourceAsStream(templatePath);

        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        RenderPolicy hackLoopSameLineTableRenderPolicy = new LoopColumnTableRenderPolicy(true);

        Configure config = Configure.builder()
                .bind("item1", policy)
                .bind("item2", policy)
                .bind("item3", policy)
                .bind("item4", policy)
                .bind("item5", policy)
                .build();

        XWPFTemplate template = XWPFTemplate.compile(is, config).render(paramMap);
        try {
            // 将模板参数写入路径
            template.writeToFile(filePath);
            template.close();
        } catch (Exception e) {
            logger.error("生成word异常{}", e.getMessage());
            e.printStackTrace();
        }
        String pathFileName = FileUploadUtils.getPathFileName(RuoYiConfig.getFilePath("/" + "plant/dailymeeting"), fileName);
        return pathFileName;
    }
}
