package com.srs.comprehensive.util;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.srs.common.utils.file.FileUtils;
import com.srs.comprehensive.domain.*;
import com.srs.comprehensive.domain.Vo.GraduateVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import com.srs.common.utils.poi.ExcelUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.function.Function;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Component
/**
 * 工具类
 * 邵政文
 * 2025-07-01
 */
public class FileUploadUtil {

    @Value("${exclepath.profile}")
    private String rootPath;

    private static final Logger log = LoggerFactory.getLogger(FileUploadUtil.class);

    /**
     * 保存文件路径
     * 邵政文
     * 2025-07-01
     */
    public String saveFile(MultipartFile file, String subDir, String fileName) throws IOException {
        String targetDir = rootPath + "/" + subDir + "/";
        File dest = new File(targetDir + fileName);

        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs(); // 创建父目录
        }

        // 先保存文件到服务器
        file.transferTo(dest); // 这是关键步骤
        return dest.getAbsolutePath();
    }

    /**
     * 批量下载文件
     * 邵政文
     * 2025-07-01
     */
    public <T> void downloadFiles(HttpServletRequest request, HttpServletResponse response,
                                 List<T> obj, String bagName, Function<T, String> getFileNameFunc, Function<T, String> getFilePathFunc) throws IOException {
        // 设置 ZIP 响应头
        String zipFileName = bagName + ".zip"; //"all_templates.zip"
        response.setContentType("application/zip");
        response.setCharacterEncoding("utf-8");

        String encodedFileName = FileUtils.safeSetFileDownloadHeader(request, zipFileName);
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);

        try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
            for (T item : obj) {
                String excelName = getFileNameFunc.apply(item);
                String filePath = getFilePathFunc.apply(item); // 获取文件路径字段

                if (excelName != null && filePath != null) {
                    File file = new File(filePath);
                    if (file.exists() && file.isFile()) {
                        try (FileInputStream fis = new FileInputStream(file)) {
                            ZipEntry entry = new ZipEntry(excelName);
                            zos.putNextEntry(entry);
                            byte[] buffer = new byte[1024];
                            int len;
                            while ((len = fis.read(buffer)) > 0) {
                                zos.write(buffer, 0, len);
                            }
                            zos.closeEntry();
                        }
                    } else {
                        log.warn("文件不存在: {}", filePath);
                    }
                }
            }
        }
    }

    /**
     * 批量下载Excel文件
     * 邵政文
     * 2025-07-01
     */
    public void downloadTemplates(HttpServletResponse response, List<Class<?>> classes, String zipFileName) throws IOException {
        response.setContentType("application/zip");
        response.setCharacterEncoding("UTF-8");

        // 设置响应头，支持中文文件名下载
        String encodedFileName = URLEncoder.encode(zipFileName + ".zip", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);

        try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
            for (Class<?> clazz : classes) {
                // 使用 ExcelUtil 创建空模板
                ExcelUtil<?> util = new ExcelUtil<>();
                ByteArrayOutputStream bos = util.createEmptyWorkbookWithHeaders(clazz, getSheetNameByClass(clazz));

                // 根据实体类名称确定输出文件名
                String entryName = getSheetNameByClass(clazz) + ".xlsx";
                ZipEntry entry = new ZipEntry(entryName);
                zos.putNextEntry(entry);
                zos.write(bos.toByteArray());
                zos.closeEntry();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据实体类返回对应的Excel表名
     * 邵政文
     * 2025-07-04
     */
    private String getSheetNameByClass(Class<?> clazz) {
        if (clazz.equals(JianDingtable.class)) {
            return "鉴定表";
        } else if (clazz.equals(PingYutable.class)) {
            return "评语表";
        }
        throw new IllegalArgumentException("未知的实体类：" + clazz.getName());
    }

    /**
     * 保存学生信息(鉴定信息)
     * 邵政文
     * 2025-07-01
     */
    public static SrsIdentifytable mapToSrsIdentifytable(SaveStudent saveStudent) {
        SrsIdentifytable srsIdentifytable = new SrsIdentifytable();

        // 普通字段赋值
        srsIdentifytable.setId(saveStudent.getId());
        srsIdentifytable.setStudentName(saveStudent.getStudentName());
        srsIdentifytable.setStudentCode(saveStudent.getStudentCode());
        srsIdentifytable.setStudentCollege(saveStudent.getStudentCollege());
        srsIdentifytable.setStudentGrade(saveStudent.getStudentGrade());
        srsIdentifytable.setStudentClass(saveStudent.getStudentClass());
        srsIdentifytable.setSex(saveStudent.getSex());
        srsIdentifytable.setNation(saveStudent.getNation());
        srsIdentifytable.setBirthData(saveStudent.getBirthData());

        List<GraduateVo> graduateVoList = saveStudent.getGraduateVoList();

        if (graduateVoList != null && !graduateVoList.isEmpty()) {
            if (graduateVoList.size() > 0) {
                srsIdentifytable.setYearOne(mapToAcademicYearInfo(graduateVoList.get(0)));
            }
            if (graduateVoList.size() > 1) {
                srsIdentifytable.setYearTwo(mapToAcademicYearInfo(graduateVoList.get(1)));
            }
            if (graduateVoList.size() > 2) {
                srsIdentifytable.setYearThree(mapToAcademicYearInfo(graduateVoList.get(2)));
            }
        }

        return srsIdentifytable;
    }

    /**
     * 映射AcademicYearInfo
     * 邵政文
     * 2025-07-01
     */
    private static AcademicYearInfo mapToAcademicYearInfo(GraduateVo graduateVo) {
        AcademicYearInfo academicYearInfo = new AcademicYearInfo();
        academicYearInfo.setPolitics(graduateVo.getPolitics());
        academicYearInfo.setMoralCharacter(graduateVo.getMoralCharacter());
        academicYearInfo.setObserveDiscipline(graduateVo.getObserveDiscipline());
        academicYearInfo.setAttitude(graduateVo.getAttitude());
        academicYearInfo.setAttendanceSituation(graduateVo.getAttendanceSituation());
        academicYearInfo.setPositionHeld(graduateVo.getPositionHeld());
        academicYearInfo.setWorkingAttitude(graduateVo.getWorkingAttitude());
        academicYearInfo.setWorkingAbility(graduateVo.getWorkingAbility());
        academicYearInfo.setLdeologicalPolitical(graduateVo.getLdeologicalPolitical());
        academicYearInfo.setScientificQuality(graduateVo.getScientificQuality());
        academicYearInfo.setPhysicalQuality(graduateVo.getPhysicalQuality());
        academicYearInfo.setTotalPoints(graduateVo.getTotalPoints() != null ? graduateVo.getTotalPoints().longValue() : 0L);
        academicYearInfo.setStuYear(graduateVo.getStuYear() != null ? graduateVo.getStuYear().longValue() : 0L);

        return academicYearInfo;
    }

    /**
     * 保存学生信息(评语信息)
     * 邵政文
     * 2025-07-01
     */
    public static SrsGraduateStudent mapToSrsGraduateStudent(SaveStudent saveStudent) {
        SrsGraduateStudent srsGraduateStudent = new SrsGraduateStudent();

        // 普通字段赋值
        srsGraduateStudent.setId(saveStudent.getId());
        srsGraduateStudent.setStudentName(saveStudent.getStudentName());
        srsGraduateStudent.setStudentCode(saveStudent.getStudentCode());

        List<GraduateVo> graduateVoList = saveStudent.getGraduateVoList();

        if (graduateVoList != null && !graduateVoList.isEmpty()) {
            if (graduateVoList.size() > 0) {
                srsGraduateStudent.setYearOne(mapToSrsRemarkData(graduateVoList.get(0)));
            }
            if (graduateVoList.size() > 1) {
                srsGraduateStudent.setYearTwo(mapToSrsRemarkData(graduateVoList.get(1)));
            }
            if (graduateVoList.size() > 2) {
                srsGraduateStudent.setYearThree(mapToSrsRemarkData(graduateVoList.get(2)));
            }
        }

        return srsGraduateStudent;
    }

    /**
     * 映射SrsRemarkData
     * 邵政文
     * 2025-07-01
     */
    private static SrsRemarkData mapToSrsRemarkData(GraduateVo graduateVo) {
        SrsRemarkData srsRemarkData = new SrsRemarkData();
        srsRemarkData.setCounselorComments(graduateVo.getCounselorComments());
        srsRemarkData.setCounselorName(graduateVo.getCounselorName());
        srsRemarkData.setFillData(graduateVo.getFillData());
        srsRemarkData.setCollegeOpinion(graduateVo.getCollegeOpinion());
        srsRemarkData.setStuYear(graduateVo.getStuYear() != null ? graduateVo.getStuYear().longValue() : 0L);
        return srsRemarkData;
    }

}
