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.pojo.EasArcTlsScoresPojo;
import com.koobietech.eas.dao.dto.ArchivesDto;
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.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
    EasArcArchivesMapper arcArchivesMapper;

    @Override
    public int addStudentScore(EasArcTlsScores easArcTlsScores) {
        easArcTlsScores.setCreateTime(new Date());
        easArcTlsScores.setModifyTime(new Date());
        easArcTlsScoresMapper.insert(easArcTlsScores);
        return saveStudentScoreArchive(easArcTlsScores) ? 1: 0;
    }

    private boolean saveStudentScoreArchive(EasArcTlsScores easArcTlsScores){
        EasArcTlsScoresExample easArcTlsScoresExample = new EasArcTlsScoresExample();
        List<EasArcTlsScores> easArcTlsScoresList = easArcTlsScoresMapper.selectByExample(easArcTlsScoresExample);
        ArchivesDto archivesDto = saveEasArcTlsScoresToExcel(easArcTlsScoresList, easArcTlsScores.getStudentNumber());
        EasArcArchives easArcArchives = new EasArcArchives();
        easArcArchives.setStudentNumber(easArcTlsScores.getStudentNumber());
        easArcArchives.setArchiveNumber(archivesDto.getArchiveCode());
        easArcArchives.setFilePath(archivesDto.getPath());
        easArcArchives.setCreateTime(new Date());
        easArcArchives.setCreateUid( SecurityManager.getLoginUid().intValue() );
        easArcArchives.setModifyTime(new Date());
        easArcArchives.setArctype(FileType.XLSX.name());
        easArcArchives.setManagerId( SecurityManager.getLoginUid().intValue() );
        easArcArchives.setValidityTime( new Date(LocalDate.now().plusMonths(20)
                .atStartOfDay().toInstant(ZoneOffset.UTC).toEpochMilli()) );
        int insert = arcArchivesMapper.insert(easArcArchives);
        return insert == 1;
    }

    @Override
    public int updateStudentScore(EasArcTlsScores easArcTlsScores) {
        easArcTlsScoresMapper.updateByPrimaryKey(easArcTlsScores);
        return saveStudentScoreArchive(easArcTlsScores) ? 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 (StringUtils.hasText(easArcTlsScores.getComment())) {
                criteria.andCommentLike("%"+easArcTlsScores.getComment()+"%");
            }
        }
        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);
            }
        } 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;
    }

    /**
     * 将学员考试分数保存为Execl文件
     */
    public ArchivesDto saveEasArcTlsScoresToExcel(List<EasArcTlsScores> easArcTlsScoresList,
                                              String studentNumber) {
        List<EasArcTlsScoresPojo> easArcTlsScoresPojoList = new ArrayList<>();
        for (EasArcTlsScores 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;
    }
}
