package com.jeeplus.hotelorder.hotelconfig.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.hotelorder.hotelconfig.domain.HotelBusinessHours;
import com.jeeplus.hotelorder.hotelconfig.domain.HotelConfig;
import com.jeeplus.hotelorder.hotelconfig.mapper.HotelBusinessHoursMapper;
import com.jeeplus.hotelorder.hotelconfig.mapper.HotelConfigMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 酒店配置服务类
 * @author jeeplus
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class HotelConfigService extends ServiceImpl<HotelConfigMapper, HotelConfig> {

    private static final Logger log = LoggerFactory.getLogger(HotelConfigService.class);

    @Resource
    private HotelConfigMapper hotelConfigMapper;

    @Resource
    private HotelBusinessHoursMapper hotelBusinessHoursMapper;

    /**
     * 获取酒店配置
     * @return 酒店配置信息
     */
    public HotelConfig getConfig() {
        QueryWrapper<HotelConfig> qw = new QueryWrapper<>();
        qw.last("LIMIT 1");
        return hotelConfigMapper.selectOne(qw);
    }

    /**
     * 保存/更新酒店配置
     * @param config 酒店配置信息
     * @return 操作结果
     */
    public String saveConfig(HotelConfig config) {
        HotelConfig existing = getConfig();
        if (existing == null) {
            config.setId(UUID.randomUUID().toString().replace("-", ""));
            config.setDelFlag(0);
            hotelConfigMapper.insert(config);
            log.info("新增酒店配置: {}", config.getHotelName());
        } else {
            config.setId(existing.getId());
            hotelConfigMapper.updateById(config);
            log.info("更新酒店配置: {}", config.getHotelName());
        }
        return "操作成功";
    }

    // ==================== 营业时段管理 ====================

    /**
     * 分页查询营业时段
     * @param page 分页参数
     * @param businessHours 查询条件
     * @return 分页结果
     * @throws Exception 查询异常
     */
    public IPage<HotelBusinessHours> findBusinessHoursPage(Page<HotelBusinessHours> page, HotelBusinessHours businessHours) throws Exception {
        QueryWrapper<HotelBusinessHours> queryWrapper = QueryWrapperGenerator.buildQueryCondition(businessHours, HotelBusinessHours.class);
        queryWrapper.eq("del_flag", 0);
        queryWrapper.orderByAsc("sort_order");
        return hotelBusinessHoursMapper.selectPage(page, queryWrapper);
    }

    /**
     * 获取营业时段列表（全部，含禁用）
     * @return 营业时段列表
     */
    public List<HotelBusinessHours> getBusinessHoursList() {
        QueryWrapper<HotelBusinessHours> qw = new QueryWrapper<>();
        qw.eq("del_flag", 0).orderByAsc("sort_order");
        return hotelBusinessHoursMapper.selectList(qw);
    }

    /**
     * 获取所有启用的营业时段
     * @return 启用的营业时段列表
     */
    public List<HotelBusinessHours> getEnabledBusinessHoursList() {
        QueryWrapper<HotelBusinessHours> qw = new QueryWrapper<>();
        qw.eq("status", "ENABLED").eq("del_flag", 0).orderByAsc("sort_order");
        return hotelBusinessHoursMapper.selectList(qw);
    }

    /**
     * 检查当前是否在营业时段内
     * 按星期几匹配（优先具体星期，其次NULL=每天），时间字符串比较判断是否在时段内
     * @return 当前营业时段信息，不在营业时段则返回null
     */
    public HotelBusinessHours checkCurrentBusinessHours() {
        Calendar calendar = Calendar.getInstance();
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1; // 0=周日
        String currentTime = String.format("%02d:%02d", calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE));

        QueryWrapper<HotelBusinessHours> qw = new QueryWrapper<>();
        qw.eq("status", "ENABLED").eq("del_flag", 0);
        qw.and(w -> w.eq("day_of_week", dayOfWeek).or().isNull("day_of_week"));
        qw.orderByAsc("sort_order");

        List<HotelBusinessHours> hoursList = hotelBusinessHoursMapper.selectList(qw);
        for (HotelBusinessHours hours : hoursList) {
            if (currentTime.compareTo(hours.getStartTime()) >= 0 && currentTime.compareTo(hours.getEndTime()) < 0) {
                return hours;
            }
        }
        return null;
    }

    /**
     * 查询营业时段详情
     * @param id 营业时段ID
     * @return 营业时段信息
     */
    public HotelBusinessHours getBusinessHoursById(String id) {
        return hotelBusinessHoursMapper.selectById(id);
    }

    /**
     * 保存营业时段（新增/编辑）
     * @param hours 营业时段信息
     * @return 操作结果
     */
    public String saveBusinessHours(HotelBusinessHours hours) {
        if (StringUtils.isBlank(hours.getId())) {
            hours.setId(UUID.randomUUID().toString().replace("-", ""));
            hours.setDelFlag(0);
            if (StringUtils.isBlank(hours.getStatus())) {
                hours.setStatus("ENABLED");
            }
            if (hours.getSortOrder() == null) {
                hours.setSortOrder(0);
            }
            hotelBusinessHoursMapper.insert(hours);
            log.info("新增营业时段: {}", hours.getMealName());
        } else {
            hotelBusinessHoursMapper.updateById(hours);
            log.info("编辑营业时段: {}", hours.getMealName());
        }
        return "操作成功";
    }

    /**
     * 切换营业时段状态（启用/禁用）
     * @param id 营业时段ID
     * @return 操作结果
     */
    public String toggleBusinessHours(String id) {
        HotelBusinessHours hours = hotelBusinessHoursMapper.selectById(id);
        if (hours == null) {
            throw new RuntimeException("营业时段不存在");
        }
        String newStatus = "ENABLED".equals(hours.getStatus()) ? "DISABLED" : "ENABLED";
        hours.setStatus(newStatus);
        hotelBusinessHoursMapper.updateById(hours);
        log.info("营业时段状态变更: {} -> {}", hours.getMealName(), newStatus);
        return "操作成功";
    }

    /**
     * 删除营业时段
     * @param id 营业时段ID
     */
    public void deleteBusinessHours(String id) {
        hotelBusinessHoursMapper.deleteById(id);
        log.info("删除营业时段: {}", id);
    }
}
