package com.ruoyi.project.plant.controller;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.project.plant.domain.TMtOpextrack;
import com.ruoyi.project.plant.mapper.TMtOpextrackMapper;
import com.ruoyi.project.plant.service.*;
import com.ruoyi.project.production.domain.TMonthplan;
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.project.plant.domain.TMtMeeting;
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;
    /**
     * 查询装置会议列表
     */
    @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:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tMtMeetingService.selectTMtMeetingById(id));
    }

    /**
     * 新增装置会议
     */
    @PreAuthorize("@ss.hasPermi('plant:meeting:add')")
    @Log(title = "装置会议", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TMtMeeting tMtMeeting)
    {
        return toAjax(tMtMeetingService.insertTMtMeeting(tMtMeeting));
    }

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

    /**
     * 删除装置会议
     */
    @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 void AutoReport(HttpServletRequest request, HttpServletResponse response, Long year ,Long meetingId) {
        logger.info("meetingId:" + meetingId);
        String savePath = request.getSession().getServletContext().getRealPath("/"); // 系统根路径
        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"));
            // 刷新缓冲
            response.flushBuffer();
            OutputStream ouputStream = response.getOutputStream();
            doc.write(ouputStream);
            ouputStream.flush();
            ouputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * @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);
        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)");

        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);
        }
    }

}
