package com.yida.data.user.listener;

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yida.data.common.core.entity.attendance.EduAttendanceRule;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.school.EduDormitory;
import com.yida.data.common.core.entity.school.EduDormitoryRoom;
import com.yida.data.common.core.entity.user.EduStudent;
import com.yida.data.common.core.vo.ImportPercentVO;
import com.yida.data.school.dto.index.EditPersonNumDTO;
import com.yida.data.school.feign.facility.RemoteDormitoryService;
import com.yida.data.user.dto.ImportStudentTypeDTO;
import com.yida.data.user.dto.ImportStudentTypeDTO;
import com.yida.data.user.mapper.EduStudentMapper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequiredArgsConstructor
public class ImportStudentTypeListener extends AnalysisEventListener<ImportStudentTypeDTO> {

    private final RedisService redisService;
    private final EduStudentMapper eduStudentMapper;

    private final ImportPercentVO res;
    private final Long schoolId;
    private final String key;

    private final static Integer BATCH_COUNT = 100;

    // 最后一行用作保存数据的进度
    private Integer rowNum = -1;
    private List<ImportStudentTypeDTO> list = new ArrayList<>(BATCH_COUNT);

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(ImportStudentTypeDTO data, AnalysisContext context) {
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        list.add(data);
        //if (list.size() >= BATCH_COUNT) {
        //    saveData();
        //    // 存储完成清理 list
        //    list = new ArrayList<>(BATCH_COUNT);
        //}
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        res.setFinish(1);
        redisService.hset(CachePrefixConstant.IMPORT_STUDENT_TYPE, key, res);
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", list.size());
        res.setTotal((long) list.size());
        if (list.size() > 0) {
            // 错误数据
            List<ImportStudentTypeDTO> errorData = new ArrayList<>();
            for (ImportStudentTypeDTO dto : list) {
                // 学生是否存在
                EduStudent student = eduStudentMapper.selectOne(Wrappers.<EduStudent>lambdaQuery()
                    .eq(EduStudent::getStuNumber, dto.getStudentNum())
                    .eq(EduStudent::getSchoolId, schoolId));

                if (student == null) {
                    dto.setError("学生不存在");
                    errorData.add(dto);
                    continue;
                }
                eduStudentMapper.update(null,
                    Wrappers.<EduStudent>lambdaUpdate().eq(EduStudent::getStuNumber, dto.getStudentNum())
                        .set(EduStudent::getType, Integer.valueOf(dto.getType())));

                rowNum++;
                if (rowNum * 100 / res.getTotal() != res.getPercent()) {
                    res.setPercent((int) (rowNum * 100 / res.getTotal()));
                    redisService.hset(CachePrefixConstant.IMPORT_STUDENT_TYPE, key, res);
                }
            }
            // 错误数据
            res.setError(errorData);
        }
    }
}
