<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>
import store from '../../../store'
import { onMounted, reactive } from 'vue'
import { getAllDepartments } from '../../../api/appointment'
import router from '../../../router'
import Cookies from 'js-cookie'
export default {
  name: 'Appointment',
  setup() {
    const treeHeight = store.state.windowSize.h - 45 + 'px'
    const data = reactive({
      activeIndex: '',
      activeCode: '',
      depts: [],
      children: [],
      showPopup: false,
    })
    if (Cookies.get('activeIndex')) {
      data.activeIndex = Cookies.get('activeIndex')
    }
    const onConfirm = (val) => {
      Cookies.set('appointmentDeptCode', val.id)
      Cookies.set('appointmentDeptName', val.text)
      router.push('/selectDoctorAndDate/' + val.id + '/' + val.text)
    }
    const onCancel = () => {
      data.showPopup = false
      data.activeCode = ''
    }
    const handleSelectNav = (val) => {
      Cookies.set('activeIndex', 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)
      }
    }
    onMounted(() => {
      getAllDepartments().then((res) => {
        data.depts = res
      })
    })
    return {
      treeHeight,
      handleSelectNav,
      handleSelectDept,
      data,
      onConfirm,
      onCancel,
    }
  },
}
</script>