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.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.ImportStudentDormDTO;
import com.yida.data.user.mapper.EduStudentMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
public class ImportStudentDormListener extends AnalysisEventListener<ImportStudentDormDTO> {
    private final RedisService redisService;
    private final EduStudentMapper eduStudentMapper;
    private final RemoteDormitoryService remoteDormitoryService;

    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<ImportStudentDormDTO> list = new ArrayList<>(BATCH_COUNT);

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(ImportStudentDormDTO 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_DORM, key, res);
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", list.size());
        res.setTotal((long) list.size());
        if (list.size() > 0) {
            // 宿舍与寝室的本地缓存
            Map<String, EduDormitory> dormMap = new HashMap<>();
            Map<String, EduDormitoryRoom> dormRoomMap = new HashMap<>();
            Map<Long, EduDormitoryRoom> dormRoomIdMap = new HashMap<>();
            // 学生id与导入数据行的对应关系
            Map<Long, ImportStudentDormDTO> studentIdMap = new HashMap<>();
            // 错误数据
            List<ImportStudentDormDTO> errorData = new ArrayList<>();
            // 要保存的学生
            List<EduStudent> saveStudent = new ArrayList<>();
            // 学号是否重复
            Map<String, List<ImportStudentDormDTO>> stuNumGroup = list.stream().collect(Collectors.groupingBy(ImportStudentDormDTO::getStudentNum));
            for (Map.Entry<String, List<ImportStudentDormDTO>> entry : stuNumGroup.entrySet()) {
                if (entry.getValue().size() > 1) {
                    errorData.addAll(entry.getValue().stream().map(x -> {
                        x.setError("学号重复");
                        return x;
                    }).collect(Collectors.toList()));
                }
            }
            for (ImportStudentDormDTO dto : list) {
                // 学生是否存在
                EduStudent student = eduStudentMapper.selectOne(Wrappers.<EduStudent>lambdaQuery()
                        .eq(EduStudent::getStuNumber, dto.getStudentNum())
                        .eq(EduStudent::getSchoolId, schoolId)
                        .eq(EduStudent::getType, 1));
                if (student == null) {
                    dto.setError("学生不存在");
                    errorData.add(dto);
                    continue;
                }
                // 学生已绑定寝室
                if (student.getDormId() != null || student.getDormRoomId() != null) {
                    dto.setError("学生已绑定宿舍");
                    errorData.add(dto);
                    continue;
                }
                // 宿舍楼是否存在
                EduDormitory dorm = dormMap.containsKey(dto.getDormName())
                        ? dormMap.get(dto.getDormName())
                        : remoteDormitoryService.getDormByName(dto.getDormName(),
                        schoolId).getData();
                if (dorm == null) {
                    dto.setError("宿舍不存在");
                    errorData.add(dto);
                    continue;
                }
                dormMap.put(dorm.getName(), dorm);
                // 寝室是否存在
                EduDormitoryRoom dormRoom = dormRoomMap.containsKey(dto.getDormName() + ":" + dto.getDormRoomName())
                        ? dormRoomMap.get(dto.getDormName() + ":" + dto.getDormRoomName())
                        : remoteDormitoryService.getDormRoomByNameAndDorm(dto.getDormRoomName(), dorm.getId()).getData();
                if (dormRoom == null) {
                    dto.setError("寝室号不存在");
                    errorData.add(dto);
                    continue;
                }
                dormRoomMap.put(dto.getDormName() + ":" + dto.getDormRoomName(), dormRoom);
                dormRoomIdMap.put(dormRoom.getId(), dormRoom);
                student.setDormId(dorm.getId());
                student.setDormRoomId(dormRoom.getId());
                saveStudent.add(student);
                studentIdMap.put(student.getId(), dto);
                rowNum++;
                if (rowNum * 100 / res.getTotal() != res.getPercent()) {
                    res.setPercent((int) (rowNum * 100 / res.getTotal()));
                    redisService.hset(CachePrefixConstant.IMPORT_STUDENT_DORM, key, res);
                }
            }
            // 更新学生数据
            if (CollUtil.isNotEmpty(saveStudent)) {
                Map<Long, List<EduStudent>> map = saveStudent.stream().collect(Collectors.groupingBy(EduStudent::getDormRoomId));
                List<EditPersonNumDTO> editDTO = new ArrayList<>();
                List<EduStudent> realSaveStudent = new ArrayList<>();
                for (Map.Entry<Long, List<EduStudent>> entry : map.entrySet()) {
                    EduDormitoryRoom dormRoom = dormRoomIdMap.get(entry.getKey());
                    // 是否超出寝室容量
                    if (dormRoom.getBedNum() - dormRoom.getCheckInNum() < entry.getValue().size()) {
                        for (EduStudent student : entry.getValue()) {
                            ImportStudentDormDTO errorDTO = studentIdMap.get(student.getId());
                            errorDTO.setError("寝室入住人员达到上限");
                            errorData.add(errorDTO);
                        }
                    } else {
                        // 将要更改的寝室
                        EditPersonNumDTO dto = new EditPersonNumDTO();
                        dto.setNum(entry.getValue().size());
                        dto.setDormRoomId(entry.getKey());
                        editDTO.add(dto);
                        // 最终要保存的数据
                        realSaveStudent.addAll(entry.getValue());
                    }
                }
                if (CollUtil.isNotEmpty(realSaveStudent)) {
                    for (EduStudent student : realSaveStudent) {
                        eduStudentMapper.updateById(student);
                    }
                    remoteDormitoryService.editPersonNum(editDTO);
                    rowNum++;
                    if (rowNum * 100 / res.getTotal() != res.getPercent()) {
                        res.setPercent((int) (rowNum * 100 / res.getTotal()));
                        redisService.hset(CachePrefixConstant.IMPORT_STUDENT_DORM, key, res);
                    }
                }
            }
            // 错误数据
            res.setError(errorData);
        }
        log.info("存储数据库成功！");
    }
}
