package com.koobietech.eas.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.bean.BeanUtil;
import com.koobietech.eas.common.constant.FileType;
import com.koobietech.eas.common.exception.EasException;
import com.koobietech.eas.common.result.PageDataResult;
import com.koobietech.eas.common.utils.SecurityManager;
import com.koobietech.eas.dao.dto.ScoresDto;
import com.koobietech.eas.dao.mapper.ScoresMapper;
import com.koobietech.eas.dao.pojo.EasArcTlsScoresPojo;
import com.koobietech.eas.dao.dto.ArchivesDto;
import com.koobietech.eas.dao.pojo.ScoresPojo;
import com.koobietech.eas.mbg.mapper.EasArcArchivesMapper;
import com.koobietech.eas.mbg.mapper.EasArcTlsScoresMapper;
import com.koobietech.eas.mbg.model.EasArcArchives;
import com.koobietech.eas.mbg.model.EasArcArchivesExample;
import com.koobietech.eas.mbg.model.EasArcTlsScores;
import com.koobietech.eas.mbg.model.EasArcTlsScoresExample;
import com.koobietech.eas.service.EasArcTlsScoresService;
import com.koobietech.eas.service.EasArchivesFilesService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author lc
 */
@Service
public class EasArcTlsScoresServiceImpl implements EasArcTlsScoresService {

    @Resource
    EasArcTlsScoresMapper easArcTlsScoresMapper;

    @Resource
    EasArchivesFilesService easArchivesFilesService;

    @Resource
    ScoresMapper scoresMapper;

    @Resource
    EasArcArchivesMapper arcArchivesMapper;

    final String FILETYPE = "scores";

    @Override
    public int addStudentScore(EasArcTlsScores easArcTlsScores) {
        if ( Objects.nonNull(easArcTlsScores.getId()) &&  easArcTlsScores.getId() > 0  ) {
            return updateStudentScore(easArcTlsScores);
        } else {
            if ( Objects.isNull(easArcTlsScores.getTestDate()) ) {
                easArcTlsScores.setTestDate(new Date());
            }
            easArcTlsScores.setCreateTime(new Date());
            easArcTlsScores.setModifyTime(new Date());
            easArcTlsScores.setCreateUid(SecurityManager.getLoginUid().intValue());
            easArcTlsScoresMapper.insert(easArcTlsScores);
            return saveStudentScoreArchive(easArcTlsScores.getStudentNumber()) ? 1 : 0;
        }
    }

    @Override
    public boolean saveStudentScoreArchive(String studentNumber){
        ScoresDto scoresDto = new ScoresDto();
        scoresDto.setStudentNumber(studentNumber);
        List<ScoresPojo> scoresPojos = scoresMapper.queryStudentScores(scoresDto);
        if ( Objects.isNull(scoresPojos) || scoresPojos.size() == 0 ) {
            return false;
        }

        // 保存到文件
        ArchivesDto archivesDto = saveEasArcTlsScoresToExcel(scoresPojos, studentNumber);

        // 删除文件
        EasArcArchivesExample easArcArchivesExample = new EasArcArchivesExample();
        EasArcArchivesExample.Criteria criteria = easArcArchivesExample.createCriteria();
        criteria.andStudentNumberEqualTo( studentNumber );
        criteria.andFiletypeEqualTo( FILETYPE );
        List<EasArcArchives> easArcArchivesOld = arcArchivesMapper.selectByExample(easArcArchivesExample);
        if ( easArcArchivesOld.size() > 0) {
            for ( EasArcArchives arc : easArcArchivesOld) {
                easArchivesFilesService.deleteArchiveFile(arc.getFilePath());
            }
            arcArchivesMapper.deleteByExample(easArcArchivesExample);
        }

        // 保存到数据库
        EasArcArchives easArcArchives = new EasArcArchives();
        easArcArchives.setStudentNumber(studentNumber);
        easArcArchives.setArchiveNumber(archivesDto.getArchiveCode());
        easArcArchives.setFilePath(archivesDto.getPath());
        easArcArchives.setCreateTime(new Date());
        easArcArchives.setCreateUid( SecurityManager.getLoginUid().intValue() );
        easArcArchives.setModifyTime(new Date());
        easArcArchives.setFiletype(FILETYPE);
        easArcArchives.setArctype(FileType.XLSX.name());
        easArcArchives.setManagerId( SecurityManager.getLoginUid().intValue() );
        easArcArchives.setValidityTime( new Date(LocalDate.now().plusMonths(20)
                .atStartOfDay().toInstant(ZoneOffset.of("+8")).toEpochMilli()) );
        int insert = arcArchivesMapper.insert(easArcArchives);
        return insert == 1;
    }

    @Override
    public int updateStudentScore(EasArcTlsScores easArcTlsScores) {
        easArcTlsScoresMapper.updateByPrimaryKeySelective(easArcTlsScores);
        return saveStudentScoreArchive(easArcTlsScores.getStudentNumber()) ? 1: 0;
    }

    @Override
    public List<EasArcTlsScores> selectAllStudentScores() {
        return easArcTlsScoresMapper.selectByExample(null);
    }

    @Override
    public PageDataResult selectScoreByExample(EasArcTlsScores easArcTlsScores) {
        EasArcTlsScoresExample easArcTlsScoresExample = new EasArcTlsScoresExample();
        EasArcTlsScoresExample.Criteria criteria = easArcTlsScoresExample.createCriteria();
        if (Objects.nonNull(easArcTlsScores)){
            if (Objects.nonNull(easArcTlsScores.getId())) {
                criteria.andIdEqualTo(easArcTlsScores.getId());
            }
            if (StringUtils.hasText(easArcTlsScores.getStudentNumber())) {
                criteria.andStudentNumberLike("%"+easArcTlsScores.getStudentNumber()+"%");
            }
            if (Objects.nonNull(easArcTlsScores.getTestDate())) {
                criteria.andTestDateGreaterThan(easArcTlsScores.getTestDate());
            }
            if (Objects.nonNull(easArcTlsScores.getScore())) {
                criteria.andScoreEqualTo(easArcTlsScores.getScore());
            }
            if (Objects.nonNull(easArcTlsScores.getPassRate())) {
                criteria.andPassRateEqualTo(easArcTlsScores.getPassRate());
            }
            if (Objects.nonNull(easArcTlsScores.getExcelRate())) {
                criteria.andExcelRateEqualTo(easArcTlsScores.getExcelRate());
            }
            if (Objects.nonNull(easArcTlsScores.getCreateTime())) {
                criteria.andCreateTimeGreaterThan(easArcTlsScores.getCreateTime());
            }
            if (Objects.nonNull(easArcTlsScores.getModifyTime())) {
                criteria.andCreateTimeGreaterThan(easArcTlsScores.getModifyTime());
            }
            if (Objects.nonNull(easArcTlsScores.getCreateUid())) {
                criteria.andCreateUidEqualTo(easArcTlsScores.getCreateUid());
            }
            if (Objects.nonNull(easArcTlsScores.getSubjectId()) && easArcTlsScores.getSubjectId() > 0) {
                criteria.andSubjectIdEqualTo(easArcTlsScores.getSubjectId());
            }

        }
        List<EasArcTlsScores> easArcTlsScores1 = easArcTlsScoresMapper.selectByExample(easArcTlsScoresExample);
        long l = easArcTlsScoresMapper.countByExample(easArcTlsScoresExample);
        return PageDataResult.init(easArcTlsScores1,l);
    }

    @Override
    public Boolean importExcelScores(InputStream inputStream) {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        try {
            List<EasArcTlsScoresPojo> score = ExcelImportUtil.importExcel(
                    inputStream, EasArcTlsScoresPojo.class, params);
            EasArcTlsScores easArcTlsScores = null;
            for ( EasArcTlsScoresPojo easArcTlsScoresPojo : score) {
                if ( Objects.isNull(easArcTlsScoresPojo.getStudentNumber())
                        || !StringUtils.hasText(easArcTlsScoresPojo.getStudentNumber()) ) {
                    continue;
                }
                easArcTlsScoresPojo.setCreateTime(new Date());
                easArcTlsScores = new EasArcTlsScores();
                BeanUtil.copyProperties(easArcTlsScoresPojo, easArcTlsScores);
                easArcTlsScoresMapper.insert(easArcTlsScores);
            }
            if ( Objects.nonNull(easArcTlsScores) ) {
                saveStudentScoreArchive(easArcTlsScores.getStudentNumber());
            }
        } catch (FileNotFoundException e) {
            throw new EasException(e.getMessage());
        } catch (Exception e) {
            throw new EasException(e.getMessage());
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e) {}
        }
        return true;
    }

    @Override
    public PageDataResult queryStudentScores(ScoresDto scoresDto) {
        List<ScoresPojo> scoresPojos = scoresMapper.queryStudentScores(scoresDto);
        Integer total = scoresMapper.queryStudentScoresCount(scoresDto);
        return PageDataResult.init(scoresPojos, total);
    }

    /**
     * 将学员考试分数保存为Execl文件
     */
    public ArchivesDto saveEasArcTlsScoresToExcel(List<ScoresPojo> easArcTlsScoresList,
                                              String studentNumber) {
        List<EasArcTlsScoresPojo> easArcTlsScoresPojoList = new ArrayList<>();
        for (ScoresPojo easArcTlsScores: easArcTlsScoresList) {
            EasArcTlsScoresPojo easArcTlsScoresPojo = new EasArcTlsScoresPojo();
            BeanUtil.copyProperties(easArcTlsScores, easArcTlsScoresPojo);
            easArcTlsScoresPojoList.add(easArcTlsScoresPojo);
        }
        ExportParams params   = new ExportParams("考试成绩表", "考试成绩");
        Workbook workbook = ExcelExportUtil.exportExcel(params,
                EasArcTlsScoresPojo.class, easArcTlsScoresPojoList);
        ArchivesDto archivesDto = easArchivesFilesService.saveArchiveFile(studentNumber, workbook);
        return archivesDto;
    }
}
