package com.koobietech.eas.service.impl;

import com.koobietech.eas.common.constant.FileType;
import com.koobietech.eas.common.result.PageDataResult;
import com.koobietech.eas.common.utils.ArchiveManager;
import com.koobietech.eas.common.utils.FileManager;
import com.koobietech.eas.dao.dto.ArchivesDto;
import com.koobietech.eas.mbg.mapper.EasArcTlsStudentsMapper;
import com.koobietech.eas.mbg.model.EasArcTlsStudents;
import com.koobietech.eas.mbg.model.EasArcTlsStudentsExample;
import com.koobietech.eas.mbg.model.EasSysStudent;
import com.koobietech.eas.service.EasArcTlsAttendanceService;
import com.koobietech.eas.service.EasArcTlsScoresService;
import com.koobietech.eas.service.EasArchivesFilesService;
import com.koobietech.eas.service.EasStuProfileService;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;

/**
 * @author lc
 */
@Service
public class EasArchivesFilesServiceImpl implements EasArchivesFilesService {

    @Value("${project.cache.path}")
    String archivesSaveCachePath;

    @Value("${project.path}")
    String archivesSavePath;

    final String BAKUP_SUFFIX =  ".bak";

    @Resource
    FileManager fileManager;

    @Resource
    EasArcTlsStudentsMapper arcTlsStudentsMapper;

    @Resource
    EasStuProfileService  easStuProfileService;

    @Resource
    EasArcTlsScoresService easArcTlsScoresService;

    @Resource
    EasArcTlsAttendanceService easArcTlsAttendanceService;

    String separator = File.separator;

    @Override
    /**
     * 保存考勤信息
     */
    public ArchivesDto saveArchiveAttendanceFile(String studentNumber, XWPFDocument document) {
        return saveArchiveDocumentFile(studentNumber, document, FileType.XLSX.name());
    }

    @Override
    /**
     * 保存考核信息
     */
    public ArchivesDto saveArchiveScoresFile(String studentNumber, XWPFDocument document) {
        return saveArchiveDocumentFile(studentNumber, document, FileType.XLSX.name());
    }

    @Override
    /**
     * 保存基本资料
     */
    public ArchivesDto saveArchiveStudentsFile(String studentNumber, XWPFDocument document) {
        return saveArchiveDocumentFile(studentNumber, document, FileType.DOCX.name());
    }

    @Override
    /**
     * 保存其他文档
     */
    public ArchivesDto saveArchiveFile(String studentNumber, Workbook workbook) {
        return saveArchiveWorkbookFile(studentNumber, workbook, FileType.XLSX.name());
    }

    @Override
    /**
     * 保存凄其他资料
     */
    public String getArchiveSavePath(String studentNumber, String archiveCode, String type) {
        return getArchivePath(studentNumber, archiveCode, FileType.valueOf(type).getSuffix(), "other");
    }

    @Override
    /**
     * 保存凄其他资料
     */
    public ArchivesDto saveArchiveFile(String studentNumber, InputStream stream, String type) {
        String archiveCode = getArchiveCode(studentNumber, String.valueOf(FileType.valueOf(type).getValue()));
        String path = getArchivePath(studentNumber, archiveCode, FileType.valueOf(type).getSuffix(), "other");
        boolean status = fileManager.saveFile(stream, path);
        return new ArchivesDto(path, status, archiveCode, type);
    }

    @Override
    /**
     * 保存凄其他资料
     */
    public ArchivesDto saveArchiveFileTemp(String studentNumber, InputStream stream, String type) {
        String archiveCode = getArchiveCode(studentNumber, String.valueOf(FileType.valueOf(type).getValue()));
        String path = getArchivePathTemp(studentNumber,  archiveCode, FileType.valueOf(type).getSuffix());
        boolean status = fileManager.saveFile(stream, path);
        return new ArchivesDto(path, status, archiveCode, type);
    }


    @Override
    /**
     * 删除文件
     */
    public boolean deleteArchiveFile(String filePath) {
        return fileManager.deleteFile(filePath);
    }

    @Override
    /**
     * 获取文件1
     */
    public FileInputStream getArchiveFile(String filePath) {
        return fileManager.getArchiveFile(filePath);
    }

    @Override
    /**
     * 获取文件2
     */
    public InputStream getResourceStream(String filePath) {
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(filePath);
        } catch (Exception e) {
        }
        return resourceAsStream;
    }

    @Override
    /**
     * 获取学员档案数据
     */
    public EasArcTlsStudents getArchiveStudentsFile(String studentNumber) {
        EasArcTlsStudentsExample easArcTlsStudentsExample = new EasArcTlsStudentsExample();
        easArcTlsStudentsExample.createCriteria().andStudentNumberEqualTo(studentNumber);
        List<EasArcTlsStudents> easArcTlsStudents = arcTlsStudentsMapper.selectByExample(easArcTlsStudentsExample);
        return easArcTlsStudents.stream().findFirst().orElse(null);
    }

    @Override
    /**
     * 备份数据
     */
    public boolean backupArchiveFile(String filePath) {
        boolean ret = false;
        if (filePath == null || filePath.isEmpty()) {
            return ret;
        }
        if ( fileManager.isFileExists(filePath) ) {
            long time = System.currentTimeMillis();
            ret = fileManager.moveFile(filePath, filePath + time + BAKUP_SUFFIX, true);
        }
        return ret;
    }

    /**
     * 刷新档案
     */

    @Override
    public boolean refreshProfile(String studentNumber) {

        /**
         * 查询所有学员
         */
        List<EasSysStudent> all = easStuProfileService.getAllOrStudentNumber(studentNumber);

        /**
         * 查询学员考核
         */
        for (EasSysStudent student : all) {
            easArcTlsScoresService.saveStudentScoreArchive(student.getStudentNumber());
        }

        /**
         * 查询学员考勤
         */
        for (EasSysStudent student : all) {
            easArcTlsAttendanceService.saveStudentAttendanceArchive(student.getStudentNumber());
        }
        /**
         * 查询学员基本信息
         */
        for (EasSysStudent student : all) {
            EasArcTlsStudents easArcTlsStudents = new EasArcTlsStudents();
            easArcTlsStudents.setStudentNumber(student.getStudentNumber());
            PageDataResult query = easStuProfileService.query(easArcTlsStudents);
            if ( query.getTotal() > 0 ) {
                EasArcTlsStudents arcStudent = (EasArcTlsStudents) query.getData()
                        .stream().findFirst().orElse(null);
                if (Objects.nonNull(arcStudent)) {
                    easStuProfileService.saveUserFile( arcStudent, student.getAvatar() );
                }
            }
        }
        return true;
    }

    @Override
    public String createZipArchives(String studentNumber) {
        String path = archivesSavePath + separator + studentNumber;
        String tempPath = archivesSavePath + separator + "zip" ;
        fileManager.createPath(tempPath);
        fileManager.createPath(path);
        String userArchivePath = tempPath + separator + studentNumber + ".zip";
        boolean zipFile = fileManager.createZipFile(userArchivePath, path);
        if ( zipFile ) {
            return userArchivePath;
        }
        return null;
    }

    private ArchivesDto saveArchiveDocumentFile(String studentNumber, XWPFDocument document, String type) {
        String archiveCode = ArchiveManager.generateArchiveCode(studentNumber, String.valueOf(FileType.valueOf(type).getValue()));
        String path = getArchivePath(studentNumber, archiveCode, FileType.valueOf(type).getSuffix());
        boolean status = fileManager.saveDocument(document, path);
        return new ArchivesDto(path, status, archiveCode, type);
    }

    private ArchivesDto saveArchiveWorkbookFile(String studentNumber, Workbook workbook, String type) {
        String archiveCode = ArchiveManager.generateArchiveCode(studentNumber, String.valueOf(FileType.valueOf(type).getValue()));
        String path = getArchivePath(studentNumber, archiveCode, FileType.valueOf(type).getSuffix());
        boolean status = fileManager.saveWorkbook(workbook, path);
        return new ArchivesDto(path, status, archiveCode, type);
    }

    private String getArchiveCode(String studentNumber, String fileCode) {
        return ArchiveManager.generateArchiveCode(studentNumber, fileCode);
    }

    private String getArchivePathTemp(String studentNumber, String archiveCode, String suffix){
        String path = archivesSaveCachePath + separator + studentNumber;
        fileManager.createPath(path);
        return path + separator + archiveCode + suffix;
    }

    private String getArchivePath(String studentNumber, String archiveCode, String suffix) {
        return getArchivePath(studentNumber,  archiveCode, suffix, null);
    }

    private String getArchivePath(String studentNumber, String archiveCode, String suffix, String level) {
        String path = archivesSavePath + separator + studentNumber;
        if ( Objects.nonNull(level) ) {
            path = path + separator + level;
        }
        fileManager.createPath(path);
        return path + separator + archiveCode + suffix;
    }

}
