<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
        >新增时段</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="List"
          @click="toggleView"
        >{{ viewMode === 'calendar' ? '列表视图' : '日历视图' }}</el-button>
      </el-col>
    </el-row>
    <br>

    <!-- 日历视图 -->
    <div v-if="viewMode === 'calendar'" class="calendar-container">
      <el-calendar v-model="calendarDate">
        <template #date-cell="{ data }">
          <div class="calendar-day">
            <div class="day-number" :class="{ 'is-today': isToday(data.day) }">
              {{ data.day.split('-').slice(-1)[0] }}
            </div>
            <div v-if="isDayBlocked(data.day)" class="blocked-day" @click="openEditForDay(data.day)">
              <span class="blocked-tag">不可预约</span>
            </div>
            <div v-else-if="getTimeSlotsForDate(data.day).length > 0" class="time-slots">
              <div 
                v-for="slot in getTimeSlotsForDate(data.day)" 
                :key="slot.id"
                class="time-slot-card"
                :class="getSlotStatusClass(slot)"
              >
                <div class="slot-time">
                  <el-icon><Clock /></el-icon>
                  {{ formatTime(slot.startTime) }}-{{ formatTime(slot.endTime) }}
                </div>
                <div class="slot-info">
                  <el-icon><User /></el-icon>
                  <span>{{ slot.currentPeople }}/{{ slot.maxPeople }}</span>
                </div>
                <div class="slot-actions">
                  <el-button 
                    link 
                    type="primary" 
                    size="small"
                    icon="Edit"
                    @click.stop="handleUpdate(slot)"
                  ></el-button>
                  <el-button 
                    link 
                    type="danger" 
                    size="small"
                    icon="Delete"
                    @click.stop="handleDelete(slot)"
                  ></el-button>
                </div>
              </div>
            </div>
            <div v-else class="no-slots">
              <span class="no-slots-text">暂无时段</span>
            </div>
          </div>
        </template>
      </el-calendar>
    </div>

    <!-- 列表视图 -->
    <div v-else>
      <el-table v-loading="loading" :data="reservationTimeSlotList">
        <el-table-column label="日期" align="center" prop="date" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.date, 'yyyy-MM-DD') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" align="center" prop="startTime" width="180">
          <template #default="scope">
            <span>{{ formatTime(scope.row.startTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime" width="180">
          <template #default="scope">
            <span>{{ formatTime(scope.row.endTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最大人数" align="center" prop="maxPeople" />
        <el-table-column label="已预约人数" align="center" prop="currentPeople" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-tag :type="statusMap[scope.row.status] ? (statusMap[scope.row.status] === '可预约' ? 'success' : 'danger') : 'info'">
              {{ statusMap[scope.row.status] || '未设置' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <br>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="queryParams.pageSize"
          layout="->, total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog v-if="isAdd" :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="reservationTimeSlotRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="日期范围" prop="dateRange">
          <el-date-picker
            v-model="form.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            unlink-panels
            clearable
          />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-time-picker
            v-model="form.startTime"
            placeholder="请选择开始时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            clearable
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-time-picker
            v-model="form.endTime"
            placeholder="请选择结束时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            clearable
          />
        </el-form-item>
        <el-form-item label="最大人数" prop="maxPeople">
          <el-input v-model="form.maxPeople" placeholder="请输入最大人数" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-else title="修改预约时段信息" v-model="open" width="600px" append-to-body>
      <el-form ref="reservationTimeSlotRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="预约日期" prop="date">
          <el-input :model-value="parseTime(form.date, 'yyyy-MM-DD')" disabled />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-time-picker
            v-model="form.startTime"
            placeholder="请选择开始时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            clearable
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-time-picker
            v-model="form.endTime"
            placeholder="请选择结束时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            clearable
          />
        </el-form-item>
        <el-form-item label="最大人数" prop="maxPeople">
          <el-input v-model="form.maxPeople" placeholder="请输入最大人数" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="不可约" :value="0" />
            <el-option label="可约" :value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">提 交</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ReservationTimeSlot">
import { ref, reactive, toRefs, getCurrentInstance } from 'vue';
import { listReservationTimeSlot, getReservationTimeSlot, delReservationTimeSlot, addReservationTimeSlot, updateReservationTimeSlot, batchAddReservationTimeSlot } from "@/api/reservationTimeSlot";

const { proxy } = getCurrentInstance();

const reservationTimeSlotList = ref([]);
const allTimeSlots = ref([]); // 存储所有时段数据用于日历显示
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref("");
const viewMode = ref('calendar'); // 'calendar' 或 'list'
const calendarDate = ref(new Date());

const statusMap = { 1: '可预约', 0: '不可约' };

const isAdd = ref(false)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    date: null,
    startTime: null,
    endTime: null,
    maxPeople: null,
    currentPeople: null,
    status: null,
    creator: null
  },
  rules: {
    dateRange: [
      { required: true, message: "预约日期范围不能为空", trigger: "blur" }
    ],
    startTime: [
      { required: true, message: "开始时间不能为空", trigger: "blur" }
    ],
    endTime: [
      { required: true, message: "结束时间不能为空", trigger: "blur" }
    ],
    maxPeople: [
      { required: true, message: "最大人数不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询预约时段列表 */
function getList() {
  loading.value = true;
  listReservationTimeSlot(queryParams.value).then(response => {
    reservationTimeSlotList.value = response.list;
    total.value = response.total;
    loading.value = false;
  });
}

/** 获取所有时段数据（用于日历视图） */
function getAllTimeSlots() {
  loading.value = true;
  const params = {
    pageNum: 1,
    pageSize: 1000 // 获取足够多的数据用于日历显示
  };
  listReservationTimeSlot(params).then(response => {
    allTimeSlots.value = response.list;
    loading.value = false;
  });
}

/** 切换视图模式 */
function toggleView() {
  viewMode.value = viewMode.value === 'calendar' ? 'list' : 'calendar';
  if (viewMode.value === 'calendar') {
    getAllTimeSlots();
  } else {
    getList();
  }
}

/** 根据日期获取时段 */
function getTimeSlotsForDate(date) {
  return allTimeSlots.value.filter(slot => {
    const slotDate = parseTime(slot.date, 'yyyy-MM-DD');
    return slotDate === date;
  }).sort((a, b) => {
    return formatTime(a.startTime).localeCompare(formatTime(b.startTime));
  });
}

function isDayBlocked(date) {
  const slots = allTimeSlots.value.filter(slot => {
    const slotDate = parseTime(slot.date, 'yyyy-MM-DD');
    return slotDate === date;
  });
  return slots.length > 0 && slots.every(s => Number(s.status) === 0);
}

function openEditForDay(date) {
  const slots = getTimeSlotsForDate(date);
  if (slots.length > 0) {
    handleUpdate(slots[0]);
  }
}

/** 格式化时间 */
function formatTime(time) {
  if (!time) return '';
  if (typeof time === 'string' && time.includes(' ')) {
    return time.split(' ')[1].substring(0, 5);
  }
  if (typeof time === 'string' && time.includes(':')) {
    return time.substring(0, 5);
  }
  return time;
}

/** 判断是否是今天 */
function isToday(date) {
  const today = new Date();
  const targetDate = new Date(date);
  return today.getFullYear() === targetDate.getFullYear() &&
         today.getMonth() === targetDate.getMonth() &&
         today.getDate() === targetDate.getDate();
}



/** 获取时段状态样式 */
function getSlotStatusClass(slot) {
  const ratio = slot.currentPeople / slot.maxPeople;
  if (ratio >= 1) return 'slot-full';
  if (ratio >= 0.8) return 'slot-almost-full';
  return 'slot-available';
}

/** 时间格式化工具函数 */
function parseTime(time, format = 'yyyy-MM-DD HH:mm:ss') {
  if (!time) return '';
  const date = new Date(time);
  const formatObj = {
    yyyy: date.getFullYear(),
    MM: String(date.getMonth() + 1).padStart(2, '0'),
    DD: String(date.getDate()).padStart(2, '0'),
    HH: String(date.getHours()).padStart(2, '0'),
    mm: String(date.getMinutes()).padStart(2, '0'),
    ss: String(date.getSeconds()).padStart(2, '0')
  };
  return format.replace(/(yyyy|MM|DD|HH|mm|ss)/g, (match) => formatObj[match]);
}

// 改变每页条数大小
function handleSizeChange(val) {
  queryParams.value.pageSize = val;
  getList();
}

// 换页
function handleCurrentChange(val) {
  queryParams.value.pageNum = val;
  getList();
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    dateRange: null,
    startTime: null,
    endTime: null,
    maxPeople: null,
    currentPeople: null,
    status: null,
    createTime: null,
    creator: null
  };
  const reservationTimeSlotRef = proxy.$refs["reservationTimeSlotRef"]
  if (reservationTimeSlotRef) {
    reservationTimeSlotRef.resetFields();
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  const queryRef = proxy.$refs["queryRef"]
  if (queryRef) {
    queryRef.resetFields();
  }
  handleQuery();
}


/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加预约时段";
  isAdd.value = true;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getReservationTimeSlot(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改预约时段信息";
    isAdd.value = false;
  });
}

/** 表单提交按钮 */
function submitForm() {
  proxy.$refs["reservationTimeSlotRef"].validate(valid => {
    if (valid) {
      if (isAdd.value) {  // 添加
        batchAddReservationTimeSlot({
          startDate: form.value.dateRange && form.value.dateRange[0],
          endDate: form.value.dateRange && form.value.dateRange[1],
          startTime: form.value.startTime,
          endTime: form.value.endTime,
          maxPeople: form.value.maxPeople,
          status: 1
        }).then(response => {
          proxy.$message({
            message: response.msg,
            type: 'success'
          })
          open.value = false;
          refreshData();
        });
      } else {  // 更新
        const payload = { ...form.value };
        if (typeof payload.startTime === 'string') {
          payload.startTime = payload.startTime.length > 8 ? payload.startTime.slice(-8) : payload.startTime;
        }
        if (typeof payload.endTime === 'string') {
          payload.endTime = payload.endTime.length > 8 ? payload.endTime.slice(-8) : payload.endTime;
        }
        updateReservationTimeSlot(payload).then(response => {
          proxy.$message({
            message: response.msg,
            type: 'success'
          })
          open.value = false;
          refreshData();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$confirm('是否确认删除预约时段编号为"' + row.id + '"的数据项？').then(function() {
    return delReservationTimeSlot(row.id);
  }).then(response => {
    refreshData();
    proxy.$message({
      message: response.msg,
      type: 'success'
    })
  }).catch(() => {});
}

/** 导出按钮操作 */
// function handleExport() {
//   proxy.download('system/reservationTimeSlot/export', {
//     ...queryParams.value
//   }, `reservationTimeSlot_${new Date().getTime()}.xlsx`)
// }

// 初始化时根据视图模式加载数据
if (viewMode.value === 'calendar') {
  getAllTimeSlots();
} else {
  getList();
}

function refreshData() {
  if (viewMode.value === 'calendar') {
    getAllTimeSlots();
  } else {
    getList();
  }
}
</script>

<style scoped>
.calendar-container {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.calendar-day {
  height: 100%;
  min-height: 110px;
  padding: 4px;
  display: flex;
  flex-direction: column;
}

.day-number {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 6px;
  padding: 2px 6px;
  border-radius: 4px;
  text-align: center;
  display: inline-block;
}

.day-number.is-today {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  color: #fff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.time-slots {
  display: flex;
  flex-direction: column;
  gap: 4px;
  flex: 1;
  overflow-y: auto;
  max-height: 200px;
}

.time-slot-card {
  background: #fff;
  border-radius: 4px;
  padding: 6px 8px;
  font-size: 11px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  border-left: 2px solid transparent;
  position: relative;
}

.time-slot-card:hover {
  transform: translateY(-1px);
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.12);
}

.slot-available {
  border-left-color: #67c23a;
  background: linear-gradient(to right, #f0f9ff 0%, #fff 100%);
}

.slot-available:hover {
  background: linear-gradient(to right, #e1f3ff 0%, #fff 100%);
}

.slot-almost-full {
  border-left-color: #e6a23c;
  background: linear-gradient(to right, #fef9f0 0%, #fff 100%);
}

.slot-almost-full:hover {
  background: linear-gradient(to right, #fdf3e1 0%, #fff 100%);
}

.slot-full {
  border-left-color: #f56c6c;
  background: linear-gradient(to right, #fef0f0 0%, #fff 100%);
  opacity: 0.8;
}

.slot-full:hover {
  background: linear-gradient(to right, #fee5e5 0%, #fff 100%);
}

.slot-time {
  display: flex;
  align-items: center;
  gap: 3px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 3px;
  font-size: 11px;
}

.slot-time .el-icon {
  font-size: 12px;
  color: #409eff;
}

.slot-info {
  display: flex;
  align-items: center;
  gap: 3px;
  color: #606266;
  margin-bottom: 2px;
  font-size: 10px;
}

.slot-info .el-icon {
  font-size: 11px;
  color: #67c23a;
}

.slot-actions {
  display: flex;
  gap: 2px;
  justify-content: flex-end;
  margin-top: 2px;
  opacity: 0;
  transition: opacity 0.2s;
}

.time-slot-card:hover .slot-actions {
  opacity: 1;
}

.slot-actions .el-button {
  padding: 2px 4px;
}

.no-slots {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 0;
  flex: 1;
}

.no-slots-text {
  font-size: 11px;
  color: #c0c4cc;
}

.blocked-day {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px 0;
  flex: 1;
  cursor: pointer;
}

.blocked-tag {
  display: inline-block;
  padding: 8px 12px;
  font-size: 14px;
  font-weight: 700;
  color: #fff;
  background: #f56c6c;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.35);
  letter-spacing: 2px;
}

:deep(.el-calendar-table .el-calendar-day) {
  padding: 2px;
  height: 140px;
}

:deep(.el-calendar-table td) {
  border: 1px solid #ebeef5;
}

:deep(.el-calendar-table td.is-selected) {
  background-color: #f0f9ff;
}

:deep(.el-calendar__header) {
  padding: 12px 20px;
  border-bottom: 2px solid #e4e7ed;
  margin-bottom: 10px;
}

:deep(.el-calendar__body) {
  padding: 0;
}

:deep(.el-calendar-table thead th) {
  padding: 8px 0;
  font-weight: 600;
  color: #303133;
  background-color: #f5f7fa;
}

.mb8 {
  margin-bottom: 8px;
}

/* 滚动条样式 */
.time-slots::-webkit-scrollbar {
  width: 4px;
}

.time-slots::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 2px;
}

.time-slots::-webkit-scrollbar-thumb:hover {
  background-color: #c0c4cc;
}

.time-slots::-webkit-scrollbar-track {
  background-color: transparent;
}
</style>
