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.result.PageDataResult;
import com.koobietech.eas.common.utils.SecurityManager;
import com.koobietech.eas.dao.dto.ArchivesDto;
import com.koobietech.eas.dao.dto.AttendanceDto;
import com.koobietech.eas.dao.mapper.AttendanceMapper;
import com.koobietech.eas.dao.pojo.AttendancePojo;
import com.koobietech.eas.dao.pojo.EasArcTlsAttendancePojo;
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.*;

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

    @Resource
    private EasArcTlsAttendanceMapper easArcTlsAttendanceMapper;

    final String FILETYPE = "attendance";

    @Resource
    private EasEduScheduleMapper easEduScheduleMapper;

    @Resource
    EasArchivesFilesService easArchivesFilesService;

    @Resource
    EasArcArchivesMapper arcArchivesMapper;

    @Resource
    EasEduCategoryMapper  easEduCategoryMapper;

    @Resource
    EasEduSubjectsMapper easEduSubjectsMapper;

    @Resource
    AttendanceMapper attendanceMapper;

    @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());
        attendance.setCreateUid( SecurityManager.getLoginUid().intValue() );
        int insert = easArcTlsAttendanceMapper.insert(attendance);
        saveStudentAttendanceArchive(attendance.getStudentNumber());
        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) {
        int i;
        //有则更新 没有则添加
        Calendar calender = Calendar.getInstance();
        calender.setTime(new Date());
        attendance.setMonth( calender.get(Calendar.MONTH) + 1);
        EasArcTlsAttendanceExample easArcTlsAttendanceExample = new EasArcTlsAttendanceExample();
        EasArcTlsAttendanceExample.Criteria criteria = easArcTlsAttendanceExample.createCriteria();
        criteria.andStudentNumberEqualTo(attendance.getStudentNumber());
        criteria.andScheduleIdEqualTo(attendance.getScheduleId());
        long l = easArcTlsAttendanceMapper.countByExample(easArcTlsAttendanceExample);
        if ( Objects.isNull(attendance.getModifyTime()) ) {
            attendance.setModifyTime(new Date());
        }
        if ( Objects.isNull(attendance.getCreateTime()) ) {
            attendance.setCreateTime(new Date());
        }
        if ( Objects.isNull(attendance.getCreateUid()) ) {
            attendance.setCreateUid(SecurityManager.getLoginUid().intValue());
        }
        if ( l > 0 ) {
            //修改的清空下 不允许修改更多信息
            EasArcTlsAttendance easArcTlsAttendance = new EasArcTlsAttendance();
            easArcTlsAttendance.setModifyTime(new Date());
            easArcTlsAttendance.setCreateTime(attendance.getCreateTime());
            easArcTlsAttendance.setAfternoon(attendance.getAfternoon());
            easArcTlsAttendance.setMorning(attendance.getMorning());
            i = easArcTlsAttendanceMapper.updateByExampleSelective(easArcTlsAttendance, easArcTlsAttendanceExample);
        } else {
            i = easArcTlsAttendanceMapper.insert(attendance);
        }
        saveStudentAttendanceArchive(attendance.getStudentNumber());
        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<AttendancePojo> getStudentList(AttendanceDto dto) {
        List<AttendancePojo> attendancePojos = attendanceMapper.queryAttendance(dto);
        return attendancePojos;
    }

    @Override
    public PageDataResult queryAttendance(AttendanceDto dto) {
        List<AttendancePojo> attendancePojos = attendanceMapper.queryAttendance(dto);
        Long aLong = attendanceMapper.queryAttendanceCount(dto);
        return PageDataResult.init(attendancePojos, aLong);
    }

    @Override
    public boolean saveStudentAttendanceArchive(String studentNumber){

        EasArcTlsAttendanceExample easArcTlsAttendanceExample = new EasArcTlsAttendanceExample();
        EasArcTlsAttendanceExample.Criteria criteria = easArcTlsAttendanceExample.createCriteria();
        criteria.andStudentNumberEqualTo(studentNumber);
        List<EasArcTlsAttendance> easArcTlsAttendances = easArcTlsAttendanceMapper.selectByExample(easArcTlsAttendanceExample);

        //保存文件
        ArchivesDto archivesDto = saveEasArcTlsAttendanceToExcel(easArcTlsAttendances, studentNumber);

        //删除文件
        EasArcArchivesExample easArcArchivesExample = new EasArcArchivesExample();
        EasArcArchivesExample.Criteria criteriaDel = easArcArchivesExample.createCriteria();
        criteriaDel.andStudentNumberEqualTo( studentNumber );
        criteriaDel.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;
    }

    private ArchivesDto saveEasArcTlsAttendanceToExcel(List<EasArcTlsAttendance> easArcTlsAttendances, String studentNumber) {

        List<EasArcTlsAttendancePojo> arcTlsAttendanceList = new ArrayList<>();
        for (EasArcTlsAttendance tlsAttendance: easArcTlsAttendances) {
            EasEduSchedule easEduSchedule = easEduScheduleMapper.selectByPrimaryKey(tlsAttendance.getScheduleId().longValue());
            EasEduCategory easEduCategory = easEduCategoryMapper.selectByPrimaryKey(easEduSchedule.getCategoryId());
            EasEduSubjects easEduSubjects = easEduSubjectsMapper.selectByPrimaryKey(easEduSchedule.getSubjectsId());
            EasArcTlsAttendancePojo easArcTlsAttendancePojo = new EasArcTlsAttendancePojo();
            BeanUtil.copyProperties(tlsAttendance, easArcTlsAttendancePojo);
            easArcTlsAttendancePojo.setSubject(easEduSubjects.getName());
            easArcTlsAttendancePojo.setCategory(easEduCategory.getName());
            arcTlsAttendanceList.add(easArcTlsAttendancePojo);
        }
        ExportParams params = new ExportParams("学员签到表", "签到");
        params.setHeaderHeight(30);
        Workbook workbook = ExcelExportUtil.exportExcel(params,
                EasArcTlsAttendancePojo.class, arcTlsAttendanceList);
        return easArchivesFilesService.saveArchiveFile(studentNumber, workbook);
    }

}




