package com.srs.staff.service.impl;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.srs.common.exception.ServiceException;
import com.srs.common.utils.DateUtils;
import com.srs.common.utils.SecurityUtils;
import com.srs.comprehensive.domain.SrsStuYear;
import com.srs.comprehensive.domain.Vo.StuYearIdName;
import com.srs.comprehensive.mapper.SrsStuYearMapper;
import com.srs.staff.domain.StaffOneStopRoom;
import com.srs.staff.domain.StaffOneStopRoomOpeningHours;
import com.srs.staff.mapper.StaffOneStopRoomMapper;
import com.srs.staff.mapper.StaffOneStopRoomOpeningHoursMapper;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.srs.staff.mapper.StaffOneStopRoomReservationMapper;
import com.srs.staff.domain.StaffOneStopRoomReservation;
import com.srs.staff.service.IStaffOneStopRoomReservationService;

/**
 * 一站式社区-功能房-预约记录Service业务层处理
 *
 * @author chc
 * @date 2024-08-12
 */
@Service
public class StaffOneStopRoomReservationServiceImpl extends ServiceImpl<StaffOneStopRoomReservationMapper, StaffOneStopRoomReservation> implements IStaffOneStopRoomReservationService {
    @Autowired
    private StaffOneStopRoomReservationMapper staffOneStopRoomReservationMapper;

    @Autowired
    private StaffOneStopRoomOpeningHoursMapper staffOneStopRoomOpeningHoursMapper;

    @Autowired
    private StaffOneStopRoomMapper staffOneStopRoomMapper;
    
    @Autowired
    private SrsStuYearMapper srsStuYearMapper;

    /**
     * 查询一站式社区-功能房-预约记录
     *
     * @param rtId 一站式社区-功能房-预约记录主键
     * @return 一站式社区-功能房-预约记录
     */
    @Override
    public StaffOneStopRoomReservation selectStaffOneStopRoomReservationByRtId(Long rtId) {
        return staffOneStopRoomReservationMapper.selectStaffOneStopRoomReservationByRtId(rtId);
    }


    @Override
    public List<StaffOneStopRoomOpeningHours> selectStaffOneStopRoomReservationByRtTime(String roomNo ,String rtTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date = LocalDate.parse(rtTime, formatter);
        // 获取星期几
        DayOfWeek dayOfWeek = date.getDayOfWeek();
        // 将DayOfWeek转换为字符串，使用默认语言环境和全称样式
        String dayOfWeekString = dayOfWeek.getDisplayName(TextStyle.FULL, Locale.getDefault());

        // 获取功能房对应的预约时间段(根据功能房编号，和指定的星期几)
        List<StaffOneStopRoomOpeningHours> staffOneStopRoomOpeningHours = staffOneStopRoomOpeningHoursMapper.selectStaffOneStopRoomOpeningHoursByOhWeekday(roomNo, dayOfWeekString);

        // 获取这个功能房的使用预约记录（根据功能房编号，和指定的时间）
        List<StaffOneStopRoomReservation> roomReservations = staffOneStopRoomReservationMapper.selectStaffOneStopRoomReservationByRtTime(roomNo, rtTime);

        // 遍历预约记录，设置所有被预约的时间
        for (StaffOneStopRoomReservation reservation : roomReservations) {
            // 如果不等于2 证明预约时间有被占用
            if (reservation.getRtState() != 2 && reservation.getAuditStatus() != 2) {
                // 查询对应的开放时间
                StaffOneStopRoomOpeningHours hours = staffOneStopRoomOpeningHoursMapper.selectStaffOneStopRoomOpeningHoursByRtNo(reservation.getRtNo());

                // 遍历开放时间列表，设置已被预约的时间
                for (StaffOneStopRoomOpeningHours roomOpeningHours : staffOneStopRoomOpeningHours) {
                    // 找到对应的预约时间段
                    if (Objects.equals(roomOpeningHours.getOhId(), hours.getOhId())) {
                        // 标记上已经被占用
                        roomOpeningHours.setIsOccupy(1L);
                    }
                }
            }
        }

        return staffOneStopRoomOpeningHours;
    }

    /**
     * 查询一站式社区-功能房-预约记录列表
     *
     * @param staffOneStopRoomReservation 一站式社区-功能房-预约记录
     * @return 一站式社区-功能房-预约记录
     */
    @Override
    public List<StaffOneStopRoomReservation> selectStaffOneStopRoomReservationList(StaffOneStopRoomReservation staffOneStopRoomReservation) {
        return staffOneStopRoomReservationMapper.selectStaffOneStopRoomReservationList(staffOneStopRoomReservation);
    }

    /**
     * 查询一站式社区-功能房-预约记录列表(用于导出)
     *
     * @param staffOneStopRoomReservation 一站式社区-功能房-预约记录
     * @return 一站式社区-功能房-预约记录
     */
    @Override
    public List<StaffOneStopRoomReservation> selectStaffOneStopRoomReservationListExport(StaffOneStopRoomReservation staffOneStopRoomReservation) {
        List<StaffOneStopRoomReservation> list = staffOneStopRoomReservationMapper.selectStaffOneStopRoomReservationList(staffOneStopRoomReservation);
        
        // 查询所有学年数据用于匹配
        List<SrsStuYear> allYears = srsStuYearMapper.selectSrsStuYearList(new SrsStuYear());
        
        for (StaffOneStopRoomReservation reservation : list) {
            // 根据预约时间确定学年
            if (reservation.getRtTime() != null && !reservation.getRtTime().isEmpty()) {
                String yearName = determineSchoolYearByTime(reservation.getRtTime(), allYears);
                reservation.setYearName(yearName);
            }
            
            // 根据功能房编码获取功能房信息并填充到预约记录中
            if (reservation.getRoomNo() != null) {
                StaffOneStopRoom room = staffOneStopRoomMapper.selectStaffOneStopRoomByRoomNo(reservation.getRoomNo());
                if (room != null) {
                    reservation.setRoomCapacity(room.getRoomCapacity());//功能房容量
                    reservation.setRoomMatter(room.getRoomMatter());
                    reservation.setRoomRule(room.getRoomRule());
                    reservation.setRoomInfo(room.getRoomInfo());
                    reservation.setRoomPurp(room.getRoomPurp());
                    reservation.setRoomImgs(room.getRoomImgs());
                }
            }
        }
        return list;
    }
    
    /**
     * 根据预约时间确定所属学年
     * @param rtTime 预约时间
     * @param allYears 所有学年数据
     * @return 学年名称
     */
    private String determineSchoolYearByTime(String rtTime, List<SrsStuYear> allYears) {
        try {
            // 解析预约时间
            Date reservationDate = null;
            // 尝试解析不同的日期格式
            if (rtTime.length() == 10) { // "yyyy-MM-dd" 格式
                reservationDate = DateUtils.parseDate(rtTime, "yyyy-MM-dd");
            } else if (rtTime.length() == 7) { // "yyyy-MM" 格式
                reservationDate = DateUtils.parseDate(rtTime + "-01", "yyyy-MM-dd");
            } else if (rtTime.length() == 4) { // "yyyy" 格式
                reservationDate = DateUtils.parseDate(rtTime + "-01-01", "yyyy-MM-dd");
            } else {
                // 尝试解析其他格式
                reservationDate = DateUtils.parseDate(rtTime);
            }
            
            if (reservationDate == null) {
                return null;
            }
            
            // 遍历所有学年，找到匹配的学年
            for (SrsStuYear year : allYears) {
                if (year.getStartTime() != null && year.getEndTime() != null) {
                    // 直接使用学年自身的起始和结束时间进行判断
                    if (reservationDate.compareTo(year.getStartTime()) >= 0 && reservationDate.compareTo(year.getEndTime()) <= 0) {
                        // 截取字符串，去掉"学年"两个字
                        String yearName = year.getStuYearName();
                        if (yearName != null && yearName.endsWith("学年")) {
                            return yearName.substring(0, yearName.length() - 2);
                        }
                        return yearName;
                    }
                }
            }
        } catch (Exception e) {
            // 解析日期失败，返回null
            System.out.println("解析预约时间失败: " + rtTime + ", 错误: " + e.getMessage());
        }
        
        return null;
    }


    /**
     * 新增一站式社区-功能房-预约记录
     *
     * @param staffOneStopRoomReservation 一站式社区-功能房-预约记录
     * @return 结果
     */
    @Override
    public int insertStaffOneStopRoomReservation(StaffOneStopRoomReservation staffOneStopRoomReservation) {
        staffOneStopRoomReservation.setRtCreatTime(DateUtils.getNowDate());
        staffOneStopRoomReservation.setCreateBy(SecurityUtils.getUsername());
        staffOneStopRoomReservation.setCreateTime(DateUtils.getNowDate());
        if (staffOneStopRoomReservation.getRtCreatRole() == null) {
            staffOneStopRoomReservation.setRtCreatRole(SecurityUtils.getLoginUser().getUser().getNickName());
        }
        StaffOneStopRoom stopRoom = staffOneStopRoomMapper.selectStaffOneStopRoomByRoomNo(staffOneStopRoomReservation.getRoomNo());
        if (!Objects.equals(stopRoom.getRoomStatus(), "1")) {
            throw new ServiceException("功能房暂未开放", 500);
        }
        return staffOneStopRoomReservationMapper.insertStaffOneStopRoomReservation(staffOneStopRoomReservation);
    }

    /**
     * 修改一站式社区-功能房-预约记录
     *
     * @param staffOneStopRoomReservation 一站式社区-功能房-预约记录
     * @return 结果
     */
    @Override
    public int updateStaffOneStopRoomReservation(StaffOneStopRoomReservation staffOneStopRoomReservation) {
        staffOneStopRoomReservation.setUpdateBy(SecurityUtils.getUsername());
        staffOneStopRoomReservation.setRtUpTime(DateUtils.getNowDate());
        List<StaffOneStopRoomOpeningHours> toUpdate = new ArrayList<>(staffOneStopRoomReservation.getStaffOneStopRoomOpeningHoursList());
        // 如果存在需要更新的记录，则执行批量更新
        if (!toUpdate.isEmpty()) {
            staffOneStopRoomOpeningHoursMapper.batchUpdateStaffOneStopRoomOpeningHours(toUpdate);
        }
        return staffOneStopRoomReservationMapper.updateStaffOneStopRoomReservation(staffOneStopRoomReservation);
    }

    /**
     * 批量删除一站式社区-功能房-预约记录
     *
     * @param rtIds 需要删除的一站式社区-功能房-预约记录主键
     * @return 结果
     */
    @Override
    public int deleteStaffOneStopRoomReservationByRtIds(Long[] rtIds) {
        return staffOneStopRoomReservationMapper.deleteStaffOneStopRoomReservationByRtIds(rtIds);
    }

    /**
     * 删除一站式社区-功能房-预约记录信息
     *
     * @param rtId 一站式社区-功能房-预约记录主键
     * @return 结果
     */
    @Override
    public int deleteStaffOneStopRoomReservationByRtId(Long rtId) {
        return staffOneStopRoomReservationMapper.deleteStaffOneStopRoomReservationByRtId(rtId);
    }
}