<template>
  <el-drawer :model-value="visible" title="患者历史购药记录" size="600" style="--el-drawer-padding-primary: 0" @close="close()">
    <my-layout v-loading="loading" class="bg-[#f2f3f4]">
      <layout-item>
        <div class="flex text-center bg-white cursor-pointer border-b border-gray-200">
          <div class="py-3 w-1/2 text-sm" :class="activeTab === 'yb' ?'bg-blue-500 text-white':''"
            @click="toggle('yb')">医保购药记录</div>
          <div class="py-3 w-1/2 text-sm" :class="activeTab === 'hlw' ?'bg-blue-500 text-white':''"
            @click="toggle('hlw')">互联网医院购药记录</div>
        </div>
      </layout-item>
      <layout-main v-if="activeTab === 'yb'" ref="mainRef">
        <empty-data v-if="ybList.length == 0" />
        <div v-for="item in ybList" :key="item.mdtrtId" class="shadow-lg bg-white mb-2.5">
          <div class="py-3 px-4 border-b">{{item.date}}</div>
          <div class="py-3 px-4">
            <div>
              <span class="text-gray-500">就诊机构：</span>
              <span class="text-darj-500">{{item.medinsName}}</span>
            </div>
            <div class="text-gray-500 mt-2">药品名称：</div>
            <div v-for="(med, idx) in item.drugs" :key="med.insuranceCode" class="mt-2">
              <div class="text-dark-500">
                <span class="text-dark-500">{{ idx+1 }}. {{ med.hiListName }}</span>
                <span class="ml-1 text-gray-500">{{ med.spec }}</span>
                <span v-if="med.quantity > 0" class="ml-2 text-dark-500"> x{{ med.quantity }}{{ med.unit }}</span>
              </div>
              <div class="text-gray-500">用法：-</div>
            </div>
          </div>
        </div>
      </layout-main>
      <layout-main v-else-if="activeTab === 'hlw'">
        <empty-data v-if="list.length == 0" />
        <div v-for="item in list" :key="item._id" class="shadow-lg bg-white mb-2.5">
          <div class="py-3 px-4 border-b">{{item.time}}</div>
          <div class="py-3 px-4">
            <div>
              <span class="text-gray-500">诊断：</span>
              <span class="text-darj-500">{{item.disease}}</span>
            </div>
            <div class="text-gray-500 mt-2">药品名称：</div>
            <div v-for="(med, idx) in item.drugs" :key="med.insuranceCode" class="mt-2">
              <div>
                <span class="text-dark-500">{{ idx+1 }}. {{ med.drugName }}</span>
                <span class="ml-2 text-gray-500">{{ med.specification }}</span>
                <span class="ml-2 text-dark-500">x{{ med.quantity }}{{ med.unit }}</span>
              </div>
              <div class="text-gray-500">
                用法： {{ med.usageName }} {{ med.frequencyName}} 每次{{ med.dosage }} {{ med.dosage_unit }}
              </div>
            </div>
          </div>
        </div>
        <div v-if="hasMore" class="flex items-center px-10 py-4">
          <div class="flex-grow border-dashed text-blue-200"></div>
          <div class="text-center flex-shrink-0 mx-2 cursor-pointer text-blue-500" @click="loadMore">
            点击加载更多
          </div>
          <div class="flex-grow border-dashed text-blue-200"></div>
        </div>
      </layout-main>
    </my-layout>
  </el-drawer>
</template>
<script setup>
import { computed, nextTick, ref, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";
import { getRecent90daysDrugRecord, getPatientPurchaseOrderList } from "@/api/hlw";
import useElPagination from "@/hooks/useElPagination";

import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";
import EmptyData from "@/components/empty-data.vue";

const props = defineProps({
  order: {
    type: Object,
    default: () => ({}),
  },
  visible: {
    type: Boolean,
    default: false,
  },
});
const activeTab = ref("yb"); // yb:医保购药记录, wk:互联网医院购药记录
const loading = ref(false)
const ybList = ref([]);

const emit = defineEmits(["close"]);
const { list, page, total, pageSize, changePage, changeSize, hasMore } = useElPagination(getHlwList);

function toggle(tab) {
  if (activeTab.value === tab) return;
  activeTab.value = tab;
  if (tab === 'hlw' && list.value.length == 0 && page.value === 1) {
    getHlwList()
  }
}

function close() {
  emit("close");
}

function loadMore() {
  if (hasMore.value && !loading.value) {
    changePage(page.value + 1)
  }
}

async function getYbList() {
  if (props.order.patientId) {
    loading.value = true;
    const res = await getRecent90daysDrugRecord(props.order.patientId)
    loading.value = false;
    const recordList = res && res.data && Array.isArray(res.data.recordList) ? res.data.recordList : []
    const drugList = res && res.data && Array.isArray(res.data.drugList) ? res.data.drugList : [];
    ybList.value = recordList.map(i => ({
      ...i,
      drugs: drugList.filter(j => j.mdtrtId === i.mdtrtId && i.mdtrtId)
    })).filter(i => i.drugs.length)
  }
}

async function getHlwList() {
  if (props.order.patientId) {
    loading.value = true;
    const params = {
      patientId: props.order.patientId,
      page: page.value,
      pageSize: pageSize.value
    }
    const res = await getPatientPurchaseOrderList(params)
    loading.value = false;
    const arr = res && res.data && Array.isArray(res.data.data) ? res.data.data.map(i => ({
      time: dayjs(i.createTime).format('YYYY-MM-DD HH:mm'),
      disease: Array.isArray(i.diagnosisList) ? i.diagnosisList.map(i => i.name).join('') : '',
      drugs: Array.isArray(i.drugs) ? i.drugs : []
    })) : [];
    total.value = res && res.data && typeof res.data.total === 'number' ? res.data.total : 0;
    list.value = page.value == 1 ? arr : [...list.value, ...arr];
    // const recordList = res && res.data && Array.isArray(res.data.recordList) ? res.data.recordList : []
    // const drugList = res && res.data && Array.isArray(res.data.drugList) ? res.data.drugList : [];
    // ybList.value = recordList.map(i => ({
    //   ...i,
    //   drugs: drugList.filter(j => j.mdtrtId === i.mdtrtId && i.mdtrtId)
    // }))
  }
}

watch(() => props.visible, n => {
  if (n) {
    ybList.value = [];
    list.value = [];
    activeTab.value = 'yb';
    getYbList()
  }
})

</script>
<style lang="scss" scoped>
.border-dashed {
  border-bottom: 1px dashed;
}
</style>
