<script setup lang="ts">
import { getDataMethod } from '@/api/pda.api.ts';
import { uploadMethod } from '@/api/file.api.ts';
import { type ScanData, useScan } from '@/core/hook/useScan.ts';
import { useStep } from '@/core/hook/useStep.ts';
import { useStepStore } from '@/stores';
import type { UploaderAfterRead, UploaderFileListItem } from 'vant';
import { nextTick } from 'vue';

const stepStore = useStepStore();
const { dataset, id, mode } = storeToRefs(stepStore);
const loaded = computed(() => !!id.value);

const keyword = ref('');
const tabIndex = ref(0);
const { menu, tabTitle, next, prev } = useStep(mode, id);

watchEffect(() => {
  keyword.value = id.value;
  nextTick(() => {
    tabIndex.value = id.value ? 3 : 0;
    if (!id.value) stepStore.$reset();
  });
});

const step = useTemplateRef<{ scan?: (data: ScanData) => void }>('step');

const { scanValue, scan } = useScan((data) => {
  /* 组件内扫描按钮 */
  if (tabIndex.value === 3 && typeof step.value?.scan === 'function') {
    scanValue.value = data.code;
    step.value.scan(data);
  } else {
    keyword.value = data.code;
    onSearch();
  }
});

async function onSearch() {
  const value = keyword.value?.trim?.();
  if (value) {
    showLoadingToast({ forbidClick: true, duration: 0, message: '查询中...' });
    try {
      dataset.value = await getDataMethod(keyword.value.trim());
      await next(dataset.value.no);
    } catch (_: unknown) {
      keyword.value = '';
    }
    closeToast();
  } else {
    showNotify({ message: '请使用设备按钮进行扫码', type: 'warning' });
  }
}

function onBack() {
  prev();
}

const files = ref<UploaderFileListItem[]>([]);
const picture = computed(() => files.value.filter((file) => file.status === 'done' && file.url != null).map((file) => file.url));
const afterRead: UploaderAfterRead = async (listItem) => {
  if (listItem && !Array.isArray(listItem)) listItem = [listItem];
  for (const item of listItem) {
    if (!item?.file) continue;
    item.status = 'uploading';
    item.message = '上传中...';
    try {
      item.url = await uploadMethod(item.file!);
      item.status = 'done';
    } catch (error) {
      console.error('[file] 文件上传失败', error);
      item.status = 'failed';
    }
  }
};
</script>

<template>
  <div class="page page__home flex flex-col size-full">
    <header class="flex-none">
      <van-nav-bar :title="menu?.title" left-text="返回" left-arrow @click-left="onBack()" />
      <van-search v-model="keyword" input-align="center" placeholder="请使用设备按钮进行扫码" @search="onSearch()" :readonly="loaded" :show-action="loaded" @cancel="onBack()" />
    </header>
    <van-tabs class="content flex-auto overflow-hidden" v-model:active="tabIndex">
      <van-tab title="就诊信息">
        <van-cell-group>
          <van-cell title="患者" :value="dataset?.patient?.name" />
          <van-cell title="性别" :value="dataset?.patient?.gender" />
          <van-cell title="年龄" :value="dataset?.patient?.age" />
          <van-cell title="手机号" :value="dataset?.patient?.phone" />
          <van-cell title="医院" :value="dataset?.patient?.hospital" />
          <van-cell title="门诊/住院" :value="dataset?.patient?.category" />
          <van-cell title="科室/病区" :value="[dataset?.patient?.department, dataset?.patient?.area].filter((v) => !!v).join('/')" />
          <van-cell title="病床" :value="dataset?.patient?.bed" />
          <van-cell title="临床诊断" :value="dataset?.patient?.name" />
          <van-cell title="开方医生" :value="dataset?.doctor?.name" />
        </van-cell-group>
      </van-tab>
      <van-tab title="处方信息">
        <van-cell-group>
          <van-cell title="处方类型" :value="dataset?.prescription?.category" />
          <van-cell title="处方状态" :value="dataset?.order?.state" />
          <van-cell title="总金额" :value="dataset?.prescription?.totalPrice" />
          <van-cell title="剂型" :value="dataset?.prescription?.dosageForm" />
          <van-cell title="剂数" :value="dataset?.prescription?.count" />
          <van-cell title="处方用法" :value="dataset?.prescription?.method" />
          <van-cell title="服药频次" :value="dataset?.prescription?.frequency" />
          <van-cell title="服药时间" :value="dataset?.prescription?.frequencyTime" />
          <van-cell title="煎药量" :value="dataset?.prescription?.volume" />
          <van-cell title="是否代煎" :value="dataset?.prescription?.decoction" />
          <van-cell title="开方医生备注" :value="dataset?.prescription?.remark1" />
          <van-cell title="配送方式" :value="dataset?.prescription?.dispatch?.method" />
          <van-cell title="收货人" :value="dataset?.prescription?.dispatch?.name" />
          <van-cell title="收货电话" :value="dataset?.prescription?.dispatch?.phone" />
          <van-cell title="收货地址" :value="dataset?.prescription?.dispatch?.address" value-class="flex-2" />
          <van-cell title="嘱托" :value="dataset?.prescription?.entrust" />
          <van-cell title="药师备注" :value="dataset?.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 dataset?.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" :disabled="!loaded">
        <router-view>
          <component ref="step" :is="menu?.component" @back="onBack()">
            <template v-slot:scanner="{ title, disabled }">
              <van-field
                :label="title"
                :readonly="disabled"
                placeholder="请使用设备按钮进行扫码"
                right-icon="scan"
                @click-right-icon="!disabled && scan()"
                v-model="scanValue"
                @update:model-value="scan($event)"
              />
            </template>
            <template v-slot:uploader="{ disabled }">
              <van-field label="拍照上传">
                <template #input>
                  <van-uploader v-model="files" :after-read="afterRead" :disabled="disabled" />
                </template>
              </van-field>
            </template>
            <template v-slot:submit="{ title, submitting, submit }">
              <div class="my-4 px-4">
                <van-button type="primary" block :loading="submitting" @click="submit(picture)">{{ title }}</van-button>
              </div>
            </template>
          </component>
        </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>
