<template>
    <window-size>
        <van-tree-select
                v-model:active-id="data.activeCode"
                v-model:main-active-index="data.activeIndex"
                :height="treeHeight"
                :items="data.depts"
                @click-nav="handleSelectNav"
                @click-item="handleSelectDept"
        />
        <van-popup v-model:show="data.showPopup" position="bottom" :style="{ height: '50%' }">
            <van-picker title="选择子科室" :columns="data.children" @confirm="onConfirm" @cancel="onCancel" />
        </van-popup>
    </window-size>
</template>

<script setup>
import store from '@/store'
import { onMounted, reactive } from 'vue'
import { getAllNightDepartments } from '@/api/appointment.js'
import router from '@/router'
import Cookies from 'js-cookie'

const treeHeight = store.state.screenSize.h - 45 + 'px'
const data = reactive({
  activeIndex: '',
  activeCode: '',
  depts: [],
  children: [],
  showPopup: false,
})
if (Cookies.get('activeNightIndex')) {
  data.activeIndex = Cookies.get('activeNightIndex')
}
const onConfirm = (val) => {
  let id = val.selectedOptions[0].id
  let text = val.selectedOptions[0].text
  Cookies.set('appointmentDeptCode', id)
  Cookies.set('appointmentDeptName', text)
  router.push('/selectDoctorAndDate/' + id + '/' + text + '/yes')
}
const onCancel = () => {
  data.showPopup = false
  data.activeCode = ''
}
const handleSelectNav = (val) => {
  Cookies.set('activeNightIndex', val)
}
const handleSelectDept = (val) => {
  if (val.children) {
    data.children = val.children
    data.showPopup = true
  } else {
    Cookies.set('appointmentDeptCode', val.id)
    Cookies.set('appointmentDeptName', val.text)
    router.push('/selectDoctorAndDate/' + val.id + '/' + val.text + '/yes')
  }
}
onMounted(() => {
  getAllNightDepartments().then((res) => {
    data.depts = res
  })
})
</script>
