<script setup lang="ts">
import { ref, computed, onMounted, h } from 'vue';
import { Page } from '@vben/common-ui';
import dayjs from 'dayjs';
import type { TableColumnType } from 'ant-design-vue';
import { Radio, Select, Button, Table } from 'ant-design-vue';
import { conferenceList } from '#/api/property/conference';
import { roomBookingList } from '#/api/property/roomBooking';
import type { RadioChangeEvent } from 'ant-design-vue';
import type { SelectValue } from 'ant-design-vue/es/select';

// 首先定义会议室和预约信息的接口类型
interface ConferenceRoom {
  id: string;
  name: string;
}

interface ConferenceBooking {
  id: string | number;
  tbConferenceId: string | number; // 会议室ID
  bookingName: string;    // 预约人
  deptName: string;       // 部门名称
  subject: string;        // 会议主题
  startTime: string;      // 开始时间
  endTime: string;        // 结束时间
  bookingDate: string;    // 预约日期
  status: number;         // 状态
}

// 视图模式
const viewMode = ref<'date' | 'room'>('date');

// 会议室列表
const roomList = ref<ConferenceRoom[]>([]);

// 选中的会议室
const selectedRoom = ref<string>('');

// 选中的日期
const selectedDate = ref<string>('');

// 一周的日期
const weekDates = ref<string[]>([]);

// 预约数据
const bookings = ref<ConferenceBooking[]>([]);

// 时间段
const timeSlots = [
  '8:00', '8:30', '9:00', '9:30', '10:00', '10:30',
  '11:00', '11:30', '12:00', '12:30', '13:00', '13:30',
  '14:00', '14:30', '15:00', '15:30', '16:00', '16:30',
  '17:00', '17:30'
];

// 生成一周日期
function generateWeekDates(): void {
  const today = dayjs();
  const dates = Array.from({ length: 7 }, (_, i) => {
    return today.add(i, 'day').format('YYYY-MM-DD');
  });
  weekDates.value = dates;
  selectedDate.value = dates[0] ?? '';
}

// 获取预约数据
async function fetchBookings(): Promise<void> {
  try {
    if (viewMode.value === 'date') {
      // 先获取会议室列表
      const roomRes = await conferenceList();
      console.log(roomRes);
      
      // roomList.value = roomRes.rows || [];
      
      // // 然后获取每个会议室的预约信息
      // const bookingPromises = roomList.value.map(room => 
      //   roomBookingList({
      //     appointmentDate: selectedDate.value,
      //     bookingStatus: 2,
      //     reviewStatus: 1,
      //     tbConferenceId: room.id
      //   })
      // );
      
      // const bookingResults = await Promise.all(bookingPromises);
      // // 合并所有预约数据
      // bookings.value = bookingResults.flatMap(res => res.rows || []);
    } else {
      // 按会议室视图时直接查询该会议室的预约
      const res = await roomBookingList({
        appointmentDate: selectedDate.value,
        bookingStatus: 2,
        reviewStatus: 1,
        tbConferenceId: selectedRoom.value
      });
      bookings.value = res.rows || [];
    }
  } catch (error) {
    console.error('获取预约数据失败:', error);
  }
}

// 切换视图模式
function handleViewModeChange(e: RadioChangeEvent): void {
  viewMode.value = e.target.value;
  if (viewMode.value === 'date') {
    selectedDate.value = weekDates.value[0] ?? '';
  } else {
    selectedRoom.value = roomList.value[0]?.id ?? '';
  }
  fetchBookings();
}

// 切换日期
function handleDateChange(date: string): void {
  selectedDate.value = date;
  fetchBookings();
}

// 切换会议室
function handleRoomChange(value: SelectValue): void {
  selectedRoom.value = value as string;
  fetchBookings();
}

// 获取单元格预约信息
function getCellBooking(col: string, time: string): ConferenceBooking | undefined {
  if (viewMode.value === 'date') {
    const room = roomList.value.find(r => r.name === col);
    return bookings.value.find(b => 
      b.tbConferenceId === room?.id && 
      dayjs(b.startTime).format('HH:mm') === time
    );
  } else {
    return bookings.value.find(b => 
      dayjs(b.bookingDate).format('YYYY-MM-DD') === col && 
      dayjs(b.startTime).format('HH:mm') === time
    );
  }
}

// 修改渲染预约单元格的函数
function renderBookingCell(booking: ConferenceBooking) {
  return h('div', 
    { 
      class: 'booking-cell' 
    }, 
    [
      h('span', 
        { class: 'booking-user' }, 
        `预约人：${booking.bookingName}`
      ),
      h('span', 
        { class: 'booking-dept' }, 
        `单位：${booking.deptName}`
      ),
      h('span', 
        { class: 'booking-subject' }, 
        `主题：${booking.subject}`
      )
    ]
  );
}

// 表格列配置
interface TableRecord {
  time: string;
  key: string;
  [key: string]: any;
}

const columns = computed<TableColumnType<TableRecord>[]>(() => {
  const baseColumns: TableColumnType<TableRecord>[] = [{
    title: '时间',
    dataIndex: 'time',
    width: 100,
    fixed: 'left' as const
  }];

  const dynamicColumns: TableColumnType<TableRecord>[] = viewMode.value === 'date'
    ? roomList.value.map(room => ({
        title: room.name,
        dataIndex: room.id,
        width: 200,
        customRender: ({ record }) => {
          const booking = getCellBooking(room.name, record.time);
          return booking ? renderBookingCell(booking) : null;
        }
      }))
    : weekDates.value.map(date => ({
        title: dayjs(date).format('MM-DD'),
        dataIndex: date,
        width: 200,
        customRender: ({ record }) => {
          const booking = getCellBooking(date, record.time);
          return booking ? renderBookingCell(booking) : null;
        }
      }));

  return [...baseColumns, ...dynamicColumns];
});

// 表格数据
const tableData = computed<TableRecord[]>(() => {
  return timeSlots.map(time => ({
    time,
    key: time,
  }));
});

onMounted(() => {
  generateWeekDates();
  fetchBookings();
});
</script>

<template>
  <Page>
    <div class="conference-view">
      <!-- 顶部控制区 -->
      <div class="control-panel">
        <Radio.Group v-model:value="viewMode" @change="handleViewModeChange">
          <Radio.Button value="date">按日期</Radio.Button>
          <Radio.Button value="room">按会议室</Radio.Button>
        </Radio.Group>

        <!-- 按会议室视图的下拉选择 -->
        <Select
          v-if="viewMode === 'room'"
          v-model:value="selectedRoom"
          class="room-select"
          placeholder="请选择会议室"
          @change="handleRoomChange"
        >
          <Select.Option 
            v-for="room in roomList"
            :key="room.id"
            :value="room.id"
          >
            {{ room.name }}
          </Select.Option>
        </Select>

        <!-- 按日期视图的日期选择 -->
        <div v-if="viewMode === 'date'" class="date-buttons">
          <Button
            v-for="date in weekDates"
            :key="date"
            :type="date === selectedDate ? 'primary' : 'default'"
            @click="handleDateChange(date)"
          >
            {{ dayjs(date).format('MM-DD') }}
          </Button>
        </div>
      </div>

      <!-- 日程表格 -->
      <Table
        :columns="columns"
        :data-source="tableData"
        :pagination="false"
        bordered
        :scroll="{ x: 'max-content' }"
      />
    </div>
  </Page>
</template>

<style lang="scss" scoped>
.conference-view {
  padding: 16px;
  
  .control-panel {
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    
    .room-select {
      width: 200px;
      margin-left: 16px;
    }
  }
  
  .date-buttons {
    margin-top: 16px;
    
    :deep(.ant-btn) {
      margin-right: 8px;
      
      &:last-child {
        margin-right: 0;
      }
    }
  }
  
  .booking-cell {
    background: #e6f7ff;
    padding: 8px;
    border-radius: 4px;
    min-height: 60px;
    display: flex;
    flex-direction: column;
    gap: 4px;
    
    span {
      display: block;
      font-size: 12px;
      line-height: 1.5;
      
      &.booking-user {
        color: #1890ff;
        font-weight: 500;
      }
      
      &.booking-dept {
        color: #666;
      }
      
      &.booking-subject {
        color: #333;
      }
    }
    
    &:hover {
      background: #bae7ff;
    }
  }
}
</style>
