<template>
  <window-size>
    <van-grid direction="horizontal" :column-num="7">
      <van-grid-item v-for="item in data.oneWeekText" :key="item" :text="'周' + item" />
    </van-grid>
    <van-grid direction="horizontal" :column-num="7">
      <van-grid-item v-for="(item, index) in data.nextSevenDate" :key="index">
        <van-badge :content="hasSource(index)" :color="badgeColor(index)">
          <van-button
            :disabled="disabledBtn(index)"
            :type="getType(index)"
            size="small"
            round
            @click="handleClickDate(index)"
            >{{ item.date }}</van-button
          >
        </van-badge>
      </van-grid-item>
    </van-grid>
    <div style="height: 5px"></div>
    <van-tag type="primary" plain style="margin-left: 5px">{{ data.dateSelected }}</van-tag>
    <div style="height: 5px"></div>
    <van-empty description="暂无可预约项目" v-if="currentSources.length === 0" />
    <div v-else :style="scrollStyle">
      <van-cell
        v-for="(item, index) in currentSources"
        :key="index"
        title="执行时间"
        :value="item.deptName"
        :label="item.beginTime + ' - ' + item.endTime"
        is-link
        center
        @click="routeToBookDetail(item)"
      ></van-cell>
    </div>
  </window-size>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import router from '@/router'
import { getFullScheduleOfMedicalForPlatform } from '@/api/bookable'
import { getOneWeekText, getNextSevenDate } from '@/utils/date'
import store from '@/store'

const screenSize = store.state.screenSize
const scrollStyle = {
  height: screenSize.h - 190 + 'px',
  overflowY: 'auto',
}
const bookItem = store.state.currentBook
const currentSources = ref([])
const data = reactive({
  currentIndex: 0,
  oneWeekText: getOneWeekText(),
  nextSevenDate: getNextSevenDate(),
  sources: {},
  statuses: [],
  dateSelected: '',
})
const getType = (index) => {
  return index === data.currentIndex ? 'primary' : 'default'
}
const hasSource = (index) => {
  return data.statuses[index] === 1 ? '有' : '无'
}
const badgeColor = (index) => {
  return data.statuses[index] === 1 ? 'green' : 'red'
}
const disabledBtn = (index) => {
  return data.statuses[index] === 0
}
const handleClickDate = (index) => {
  data.currentIndex = index
  data.dateSelected = data.nextSevenDate[index].fullDate
  currentSources.value = data.sources[data.dateSelected] || []
}

const routeToBookDetail = (item) => {
  bookItem.recordDate = item.recordDate
  bookItem.beginTime = item.beginTime
  bookItem.endTime = item.endTime
  bookItem.id = item.id
  router.push('/bookExam')
}

onMounted(() => {
  getFullScheduleOfMedicalForPlatform(bookItem.execUnit).then((res) => {
    data.sources = res.sources
    data.statuses = res.statuses
    for (let i = 0; i < 7; i++) {
      handleClickDate(i)
      if (res.statuses[i] === 1) {
        break
      }
    }
  })
})

</script>