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

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

import SensitiveText from '#/components/sensitive-text/SensitiveText.vue';
import { invitedSalespersonListApi } from '#/views/business/store/settings/api';

const open = ref(false);
const loading = ref(false);
const salespersonId = ref(0);
const nickName = ref('');
const list = ref<any[]>([]);

const columns = [
  { title: '名称', dataIndex: 'nick_name', key: 'nick_name', width: 120 },
  {
    title: '手机号',
    key: 'phone',
    width: 120,
    customRender: ({ record }: any) =>
      h(SensitiveText, { record, field: 'phone', showEye: false }),
  },
  { title: '邀请分成', dataIndex: 'inviter_split', key: 'inviter_split', width: 90 },
  { title: '待结算', dataIndex: 'invite_pending_amount', key: 'pending', width: 100 },
  { title: '已结算', dataIndex: 'invite_settled_amount', key: 'settled', width: 100 },
  { title: '累计收益', dataIndex: 'invite_total_amount', key: 'total', width: 100 },
  { title: '入驻时间', dataIndex: 'created_at_text', key: 'created_at_text', width: 160 },
];

async function loadList() {
  if (salespersonId.value <= 0) return;
  loading.value = true;
  try {
    const res = await invitedSalespersonListApi({
      salesperson_id: salespersonId.value,
      page: 1,
      pageSize: 100,
    });
    list.value = res?.items ?? [];
  } finally {
    loading.value = false;
  }
}

watch(open, (val) => {
  if (val) loadList();
});

function openDrawer(item: { id: number; nick_name?: string }) {
  salespersonId.value = item.id;
  nickName.value = item.nick_name || '';
  open.value = true;
}

defineExpose({ open: openDrawer });
</script>

<template>
  <Drawer
    v-model:open="open"
    :title="`${nickName} · 下级推广员`"
    width="760"
  >
    <Table
      :columns="columns"
      :data-source="list"
      :loading="loading"
      :pagination="false"
      row-key="id"
      size="small"
    />
  </Drawer>
</template>
