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

import { Button, Drawer, Empty, List, message, Tag } from 'ant-design-vue';

import { getSalespersonTransferByRegisterApi } from '#/views/business/salesperson-transfer-prescription/api';

const props = defineProps<{
  open: boolean;
  registerId: number;
}>();

const emit = defineEmits<{
  'update:open': [boolean];
  import: [any];
}>();

const loading = ref(false);
const list = ref<any[]>([]);

function parseDrugList(item: any) {
  if (item.drug_list?.length) return item.drug_list;
  if (item.prescription?.content?.length) return item.prescription.content;
  const content = item.content;
  if (!content?.repice) return [];
  const drugs: any[] = [];
  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)) drugs.push(...rc);
  }
  return drugs;
}

async function loadList() {
  if (!props.registerId) return;
  loading.value = true;
  try {
    const res = await getSalespersonTransferByRegisterApi(props.registerId);
    list.value = Array.isArray(res) ? res : [];
  } catch (e) {
    console.error(e);
    list.value = [];
  } finally {
    loading.value = false;
  }
}

watch(
  () => [props.open, props.registerId],
  ([open]) => {
    if (open) loadList();
  },
);

function matchTypeLabel(matchType?: string) {
  if (matchType === 'mobile') return '手机号匹配';
  if (matchType === 'store_pending') return '本店待导入';
  return '';
}

function handleImport(item: any) {
  const drugList = parseDrugList(item);
  if (!drugList.length) {
    message.warning('传方药品为空');
    return;
  }
  emit('import', {
    transferId: item.id,
    clinical_diagnose: item.clinical_diagnose || item.content?.clinical_diagnose || '',
    doctor_order: item.doctor_order || item.content?.doctor_order || '',
    drugList,
  });
  emit('update:open', false);
}

function close() {
  emit('update:open', false);
}
</script>

<template>
  <Drawer :open="open" title="推广员传方记录" width="560" @close="close">
    <Empty v-if="!loading && !list.length" description="暂无待导入传方" />
    <List v-else :loading="loading" :data-source="list" item-layout="horizontal">
      <template #renderItem="{ item }">
        <List.Item>
          <List.Item.Meta
            :title="`${item.patient_name || ''} ${item.patient_mobile || ''}`"
            :description="`推广员：${item.salesperson_name || '-'} · ${item.transfer_time_text || ''}`"
          />
          <template #actions>
            <Tag v-if="matchTypeLabel(item.match_type)" :color="item.match_type === 'mobile' ? 'success' : 'processing'">
              {{ matchTypeLabel(item.match_type) }}
            </Tag>
            <Tag color="warning">待导入</Tag>
            <Button type="link" @click="handleImport(item)">导入</Button>
          </template>
        </List.Item>
      </template>
    </List>
  </Drawer>
</template>
