package com.ruoyi.project.production.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.druid.sql.dialect.postgresql.ast.stmt.PGUpdateStatement;
import com.alibaba.fastjson.JSON;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.common.domain.TCommonfile;
import com.ruoyi.project.common.mapper.TCommonfileMapper;
import com.ruoyi.project.common.service.ITCommonfileService;
import com.ruoyi.project.plant.domain.TMtdDaily;
import com.ruoyi.project.plant.domain.TMtdItem;
import com.ruoyi.project.plant.mapper.TMtdItemMapper;
import com.ruoyi.project.plant.service.ITMtdDailyService;
import com.ruoyi.project.production.domain.TPrdRecordItem;
import com.ruoyi.project.production.mapper.TPrdRecordItemMapper;
import com.ruoyi.project.production.mapper.TPrdRecordMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
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.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.production.domain.TPrdRecord;
import com.ruoyi.project.production.service.ITPrdRecordService;
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.imageio.ImageIO;

/**
 * 生产记录Controller
 *
 * @author ssy
 * @date 2024-10-08
 */
@RestController
@RequestMapping("/production/prdRecord")
public class TPrdRecordController extends BaseController
{
    @Autowired
    private ITPrdRecordService tPrdRecordService;
    @Autowired
    private ITMtdDailyService tMtdDailyService;
    @Resource
    private TMtdItemMapper tMtdItemMapper;
    @Resource
    private TPrdRecordMapper tPrdRecordMapper;
    @Resource
    private TPrdRecordItemMapper tPrdRecordItemMapper;
    @Resource
    private TCommonfileMapper tCommonfileMapper;

    /**
     * 查询生产记录列表
     */
    @PreAuthorize("@ss.hasPermi('production:prdRecord:list')")
    @GetMapping("/list")
    public TableDataInfo list(TPrdRecord tPrdRecord)
    {
        startPage();
        List<TPrdRecord> list = tPrdRecordService.selectTPrdRecordList(tPrdRecord);
        for (TPrdRecord r: list
             ) {
            TPrdRecordItem query = new TPrdRecordItem();
            query.setDailyId(r.getId());
            r.setContent("");
            List<TPrdRecordItem> items = tPrdRecordItemMapper.selectTPrdRecordItemList(query);
            int code = 1;
            for (TPrdRecordItem i :items
                 ) {
                r.setContent(r.getContent() + code + "、" + i.getDescription() + "\n");
                code++;
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出生产记录列表
     */
    @PreAuthorize("@ss.hasPermi('production:prdRecord:export')")
    @Log(title = "生产记录", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPrdRecord param)
    {
        TPrdRecord tPrdRecord =  tPrdRecordService.selectTPrdRecordById(param.getId());
        TPrdRecordItem query = new TPrdRecordItem();
        query.setDailyId(param.getId());
        List<TPrdRecordItem> items = tPrdRecordItemMapper.selectTPrdRecordItemList(query);
        tPrdRecord.setItems(items);
        // 创建一个 Word 文档
        XWPFDocument document = new XWPFDocument();
        try {
            // 创建输出文件的路径
            FileOutputStream out = null;
            // 添加每日的记录
            addDayContent(document, tPrdRecord);
            // 将内容写入文件
            out = new FileOutputStream(ExcelUtil.getAbsoluteFile("daily_report.docx"));
            document.write(out);
            out.close();
            System.out.println("Word 文档生成成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success("daily_report.docx");
    }
    /**
     * 导出生产记录列表
     */
    @PreAuthorize("@ss.hasPermi('production:prdRecord:export')")
    @Log(title = "生产记录", businessType = BusinessType.EXPORT)
    @GetMapping("/exportMonth")
    public AjaxResult exportMonth(TPrdRecord param)
    {
        List<TPrdRecord> list = tPrdRecordService.selectTPrdRecordList(param);
        // 创建一个 Word 文档
        XWPFDocument document = new XWPFDocument();
        try {
            // 创建输出文件的路径
            FileOutputStream out = null;
            for (TPrdRecord t: list
                 ) {
                TPrdRecordItem query = new TPrdRecordItem();
                query.setDailyId(t.getId());
                List<TPrdRecordItem> items = tPrdRecordItemMapper.selectTPrdRecordItemList(query);
                t.setItems(items);
                // 添加每日的记录
                addDayContent(document, t);
            }


            // 将内容写入文件
            out = new FileOutputStream(ExcelUtil.getAbsoluteFile("daily_report.docx"));
            document.write(out);
            out.close();
            System.out.println("Word 文档生成成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success("daily_report.docx");
    }



    // 添加每日的内容
    private void addDayContent(XWPFDocument document,TPrdRecord t ) {
        Date date = t.getRecordDate();
        List<TPrdRecordItem> items = t.getItems();
        String remarks = t.getRemarks();
        // 添加日期为标题
        XWPFParagraph dateParagraph = document.createParagraph();
        XWPFRun dateRun = dateParagraph.createRun();
        dateRun.setBold(true);
        String pattern = "yyyy年MM月dd日"; // 定义日期格式化模板

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

        String formattedDate = dateFormat.format(date); // 将日期转换为字符串
        dateRun.setText(formattedDate);

        XWPFParagraph dateParagraph2 = document.createParagraph();
        XWPFRun dateRun2 = dateParagraph2.createRun();
        dateRun2.setBold(true);
        dateRun2.setText("生产记录");

        // 添加条目列表
        for (int i = 0; i < items.size(); i++) {
            XWPFParagraph itemParagraph = document.createParagraph();
            XWPFRun itemRun = itemParagraph.createRun();
            itemRun.setText((i + 1) + "、\t" + items.get(i).getDescription());
        }
        //异常
        if (StringUtils.isNotEmpty(remarks)) {
            // 添加日期为标题
            XWPFParagraph markParagraph = document.createParagraph();
            XWPFRun markRun = markParagraph.createRun();
            markRun.setBold(true);
            markRun.setText("异常情况记录");

            XWPFParagraph markParagraph2 = document.createParagraph();
            XWPFRun markRun2 = markParagraph2.createRun();
            markRun2.setText(remarks);
        }

        TCommonfile tCommonfile = new TCommonfile();
        tCommonfile.setpType("prdRecord");
        tCommonfile.setpId(t.getId());
        List<TCommonfile> exceptionImages = tCommonfileMapper.selectTCommonfileList(tCommonfile);

        // 添加异常图片
        if (exceptionImages != null && exceptionImages.size() >0) {
            XWPFParagraph imageTitlePara = document.createParagraph();
            XWPFRun titleRun = imageTitlePara.createRun();
            titleRun.setText("异常图片：");
            titleRun.setBold(true);
            titleRun.addBreak();

            for (TCommonfile commonfile : exceptionImages) {
                String imgPath = RuoYiConfig.getProfile() + commonfile.getFileUrl().replaceFirst("/profile", "");
                try (FileInputStream fis = new FileInputStream(imgPath)) {
                    XWPFParagraph imgPara = document.createParagraph();
                    XWPFRun imgRun = imgPara.createRun();

                    String extension = imgPath.substring(imgPath.lastIndexOf(".") + 1).toLowerCase();
                    int picType = determinePictureType(extension);

                    // 动态尺寸计算
                    BufferedImage img = ImageIO.read(new File(imgPath));
                    int targetWidthPixel = 400; // 目标宽度像素
                    double aspectRatio = (double) img.getHeight() / img.getWidth();
                    int targetHeightPixel = (int) (targetWidthPixel * aspectRatio);

                    try {
                        imgRun.addPicture(
                                fis,
                                picType,
                                imgPath,
                                Units.toEMU(targetWidthPixel),
                                Units.toEMU(targetHeightPixel)
                        );
                    } catch (InvalidFormatException e) {
                        e.printStackTrace();
                    }
                    imgRun.addBreak(BreakType.TEXT_WRAPPING);
                } catch (Exception e) {
                    System.err.println("无法加载图片: " + imgPath);
                }
            }
        }
        // 添加空白
        XWPFParagraph endParagraph = document.createParagraph();
        XWPFRun endRun = endParagraph.createRun();
    }

    public void syncMeeting(long meetingId){
        TMtdDaily tMtdDaily = tMtdDailyService.selectTMtdDailyById(meetingId);
        if (tMtdDaily != null) {
            TPrdRecord del = new TPrdRecord();
            del.setRecordDate(tMtdDaily.getMeetingDate());
            tPrdRecordMapper.deleteTPrdRecordByDate(del);
        }
        // 插入主表
        TPrdRecord record = new TPrdRecord();
        record.setRecordDate(tMtdDaily.getMeetingDate());
        tPrdRecordMapper.insertTPrdRecord(record);
        List<TPrdRecordItem> tPrdRecordItemList = new ArrayList<>();

        TPrdRecordItem recordItem1= new TPrdRecordItem();
        recordItem1.setDailyId(record.getId());
        recordItem1.setDescription("裂解炉运行模式" +  tMtdDaily.getOptMode());
        tPrdRecordItemList.add(recordItem1);

        TPrdRecordItem recordItem2= new TPrdRecordItem();
        recordItem2.setDescription("负荷(t/hr)：裂解:" +  tMtdDaily.getSplit()+ " AEU:" + tMtdDaily.getAeu() + " PGU:" + tMtdDaily.getPgu());
        recordItem2.setDailyId(record.getId());
        tPrdRecordItemList.add(recordItem2);

        //获取item列表
        TMtdItem item = new TMtdItem();
        item.setDailyId(meetingId);
        item.setItemType(0);
        List<TMtdItem> item0 = tMtdItemMapper.selectTMtdItemList(item);

        item.setItemType(1);
        List<TMtdItem> item1 = tMtdItemMapper.selectTMtdItemList(item);
        item0.addAll(item1);

        item.setItemType(2);
        List<TMtdItem> item2 = tMtdItemMapper.selectTMtdItemList(item);
        item0.addAll(item2);

        item.setItemType(3);
        List<TMtdItem> item3 = tMtdItemMapper.selectTMtdItemList(item);
        item0.addAll(item3);

        for (TMtdItem i: item0
        ) {
            TPrdRecordItem recordItem= new TPrdRecordItem();
            recordItem.setItem(i.getItem());
            recordItem.setDailyId(record.getId());
            recordItem.setDescription(i.getDescription());
            tPrdRecordItemList.add(recordItem);
        }
        for (TPrdRecordItem i : tPrdRecordItemList
             ) {
            tPrdRecordItemMapper.insertTPrdRecordItem(i);
        }

    }

    /**
     * 获取生产记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('production:prdRecord:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        TPrdRecord tPrdRecord = tPrdRecordService.selectTPrdRecordById(id);
        TPrdRecordItem query = new TPrdRecordItem();
        query.setDailyId(tPrdRecord.getId());
        List<TPrdRecordItem> items = tPrdRecordItemMapper.selectTPrdRecordItemList(query);

        tPrdRecord.setItems(items);
        return AjaxResult.success(tPrdRecord);
    }

    /**
     * 新增生产记录
     */
    @PreAuthorize("@ss.hasPermi('production:prdRecord:add')")
    @Log(title = "生产记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPrdRecord tPrdRecord)
    {
        logger.info(JSON.toJSONString(tPrdRecord));
        tPrdRecordService.insertTPrdRecord(tPrdRecord);
        for (TPrdRecordItem i : tPrdRecord.getItems()
        ) {
            i.setDailyId(tPrdRecord.getId());
            tPrdRecordItemMapper.insertTPrdRecordItem(i);
        }
        return toAjax(1);
    }

    /**
     * 修改生产记录
     */
    @PreAuthorize("@ss.hasPermi('production:prdRecord:edit')")
    @Log(title = "生产记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPrdRecord tPrdRecord)
    {
        logger.info(JSON.toJSONString(tPrdRecord));
        tPrdRecordService.updateTPrdRecord(tPrdRecord);
        tPrdRecordItemMapper.deleteTPrdRecordItemByRecordId(tPrdRecord.getId());
        for (TPrdRecordItem i : tPrdRecord.getItems()
        ) {
            i.setDailyId(tPrdRecord.getId());
            tPrdRecordItemMapper.insertTPrdRecordItem(i);
        }
        return toAjax(1);
    }

    /**
     * 删除生产记录
     */
    @PreAuthorize("@ss.hasPermi('production:prdRecord:remove')")
    @Log(title = "生产记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tPrdRecordService.deleteTPrdRecordByIds(ids));
    }

    private static int determinePictureType(String extension) {
        switch (extension) {
            case "jpg":
            case "jpeg":
                return Document.PICTURE_TYPE_JPEG;
            case "png":
                return Document.PICTURE_TYPE_PNG;
            case "gif":
                return Document.PICTURE_TYPE_GIF;
            case "bmp":
                return Document.PICTURE_TYPE_BMP;
            default:
                return Document.PICTURE_TYPE_PNG; // 默认类型
        }
    }
}
