import router from '../router'
import store from '../store'
import { getPatientIdByOpenId } from '../api/patient-id-cards'
import { Dialog } from 'vant'
import Cookies from 'js-cookie'

export function checkPatientId() {
  const openId = getLocalOpenId()
  if (!openId) {
    return
  }
  getPatientIdByOpenId(openId).then((res) => {
    if (res.length > 0) {
      store.commit('SET_PATIENTCARDS', res)
    } else {
      setTimeout(() => {
        Dialog.alert({
          title: '提示',
          message: '您的就诊人为空，请前往添加。',
        }).then(() => {
          router.push('/myPatientIdCards')
        })
      }, 100)
    }
  })
}

export function getLocalOpenId() {
  let openId = Cookies.get('openId')
  openId = openId ? openId : localStorage.openId
  return openId
}

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