<script setup lang="ts">
import { computed, ref, watch } from 'vue';

import { Modal, Table } from 'ant-design-vue';

import { getSalespersonTransferDetailApi } from '../api';

const visible = ref(false);
const loading = ref(false);
const detail = ref<any>(null);

const drugColumns = [
  { title: '药品名称', dataIndex: 'drug_name', key: 'drug_name', customRender: ({ record }: any) => record.drug_name || record.name || '-' },
  { title: '数量', dataIndex: 'number', key: 'number', width: 80 },
];

const drugList = computed(() => {
  const d = detail.value;
  if (!d) return [];
  if (Array.isArray(d.drug_list) && d.drug_list.length) return d.drug_list;
  if (d.prescription?.content && Array.isArray(d.prescription.content)) {
    return d.prescription.content;
  }
  const content = d.content;
  if (!content || typeof content !== 'object') return [];
  const list: any[] = [];
  if (Array.isArray(content.repice)) {
    for (const recipe of content.repice) {
      let rc = recipe.content;
      if (typeof rc === 'string') {
        try {
          rc = JSON.parse(rc);
        } catch {
          rc = [];
        }
      }
      if (Array.isArray(rc)) list.push(...rc);
    }
  }
  return list;
});

async function open(id: number) {
  visible.value = true;
  loading.value = true;
  try {
    detail.value = await getSalespersonTransferDetailApi(id);
  } finally {
    loading.value = false;
  }
}

function close() {
  visible.value = false;
  detail.value = null;
}

defineExpose({ open });
</script>

<template>
  <Modal
    v-model:open="visible"
    title="传方药品详情"
    width="720"
    :footer="null"
    destroy-on-close
    @cancel="close"
  >
    <div v-if="detail" class="mb-3 text-sm text-gray-500">
      <div>患者：{{ detail.patient_name }} {{ detail.patient_mobile }}</div>
      <div>诊断：{{ detail.clinical_diagnose || '-' }}</div>
      <div>医嘱：{{ detail.doctor_order || '-' }}</div>
    </div>
    <Table
      :loading="loading"
      :columns="drugColumns"
      :data-source="drugList"
      :pagination="false"
      row-key="drug_id"
      size="small"
    />
  </Modal>
</template>
