<script setup lang="ts">
import { useStepStore } from '@/stores';
import { useRequest } from 'alova/client';
import { getDataMethod } from '@/api/pda.api.ts';
import { defaultMenus } from '@/model/menu.model.ts';
import { tryOnBeforeMount, tryOnUnmounted } from '@vueuse/core';

const router = useRouter();
const route = useRoute();
const stepStore = useStepStore();
const { dataset } = storeToRefs(stepStore);

const navTitle = computed(() => defaultMenus.find((menu) => menu.path === `/step/${route.params.mode}`)?.name ?? import.meta.env.SIX_TITLE);
const tabTitle = computed(() => navTitle.value?.replace('管理', '确认'));
const tabIndex = ref(0);

const loaded = computed(() => !!data.value?.no);
const readonly = ref(false);
const keyword = ref<string>(dataset.value?.no ?? '');

const ignoreParentScanner = ref(false);
provide('ignoreParentScanner', ignoreParentScanner);
let onCleanup = () => {};
tryOnBeforeMount(() => {
  if (window.bridge) {
    onCleanup = window.bridge.addEventListener('scan', event => {
      const detail = event.detail;
      if ( detail.code !== 0 || detail.data?.code == null ) return;
      if (ignoreParentScanner.value) {
        event.stopPropagation();
        event.preventDefault();
      } else {
        keyword.value = event.detail.data?.code ?? '';
        const toast = showLoadingToast({ message: '查询中...', duration: 0 });
        search().finally(() => toast.close());
      }
    });
  } else if (window.platform) {
    const update = (event: CustomEvent) => {
      if (ignoreParentScanner.value) {
        event.stopPropagation();
        event.preventDefault();
      } else {
        keyword.value = event.detail.code;
        const toast = showLoadingToast({ message: '查询中...', duration: 0 });
        search().finally(() => toast.close());
      }
    };
    platform.addEventListener('scan', update)
    onCleanup = () => { platform.removeEventListener('scan', update) }
  }
});
tryOnUnmounted(() => onCleanup?.());

const {
  data,
  loading,
  send: search,
} = useRequest(() => getDataMethod(keyword.value?.trim()), {
  immediate: false,
  initialData: { ...dataset.value },
})
  .onSuccess(async ({ data }) => {
    keyword.value = data.no;
    dataset.value = data;

    const { mode, value } = route.params;

    if (value) {
      await router.push({ path: `${keyword.value}`, replace: true });
    } else {
      await router.push({ path: `${mode}/${keyword.value}` });
    }
    tabIndex.value = 3;
  })
  .onError(() => {
    keyword.value = '';
  });

watch(loading, (value) => {
  if (value) {
    showLoadingToast({ forbidClick: true, duration: 0, message: '加载中...' });
  } else {
    closeToast();
  }
});

function back(delta?: number) {
  stepStore.$reset();
  data.value = { ...dataset.value! };
  keyword.value = '';
  delta ??= route.params.value ? -2 : -1;
  tabIndex.value = 0;
  router.go(delta);
}
</script>

<template>
  <div class="page page__home flex flex-col size-full">
    <header class="flex-none">
      <van-nav-bar :title="navTitle" left-text="返回" left-arrow @click-left="back()" />
      <van-search
        v-model="keyword"
        input-align="center"
        placeholder="请使用设备按钮进行扫码"
        :readonly="readonly || loading || loaded"
        :show-action="loaded"
        @search="keyword && search()"
        @cancel="back(-1)"
      />
    </header>
    <van-tabs class="content flex-auto overflow-hidden" v-model:active="tabIndex">
      <van-tab title="就诊信息">
        <van-cell-group>
          <van-cell title="患者" :value="data.patient?.name" />
          <van-cell title="性别" :value="data.patient?.gender" />
          <van-cell title="年龄" :value="data.patient?.age" />
          <van-cell title="手机号" :value="data.patient?.phone" />
          <van-cell title="医院" :value="data.patient?.hospital" />
          <van-cell title="门诊/住院" :value="data.patient?.category" />
          <van-cell title="科室/病区" :value="[data.patient?.department, data.patient?.area].filter((v) => !!v).join('/')" />
          <van-cell title="病床" :value="data.patient?.bed" />
          <van-cell title="临床诊断" :value="data.patient?.name" />
          <van-cell title="开方医生" :value="data.doctor?.name" />
        </van-cell-group>
      </van-tab>
      <van-tab title="处方信息">
        <van-cell-group>
          <van-cell title="处方类型" :value="data.prescription?.category" />
          <van-cell title="处方状态" :value="data.order?.state" />
          <van-cell title="总金额" :value="data.prescription?.totalPrice" />
          <van-cell title="剂型" :value="data.prescription?.dosageForm" />
          <van-cell title="剂数" :value="data.prescription?.count" />
          <van-cell title="处方用法" :value="data.prescription?.method" />
          <van-cell title="服药频次" :value="data.prescription?.frequency" />
          <van-cell title="服药时间" :value="data.prescription?.frequencyTime" />
          <van-cell title="煎药量" :value="data.prescription?.volume" />
          <van-cell title="是否代煎" :value="data.prescription?.decoction" />
          <van-cell title="开方医生备注" :value="data.prescription?.remark1" />
          <van-cell title="配送方式" :value="data.prescription?.dispatch?.method" />
          <van-cell title="收货人" :value="data.prescription?.dispatch?.name" />
          <van-cell title="收货电话" :value="data.prescription?.dispatch?.phone" />
          <van-cell title="收货地址" :value="data.prescription?.dispatch?.address" value-class="flex-2" />
          <van-cell title="嘱托" :value="data.prescription?.entrust" />
          <van-cell title="药师备注" :value="data.prescription?.remark2" />
        </van-cell-group>
      </van-tab>
      <van-tab title="药品信息">
        <table class="min-w-[600px] w-full">
          <thead>
            <tr>
              <th scope="col"></th>
              <th scope="col">药品名称</th>
              <th scope="col">药品规格</th>
              <th scope="col">剂量</th>
              <th scope="col">单位</th>
              <th scope="col">用法</th>
              <th scope="col">零售价</th>
              <th scope="col">产地</th>
              <th scope="col">小计</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(medicine, index) in data.medicines" :key="medicine.id">
              <th scope="row">{{ index + 1 }}</th>
              <td class="w-24">{{ medicine.name }}</td>
              <td>{{ medicine.size }}</td>
              <td style="text-align: right">{{ medicine.dosage }}</td>
              <td>{{ medicine.unit }}</td>
              <td>{{ medicine.usage }}</td>
              <td>{{ medicine.place }}</td>
              <td style="text-align: right">{{ medicine.unitPrice }}</td>
              <td style="text-align: right">{{ medicine.totalPrice }}</td>
            </tr>
          </tbody>
        </table>
      </van-tab>
      <van-tab :title="tabTitle">
        <router-view :title="navTitle" @back="back"></router-view>
      </van-tab>
    </van-tabs>
  </div>
</template>

<style scoped lang="scss">
.content {
  display: flex;
  flex-direction: column;

  :deep(.van-tabs__wrap) {
    flex: none;
  }

  :deep(.van-tabs__content) {
    flex: auto;
    overflow: auto;
  }

  //--van-cell-text-color: #fff
  --van-cell-value-color: var(--van-text-color);
  --van-cell-text-color: var(--van-text-color-2);

  table {
    border-collapse: collapse;
    border: 2px solid rgb(140 140 140);
    font-size: 14px;
    letter-spacing: 1px;
  }

  thead,
  tfoot {
    background-color: rgb(228 240 245);
  }

  th,
  td {
    border: 1px solid rgb(160 160 160);
    padding: 8px 10px;
    text-align: center;
  }
}
</style>
<style>
.flex-2 {
  flex: 2;
}
</style>
