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

import { Page } from '@vben/common-ui';

import { Button, Empty, Spin, Table, Tag } from 'ant-design-vue';

import DetailModal from './components/DetailModal.vue';
import { getSalespersonTransferListApi } from './api';

const loading = ref(true);
const list = ref<any[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(20);
const detailRef = ref<InstanceType<typeof DetailModal>>();

const columns = [
  { title: '诊所', dataIndex: 'store_name', key: 'store_name' },
  { title: '推广员', dataIndex: 'salesperson_name', key: 'salesperson_name' },
  { title: '患者', key: 'patient', customRender: ({ record }: any) => `${record.patient_name || ''} ${record.patient_mobile || ''}` },
  { title: '传方时间', dataIndex: 'transfer_time_text', key: 'transfer_time_text' },
  {
    title: '是否已导入',
    key: 'is_imported',
    customRender: ({ record }: any) =>
      record.is_imported
        ? h(Tag, { color: 'success' }, () => '已导入')
        : h(Tag, { color: 'warning' }, () => '待导入'),
  },
  {
    title: '处方',
    key: 'action',
    customRender: ({ record }: any) =>
      h(Button, { type: 'link', onClick: () => detailRef.value?.open(record.id) }, () => '查看'),
  },
];

async function loadList() {
  loading.value = true;
  try {
    const res = await getSalespersonTransferListApi({
      page: page.value,
      pageSize: pageSize.value,
    });
    list.value = res?.items ?? [];
    total.value = res?.total ?? 0;
  } finally {
    loading.value = false;
  }
}

onMounted(loadList);

function onPageChange(p: number, ps: number) {
  page.value = p;
  pageSize.value = ps;
  loadList();
}
</script>

<template>
  <Page auto-content-height title="传方记录">
    <Spin :spinning="loading">
      <Empty v-if="!loading && !list.length" description="暂无传方记录" />
      <Table
        v-else
        :columns="columns"
        :data-source="list"
        :pagination="{
          current: page,
          pageSize,
          total,
          showSizeChanger: true,
          onChange: onPageChange,
        }"
        row-key="id"
      />
    </Spin>
    <DetailModal ref="detailRef" />
  </Page>
</template>
