package com.sdut.labex.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdut.labex.dto.TimeTable;
import com.sdut.labex.entity.BorrowInfo;
import com.sdut.labex.entity.Room;
import com.sdut.labex.entity.TimeOption;
import com.sdut.labex.mapper.BorrowInfoMapper;
import com.sdut.labex.mapper.RoomMapper;
import com.sdut.labex.mapper.TimeOptionMapper;
import com.sdut.labex.service.TableService;
import com.sdut.labex.utils.ExcelUtils;
import com.sdut.labex.utils.ResVo;
import com.sdut.labex.utils.SFFileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * File: TableServiceImpl
 * Created: 2023/6/15
 * Author: springforest
 * Description:
 */
@Slf4j
@Service
public class TableServiceImpl implements TableService {

    @Resource
    private BorrowInfoMapper borrowInfoMapper;
    @Resource
    private RoomMapper roomMapper;
    @Resource
    private TimeOptionMapper timeOptionMapper;

    @Override
    public ResVo getUnUsedTable(String room, String date) {
        QueryWrapper<BorrowInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("date", date)
                .eq("room_name", room);
        List<BorrowInfo> borrowedList = borrowInfoMapper.selectList(queryWrapper);
        Map<String, List<String>> tempMap = new HashMap<>();
        // 获取所有教室
        List<Room> roomList = roomMapper.selectList(null);
        // 获取所有时间（按顺序）
        List<TimeOption> timeOptionList = timeOptionMapper.selectList(null);

        for (TimeOption time : timeOptionList) {
            List<String> rooms = new ArrayList<>();
            tempMap.put(time.getName(), rooms);
        }

        for (BorrowInfo item : borrowedList) {
            tempMap.get(item.getTime()).add(item.getRoomName());
        }

        Map<String, Object> map = new HashMap<>();
        List<List<String>> res = new ArrayList<>();

        // 获取不在borrowedList中的教室
        for (TimeOption key : timeOptionList) {
            List<String> rooms = new ArrayList<>();
            for (Room item : roomList) {
                if (!tempMap.get(key.getName()).contains(item.getName())) {
                    rooms.add(item.getName());
                }
            }
            res.add(rooms);
        }

        // Remove rooms that are not equal to the provided room when room is not null
        if (room != null && !room.isEmpty()) {
            for (List<String> rooms : res) {
                rooms.removeIf(r -> !r.equals(room));
            }
        }

        map.put("list", res);
        return ResVo.ok(map);
    }


    @Override
    public ResVo uploadTable(MultipartFile file, String startDate, String roomName) {
        try {
            // 使用SFFileUtils类封装文件操作
            SFFileUtils sfFile = new SFFileUtils(file);

            // 使用ExcelUtils类封装Excel操作
            ExcelUtils excel = new ExcelUtils(sfFile.getFile(), sfFile.getEndName());
            if (excel.isEmpty) {
                return ResVo.error("Excel文件为空");
            }

            // 解析文件，将单元格内容解析为List
            // 处理list
            Map<String, Object> map = new HashMap<>();

            // 获取当前日期
            Date today = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

            // 解析开始日期
            Date date;
            SimpleDateFormat formatter;
            try {
                formatter = new SimpleDateFormat("yyyy-MM-dd");
                date = formatter.parse(startDate); // 使用开始日期
            } catch (ParseException e) {
                e.printStackTrace();
                return ResVo.error("开始日期解析失败");
            }

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date); // 设置时间为学期开始日期

            for (int i = 2; i <= 8; i++) { // 列
                int dayFix = i - 2; // 周内日期修正（偏移量）

                for (int j = 2; j <= 6; j++) { // 行
                    calendar.setTime(date); // 每次循环前重置时间为学期开始日期
                    calendar.add(Calendar.DATE, dayFix); // 周内时间偏移

                    String temp = excel.readCell(j, i);
                    if (temp != null) {
                        String[] ttmp = temp.split("/");
                        if (ttmp.length <= 10) {
                            TimeTable timeTable = new TimeTable(temp);
                            map.put("applyUser", timeTable.getApplyUser());
                            map.put("roomName", roomName);
                            map.put("date", dateFormat.format(today));
                            map.put("isAdmit", "1");
                            map.put("applyDate", new Date());
                            calendar.add(Calendar.DATE, 7 * (timeTable.getStartWeek() - 1)); // 设置开始周

                            try {
                                for (int k = timeTable.getStartWeek(); k <= timeTable.getEndWeek(); k++) {
                                    map.put("date", formatter.format(calendar.getTime())); // 日期单独处理
                                    map.put("time", timeTable.getTime()[0]);
                                    // 插入记录
                                    borrowInfoMapper.addTimeTable(map);

                                    map.put("time", timeTable.getTime()[1]);
                                    borrowInfoMapper.addTimeTable(map);

                                    calendar.add(Calendar.DATE, 7); // 增加7天
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                return ResVo.error(String.valueOf(e));
                            }
                        }
                    }
                }
            }
            return ResVo.ok("上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResVo.error("文件读取失败");
        }
    }

    @Override
    public ResVo getUsedTable(String room, String date) {
        QueryWrapper<BorrowInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("date", date)
                .eq("room_name", room);
        List<BorrowInfo> borrowedList = borrowInfoMapper.selectList(queryWrapper);
        Map<String, List<String>> tempMap = new HashMap<>();
        // 获取所有教室
        List<Room> roomList = roomMapper.selectList(null);
        // 获取所有时间（按顺序）
        List<TimeOption> timeOptionList = timeOptionMapper.selectList(null);

        for (TimeOption time : timeOptionList) {
            List<String> rooms = new ArrayList<>();
            tempMap.put(time.getName(), rooms);
        }

        for (BorrowInfo item : borrowedList) {
            tempMap.get(item.getTime()).add(item.getRoomName());
        }

        Map<String, Object> map = new HashMap<>();
        List<List<String>> res = new ArrayList<>();

        // 获取不在borrowedList中的教室
        for (TimeOption key : timeOptionList) {
            List<String> rooms = new ArrayList<>();
            for (Room item : roomList) {
                if (tempMap.get(key.getName()).contains(item.getName())) {
                    rooms.add(item.getName());
                }
            }
            res.add(rooms);
        }

        if (room != null && !room.isEmpty()) {
            for (List<String> rooms : res) {
                rooms.removeIf(r -> !r.equals(room));
            }
        }

        map.put("list", res);
        return ResVo.ok(map);
    }
}
