package com.ruoyi.ss.room.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.common.constant.ServiceConstants;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.collection.CollectionUtils;
import com.ruoyi.ss.device.domain.vo.DeviceVO;
import com.ruoyi.ss.device.service.DeviceService;
import com.ruoyi.ss.equipment.domain.EquipmentQuery;
import com.ruoyi.ss.equipment.domain.EquipmentVO;
import com.ruoyi.ss.equipment.service.IEquipmentService;
import com.ruoyi.ss.feeRule.domain.FeeRuleVO;
import com.ruoyi.ss.feeRule.service.IFeeRuleService;
import com.ruoyi.ss.order.domain.OrderQuery;
import com.ruoyi.ss.order.domain.vo.ReservedTimePeriod;
import com.ruoyi.ss.order.service.IOrderService;
import com.ruoyi.ss.room.domain.RoomVO;
import com.ruoyi.ss.room.service.IRoomAssembler;
import com.ruoyi.ss.store.domain.StoreVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

import static com.ruoyi.common.constant.ServiceConstants.*;

/**
 * @author qzz
 * 2024/4/29
 */
@Service
public class RoomAssemblerImpl implements IRoomAssembler {

    @Autowired
    private IFeeRuleService feeRuleService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private IEquipmentService equipmentService;

    /**
     * 拼接设备数量
     *
     * @param list 店铺列表
     */
    @Override
    public void assembleRuleInfo(List<RoomVO> list) {
        if (CollectionUtils.isEmptyElement(list)) {
            return;
        }
        list.forEach(room -> {
            // 每个小时价格和最低套餐
            assembleRule(room);

            // 已售数
            int soldNum = orderService.selectSoldNum(room.getRoomId());
            room.setSoldNum(soldNum);

            //已预定时间段(包含)
            assembleReservedTimePeriods(room);
        });
    }

    /**
     * 拼接设备数量
     *
     * @param list 店铺列表
     */
    @Override
    public void assembleRuleInfo2(List<RoomVO> list) {
        if (CollectionUtils.isEmptyElement(list)) {
            return;
        }
        list.forEach(room -> {
            // room.getRuleIds()为空时跳过
            if (CollectionUtils.isEmptyElement(room.getRuleIds())) {
                return;
            }
            List<FeeRuleVO> feeRuleVOS = feeRuleService.selectEFeeRuleListByRuleIds(room.getRuleIds());
            if(!feeRuleVOS.isEmpty()){
                room.setFeeRules(feeRuleVOS);
            }
        });
    }

    /**
     * 拼接设备数量
     *
     * @param room 房间对象
     */
    @Override
    public void assembleRuleInfo2(RoomVO room) {
        if (room == null) {
            return;
        }
        // room.getRuleIds()为空时跳过
        if (CollectionUtils.isEmptyElement(room.getRuleIds())) {
            return;
        }
        List<FeeRuleVO> feeRuleVOS = feeRuleService.selectEFeeRuleListByRuleIds(room.getRuleIds());
        if(!feeRuleVOS.isEmpty()){
            room.setFeeRules(feeRuleVOS);
            room.setBillingMode(feeRuleVOS.get(0).getMode());
        }
        // 总营收  总订单数
        setIncome(room);
    }

    private void setIncome(RoomVO vo) {
        OrderQuery orderQuery = new OrderQuery();
        if(vo.getType2().equals(ServiceConstants.ROOM_TYPE2_PRIVATE_ROOM)){
            orderQuery.setRoomId(vo.getRoomId());
        }else{
            orderQuery.setEquipmentId(vo.getRoomId());
        }
        String[] statusList = {"1", "2", "3", "4", "7", "8", "9"};
        orderQuery.setStatusList(statusList);
        BigDecimal totalRevenue = orderService.getOrderFee(orderQuery);
        vo.setTotalIncome(totalRevenue);// 总营收
        // 已售数
        int soldNum = orderService.selectSoldNum(vo.getRoomId());
        vo.setSoldNum(soldNum);
    }

    /**
     * 拼接设备信息
     * @param list 店铺列表
     */
    @Override
    public void assembleDeviceInfo(List<RoomVO> list) {
        if (CollectionUtils.isEmptyElement(list)) {
            return;
        }
        // 先获取到设施，再获取到设备信息
        list.forEach(this::assembleEquipmentList);
    }

    @Override
    public void assembleReservedTimePeriods(RoomVO room) {
        //以当前时间开始的24小时内的已经预定成功的订单时间，预定成功的判断是  order.status == 2 的订单 ,只返回 order.reserveStartTime（Date）和reserveEndTime（Date）,放在list中，list的结构：
        // [{"startTime":"2024-04-29 14:00:00","endTime":"2024-04-29 15:00:00"}, {"startTime":"2024-04-29 16:00:00","endTime":"2024-04-29 17:00:00"}]
        // 获取当前时间
        Date startTime = new Date();

        // 获取24小时后的时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startTime);
        calendar.add(Calendar.HOUR, 24);
        Date endTime = calendar.getTime();

        // 获取已预定时间段：预定成功的订单，时间在当前时间的24小时内
        List<ReservedTimePeriod> reservedTimes = orderService.selectReservedTimes(room.getRoomId(), startTime, endTime);
        room.setReservedTimePeriods(reservedTimes);
    }

    @Override
    public void assembleReservedTimePeriods(EquipmentVO room) {
        //以当前时间开始的24小时内的已经预定成功的订单时间，预定成功的判断是  order.status == 2 的订单 ,只返回 order.reserveStartTime（Date）和reserveEndTime（Date）,放在list中，list的结构：
        // [{"startTime":"2024-04-29 14:00:00","endTime":"2024-04-29 15:00:00"}, {"startTime":"2024-04-29 16:00:00","endTime":"2024-04-29 17:00:00"}]
        // 获取当前时间
        Date startTime = new Date();

        // 获取24小时后的时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startTime);
        calendar.add(Calendar.HOUR, 24);
        Date endTime = calendar.getTime();

        // 获取已预定时间段：预定成功的订单，时间在当前时间的24小时内
        List<ReservedTimePeriod> reservedTimes = orderService.selectReservedTimes(room.getRoomId(), startTime, endTime);
        room.setReservedTimePeriods(reservedTimes);
    }

    @Override
    public List<ReservedTimePeriod> getReservedTimePeriods(Long roomId, Date startTime) {
        //以当前时间开始的24小时内的已经预定成功的订单时间，预定成功的判断是  order.status == 2 的订单 ,只返回 order.reserveStartTime（Date）和reserveEndTime（Date）,放在list中，list的结构：
        // [{"startTime":"2024-04-29 14:00:00","endTime":"2024-04-29 15:00:00"}, {"startTime":"2024-04-29 16:00:00","endTime":"2024-04-29 17:00:00"}]

        // 获取24小时后的时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startTime);
        calendar.add(Calendar.HOUR, 24);
        Date endTime = calendar.getTime();

        // 获取已预定时间段：预定成功的订单，时间在当前时间的24小时内
        return orderService.selectReservedTimes(roomId, startTime, endTime);
    }

    @Override
    public void assembleEquipmentList(RoomVO roomVO) {
        List<EquipmentVO> equipmentVOS = equipmentService.selectEquipmentListByRoomId(roomVO.getRoomId());

        if(!equipmentVOS.isEmpty()){
            roomVO.setEquipmentList(equipmentVOS);
            equipmentVOS.forEach(e -> {
                DeviceVO deviceVO = deviceService.selectById(e.getDeviceId());
                if(ObjectUtils.isNotNull(deviceVO)){
                    e.setDevice(deviceVO);
                }
            });
        }
    }

    @Override
    public void assembleEquipmentList(List<RoomVO> roomVO) {
        if(roomVO.isEmpty()){
            return;
        }
        roomVO.forEach(this::assembleEquipmentList);
    }

//    /**
//     * 拼接大厅下所有设施
//     * @param rooms 房间对象
//     */
//    @Override
//    public List<RoomVO> assembleHallEquipmentList(List<RoomVO> rooms,String type) {
//        if(rooms.isEmpty()){
//            return rooms;
//        }
//        List<RoomVO> hallRooms = new ArrayList<>();
//        for (RoomVO room : rooms) {
//            if (ServiceConstants.ROOM_TYPE2_HALL.equals(room.getType2())) {
//                EquipmentQuery query = new EquipmentQuery();
//                query.setRoomId(room.getRoomId());
//                query.setType(type);
//                List<EquipmentVO> equipmentVOS = equipmentService.selectEquipmentList(query);
////                List<RoomVO> newRooms = hallEquipmentToRoomVO(equipmentVOS);
////                hallRooms.addAll(newRooms);
//            }
//        }
//        List<RoomVO> updatedRooms = new ArrayList<>(hallRooms);
//        // 去掉大厅 if (ServiceConstants.ROOM_TYPE2_HALL.equals(room.getType2()))就是dating
//        rooms.removeIf(room -> ServiceConstants.ROOM_TYPE2_HALL.equals(room.getType2()) || ServiceConstants.ROOM_TYPE2_BATHROOM.equals(room.getType2()));
//        updatedRooms.addAll(rooms);
//        return updatedRooms;
//    }

//    /**
//     * 大厅下设施转成房间对象
//     * @param equipmentVOS 设备列表
//     */
//    private List<RoomVO> hallEquipmentToRoomVO(List<EquipmentVO> equipmentVOS) {
//        List<RoomVO> newRooms = new ArrayList<>();
//        if (equipmentVOS.isEmpty()) {
//            return newRooms;
//        }
//        // 遍历设备列表，将设备对象转换为房间对象
//        equipmentVOS.forEach(e -> {
//            RoomVO roomVO = new RoomVO();
//            roomVO.setRoomId(e.getRoomId());
//            roomVO.setRoomName(e.getName());
////            roomVO.setPicture(e.getPicture());
////            roomVO.setTags(e.getTags());
//            roomVO.setViewType("2");
//
//            // 每个小时价格和最低套餐
//            assembleRule(e);
//
//            //已预定时间段(包含)
//            assembleReservedTimePeriods(e);
//            newRooms.add(roomVO);
//        });
//        return newRooms;
//    }

    @Override
    public void assembleRule(RoomVO room) {
        if (CollectionUtils.isEmptyElement(room.getRuleIds())) {
            return;
        }
        List<FeeRuleVO> feeRuleVOS = feeRuleService.selectEFeeRuleListByRuleIds(room.getRuleIds());
        // 检查 feeRuleVOS 是否为空
        if (feeRuleVOS == null || feeRuleVOS.isEmpty()) {
            return; // 如果为空则跳过处理
        }

        // 处理逻辑：优先获取 mode 为 "1" 的 FeeRuleVO
        FeeRuleVO modeOneFeeRule = feeRuleVOS.stream()
                .filter(feeRule -> "1".equals(feeRule.getMode())) // 筛选 mode 为 "1"
                .findFirst() // 获取第一个符合条件的 FeeRuleVO
                .orElse(null); // 如果没有找到，返回 null

        if (modeOneFeeRule != null) {
            // 如果找到了 mode 为 "1" 的记录，直接设置 hour
            room.setHour(modeOneFeeRule.getPrice());
        } else {
            // 如果没有 mode 为 "1" 的记录，计算 price / hours
            feeRuleVOS.stream()
                    .filter(feeRule -> feeRule.getHours() != null && feeRule.getHours() > 0) // 确保 hours 有效
                    .map(feeRule -> feeRule.getPrice().divide(BigDecimal.valueOf(feeRule.getHours()), 2, RoundingMode.HALF_UP)) // 计算 price / hours
                    .findFirst() // 获取第一个计算结果
                    .ifPresent(room::setHour); // 设置 hour
        }

        // 套餐价格，返回： 4小时套餐：￥149.9/场
        // 获取 mode 为 "2" 且 hours 最小的 FeeRuleVO
        feeRuleVOS.stream()
                .filter(feeRule -> "2".equals(feeRule.getMode()) && feeRule.getPrice() != null) // 筛选 mode 为 "2" 且 price 不为 null
                .min(Comparator.comparing(FeeRuleVO::getPrice)) // 按照 price 升序排序并获取价格最低的 FeeRuleVO
                .ifPresent(room::setBottomPriceFeeRule);
    }

//    @Override
//    public void assembleRule(EquipmentVO equipmentVO) {
//        List<FeeRuleVO> feeRuleVOS = feeRuleService.selectEFeeRuleListByRuleIds(equipmentVO.getRuleIds());
//        // 检查 feeRuleVOS 是否为空
//        if (feeRuleVOS == null || feeRuleVOS.isEmpty()) {
//            return; // 如果为空则跳过处理
//        }
//
//        // 处理逻辑：优先获取 mode 为 "1" 的 FeeRuleVO
//        FeeRuleVO modeOneFeeRule = feeRuleVOS.stream()
//                .filter(feeRule -> "1".equals(feeRule.getMode())) // 筛选 mode 为 "1"
//                .findFirst() // 获取第一个符合条件的 FeeRuleVO
//                .orElse(null); // 如果没有找到，返回 null
//
//        if (modeOneFeeRule != null) {
//            // 如果找到了 mode 为 "1" 的记录，直接设置 hour
//            equipmentVO.setHour(modeOneFeeRule.getPrice());
//        } else {
//            // 如果没有 mode 为 "1" 的记录，计算 price / hours
//            feeRuleVOS.stream()
//                    .filter(feeRule -> feeRule.getHours() != null && feeRule.getHours() > 0) // 确保 hours 有效
//                    .map(feeRule -> feeRule.getPrice().divide(BigDecimal.valueOf(feeRule.getHours()), 2, RoundingMode.HALF_UP)) // 计算 price / hours
//                    .findFirst() // 获取第一个计算结果
//                    .ifPresent(equipmentVO::setHour); // 设置 hour
//        }
//
//        // 套餐价格，返回： 4小时套餐：￥149.9/场
//        // 获取 mode 为 "2" 且 hours 最小的 FeeRuleVO
//        feeRuleVOS.stream()
//                .filter(feeRule -> "2".equals(feeRule.getMode()) && feeRule.getPrice() != null) // 筛选 mode 为 "2" 且 price 不为 null
//                .min(Comparator.comparing(FeeRuleVO::getPrice)) // 按照 price 升序排序并获取价格最低的 FeeRuleVO
//                .ifPresent(equipmentVO::setBottomPriceFeeRule);
//    }

    @Override
    public void assembleAllRule(RoomVO room) {
        if (CollectionUtils.isEmptyElement(room.getRuleIds())) {
            return;
        }
        List<FeeRuleVO> feeRuleVOS = feeRuleService.selectEFeeRuleListByRuleIds(room.getRuleIds());
        // 检查 feeRuleVOS 是否为空
        if (feeRuleVOS == null || feeRuleVOS.isEmpty()) {
            return; // 如果为空则跳过处理
        }
        // 处理逻辑：优先获取 mode 为 "1" 的 FeeRuleVO
        FeeRuleVO modeOneFeeRule = feeRuleVOS.stream()
                .filter(feeRule -> "1".equals(feeRule.getMode())) // 筛选 mode 为 "1"
                .findFirst() // 获取第一个符合条件的 FeeRuleVO
                .orElse(null); // 如果没有找到，返回 null

        if (modeOneFeeRule != null) {
            // 如果找到了 mode 为 "1" 的记录，直接设置 hour
            room.setHour(modeOneFeeRule.getPrice());
        } else {
            // 如果没有 mode 为 "1" 的记录，计算 price / hours
            feeRuleVOS.stream()
                    .filter(feeRule -> feeRule.getHours() != null && feeRule.getHours() > 0) // 确保 hours 有效
                    .map(feeRule -> feeRule.getPrice().divide(BigDecimal.valueOf(feeRule.getHours()), 2, RoundingMode.HALF_UP)) // 计算 price / hours
                    .findFirst() // 获取第一个计算结果
                    .ifPresent(room::setHour); // 设置 hour
        }
        room.setFeeRules(feeRuleVOS);
    }


    @Override
    public void assembleRules(RoomVO room) {
        if(room == null || room.getRuleIds().isEmpty()){
            return;
        }
        List<FeeRuleVO> feeRuleVOS = feeRuleService.selectEFeeRuleListByRuleIds(room.getRuleIds());
        // 检查 feeRuleVOS 是否为空
        if (feeRuleVOS.isEmpty()) {
            return; // 如果为空则跳过处理
        }
        room.setFeeRules(feeRuleVOS);
    }

    /**
     * 拼接大厅设施中的device
     * @param roomVO 房间对象
     */
    @Override
    public void assembleHallDevice(RoomVO roomVO) {
        if(roomVO == null || roomVO.getType2().equals(ROOM_TYPE2_PRIVATE_ROOM)){
            return;
        }
        List<EquipmentVO> equipmentVOS = equipmentService.selectEquipmentListByRoomId(roomVO.getRoomId());
        if(!equipmentVOS.isEmpty()){
            Long deviceId = equipmentVOS.get(0).getDeviceId();
            if(deviceId == null){
                return;
            }
            roomVO.setDeviceId(deviceId);
            roomVO.setSn(equipmentVOS.get(0).getSn());
        }
    }

    /**
     * 拼接大厅设施中的device
     * @param roomVO 房间对象
     */
    @Override
    public void assembleHallDevice(List<RoomVO> roomVO) {
        for (RoomVO roomVO1 : roomVO) {
            assembleHallDevice(roomVO1);
        }
    }
}
