package cn.cslg.report.service.business;

import cn.cslg.report.common.model.dto.invalidReReport.InvalidReasonDTO;
import cn.cslg.report.common.model.dto.invalidReReport.InvalidReasonFieldValueDTO;
import cn.cslg.report.common.model.vo.invalidReReport.ExportInvalidReasonVO;
import cn.cslg.report.common.model.vo.invalidReReport.QueryInvalidReasonVO;
import cn.cslg.report.common.utils.WordUtil;
import cn.cslg.report.entity.invalidReReport.InvalidReasonField;
import cn.cslg.report.service.business.InvalidReReport.InvalidReasonFieldService;
import cn.cslg.report.service.business.InvalidReReport.InvalidReasonService;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 导出无效理由实现类
 *
 * @Author xiexiang
 * @Date 2023/7/24
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class ExportArgumentsScenariosService {
    private final InvalidReasonService invalidReasonService;
    private final InvalidReasonFieldService invalidReasonFieldService;

    public void ExportToExcel(Integer reportId, String filePath) throws IOException {
        XWPFDocument doc = new XWPFDocument();
        //根据报告id查询所有自定义字段
        LambdaQueryWrapper<InvalidReasonField> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(InvalidReasonField::getReportId, reportId)
                .orderByAsc(InvalidReasonField::getReportId);
        List<InvalidReasonField> fields = invalidReasonFieldService.list(wrapper);
        List<String> nameList = new ArrayList<>();
        nameList.add("序号");
        nameList.add("无效理由");
        nameList.add("涉及内容");
        nameList.add("相关证据");
        nameList.add("陈述意见");

        List<String> tem = fields.stream().map(InvalidReasonField::getFieldName).collect(Collectors.toList());
        nameList.addAll(tem);
        //根据报告id查询无效理由
        List<QueryInvalidReasonVO> queryInvalidReasonVOS = invalidReasonService.queryInvalidReason(reportId);
        //根据无效类型排序，方便合并单元格
        queryInvalidReasonVOS.sort(Comparator.comparing(QueryInvalidReasonVO::getInvalidName));
        //设置页脚
//        WordUtil.createDefaultFooter(doc);
        //设置页边距
        WordUtil.setMargin(doc, 1000, 1000, 500, 100);
        //设置标题
        WordUtil.setParagraph(doc, "标题", "宋体", 16, 10, true, ParagraphAlignment.CENTER);
        //设置副标题
        WordUtil.setParagraph(doc, 1 + "到" + 2, "宋体", 10, 10, true, ParagraphAlignment.RIGHT);
        int colTotalCount = fields.size() + 5;
        //总条数
        int dataCount = queryInvalidReasonVOS.size();
        //创建表格
        XWPFTable xTable = doc.createTable(1, colTotalCount);
        //设置边框
        WordUtil.setTableBolder(xTable, 10, "000000");
        // 创建表头数据
        for (int j = 0; j < colTotalCount; j++) {
            WordUtil.setCellText(xTable.getRow(0).getCell(j), nameList.get(j), 200, "宋体", 10, true);
        }
        //记录合并数据map
        Map<Integer, Integer> map = new HashMap<>();
        // 创建表格内容
        for (int i2 = 0; i2 < dataCount; i2++) {
            QueryInvalidReasonVO queryInvalidReasonVO = queryInvalidReasonVOS.get(i2);
            int name = queryInvalidReasonVO.getInvalidName();
            //记录合并数据
            if (!map.containsKey(name)) {
                map.put(name, 1);
            } else {
                map.put(name, map.get(name) + 1);
            }
            List<InvalidReasonFieldValueDTO> fieldValueDTOS = queryInvalidReasonVO.getFields();
            XWPFTableRow row = xTable.insertNewTableRow(i2 + 1);
            row.setHeight(300);
            for (int j = 0; j < colTotalCount; j++) {
                XWPFTableCell cell = row.createCell();
                XWPFRun run;
                run = WordUtil.setTableCellStyle(cell, ParagraphAlignment.CENTER, "微软雅黑", 9, false);
                if (j == 0) {
                    run.setText(String.valueOf(i2));
                } else if (j == 1) {
                    if (name == 0) {
                        run.setText("权利要求不清楚");
                    } else if (name == 1) {
                        run.setText("说明书公开不充分");
                    } else if (name == 2) {
                        run.setText("不具备创造性");
                    } else if (name == 3) {
                        // 创建一个段落
                        XWPFParagraph paragraph = cell.getParagraphs().get(0);

                        // 创建一个运行
                        XWPFRun run1 = paragraph.createRun();
                        CTR ctr = run1.getCTR();
                        ctr.addNewRPr().addNewB();
                        ctr.addNewT().setStringValue("<b>Bold text</b> Normal text");
//                        run.setText("<h1>不具备新颖性<h1>");
                    }
                } else if (j == 2) {
                    int content = queryInvalidReasonVO.getContent();
                    if (content == -1) {
                        run.setText("说明书");
                    } else {
                        run.setText("权要" + content);
                    }
                } else if (j == 3) {
                    if (name == 0 || name == 1) {
                        run.setText(queryInvalidReasonVO.getProofStr());
                    } else {
                        StringBuilder stringBuilder = new StringBuilder();
                        List<QueryInvalidReasonVO.proofGroupIn> proofGroupIns = queryInvalidReasonVO.getProofGroups();
                        for (int t = 0; t < proofGroupIns.size(); t++) {
                            List<QueryInvalidReasonVO.proofIn> proofIns = proofGroupIns.get(t).getProofs();
                            List<Integer> strs = proofIns.stream().map(QueryInvalidReasonVO.proofIn::getSort).collect(Collectors.toList());
                            for (int i = 0; i < strs.size(); i++) {
                                if (t == 0 && i == 0) {
                                    stringBuilder.append("D" + strs.get(i));

                                } else if (t != 0 && i == 0) {
                                    stringBuilder.append(" D" + strs.get(i));
                                } else {
                                    stringBuilder.append("+D" + strs.get(i));
                                }
                            }
                        }
                        run.setText(stringBuilder.toString());
                    }
                } else if (j == 4) {
                    run.setText(queryInvalidReasonVO.getArgumentStr());
                } else {
                    InvalidReasonField field = fields.get(j - 5);
                    InvalidReasonFieldValueDTO valueDTO = fieldValueDTOS.stream().filter(item -> item.getFieldId().equals(field.getId())).findFirst().orElse(new InvalidReasonFieldValueDTO());
                    run.setText(valueDTO.getFieldValue());
                }
            }
        }
        //记录合并起始位置
        Integer t=1;
        for(int i :map.keySet()){
            int end =t+map.get(i)-1;
       WordUtil.mergeCellsVertically(xTable,1,t,end);
      t= t+map.get(i);
        }
        FileOutputStream os = new FileOutputStream("output.docx");
        doc.write(os);
        os.close();
        doc.close();
    }


}

