package com.amms.controller;

import com.amms.domain.dto.BatchAddReservationTimeSlotParam;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.amms.domain.vo.Result;
import com.amms.domain.ReservationTimeSlot;
import com.amms.service.IReservationTimeSlotService;
import java.util.List;
import java.util.Date;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.stream.Collectors;
import java.lang.reflect.Method;

/**
 * 预约时段Controller
 */
@RestController
@RequestMapping("/reservationTimeSlot")
public class ReservationTimeSlotController {

    @Autowired
    private IReservationTimeSlotService reservationTimeSlotService;

    /**
     * 查询预约时段列表
     */
    @GetMapping("/list")
    public PageInfo list(ReservationTimeSlot reservationTimeSlot, @RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ReservationTimeSlot> reservationTimeSlots = reservationTimeSlotService.selectReservationTimeSlotList(reservationTimeSlot);
        return new PageInfo(reservationTimeSlots);
    }

    /**
     * 查询全部预约时段列表
     */
    @GetMapping("/listAll")
    public List<ReservationTimeSlot> listAll(ReservationTimeSlot reservationTimeSlot) {
        return reservationTimeSlotService.selectReservationTimeSlotList(reservationTimeSlot);
    }

    /**
     * 获取预约时段详细信息
     */
    @GetMapping(value = "/info/{id}")
    public Result getInfo(@PathVariable("id") Long id) {
        return Result.success(reservationTimeSlotService.selectReservationTimeSlotById(id));
    }

    /**
     * 新增预约时段
     */
    @PostMapping("/add")
    public Result add(@RequestBody ReservationTimeSlot reservationTimeSlot) {
        return reservationTimeSlotService.insertReservationTimeSlot(reservationTimeSlot) > 0 ? Result.success("新增成功") : Result.error("新增失败");
    }

    /**
     * 批量新增预约时段（根据日期范围）
     */
    @PostMapping("/batchAdd")
    public Result batchAdd(@RequestBody BatchAddReservationTimeSlotParam param) {
        int affected = reservationTimeSlotService.batchInsertReservationTimeSlots(
                param.getStartDate(), param.getEndDate(), param.getStartTime(), param.getEndTime(), param.getMaxPeople(), param.getStatus()
        );
        return affected > 0 ? Result.success("新增成功") : Result.error("新增失败");
    }

    /**
     * 修改预约时段
     */
    @PutMapping
    public Result update(@RequestBody ReservationTimeSlot reservationTimeSlot) {
        return reservationTimeSlotService.updateReservationTimeSlot(reservationTimeSlot) > 0 ? Result.success("修改成功") : Result.error("修改失败");
    }

    /**
     * 删除预约时段
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Long id) {
        return reservationTimeSlotService.deleteReservationTimeSlotById(id) > 0 ? Result.success("删除成功") : Result.error("删除失败");
    }

    /**
     * 查询当天及往后推7天的预约时段信息
     */
    @GetMapping("/listNext7Days")
    public Result listNext7Days() {
        List<ReservationTimeSlot> all = reservationTimeSlotService.selectReservationTimeSlotList(new ReservationTimeSlot());
        LocalDate today = LocalDate.now();
        LocalDate end = today.plusDays(7);

        List<ReservationTimeSlot> filtered = all.stream().filter(slot -> {
            Date date = extractDate(slot);
            if (date == null) return false;
            LocalDate ld = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            return (!ld.isBefore(today)) && (!ld.isAfter(end));
        }).collect(Collectors.toList());
        return Result.success(filtered);
    }

    private Date extractDate(ReservationTimeSlot slot) {
        try {
            Method m = slot.getClass().getMethod("getDate");
            Object v = m.invoke(slot);
            if (v instanceof Date) return (Date) v;
        } catch (Exception ignored) {}
        try {
            Method m = slot.getClass().getMethod("getStartTime");
            Object v = m.invoke(slot);
            if (v instanceof Date) return (Date) v;
        } catch (Exception ignored) {}
        return null;
    }
}
