package com.yida.data.school.facility.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.vo.ImportPercentVO;
import com.yida.data.school.dto.index.ImportDormRoomDTO;
import com.yida.data.school.facility.mapper.EduDormitoryMapper;
import com.yida.data.school.facility.service.EduDormitoryRoomService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequiredArgsConstructor
public class ImportDormRoomListener extends AnalysisEventListener<ImportDormRoomDTO> {

    private final RedisService redisService;
    private final EduDormitoryMapper eduDormitoryMapper;
    private final EduDormitoryRoomService eduDormitoryRoomService;

    private final ImportPercentVO<ImportDormRoomDTO> res;
    private final Long dormId;
    private final Long schoolId;
    private final String key;

    private final static Integer BATCH_COUNT = 100;

    private Integer rowNum = 0;
    private Map<Long, EduDormitory> dormCache = new HashMap<>();
    private List<ImportDormRoomDTO> list = new ArrayList<>(BATCH_COUNT);

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

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", list.size());
        if (list.size() > 0) {
            List<EduDormitoryRoom> roomList = new ArrayList<>();
            EduDormitory dorm = eduDormitoryMapper.selectById(dormId);
            for (ImportDormRoomDTO dto : list) {
                rowNum++;
                if (dorm == null) {
                    dto.setError("宿舍楼不存在");
                    res.getError().add(dto);
                    continue;
                }
                if (!dorm.getName().equals(dto.getDormName())) {
                    dto.setError("宿舍楼名称不匹配");
                    res.getError().add(dto);
                    continue;
                }
                EduDormitoryRoom exist = eduDormitoryRoomService
                    .getOne(Wrappers.<EduDormitoryRoom>lambdaQuery().eq(EduDormitoryRoom::getDormId, dorm.getId())
                        .eq(EduDormitoryRoom::getName, dto.getDormRoomName()));
                // 该寝室号已存在 且入住人数大于新的床数  则不可导入
                if (exist != null && exist.getCheckInNum() > dto.getBedNum()) {
                    dto.setError("寝室已存在且已入住人数大于新的床位数");
                    res.getError().add(dto);
                    continue;
                }
                if (dto.getFloor() > dorm.getFloorNum()) {
                    dto.setError("寝室楼层不存在");
                    res.getError().add(dto);
                    continue;
                }
                EduDormitoryRoom room = new EduDormitoryRoom();
                room.setBedNum(dto.getBedNum());
                room.setFloor(dto.getFloor());
                room.setName(dto.getDormRoomName());
                room.setDormId(dorm.getId());
                if (exist != null) {
                    room.setId(exist.getId());
                }
                roomList.add(room);
                if (rowNum * 100 / res.getTotal() != res.getPercent()) {
                    res.setPercent((int) (rowNum * 100 / res.getTotal()));
                    redisService.hset(CachePrefixConstant.IMPORT_DORM_ROOM, key, res);
                }
            }
            if (CollUtil.isNotEmpty(roomList)) {
                eduDormitoryRoomService.saveOrUpdateBatch(roomList);
            }
        }
        log.info("存储数据库成功！");
    }
}
