<template>
  <window-size>
    <van-field v-model="searchContent" label="检索" placeholder="请输入项目名称" left-icon="search"></van-field>
    <van-empty v-if="examItems.length === 0" description="暂时没有可以预约的项目"></van-empty>
    <div v-else>
      <div :style="scrollStyle">
        <van-cell
          v-for="item in cptExamItems.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
          :key="item.code"
          :title="item.name"
          is-link
          :value="item.execUnitName"
          @click="routeToSelectDate(item)"
        ></van-cell>
      </div>
      <van-pagination v-model="currentPage" :total-items="cptExamItems.length" :items-per-page="10" />
    </div>
  </window-size>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import { getBookableData } from '@/api/bookable'
import router from '@/router'
import store from '@/store'

const screenSize = store.state.screenSize
const scrollStyle = {
  marginTop: '4px',
  height: screenSize.h - 140 + 'px',
  overflowY: 'auto',
}
const currentPage = ref(1)
const pageSize = 20
const flag = router.currentRoute.value.params.flag
const patientId = router.currentRoute.value.params.patientId
const tableName = flag === 'jc' ? 'jc_zd_item' : 'jy_zd_item'
const searchContent = ref('')
const examItems = ref([])
const cptExamItems = computed(() => {
  return examItems.value.filter((item) => {
    return item.name.indexOf(searchContent.value) !== -1
  })
})

function getPatientNameByPatientId(patientId) {
  const cards = store.getters.patientCards
  for (let i = 0; i < cards.length; i++) {
    if (cards[i].patientId === patientId) {
      return cards[i].name
    }
  }
}

const routeToSelectDate = (item) => {
  item.patientId = patientId
  item.patientName = getPatientNameByPatientId(patientId)
  item.tableName = tableName
  store.dispatch({
    type: 'storeCurrentBookItem',
    bookItem: item
  }).then(() => {
    router.push('/selectBookDate')
  })
}
onMounted(() => {
  getBookableData(tableName).then((res) => {
    examItems.value = res
  })
})

</script> 