<template>
  <window-size :show-back-nav="false">
    <div v-if="isWxBrowser" id="weixin-tip">
      <p>
        <img style="width:82%" :src="leaveWx" alt="微信打开"/><span id="close" title="关闭" class="close">×</span>
      </p>
    </div>
    <div v-else>
      <van-field v-model="idCard" center label="身份证" placeholder="请输入身份证">
        <template #button>
          <van-button size="small" type="primary" icon="search" @click="handleClickSearch">查询</van-button>
        </template>
      </van-field>
      <van-list :style="listBoxStyle" id="listWrapper" v-model:loading="listLoading" :finished="listFinished" finished-text="没有更多了" @load="onLoadingList">
        <van-cell v-for="item in examIndexes" :key="item['条码号']" :title="item['工作单位']" :value="item['checkTime']"
                  center clickable @click="handleClickIndex(item)"></van-cell>
      </van-list>
    </div>
  </window-size>
</template>
<script setup>
import {getPhysicalCheckIndex} from '@/api/physical-exam'
import {useRouter} from "vue-router";
import {onMounted, ref} from "vue";
import {useStore} from "vuex";
import axios from "axios";
import leaveWx from '@/assets/leave_weixin.png'
import {showToast} from "vant";

const store = useStore();
const router = useRouter();
const patientId = router.currentRoute.value.params.patientId;

const listBoxStyle = {
  height: store.state.screenSize.h - 100 + 'px',
  overflowY: 'scroll'
}

const idCard = ref();
const idCardTemp = ref();
const nextPage = ref(1);

const listLoading = ref(false);
const listFinished = ref(false);
const examIndexes = ref([]);

const onLoadingList = () => {
  if (idCard.value) {
    fetchIndexData()
  } else {
    listLoading.value = false
  }
};

const handleClickSearch = () => {
  if (idCard.value !== idCardTemp.value) {
    listFinished.value = false
    nextPage.value = 1
    examIndexes.value = []
  }
  if (listFinished.value) {
    return
  }
  idCardTemp.value = idCard.value
  fetchIndexData()
}

const fetchIndexData = () => {
  getPhysicalCheckIndex({idCard: idCard.value, patNo: patientId, pageNo: nextPage.value}).then(index => {
    listLoading.value = false
    listFinished.value = index['pageInfo'].nextPage === 0;
    examIndexes.value = examIndexes.value.concat(index['rows'])
    if (index['pageInfo'].nextPage > 0) {
      nextPage.value = index['pageInfo'].nextPage
      store.dispatch({
        type: 'storePhysicalExamNextPage',
        physicalExamNextPage: nextPage.value
      })
    }
    store.dispatch({
      type: 'storePhysicalExamListFinished',
      physicalExamListFinished: listFinished.value
    })
    store.dispatch({
      type: 'storePhysicalExamIndexes',
      physicalExamIndexes: examIndexes.value
    })
  });
}

const handleClickIndex = (tjIndex) => {
  const fileName = (tjIndex['工作单位'] ? tjIndex['工作单位'] : '长沙泰和医院体检报告' ) + '.pdf'
  axios({
    method: 'post',
    url: 'https://staticweb.hnthyy.cn/wxserver/physicalCheck/exportPDF',
    data: tjIndex,
    responseType: 'blob',
  }).then((res) => {
    if (res.data.type === 'application/x-download') {
      let blob = new Blob([res.data], { type: 'application/pdf' })
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.style.display = 'none'
      link.download = fileName //下载的文件名
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    } else {
      showToast({
        message: '没有查询到可导出的体检报告。',
        position: 'top',
      });
    }
  }).catch((error) => {
    console.error(error)
  })
}

const isWxBrowser = ref(false)

const judgeWeChatBrowser = () => {
  var ua = navigator.userAgent.toLowerCase();
  return ua.match(/MicroMessenger/i) == "micromessenger";
}

onMounted(() => {
  isWxBrowser.value = judgeWeChatBrowser()
  nextPage.value = store.state.physicalExamNextPage;
  examIndexes.value = store.state.physicalExamIndexes
  listFinished.value = store.state.physicalExamListFinished
  const currentTjid = store.state.currentTjid
  if (currentTjid && examIndexes.value.length > 0) {
    const currentIndex = examIndexes.value.findIndex((item) => {
      return item['条码号'] === currentTjid
    })
    document.getElementById('listWrapper').scrollTop = 66 * currentIndex - 100
  }
})
</script>

<style>
#weixin-tip{display:block;position:fixed;left:0;top:0;background:rgba(0,0,0,0.8);filter:alpha(opacity=80);width:100%;height:100%;z-index:100;}
#weixin-tip p{text-align:center;margin-top:10%;padding:0 5%;position:relative;}
#weixin-tip .close{color:#fff;padding:5px;font:bold 20px/24px simsun;text-shadow:0 1px 0 #ddd;position:absolute;top:0;left:5%;}
</style>