package com.ics.controller.mobile.meeting;

import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ics.common.core.controller.BaseController;
import com.ics.admin.service.meeting.IReservationService;
import com.ics.common.core.domain.R;
import com.ics.admin.domain.meeting.Reservation;
import com.ics.admin.domain.meeting.RoomContent;
import com.ics.admin.service.IRoomService;
import com.ics.admin.service.meeting.IRoomContentService;
import com.ics.admin.domain.Room;
import org.wf.jwtp.annotation.Ignore;
import org.wf.jwtp.annotation.RequiresPermissions;

/**
 * 预约记录 提供者
 *
 * @author chen
 * @date 2024-02-25
 */
@Slf4j
@RestController
@RequestMapping("/api/reservation")
public class ApiReservationController extends BaseController {

    @Autowired
    private IReservationService reservationService;
    
    @Autowired
    private IRoomContentService roomContentService;
    
    @Autowired
    private IRoomService roomService;

    /**
     * 获取今日会议室预约数据
     * 
     * @return 会议室预约数据
     */
    @RequiresPermissions("member:center:view")
    @GetMapping("/today")
    public R getTodayReservations() {
        try {

            // 获取当前用户ID
            Long currentUserId = getCurrentUserId();
            System.out.println();
            // 获取今日预约列表
            List<Reservation> todayReservations = reservationService.selectReservationListByDay();
            
            // 按会议室分组的预约数据
            Map<String, Map<String, List<Double>>> roomBookingData = new HashMap<>();
            
            // 处理预约数据
            for (Reservation reservation : todayReservations) {
                // 获取会议室内容
                Long roomContentId = reservation.getRoomContentId();
                if (roomContentId == null) {
                    continue;
                }
                
                RoomContent roomContent = roomContentService.selectRoomContentById(roomContentId);
                if (roomContent == null || roomContent.getRoomId() == null) {
                    continue;
                }
                
                // 获取会议室
                Room room = roomService.selectRoomById(roomContent.getRoomId());
                if (room == null) {
                    continue;
                }
                
                // 会议室名称作为key
                String roomKey = room.getName();
                
                // 确保Map中有当前会议室的数据结构
                if (!roomBookingData.containsKey(roomKey)) {
                    Map<String, List<Double>> bookingInfo = new HashMap<>();
                    bookingInfo.put("myBookings", new ArrayList<>());
                    bookingInfo.put("otherBookings", new ArrayList<>());
                    roomBookingData.put(roomKey, bookingInfo);
                }
                
                // 判断是当前用户的预约还是其他用户的预约
                String bookingType = reservation.getUserId().equals(currentUserId) ? "myBookings" : "otherBookings";
                
                // 将预约时间转换为小时格式（例如：9.0, 9.5, 10.0 等）
                Date startTime = reservation.getStartTime();
                Date endTime = reservation.getEndDate();
                
                if (startTime != null && endTime != null) {
                    List<Double> timeSlots = convertToTimeSlots(startTime, endTime);
                    roomBookingData.get(roomKey).get(bookingType).addAll(timeSlots);
                }
            }
            
            // 将结果转换为需要的格式
            Map<String, Map<String, double[]>> finalRoomBookingData = new HashMap<>();
            for (Map.Entry<String, Map<String, List<Double>>> entry : roomBookingData.entrySet()) {
                Map<String, double[]> roomData = new HashMap<>();
                
                List<Double> myBookings = entry.getValue().get("myBookings");
                List<Double> otherBookings = entry.getValue().get("otherBookings");
                
                roomData.put("myBookings", myBookings.stream().mapToDouble(Double::doubleValue).toArray());
                roomData.put("otherBookings", otherBookings.stream().mapToDouble(Double::doubleValue).toArray());
                
                finalRoomBookingData.put(entry.getKey(), roomData);
            }
            
            // 如果数据库没有足够数据，添加一些虚拟数据用于演示
            // if (finalRoomBookingData.isEmpty() || finalRoomBookingData.size() < 6) {
            //     addDemoData(finalRoomBookingData);
            // }
            
            return R.ok().put("data", finalRoomBookingData);
        } catch (Exception e) {
            log.error("获取今日会议室预约数据失败", e);
            return R.error("获取今日会议室预约数据失败");
        }
    }
    
    /**
     * 将开始时间和结束时间转换为0.5小时为单位的时间槽列表
     * 例如：9:00-10:30 转换为 [9.0, 9.5, 10.0]
     */
    private List<Double> convertToTimeSlots(Date startTime, Date endTime) {
        List<Double> timeSlots = new ArrayList<>();
        
        Calendar startCal = Calendar.getInstance();
        startCal.setTime(startTime);
        
        Calendar endCal = Calendar.getInstance();
        endCal.setTime(endTime);
        
        // 取整到最近的半小时
        int startHour = startCal.get(Calendar.HOUR_OF_DAY);
        int startMinute = startCal.get(Calendar.MINUTE);
        
        double currentTimeSlot = startHour;
        if (startMinute >= 30) {
            currentTimeSlot += 0.5;
        }
        
        // 将结束时间向上取整到最近的半小时
        int endHour = endCal.get(Calendar.HOUR_OF_DAY);
        int endMinute = endCal.get(Calendar.MINUTE);
        
        double endTimeSlot = endHour;
        if (endMinute > 0) {
            endTimeSlot += 0.5;
        }
        
        // 添加所有时间槽
        while (currentTimeSlot < endTimeSlot) {
            timeSlots.add(currentTimeSlot);
            currentTimeSlot += 0.5;
        }
        
        return timeSlots;
    }
    
    /**
     * 添加演示数据
     */
    private void addDemoData(Map<String, Map<String, double[]>> finalRoomBookingData) {
        if (!finalRoomBookingData.containsKey("401")) {
            Map<String, double[]> room401 = new HashMap<>();
            room401.put("myBookings", new double[]{16, 16.5, 17});
            room401.put("otherBookings", new double[]{10, 10.5, 11, 11.5, 12});
            finalRoomBookingData.put("401", room401);
        }
        
        if (!finalRoomBookingData.containsKey("709")) {
            Map<String, double[]> room709 = new HashMap<>();
            room709.put("myBookings", new double[]{15, 15.5, 16});
            room709.put("otherBookings", new double[]{9, 9.5, 10, 10.5, 11});
            finalRoomBookingData.put("709", room709);
        }
        
        if (!finalRoomBookingData.containsKey("705")) {
            Map<String, double[]> room705 = new HashMap<>();
            room705.put("myBookings", new double[]{18, 18.5, 19});
            room705.put("otherBookings", new double[]{9, 9.5, 10, 10.5, 11});
            finalRoomBookingData.put("705", room705);
        }
        
        if (!finalRoomBookingData.containsKey("302")) {
            Map<String, double[]> room302 = new HashMap<>();
            room302.put("myBookings", new double[]{14, 14.5, 15});
            room302.put("otherBookings", new double[]{11, 11.5, 12, 17, 17.5, 18});
            finalRoomBookingData.put("302", room302);
        }
        
        if (!finalRoomBookingData.containsKey("305")) {
            Map<String, double[]> room305 = new HashMap<>();
            room305.put("myBookings", new double[]{9, 9.5, 10});
            room305.put("otherBookings", new double[]{14, 14.5, 15, 15.5, 16, 16.5, 17});
            finalRoomBookingData.put("305", room305);
        }
        
        if (!finalRoomBookingData.containsKey("407")) {
            Map<String, double[]> room407 = new HashMap<>();
            room407.put("myBookings", new double[]{12, 12.5, 13});
            room407.put("otherBookings", new double[]{9, 9.5, 10, 16, 16.5, 17});
            finalRoomBookingData.put("407", room407);
        }
    }
}

