package com.koobietech.eas.service.impl;

import com.koobietech.eas.common.constant.FileType;
import com.koobietech.eas.common.exception.EasException;
import com.koobietech.eas.common.result.JsonResult;
import com.koobietech.eas.common.utils.DateUtils;
import com.koobietech.eas.common.utils.StudentArchiveGenerator;
import com.koobietech.eas.dao.dto.ArchivesDto;
import com.koobietech.eas.mbg.mapper.EasArcArchivesMapper;
import com.koobietech.eas.mbg.mapper.EasArcTlsStudentsMapper;
import com.koobietech.eas.mbg.mapper.EasSysStudentMapper;
import com.koobietech.eas.mbg.model.EasArcArchives;
import com.koobietech.eas.mbg.model.EasArcTlsStudents;
import com.koobietech.eas.mbg.model.EasSysStudent;
import com.koobietech.eas.service.EasArchivesFilesService;
import com.koobietech.eas.service.EasStuProfileService;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
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.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Service
public class EasStuProfileServiceImpl implements EasStuProfileService {

    private static final String TEMPLATE_PATH = "temp/StuRegistTemp.docx";
    private static final String PHOTO_PATH = "temp/kun.jpeg";

    @Resource
    private EasArcTlsStudentsMapper easArcTlsStudentsMapper;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private EasSysStudentMapper easSysStudentMapper;

    @Resource
    private EasArcArchivesMapper easArcArchivesMapper;

    @Resource
    private EasArchivesFilesService easArchivesFilesService;

    @Override
    public boolean StuProfileDownload(EasArcTlsStudents easArcTlsStudents,Integer manager_id) {
        try (InputStream wordStream = getClass().getClassLoader().getResourceAsStream(TEMPLATE_PATH)) {
            assert wordStream != null;
            try (XWPFDocument doc = new XWPFDocument(wordStream)) {

                Map<String, Object> map = new HashMap<>();
                map.put("student_name", easArcTlsStudents.getStudentName());

                //调用内部类方法 把MF转换成 男女
                map.put("gender", convertToGender(easArcTlsStudents.getGender()));

                map.put("major", easArcTlsStudents.getMajor());
                map.put("grade", easArcTlsStudents.getGrade());

                //调用自定义的时间格式转换器 把前端传过来的带时分秒时间转换成 2019年12月12日
                map.put("enrollment_date", DateUtils.convertToYearMonthDay(easArcTlsStudents.getEnrollmentDate()));

                map.put("phone", easArcTlsStudents.getPhone());
                map.put("university", easArcTlsStudents.getUniversity());
                map.put("student_idnumber", easArcTlsStudents.getStudentIdnumber());
                map.put("avatar", getClass().getClassLoader().getResourceAsStream(PHOTO_PATH));

                //调用内部类方法 生成学号
                String studentNumber = generateStudentNumber(easArcTlsStudents);
                map.put("student_number", studentNumber);

                replacePlaceholders(doc, map);

                //将easArcTlsStudents 保存到数据库
                easArcTlsStudentsMapper.insert(easArcTlsStudents);

                //使用BeanUtils 将easArcTlsStudents 转换成 eassysstudent
                EasSysStudent easSysStudents = new EasSysStudent();
                BeanUtils.copyProperties(easArcTlsStudents,easSysStudents);
                //设置初始密码 使用 passwordEncoder 设置初始密码为123456
                easSysStudents.setPasswd(passwordEncoder.encode("123456"));
                easSysStudents.setDisabled("N");

                easSysStudentMapper.insert(easSysStudents);

                String archiveCode = StudentArchiveGenerator.generateArchiveCode(studentNumber, String.valueOf(FileType.DOCX));
                ArchivesDto archivesDto = easArchivesFilesService.saveArchiveStudentsFile(easArcTlsStudents.getStudentIdnumber(), doc);
                String filePath = archivesDto.getPath();
                String arctype = archivesDto.getFileType();
                Date creat_time = DateUtils.convertToYearMonthDayToDate(new Date());
                Date modify_time = new Date();

                //validity_time 暂且设置成create_date + 1年
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(creat_time);
                calendar.add(Calendar.YEAR, 1);
                Date create_date = calendar.getTime();

                int create_uid = 0;

                EasArcArchives easArcArchives = new EasArcArchives();
                easArcArchives.setArchiveNumber(archiveCode);
                easArcArchives.setStudentNumber(studentNumber);
                easArcArchives.setFilePath(filePath);
                easArcArchives.setArctype(arctype);
                easArcArchives.setCreateTime(creat_time);
                easArcArchives.setModifyTime(modify_time);
                easArcArchives.setValidityTime(create_date);
                easArcArchives.setManagerId(manager_id);
                easArcArchives.setCreateUid(create_uid);
                easArcArchives.setCreateDate(new Date());
                easArcArchivesMapper.insert(easArcArchives);
            }
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    private String generateStudentNumber(EasArcTlsStudents easArcTlsStudents) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(easArcTlsStudents.getEnrollmentDate());
        String year = String.valueOf(calendar.get(Calendar.YEAR));

        return StudentArchiveGenerator.generateStudentCode("",
                easArcTlsStudents.getStudentIdnumber(), easArcTlsStudents.getUniversity(), year);
    }

    private String convertToGender(String gender) {
        if (gender.equals("M")) {
            return "男";
        } else if (gender.equals("F")) {
            return "女";
        } else {
            return "未知";
        }
    }

    private void replacePlaceholders(XWPFDocument document, Map<String, Object> map) {
        for (XWPFTable table : document.getTables()) {
            for (XWPFTableRow row : table.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    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 EasException("学员导入失败");
                            }
                        }
                    });
                }
            }
        }
    }
}


