<script setup lang="ts">
import { sceneBookingApi } from '@/api/api/sceneBooking'
import router from '@/router'
import { useStore } from '@/stores'
import { showToast } from 'vant'

const dateArray = ref([] as any)
const store = useStore()

const getFutureDates = (numDays: number) => {
  const datesArray = []
  const today = new Date()
  const dateFormat = 'yyyy-MM-dd 星期X' // 新增星期格式

  for (let i = 0; i <= numDays; i++) {
    const futureDate = new Date(today.getTime())
    futureDate.setDate(today.getDate() + i)
    const formattedDate = formatDate(futureDate, dateFormat)
    datesArray.push({
      date: formattedDate,
      isDisabled: false
    })
  }
  return datesArray
}

const formatDate = (date: any, format: any) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const weekDay = getWeekDay(date)

  return format.replace('yyyy', year).replace('MM', month).replace('dd', day).replace('X', weekDay)
}

const getWeekDay = (date: any) => {
  const daysOfWeek = ['日', '一', '二', '三', '四', '五', '六']
  return daysOfWeek[date.getDay()]
}

const selectDate = ref('' as string)
const selectTime = ref('' as string)
const selectId = ref('' as string)

const bookingTimeList = ref([] as any)
const disableTimeList = ref([] as any)

const noticeText = ref('' as any)

// 获得可预约时间段
const getBookingTime = async () => {
  const res: any = await sceneBookingApi.getBookingTimeAPI(selectDate.value.slice(0, 10))
  if (res.code == 0) {
    bookingTimeList.value = res.data.time.map((v:any)=>({
      ...v,
      lastTime:v.time.split('-')[1]
    }))
    disableTimeList.value = res.data.stopDate
    noticeText.value = res.data.notice

    console.log(noticeText.value)
  } else {
    showToast(res.msg)
  }
}

watch(selectDate, () => {
  // 获取time
  getBookingTime()
})

watch(
  disableTimeList,
  (newVal: any) => {
    dateArray.value = dateArray.value.map((item: any) => {
      return {
        ...item,
        isDisabled: disableTimeList.value.includes(item.date.slice(0, 10))
      }
    })
    let today = selectDate.value.slice(0, 10)
    if (newVal.includes(today)) {
      const newDate = dateArray.value.find((item: any) => {
        return item.isDisabled == false
      })
      selectDate.value = newDate.date
      console.log(selectDate.value)
    }
  },
  { immediate: true }
)

const selectDateFu = (item: any) => {
  if (item.isDisabled) {
    showToast('该日期不可预约，请选择其他日期')
  } else {
    selectDate.value = item.date
    selectTime.value = ''
    selectId.value = ''
  }
}

const selectTimeFu = (item: any) => {
  // router.go(0)
  if (item.pcs <= 0) {
    showToast('该时段预约已满，请选择其他时段进行预约')
  } else {
    selectTime.value = item.time
    selectId.value = item.id
  }
}

const goInpitInfo = async () => {
  const res: any = await sceneBookingApi.getBookingTimeAPI(selectDate.value.slice(0, 10))
  if (res.code == 0) {
    const selectTimeItem = res.data.time.filter((item: any) => {
      return item.time === selectTime.value
    })
    if (selectTimeItem.length > 0 && selectTimeItem[0].pcs > 0) {
      store.selectDate = selectDate.value
      store.selectTime = selectTime.value
      store.selectId = selectId.value
      router.push({ name: 'bookInputInfo' })
    } else {
      router.go(0)
    }
  } else {
    showToast(res.msg)
  }
}

onMounted(() => {
  dateArray.value = getFutureDates(13)
  if (store.selectDate != '' && store.selectTime != '') {
    selectDate.value = store.selectDate
    selectTime.value = store.selectTime
  } else {
    selectDate.value = dateArray.value[0].date
  }
})


// 获取当前时间小时，比较时间
const nowTime =(lastTime:string)=>{
  let d = new Date();
  let t =d.getHours()

  let aa =Number(lastTime.split(':')[0])
  return t<aa
  
}
</script>

<template>
  <div class="time-box">
    <div class="date-select-box">
      <div
        class="date-select-item"
        v-for="(item, index) in dateArray"
        :key="index"
        :class="{ active: item.date === selectDate, disAble: item.isDisabled }"
        @click="selectDateFu(item)"
      >
        {{ item.date.slice(5) }}
      </div>
    </div>
    <div class="time-select-box">
      <div
        class="time-select-item"
        v-for="(item, index) in bookingTimeList"
        :key="index"
        :class="{ active: item.time === selectTime,noAc:!nowTime(item.lastTime) }"
        :style="{ color: item.pcs <= 0 ? '#9D4F0B' : '' }"
        @click="
          () => {
            selectTimeFu(item)
          }
        "
      >
        <div>{{ item.time }}</div>
        <div>{{nowTime(item.lastTime)?item.pcs <= 0 ? `预约已满` : `剩余${item.pcs}`:'超过预约时间' }}</div>
      </div>

      <div class="notice-box" v-html="noticeText"></div>
    </div>
    <div class="online-box" v-if="selectDate != '' && selectTime != ''" @click="goInpitInfo()">
      发起预约
    </div>
  </div>
</template>

<style lang="less" scoped>
.time-box {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: start;
  align-items: center;
  background: #f1e9d4;
  margin: 0;
  box-sizing: border-box;
  font-family: 'SourceHanSansCN-Regular';
  max-width: 500px;
  position: relative;
  overflow: auto;

  .date-select-box {
    width: 35%;
    height: 100%;
    overflow: auto;

    .date-select-item {
      width: 100%;
      height: 80px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #88866f;
      margin-bottom: 3px;
      background: #f7f3e8;
    }

    .active {
      background: #e4dcc5;
      color: #333333;
    }


    .disAble {
      background: #e4dcc5;
      color: rgba(51, 51, 51, 0.2);
    }
  }

  .time-select-box {
    width: 65%;
    height: 100%;
    overflow: auto;
    padding: 15px;
    box-sizing: border-box;

    .time-select-item {
      width: 100%;
      height: 50px;
      background: #f7f3e8;
      border-radius: 5px;
      color: #88866f;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 15px;
      box-sizing: border-box;
      margin-bottom: 20px;
    }

    .active {
      background: #e4dcc5;
      color: #333333;
    }
    .noAc{
      opacity: .5;
      pointer-events: none;
    }
    .notice-box {
      width: 100%;
      white-space: pre-wrap;
      color: #88866fad;
    }
  }
}

.online-box {
  width: 80%;
  max-width: 400px;
  height: 60px;
  border-radius: 50px;
  background: url(@/assets/images/onlineBg.png);
  background-size: 100% 100%;
  color: #f1e9d4;
  position: fixed;
  left: 50%;
  transform: translateX(-50%);
  bottom: 3vh;
  display: flex;
  justify-content: center;
  align-items: center;
  letter-spacing: 2px;
  font-weight: bold;
  z-index: 2;
}
</style>
