package com.koobietech.eas.service.impl;

import com.koobietech.eas.common.result.JsonResult;
import com.koobietech.eas.common.utils.StudentArchiveGenerator;
import com.koobietech.eas.mbg.model.EasArcTlsStudents;
import com.koobietech.eas.service.EasStuProfileService;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.poi.util.Units;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.*;

@Service
public class EasStuProfileServiceImpl implements EasStuProfileService {

    private static final Logger LOGGER = LoggerFactory.getLogger(EasStuProfileServiceImpl.class);
    private static final String TEMPLATE_PATH = "temp/StuRegistTemp.docx";
    private static final String PHOTO_PATH = "temp/kun.jpeg";
    private static final String OUTPUT_PATH = "D:\\myDesk\\test.docx";

    @Override
    public JsonResult StuProfileDownload(EasArcTlsStudents easArcTlsStudents) {
        LOGGER.info("开始学员档案导出：{}", easArcTlsStudents);

        try (InputStream wordStream = getClass().getClassLoader().getResourceAsStream(TEMPLATE_PATH)) {
            assert wordStream != null;
            XWPFDocument doc = new XWPFDocument(wordStream);

            Map<String, Object> map = new HashMap<>();
            map.put("student_name", easArcTlsStudents.getStudentName());
            map.put("gender", easArcTlsStudents.getGender());
            map.put("major", easArcTlsStudents.getMajor());
            map.put("grade", easArcTlsStudents.getGrade());
            map.put("enrollment_date", easArcTlsStudents.getEnrollmentDate());
            map.put("phone", easArcTlsStudents.getPhone());
            map.put("university", easArcTlsStudents.getUniversity());

            InputStream photo = getClass().getClassLoader().getResourceAsStream(PHOTO_PATH);
            System.out.println( photo );
            map.put("avatar", photo);

            /**
             public static String generateStudentCode(String studentNumber, String studentId, String schoolName, String enrollmentDate) {
             LocalDate localDateEnrollmentDate = LocalDate.of(Integer.parseInt(enrollmentDate), 1, 1);
             String studentAge = String.valueOf(getStudentAge(studentId));
             String studentNum = getStudentNum(studentNumber);
             String studentGender = getStudentGender(studentId).substring(0, 1); // 取性别代码的首字母
             String graduationDate = String.valueOf(getStudentGraduationDate(localDateEnrollmentDate).getYear());

             String studentCode = STUDENT_CODE_PEREFIX + studentNum + studentAge +
             studentGender + graduationDate + schoolName;

             // 如果生成的档案编码长度不足，用UUID填充
             if (studentCode.length() < STUDENT_CODE_LENGTH) {
             studentCode += UUID.randomUUID().toString()
             .substring(0, STUDENT_CODE_LENGTH - studentCode.length());
             }
             return studentCode;
             }
             */
            //使用工具类生成学员档案号
            String student_number = StudentArchiveGenerator.generateStudentCode(
                    "", "232126199003194781", "11273", "2023");


            replacePlaceholders(doc, map);

            saveDocument(doc);
        } catch (IOException e) {
            LOGGER.error("学员档案导出失败：{}", e.getMessage(), e);
            return JsonResult.fail("学员档案导出失败！");
        }

        LOGGER.info("学员档案导出成功！");
        return JsonResult.ok("学员档案导出成功！");
    }

    private void replacePlaceholders(XWPFDocument document, Map<String, Object> map) {
        Iterator<XWPFTable> it = document.getTablesIterator();

        while (it.hasNext()) {
            XWPFTable table = it.next();
            int rcount = table.getNumberOfRows();
            for (int n = 0; n < rcount; n++) {
                XWPFTableRow wrow = table.getRow(n);
                List<XWPFTableCell> cells = wrow.getTableCells();
                for (XWPFTableCell cell : cells) {
                    String cellText = cell.getText();
                    if (!cellText.contains("${")) {
                        continue;
                    }
                    map.forEach((key, value) -> {
                        String placeholder = "${" + key + "}";
                        if (cellText.contains(placeholder) && Objects.nonNull(value)) {
                            try {
                                cell.removeParagraph(0);
                                if (value instanceof InputStream) {
                                    //如果是放置图片的单元格，在这里添加一个计算图片合适大小的方法，按比例
                                    cell.addParagraph().createRun().addPicture((InputStream) value,
                                            XWPFDocument.PICTURE_TYPE_JPEG, "avatar.jpg",
                                            Units.pixelToEMU(110), Units.pixelToEMU(140));
                                } else {
                                    cell.setText(cellText.replace(placeholder, value.toString()));
                                }
                            } catch (IOException | InvalidFormatException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    });
                }
            }
        }
    }

    private void saveDocument(XWPFDocument document) throws IOException {
        try (FileOutputStream outputStream = new FileOutputStream(OUTPUT_PATH)) {
            document.write(outputStream);
        }
    }


}
