<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>
        <van-text-ellipsis
            rows="3"
            :content="data.doctorInfo.introduction"
            expand-text="展开"
            collapse-text="收起"
        />
        <div style="color: #333333; margin-top: 10px">擅长</div>
        <van-text-ellipsis
            rows="3"
            :content="data.doctorInfo.specialty"
            expand-text="展开"
            collapse-text="收起"
        />
      </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="beforeConfirmAppointment(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="暂未获取到医生排班信息" />
    <van-action-sheet v-model:show="showTimeSections" title="请选择">
      <div style="padding: 16px 16px 30px">
        <van-radio-group v-model="currentAppointmentItem.apTime">
          <van-cell-group inset>
            <van-cell v-for="obj in timeSections" :title="'时段：' +　obj.apValue" :value="'余号：' + obj.apLeftNum" clickable
                      @click="currentAppointmentItem.apTime = obj.apTime;currentAppointmentItem.apValue = obj.apValue"
                      value-class="need-padding">
              <template #right-icon>
                <van-radio :name="obj.apTime" :disabled="obj.apLeftNum === '0'"/>
              </template>
            </van-cell>
          </van-cell-group>
        </van-radio-group>
        <van-button style="margin-top: 20px" block type="primary" @click="toConfirmAppointment"
                    :disabled="!currentAppointmentItem.apTime">确认</van-button>
      </div>
    </van-action-sheet>

    <div style="margin-top: 8px; background: white">
      <van-cell title="患者评价" value="查看全部" is-link @click="handleClickShowAllComments"></van-cell>
      <div style="margin-top: 8px" v-for="item in fewComments">
        <div style="position: relative; display: flex; align-items: center; font-size: 12px; padding: 0 16px">
          <div style="color: rgb(128,128,128)">{{ item.fuzzyName }}</div>
          <div style="margin-left: 8px">
            <van-rate
                v-model="item.commentLevel"
                :size="15"
                color="#ffd21e"
                void-icon="star"
                void-color="#eee"
            />
          </div>
          <div style="color: rgb(128,128,128); position: absolute; right: 20px">
            {{ item.commentTime }}
          </div>
        </div>
        <div style="padding: 8px 16px; font-size: 12px; color: black">
          {{ item.commentContent }}
        </div>
      </div>
    </div>

    <van-action-sheet v-model:show="showAllComments" title="患者评价">
      <van-list
          v-model:loading="commentLoading"
          :finished="allComments.finished"
          finished-text="没有更多了"
          :offset="100"
          @load="onCommentLoad">
        <div style="margin-top: 8px; border-bottom: 1px solid lightgray" v-for="item in allComments.list">
          <div style="position: relative; display: flex; align-items: center; font-size: 12px; padding: 0 16px">
            <div style="color: rgb(128,128,128)">{{ item.fuzzyName }}</div>
            <div style="margin-left: 8px">
              <van-rate
                  v-model="item.commentLevel"
                  :size="15"
                  color="#ffd21e"
                  void-icon="star"
                  void-color="#eee"
              />
            </div>
            <div style="color: rgb(128,128,128); position: absolute; right: 20px">
              {{ item.commentTime }}
            </div>
          </div>
          <div style="padding: 8px 16px; font-size: 12px; color: black">
            {{ item.commentContent }}
          </div>
        </div>
      </van-list>
    </van-action-sheet>

  </window-size>
</template>

<script setup>
import empty from '../../../assets/empty.png'
import store from '../../../store'
import { useRouter } from 'vue-router'
import { computed, onMounted, reactive, ref } 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 { showToast } from 'vant'
import {fetchDoctorComments} from "../../../api/comment";
import Cookies from 'js-cookie'

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 currentAppointmentItem = ref({})
const timeSections = ref([])
const showTimeSections = ref(false)
const amSectionLabel = [
  {apTime: 'a1', apValue: '08:00-08:30'},
  {apTime: 'a2', apValue: '08:30-09:00'},
  {apTime: 'a3', apValue: '09:00-09:30'},
  {apTime: 'a4', apValue: '09:30-10:00'},
  {apTime: 'a5', apValue: '10:00-10:30'},
  {apTime: 'a6', apValue: '10:30-11:00'},
  {apTime: 'a7', apValue: '11:00-11:30'},
  {apTime: 'a8', apValue: '11:30-12:00'}]
const pmSectionLabel = [
  {apTime: 'p1', apValue: '14:00-14:30'},
  {apTime: 'p2', apValue: '14:30-15:00'},
  {apTime: 'p3', apValue: '15:00-15:30'},
  {apTime: 'p4', apValue: '15:30-16:00'},
  {apTime: 'p5', apValue: '16:00-16:30'},
  {apTime: 'p6', apValue: '16:30-17:00'},
  {apTime: 'p7', apValue: '17:00-17:30'},
]
const beforeConfirmAppointment = (item) => {
  currentAppointmentItem.value = item
  currentAppointmentItem.value.deptCode = Cookies.get('appointmentDeptCode')
  currentAppointmentItem.value.deptName = Cookies.get('appointmentDeptName')
  currentAppointmentItem.value.date = data.date
  currentAppointmentItem.value.week = weekText.value
  if (item.ampm !== '上午' && item.ampm !== '下午') {
    toConfirmAppointment()
  } else {
    timeSections.value = []
    const sectionLabels = item.ampm === '上午' ? amSectionLabel : pmSectionLabel
    sectionLabels.forEach(section => {
      let temp = { apTime: section.apTime, apValue: section.apValue, apLeftNum: item[section.apTime]}
      if (temp.apLeftNum !== null && temp.apLeftNum !== undefined) {
        timeSections.value.push(temp)
      }
    })
    showTimeSections.value = true
  }
}

const toConfirmAppointment = () => {
  store.commit('SET_APPOINTMENTINFO', currentAppointmentItem.value)
  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(() => {
      showToast({
        message: '已收藏',
        position: 'top'
      })
      getDoctorInfo(doctorCode, openId).then((res) => {
        data.doctorInfo = res
        if (!res.portrait) {
          data.doctorInfo.portrait = genTextPortrait(res.doctorName)
        }
      })
    })
  } else {
    disCollectDoctor(param).then(() => {
      showToast({
        message: '已取消收藏',
        position: 'top'
      })
      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 weekText = ref('')
const handleClickDate = (index) => {
  if (index > 6) {
    return
  }
  weekText.value = '星期' + data.oneWeekText[index]
  data.currentIndex = index
  data.date = data.nextSevenDate[index].fullDate
  const param = {
    date: data.date,
    deptCode: deptCode,
    doctorCode: doctorCode,
    needExcludePassedTime: true,
  }
  getDoctorArrangement(param).then((res) => {
    data.arrangements = res
  }).catch(() => {
    handleClickDate(++index)
  })
}

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

const fewComments = ref([])
const showAllComments = ref(false)
const commentLoading = ref(false);
const allComments = reactive({
  finished: false,
  minId: null,
  list: []
})

const handleClickShowAllComments = () => {
  showAllComments.value = true
  onCommentLoad()
}
const onCommentLoad = () => {
  if (allComments.finished) {
    return
  }
  fetchDoctorComments({doctorCode: doctorCode, pageSize: 20, minId: allComments.minId}).then(res => {
    allComments.minId = res.minId
    allComments.finished = res.finished
    allComments.list = allComments.list.concat(res.list)
    commentLoading.value = false;
  })
};


onMounted(() => {
  getDoctorInfo(doctorCode, openId).then((res) => {
    data.doctorInfo = res
    if (!res.portrait) {
      data.doctorInfo.portrait = genTextPortrait(res.doctorName)
    }
  })

  fetchDoctorComments({doctorCode}).then(res => {
    fewComments.value = res.list
  })

  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)
      }
    }
  })
})

</script>

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