package com.koobietech.eas.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
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.EasArcTlsAttendancePojo;
import com.koobietech.eas.dao.pojo.EasArcTlsScoresPojo;
import com.koobietech.eas.dao.dto.ArchivesDto;
import com.koobietech.eas.mbg.mapper.*;
import com.koobietech.eas.mbg.model.*;
import com.koobietech.eas.service.EasArcTlsAttendanceService;
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.time.LocalDate;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lc
 */
@Service
public class EasArcTlsAttendanceServiceImpl implements EasArcTlsAttendanceService {

    @Resource
    private EasArcTlsAttendanceMapper easArcTlsAttendanceMapper;

    @Resource
    private EasEduCltRelationMapper easEduCltRelationMapper;

    @Resource
    private EasSysStudentMapper easSysStudentMapper;

    @Resource
    private EasEduScheduleMapper easEduScheduleMapper;

    @Resource
    EasArchivesFilesService easArchivesFilesService;

    @Resource
    EasArcArchivesMapper arcArchivesMapper;

    @Override
    public PageDataResult query(EasArcTlsAttendance attendance) {
        EasArcTlsAttendanceExample easArcTlsAttendanceExample = new EasArcTlsAttendanceExample();
        EasArcTlsAttendanceExample.Criteria criteria = easArcTlsAttendanceExample.createCriteria();
        if (Objects.nonNull(attendance)) {

            if (Objects.nonNull(attendance.getId()) && attendance.getId() != 0) {
                criteria.andIdEqualTo(attendance.getId());
            }
            if (Objects.nonNull(attendance.getCheckinDate())) {
                criteria.andCheckinDateEqualTo(attendance.getCheckinDate());
            }
            if (Objects.nonNull(attendance.getScheduleId()) && attendance.getScheduleId() != 0) {
                criteria.andScheduleIdEqualTo(attendance.getScheduleId());
            }
            if (Objects.nonNull(attendance.getMonth()) && attendance.getMonth() != 0) {
                criteria.andMonthEqualTo(attendance.getMonth());
            }
            if (StringUtils.hasText(attendance.getMorning())) {
                criteria.andMorningEqualTo(attendance.getMorning());
            }
            if (StringUtils.hasText(attendance.getAfternoon())) {
                criteria.andAfternoonEqualTo(attendance.getAfternoon());
            }
            if (StringUtils.hasText(attendance.getStudentNumber())) {
                criteria.andStudentNumberLike("%" + attendance.getStudentNumber() + "%");
            }
            if (Objects.nonNull(attendance.getCreateUid()) && attendance.getCreateUid() != 0) {
                criteria.andCreateUidEqualTo(attendance.getCreateUid());
            }
            if (Objects.nonNull(attendance.getCreateTime())) {
                criteria.andCreateTimeEqualTo(attendance.getCreateTime());
            }
            if (Objects.nonNull(attendance.getModifyTime())) {
                criteria.andModifyTimeEqualTo(attendance.getModifyTime());
            }
        }

        List<EasArcTlsAttendance> easArcTlsAttendances =
                easArcTlsAttendanceMapper.selectByExample(easArcTlsAttendanceExample);
        long l = easArcTlsAttendanceMapper.countByExample(easArcTlsAttendanceExample);
        PageDataResult ret = new PageDataResult();
        ret.setData(easArcTlsAttendances);
        ret.setTotal(l);
        return ret;

    }

    @Override
    public Boolean add(EasArcTlsAttendance attendance) {
        //签到日期前端会自己传 所以就不需要再写一次了
        attendance.setCreateTime(new Date());
        attendance.setModifyTime(new Date());
        int insert = easArcTlsAttendanceMapper.insert(attendance);
        saveStudentAttendanceArchive(attendance);
        return insert == 1;
    }

    @Override
    public Boolean delete(EasArcTlsAttendance attendance) {
        //虽然接收的是对象，但是后端是根据checkin_date和student_number来删除的
        EasArcTlsAttendanceExample easArcTlsAttendanceExample = new EasArcTlsAttendanceExample();
        EasArcTlsAttendanceExample.Criteria criteria = easArcTlsAttendanceExample.createCriteria();
        if (Objects.nonNull(attendance)) {
            if (Objects.nonNull(attendance.getCheckinDate())
                    && StringUtils.hasText(attendance.getStudentNumber())) {
                criteria.andCheckinDateEqualTo(attendance.getCheckinDate());
                criteria.andStudentNumberEqualTo(attendance.getStudentNumber());
                return easArcTlsAttendanceMapper.deleteByExample(easArcTlsAttendanceExample) == 1;
            }
        }
        return false;
    }

    @Override
    public Boolean update(EasArcTlsAttendance attendance) {
        attendance.setModifyTime(new Date());
        int i = easArcTlsAttendanceMapper.updateByPrimaryKey(attendance);
        saveStudentAttendanceArchive(attendance);
        return i == 1;
    }

    @Override
    public boolean isExist(EasArcTlsAttendance attendance) {
        EasArcTlsAttendanceExample easArcTlsAttendanceExample = new EasArcTlsAttendanceExample();
        EasArcTlsAttendanceExample.Criteria criteria = easArcTlsAttendanceExample.createCriteria();
        if (Objects.nonNull(attendance)) {
            if (Objects.nonNull(attendance.getCheckinDate())
                    && StringUtils.hasText(attendance.getStudentNumber())) {
                criteria.andCheckinDateEqualTo(attendance.getCheckinDate());
                criteria.andStudentNumberEqualTo(attendance.getStudentNumber());
                return easArcTlsAttendanceMapper.countByExample(easArcTlsAttendanceExample) == 1;
            }
        }
        return false;
    }

    @Override
    public List<EasArcTlsAttendance> getStudentList(Long scheduleId) {
        // 根据课表ID查找EasEduSchedule表，获取班级ID
        EasEduSchedule easEduSchedule = easEduScheduleMapper.selectByPrimaryKey(scheduleId);
        Long classId = Optional.ofNullable(easEduSchedule)
                .map(s -> Long.valueOf(s.getClassId()))
                .orElseThrow(() -> new EasException("未查询到对应课表，请检查数据库", 9595));

        // 根据班级ID查找EasEduCltRelation表，获取学生ID列表
        EasEduCltRelationExample easEduCltRelationExample = new EasEduCltRelationExample();
        easEduCltRelationExample.createCriteria().andClassIdEqualTo(classId);

        // 查询EasEduCltRelation表，获取符合条件的学生ID列表
        List<Long> studentIds = easEduCltRelationMapper.selectByExample(easEduCltRelationExample)
                .stream()
                .map(r -> Long.valueOf(r.getStudentId()))
                .collect(Collectors.toList());

        // 根据学生ID列表查询EasSysStudent表，获取学生信息
        EasSysStudentExample easSysStudentExample = new EasSysStudentExample();
        easSysStudentExample.createCriteria().andIdIn(studentIds);
        List<EasSysStudent> easSysStudents = easSysStudentMapper.selectByExample(easSysStudentExample);

        // 封装查询结果到PageData对象并返回
        return easSysStudents.stream()
                .map(s -> {
                    EasArcTlsAttendance easArcTlsAttendance = new EasArcTlsAttendance();
                    easArcTlsAttendance.setStudentNumber(s.getStudentNumber());
                    easArcTlsAttendance.setStudentName(s.getStudentName());
                    return easArcTlsAttendance;
                })
                .collect(Collectors.toList());
    }

    public boolean saveStudentAttendanceArchive(EasArcTlsAttendance attendance){
        EasArcTlsAttendanceExample easArcTlsAttendanceExample = new EasArcTlsAttendanceExample();
        EasArcTlsAttendanceExample.Criteria criteria = easArcTlsAttendanceExample.createCriteria();
        criteria.andStudentNumberEqualTo(attendance.getStudentNumber());
        //criteria.andScheduleIdEqualTo(attendance.getScheduleId());
        List<EasArcTlsAttendance> easArcTlsAttendances = easArcTlsAttendanceMapper.selectByExample(easArcTlsAttendanceExample);
        ArchivesDto archivesDto = saveEasArcTlsAttendanceToExcel(easArcTlsAttendances, attendance.getStudentNumber());
        EasArcArchives easArcArchives = new EasArcArchives();
        easArcArchives.setStudentNumber(attendance.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;
    }

    private ArchivesDto saveEasArcTlsAttendanceToExcel(List<EasArcTlsAttendance> easArcTlsAttendances, String studentNumber) {
        List<EasArcTlsAttendancePojo> arcTlsAttendanceList = new ArrayList<>();
        for (EasArcTlsAttendance tlsAttendance: easArcTlsAttendances) {
            EasArcTlsAttendancePojo easArcTlsAttendancePojo = new EasArcTlsAttendancePojo();
            BeanUtil.copyProperties(tlsAttendance, easArcTlsAttendancePojo);
            arcTlsAttendanceList.add(easArcTlsAttendancePojo);
        }
        ExportParams params   = new ExportParams("学员签到表", "签到");
        Workbook workbook = ExcelExportUtil.exportExcel(params,
                EasArcTlsScoresPojo.class, arcTlsAttendanceList);
        ArchivesDto archivesDto = easArchivesFilesService.saveArchiveFile(studentNumber, workbook);
        return archivesDto;
    }

}




