package com.koobietech.eas.common.utils;

import com.koobietech.eas.common.constant.FileType;
import com.koobietech.eas.common.constant.UniversityCode;
import com.koobietech.eas.common.exception.EasException;
import com.koobietech.eas.common.pojo.ArchiveNumberInfoPojo;
import com.koobietech.eas.common.pojo.StudentNumberInfoPojo;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.UUID;

/**
 * @author lc
 */
public class ArchiveManager {

    private static final String ARCHIVE_CODE_PREFIX = "SA";
    private static final int ARCHIVE_CODE_LENGTH = 25;

    private static final String STUDENT_CODE_PEREFIX = "ST";
    private static final int STUDENT_CODE_LENGTH = 25;
    private static final int STUDENT_NUM_LENGTH = 8;

    /**
     * 生成文件档案编号
     * @param generateStudentCode
     * @param fileTypeCode
     * @return SA911X3B98723081544551720
     */
    public static String generateArchiveCode(String generateStudentCode, String fileTypeCode) {
        String studentNum = generateStudentCode.substring(2, STUDENT_NUM_LENGTH + 3);
        String nowDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMddHhmmss", Locale.CHINA));
        String archiveCode = ARCHIVE_CODE_PREFIX + studentNum + nowDate + fileTypeCode;
        if (archiveCode.length() < ARCHIVE_CODE_LENGTH) {
            archiveCode += UUID.randomUUID().toString()
                    .substring(0, ARCHIVE_CODE_LENGTH - archiveCode.length());
        }
        return archiveCode;
    }

    /**
     *解析档案编号信息
     *
     * @param archiveNumber
     * @return
     */
    public static ArchiveNumberInfoPojo parseArchiveNumber(String archiveNumber) {
        ArchiveNumberInfoPojo archiveInfo = new ArchiveNumberInfoPojo();
        String studentCode = archiveNumber.substring(2, STUDENT_NUM_LENGTH + 3);
        String studentId = studentCode.split("X")[0];
        String createTime = archiveNumber.substring(STUDENT_NUM_LENGTH + 3, STUDENT_NUM_LENGTH + 15);
        String fileTypeCode = archiveNumber.substring(ARCHIVE_CODE_LENGTH - 2);
        archiveInfo.setStudentId(Integer.parseInt(studentId));
        archiveInfo.setStudentCode(studentCode);
        archiveInfo.setCreateTime(Long.parseLong(createTime));
        archiveInfo.setFileTypeCode(Integer.parseInt(fileTypeCode));
        archiveInfo.setFileSuffix(FileType.getSuffix(Integer.parseInt(fileTypeCode)));
        return archiveInfo;
    }



    /**
     * 生成学生档案编码
     * @param studentNumber
     * @param studentCardId
     * @param schoolName
     * @param enrollmentDate
     * @return  ST911X3B98736M20251021273
     */
    public static String generateStudentCode(String studentNumber, String studentCardId, String schoolName, String enrollmentDate) {
        if ( !StringUtils.hasText(studentCardId)
                || !StringUtils.hasText(schoolName) || !StringUtils.hasText(enrollmentDate) ) {
            throw new EasException("参数不能为空");
        }
        LocalDate localDateEnrollmentDate = LocalDate.of(Integer.parseInt(enrollmentDate), 1, 1);
        String studentAge = String.valueOf(getStudentAge(studentCardId));
        String studentNum = getStudentNum(studentNumber);
        // 取性别代码的首字母
        String studentGender = getStudentGender(studentCardId).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;
    }

    /**
     * 解析学生档案编号信息
     *
     * @param studentNumber 学生档案编号
     * @return 学生档案编号信息
     */
    public static StudentNumberInfoPojo parseStudentNumber(String studentNumber) {
        if (studentNumber == null) {
            return null;
        }
        String studentNum = studentNumber.substring(2, STUDENT_NUM_LENGTH + 3);
        String studentId = studentNum.split("X")[0];
        String studentAge = studentNumber.substring(STUDENT_NUM_LENGTH + 3, STUDENT_NUM_LENGTH + 5);
        String studentGender = studentNumber.substring(STUDENT_NUM_LENGTH + 5, STUDENT_NUM_LENGTH + 6);
        String graduationDate = studentNumber.substring(STUDENT_NUM_LENGTH + 6, STUDENT_NUM_LENGTH + 10);
        String schoolCode = studentNumber.substring(STUDENT_NUM_LENGTH + 10, STUDENT_NUM_LENGTH + 15);
        StudentNumberInfoPojo info = new StudentNumberInfoPojo();
        info.setStudentNum(studentNum);
        info.setStudentId(Long.valueOf(studentId));
        info.setStudentAge(Integer.parseInt(studentAge));
        info.setStudentGender(studentGender);
        info.setGraduationDate(graduationDate);
        info.setSchoolName(UniversityCode.getName(Integer.parseInt(schoolCode)));
        info.setSchoolCode(Integer.parseInt(schoolCode));
        return info;
    }

    /**
     * 获取学生编号，自动补齐
     * @param studentNumber
     * @return
     */
    private static String getStudentNum(String studentNumber) {
        if (studentNumber.length() < STUDENT_NUM_LENGTH) {
            studentNumber = studentNumber + "X" +
                    (UUID.randomUUID().toString().replace("-", "").replace("X", ""))
                    .toUpperCase(Locale.ROOT).substring(0, STUDENT_NUM_LENGTH - studentNumber.length());
        }
        return studentNumber;
    }

    /**
     * 获取学生年龄
     * @param studentCardId
     * @return
     */
    private static int getStudentAge(String studentCardId) {
        LocalDate currentDate = LocalDate.now();
        LocalDate birthDateWithDate = extractBirthDate(studentCardId);
        Period period = Period.between(birthDateWithDate, currentDate);
        return period.getYears();
    }

    /**
     * 获取学生性别
     * @param studentCardId
     * @return
     */
    private static String getStudentGender(String studentCardId) {
        // 根据身份证号获取性别，这里只取身份证号的倒数第二位判断性别，假设性别代码为奇数表示男性，偶数表示女性
        int genderCode = Integer.parseInt(studentCardId.substring(16, 17));
        return genderCode % 2 == 0 ? "F" : "M";
    }

    /**
     * 获取学生毕业日期
     * @param enrollmentDate
     * @return
     */
    private static LocalDate getStudentGraduationDate(LocalDate enrollmentDate) {
        // 假设毕业时间为入学时间的四年后
        return enrollmentDate.plusYears(4);
    }

    /**
     * 提取身份证号码的出生日期部分
     * @param idCard
     * @return
     */
    private static LocalDate extractBirthDate(String idCard) {
        // 提取身份证号码中的出生日期部分
        String birthdate = idCard.substring(6, 14);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        return LocalDate.parse(birthdate, formatter);
    }
}
