<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore, useInfoStore } from '@/stores'
import { timeUseService } from '@/api/information'
import { reservationSubmitService } from '@/api/reservation'
import { useRouter } from 'vue-router'
import { formatTime } from '@/utils/format'
import BaseLayout from '@/components/BaseLayout.vue'
import { ElMessage, ElButton } from 'element-plus'
const router = useRouter()
const userStore = useUserStore()
const infoStore = useInfoStore()
// 用户基本信息
const userInfo = ref({ ...userStore.user })
// 场馆及场地基本信息
const baseInfo = ref({ ...infoStore.info })
// 构建提交的表单信息
const formModel = ref({
  userId: 16,
  venueId: 74,
  times: [
    {
      id: 2,
      startTime: '13:00:00',
      endTime: '14:00:00'
    }
  ],
  reservationDate: '2025-03-07',
  money: 9
})

// 模拟数据
const venueData = ref([
  { id: 1, startTime: '08:00', endTime: '09:00', disabled: false },
  { id: 2, startTime: '09:00', endTime: '10:00', disabled: false },
  { id: 3, startTime: '10:00', endTime: '11:00', disabled: false },
  { id: 4, startTime: '11:00', endTime: '12:00', disabled: false },
  { id: 5, startTime: '12:00', endTime: '13:00', disabled: false },
  { id: 6, startTime: '13:00', endTime: '14:00', disabled: false },
  { id: 7, startTime: '14:00', endTime: '15:00', disabled: false },
  { id: 8, startTime: '15:00', endTime: '16:00', disabled: false },
  { id: 9, startTime: '16:00', endTime: '17:00', disabled: false },
  { id: 10, startTime: '17:00', endTime: '18:00', disabled: false }
])
// 加载可用时间段
const getVenueData = async (dataStr) => {
  const {
    data: { data, message }
  } = await timeUseService({
    reservationDate: dataStr,
    typeId: baseInfo.value.typeId,
    informationId: baseInfo.value.informationId
  })
  console.log('data', data)
  if (data === null) {
    ElMessage.info(message)
    venueData.value = []
  } else {
    venueData.value = data.times
  }
}
// 状态管理
const selectedDateIndex = ref(0)
const selectedTimes = ref([])
// const timeSlots = ref([...venueData])
const dateList = ref([])

// 初始化日期列表
const initDateList = () => {
  const result = []
  const today = new Date()

  for (let i = 0; i < 7; i++) {
    const date = new Date(today)
    date.setDate(today.getDate() + i)

    const dayOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][
      date.getDay()
    ]
    const month = date.getMonth() + 1
    const dateNum = date.getDate()
    result.push({
      dayOfWeek,
      month,
      date: dateNum,
      fullDate: date
    })
  }

  dateList.value = result
}

// 计算属性
const totalPrice = computed(() => {
  return selectedTimes.value.length * baseInfo.value.price
})

// 方法
const selectDate = (index) => {
  if (selectedDateIndex.value !== index) {
    selectedDateIndex.value = index
    selectedTimes.value = [] // 切换日期时重置已选时间段
    console.log(formatTime(dateList.value[index].fullDate))
    getVenueData(formatTime(dateList.value[index].fullDate))
    // 模拟根据日期加载不同的时间段数据
    console.log('Selected date:', dateList.value[index].fullDate)
    // 这里可以添加API请求逻辑
  }
}

const selectTime = (timeId) => {
  // 如果是取消选择，直接移除
  if (selectedTimes.value.includes(timeId)) {
    selectedTimes.value = selectedTimes.value.filter((id) => id !== timeId)
    return
  }

  // 添加新选择
  const newSelectedTimes = [...selectedTimes.value, timeId].sort(
    (a, b) => a - b
  )

  // 检查是否连续
  if (newSelectedTimes.length > 1) {
    let isContinuous = true
    for (let i = 1; i < newSelectedTimes.length; i++) {
      if (newSelectedTimes[i] - newSelectedTimes[i - 1] !== 1) {
        isContinuous = false
        break
      }
    }

    if (!isContinuous) {
      // 不连续，清除之前的选择，只保留当前选择
      selectedTimes.value = [timeId]
      ElMessage.warning('请选择连续的时间段，已自动清除之前的选择')
      return
    }
  }

  // 连续的，更新选择
  selectedTimes.value = newSelectedTimes
}

const getSelectedTimeDisplay = () => {
  if (selectedTimes.value.length === 0) return '未选择时间段'

  const selected = venueData.value.filter((time) =>
    selectedTimes.value.includes(time.id)
  )
  if (selected.length === 0) return '未选择时间段'

  // 按id排序
  selected.sort((a, b) => a.id - b.id)

  // 生成显示文本
  return selected.map((time) => `${time.startTime}-${time.endTime}`).join('、')
}
const selectedDateStr = ref('')
const getSelectedDateDisplay = () => {
  if (dateList.value.length === 0) return ''
  const date = dateList.value[selectedDateIndex.value]

  selectedDateStr.value = formatTime(date.fullDate)
  return `${date.month}月${date.date}日 ${date.dayOfWeek}${selectedDateIndex.value === 0 ? '（今天）' : ''}`
}

const submitBooking = () => {
  if (selectedTimes.value.length === 0) {
    ElMessage.warning('请选择预约时间段')
    return
  }
  ElMessageBox.confirm(
    `
    <div style="text-align: left;font-weight: 700">
      <p>您确认提交以下预约信息吗？</p>
      <p>用户：${userInfo.value.username}</p>
      <p>场馆：${baseInfo.value.typeName}</p>
      <p>场地：${baseInfo.value.informationName}</p>
      <p>预约日期：${selectedDateStr.value}</p>
      <p>预约时间段：${getSelectedTimeDisplay()}</p>
      <p>预约费用：${totalPrice.value.toFixed(2)} 元</p>
    </div>
  `,
    '确认预约',
    {
      confirmButtonText: '确认预约',
      cancelButtonText: '取消',
      type: 'none',
      dangerouslyUseHTMLString: true
    }
  )
    .then(async () => {
      // 调用预约接口
      formModel.value = {
        userId: userInfo.value.id,
        venueId: baseInfo.value.informationId,
        reservationDate: selectedDateStr.value,
        times: getSelectedTimeDisplay()
          .split('、')
          .map((slot, index) => {
            const [start, end] = slot.split('-')
            return { id: index + 1, startTime: start, endTime: end }
          }),
        money: totalPrice.value.toFixed(2)
      }
      const {
        data: { data }
      } = await reservationSubmitService(formModel.value)
      console.log(data)

      // 设置订单信息
      infoStore.setResponseInfo({
        user: userInfo.value.username,
        venue: baseInfo.value.typeName,
        site: baseInfo.value.informationName,
        date: selectedDateStr.value,
        timeSlots: getSelectedTimeDisplay(),
        cost: totalPrice.value.toFixed(2)
      })
      // 设置支付信息
      infoStore.setPaymentInfo(data)
      // 成功之后，将返回的订单信息传递给前端
      router.push('/mobile/result/success')
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '预约已取消'
      })
    })

  // 模拟提交预约
  console.log('提交预约:', formModel.value)

  ElMessage.success('预约提交成功，请在30分钟内完成支付')
}

const resetSelection = () => {
  selectedTimes.value = []
}

// 初始化
onMounted(() => {
  console.log(infoStore.info)
  initDateList()
  getVenueData(formatTime(new Date()))
})
</script>
<template>
  <BaseLayout>
    <div class="app-container">
      <!-- 主内容区 -->
      <main>
        <div class="content-container">
          <div class="booking-container">
            <!-- 左侧：预约选择区 -->
            <div class="booking-form">
              <h2 class="section-title">场馆预约</h2>

              <!-- 已选信息 -->
              <div class="selected-info">
                <h3 class="info-title">已选信息</h3>
                <div class="info-grid">
                  <div class="info-item">
                    <p class="info-label">场馆名称</p>
                    <p class="info-value">{{ baseInfo.typeName }}</p>
                  </div>
                  <div class="info-item">
                    <p class="info-label">场地名称</p>
                    <p class="info-value">{{ baseInfo.informationName }}</p>
                  </div>
                  <div class="info-item">
                    <p class="info-label">场地单价</p>
                    <p class="info-value">
                      ¥{{
                        baseInfo.price ? baseInfo.price.toFixed(2) : 0.0
                      }}/小时
                    </p>
                  </div>
                  <div class="info-item">
                    <p class="info-label">预约人</p>
                    <p class="info-value">{{ userInfo.username }}</p>
                  </div>
                </div>
              </div>

              <!-- 选择日期 -->
              <div class="date-selection">
                <h3 class="selection-title">选择日期</h3>
                <div class="date-grid">
                  <div
                    v-for="(dateItem, index) in dateList"
                    :key="index"
                    class="date-item"
                    :class="{
                      'date-item-selected': selectedDateIndex === index
                    }"
                    @click="selectDate(index)"
                  >
                    <div class="date-day">{{ dateItem.dayOfWeek }}</div>
                    <div class="date-date">
                      {{ dateItem.month }}月{{ dateItem.date }}日
                    </div>
                    <div v-if="index === 0" class="date-today">今天</div>
                  </div>
                </div>
              </div>

              <!-- 选择时间段 -->
              <div class="time-selection">
                <h3 class="selection-title">选择时间段（连续的时间段）</h3>
                <div class="time-grid">
                  <div v-if="venueData.length === 0">当前暂无可选时间段</div>
                  <div
                    v-for="time in venueData"
                    :key="time.id"
                    class="time-slot"
                    :class="{
                      'time-slot-selected': selectedTimes.includes(time.id),
                      'time-slot-disabled': time.disabled
                    }"
                    @click="!time.disabled && selectTime(time.id)"
                  >
                    {{ time.startTime }}-{{ time.endTime }}
                  </div>
                </div>
                <div
                  v-if="selectedTimes.length > 0"
                  class="selected-times-display"
                >
                  已选时间段: {{ getSelectedTimeDisplay() }}
                </div>
              </div>

              <!-- 操作按钮 -->
              <div class="action-buttons">
                <el-button
                  type="primary"
                  @click="submitBooking"
                  :disabled="selectedTimes.length === 0"
                  >确认预约</el-button
                >
                <el-button type="info" @click="resetSelection">重置</el-button>
                <el-button type="info" @click="router.go(-1)">返回</el-button>
              </div>
            </div>

            <!-- 右侧：订单信息 -->
            <div class="order-info">
              <h2 class="section-title">订单信息</h2>
              <div class="order-details">
                <div class="order-item">
                  <span class="order-label">场馆名称：</span>
                  <span class="order-value">{{ baseInfo.typeName }}</span>
                </div>
                <div class="order-item">
                  <span class="order-label">场地名称：</span>
                  <span class="order-value">{{
                    baseInfo.informationName
                  }}</span>
                </div>
                <div class="order-item">
                  <span class="order-label">预约日期：</span>
                  <span class="order-value">{{
                    getSelectedDateDisplay()
                  }}</span>
                </div>
                <div class="order-item">
                  <span class="order-label">预约时间：</span>
                  <span class="order-value">
                    <li
                      v-for="(slot, index) in getSelectedTimeDisplay().split(
                        '、'
                      )"
                      :key="index"
                    >
                      <el-tag type="success">{{ slot }}</el-tag>
                    </li>
                  </span>
                </div>
                <div class="order-item">
                  <span class="order-label">预约时长：</span>
                  <span class="order-value"
                    >{{ selectedTimes.length }}小时</span
                  >
                </div>
                <div class="order-item total">
                  <span class="order-label">订单总价：</span>
                  <span class="order-value total-price"
                    >¥{{ totalPrice.toFixed(2) }}</span
                  >
                </div>
              </div>
              <div class="order-notes">
                <p class="note">* 预约成功后，请在30分钟内完成支付</p>
                <p class="note">* 如需取消预约，请提前24小时操作</p>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  </BaseLayout>
</template>
<style scoped>
/* 全局样式 */
.app-container {
  background-color: #f9fafb;
  min-height: 100vh;
  font-family: 'Inter', sans-serif;
}
li {
  text-decoration: none;
  list-style: none;
  margin-bottom: 3px;
}
/* 头部样式 */
header {
  background-color: #ffffff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.header-content {
  max-width: 1280px;
  margin: 0 auto;
  padding: 16px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo-section {
  display: flex;
  align-items: center;
}

.main-title {
  color: #165dff;
  font-size: 20px;
  font-weight: bold;
  margin-right: 8px;
}

.divider {
  color: #94a3b8;
  margin-right: 8px;
}

.sub-title {
  color: #64748b;
  font-size: 14px;
  font-weight: 500;
}

.user-section {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #e2e8f0;
}

.user-name {
  margin-left: 8px;
  color: #334155;
  font-weight: 500;
}

.user-icon {
  margin-left: 4px;
  color: #94a3b8;
}

/* 主内容区样式 */
main {
  max-width: 1280px;
  margin: 0 auto;
  padding: 32px 24px;
}

.content-container {
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow:
    0 4px 6px -1px rgba(0, 0, 0, 0.1),
    0 2px 4px -1px rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

.booking-container {
  display: grid;
  grid-template-columns: 2fr 1fr;
}

/* 左侧表单样式 */
.booking-form {
  padding: 32px;
  border-right: 1px solid #e2e8f0;
}

.section-title {
  font-size: 20px;
  font-weight: bold;
  color: #1e293b;
  margin-bottom: 24px;
}

.selected-info {
  background-color: #f8fafc;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 24px;
}

.info-title {
  font-weight: 500;
  color: #475569;
  margin-bottom: 16px;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.info-item {
  display: flex;
  flex-direction: column;
}

.info-label {
  font-size: 12px;
  color: #64748b;
  margin-bottom: 4px;
}

.info-value {
  font-weight: 500;
  color: #1e293b;
}

.date-selection,
.time-selection {
  margin-top: 20px;
  margin-bottom: 24px;
}

.selection-title {
  font-weight: 500;
  color: #475569;
  margin-bottom: 12px;
}

.date-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 8px;
}

.date-item {
  background-color: #f1f5f9;
  border-radius: 8px;
  padding: 12px 0;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
}

.date-item:hover {
  background-color: #e2e8f0;
}

.date-item-selected {
  background-color: #165dff;
  color: white;
}

.date-day {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 4px;
}

.date-date {
  font-size: 12px;
}

.date-today {
  position: absolute;
  top: -8px;
  right: -8px;
  background-color: #ef4444;
  color: white;
  font-size: 10px;
  padding: 2px 4px;
  border-radius: 4px;
}

.time-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 8px;
}

.time-slot {
  background-color: #f1f5f9;
  border-radius: 6px;
  padding: 8px 4px;
  text-align: center;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.time-slot:hover:not(.time-slot-disabled) {
  background-color: #e2e8f0;
}

.time-slot-selected {
  background-color: #165dff;
  color: white;
}

.time-slot-disabled {
  background-color: #f8fafc;
  color: #cbd5e1;
  cursor: not-allowed;
}

.selected-times-display {
  margin-top: 12px;
  font-size: 14px;
  color: #64748b;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 右侧订单信息样式 */
.order-info {
  padding: 32px;
  background-color: #f8fafc;
}

.order-details {
  background-color: #ffffff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 24px;
}

.order-item {
  display: flex;
  padding: 8px 0;
  border-bottom: 1px solid #f1f5f9;
}

.order-item:last-child {
  border-bottom: none;
}

.order-label {
  flex: 1;
  color: #64748b;
}

.order-value {
  flex: 1;
  text-align: right;
  font-weight: 500;
  color: #1e293b;
}

.total {
  margin-top: 8px;
}

.total-price {
  color: #ef4444;
  font-weight: bold;
}

.order-notes {
  font-size: 12px;
  color: #94a3b8;
}

.note {
  margin-bottom: 4px;
}

/* Element UI 组件样式调整 */
.el-button {
  padding: 8px 16px;
}
</style>
