<template>
  <window-size>
    <van-grid :column-num="1" :center="false">
      <van-grid-item>
        <div style="display: flex">
          <van-image
            round
            fit="cover"
            width="60px"
            height="80px"
            :src="'data:image/png;base64,' + data.doctorInfo.portrait"
          />
          <div style="min-width: 60%">
            <van-cell center :title="data.doctorInfo.doctorName">
              <template #label>
                <div>{{ data.doctorInfo.deptName }}</div>
                <div>{{ data.doctorInfo.doctorTitle }}</div>
              </template>
            </van-cell>
          </div>
          <div>
            <div style="height: 5px"></div>
            <van-button type="primary" plain size="small" :icon="collected.icon" @click="collectAction">
              {{ collected.text }}
            </van-button>
            <div style="height: 5px"></div>
            <van-button type="primary" plain size="small" icon="qr" @click="showDoctorQrCode">二维码</van-button>
          </div>
        </div>
      </van-grid-item>
    </van-grid>
    <van-collapse v-model="data.activeCollapse">
      <van-collapse-item title="介绍" name="1">
        <div style="color: #333333; margin-top: 10px">简介</div>
        {{ data.doctorInfo.introduction }}
        <div style="color: #333333; margin-top: 10px">擅长</div>
        {{ data.doctorInfo.specialty }}
      </van-collapse-item>
      <div id="noPadding">
        <van-collapse-item title="挂号" name="2">
          <van-collapse v-model="data.activeDate" accordion>
            <van-collapse-item :title="getSelectDate" name="dateSelection" value="更多日期">
              <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
                      :type="getType(index)"
                      size="small"
                      round
                      @click="handleClickDate(index)"
                      :disabled="hasSource(index) === '无'"
                      >{{ item.date }}</van-button
                    >
                  </van-badge>
                </van-grid-item>
              </van-grid>
            </van-collapse-item>
          </van-collapse>
          <div v-for="item in data.arrangements" :key="item.mzyRequestId" @click="toAppointConfirm(item)">
            <van-cell center :title="item.ampm" is-link>
              <template #label>
                <span v-html="hasLeftNum(item.leftNum)"></span>
              </template>
              <template #default>
                <span style="color: orangered">￥{{ item.fee }}</span>
              </template>
            </van-cell>
          </div>
        </van-collapse-item>
      </div>
    </van-collapse>
    <van-popup v-model:show="data.showQr" closeable position="bottom" :style="{ height: '300px' }">
      <van-grid :border="false" :column-num="1">
        <van-grid-item>
          <van-image fit="fill" style="width: 240px; height: 240px" :src="data.qrcode" />
          <span style="color: orangered; font-size: 12px; margin-top: 5px">长按二维码识别或保存</span>
        </van-grid-item>
      </van-grid>
    </van-popup>
    <van-empty :image="empty" v-show="data.arrangements.length === 0" description="暂未获取到医生排班信息" />
  </window-size>
</template>

<script>
import empty from '../../../assets/empty.png'
import store from '../../../store'
import { useRouter } from 'vue-router'
import { computed, onMounted, reactive } from 'vue'
import {
  getDoctorInfo,
  getSourcesByDateAndDoctor,
  getDoctorArrangement,
  getDoctorQrCode,
} from '../../../api/appointment'
import { collectDoctor, disCollectDoctor } from '../../../api/my-collection'
import { getLocalOpenId } from '../../../utils/check-patient-id'
import { genTextPortrait } from '../../../utils/portrait'
import { getOneWeekText, getNextSevenDate } from '../../../utils/date'
import { Toast } from 'vant'
import Cookies from 'js-cookie'
export default {
  name: 'DoctorArangement',
  setup() {
    const router = useRouter()
    const deptCode = router.currentRoute.value.params.dept
    const doctorCode = router.currentRoute.value.params.doctor
    const date = router.currentRoute.value.params.date
    const data = reactive({
      activeCollapse: ['1', '2'],
      activeDate: '',
      doctorInfo: {},
      arrangements: [],
      showQr: false,
      date: date,
      currentIndex: 0,
      oneWeekText: getOneWeekText(),
      nextSevenDate: getNextSevenDate(),
      nextSevenDaySources: new Array(7).fill(4001),
      qrcode: '',
    })
    const toAppointConfirm = (item) => {
      item.deptCode = Cookies.get('appointmentDeptCode')
      item.deptName = Cookies.get('appointmentDeptName')
      item.date = data.date
      store.commit('SET_APPOINTMENTINFO', item)
      router.push('/appointmentConfirm')
    }
    const collected = computed(() => {
      const icon = data.doctorInfo.collected > 0 ? 'star' : 'star-o'
      const text = data.doctorInfo.collected > 0 ? '已收藏' : '未收藏'
      return { icon, text }
    })

    const openId = getLocalOpenId()
    const collectAction = () => {
      const param = {
        openId,
        doctorCode,
        deptCode,
      }
      if (data.doctorInfo.collected === 0) {
        collectDoctor(param).then(() => {
          Toast.success('已收藏')
          getDoctorInfo(doctorCode, openId).then((res) => {
            data.doctorInfo = res
            if (!res.portrait) {
              data.doctorInfo.portrait = genTextPortrait(res.doctorName)
            }
          })
        })
      } else {
        disCollectDoctor(param).then(() => {
          Toast.success('已取消收藏')
          getDoctorInfo(doctorCode, openId).then((res) => {
            data.doctorInfo = res
            if (!res.portrait) {
              data.doctorInfo.portrait = genTextPortrait(res.doctorName)
            }
          })
        })
      }
    }
    const getSelectDate = computed(() => {
      return data.date
    })
    const getType = (index) => {
      return index === data.currentIndex ? 'primary' : 'default'
    }
    const hasSource = (index) => {
      return data.nextSevenDaySources[index] === 200 ? '有' : '无'
    }
    const badgeColor = (index) => {
      return data.nextSevenDaySources[index] === 200 ? 'green' : 'red'
    }
    const hasLeftNum = (val) => {
      return val > 0
        ? '<span style="font-size: 12px;color:green">有号</span>'
        : '<span style="font-size: 12px;color:red">无号</span>'
    }
    const handleClickDate = (index) => {
      if (index > 6) {
        return
      }
      data.currentIndex = index
      data.date = data.nextSevenDate[index].fullDate
      const param = {
        date: data.date,
        deptCode: deptCode,
        doctorCode: doctorCode,
      }
      getDoctorArrangement(param)
        .then((res) => {
          data.arrangements = res
        })
        .catch(() => {
          handleClickDate(++index)
        })
    }

    const showDoctorQrCode = () => {
      getDoctorQrCode(doctorCode).then((res) => {
        data.qrcode = res
        data.showQr = true
      })
    }

    onMounted(() => {
      getDoctorInfo(doctorCode, openId).then((res) => {
        data.doctorInfo = res
        if (!res.portrait) {
          data.doctorInfo.portrait = genTextPortrait(res.doctorName)
        }
      })
      const param = {
        date: data.nextSevenDate[0].fullDate,
        deptCode: deptCode,
        doctorCode: doctorCode,
      }
      getSourcesByDateAndDoctor(param).then((res) => {
        data.nextSevenDaySources = res
        for (let i = 0; i < 7; i++) {
          if (data.nextSevenDate[i].fullDate === date) {
            handleClickDate(i)
          }
        }
      })
    })
    return {
      empty,
      data,
      collected,
      collectAction,
      toAppointConfirm,
      getSelectDate,
      getType,
      hasSource,
      badgeColor,
      handleClickDate,
      showDoctorQrCode,
      hasLeftNum,
    }
  },
}
</script>

<style>
#noPadding .van-collapse-item__content {
  padding: 0;
}
</style>