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

import { deleteBdMember, pageBdMemberTable } from '#/api/legacy/team';
import AccountInput from '#/components/account-input.vue';
import SysOriginLabel from '#/components/sys-origin-label.vue';
import { formatDate } from '#/views/system/shared';

import {
  Button,
  Drawer,
  Modal,
  Pagination,
  Space,
  Table,
  message,
} from 'antdv-next';

const props = defineProps<{
  open: boolean;
  row: null | Record<string, any>;
}>();

const router = useRouter();

const loading = ref(false);
const total = ref(0);
const list = ref<Array<Record<string, any>>>([]);
const sysOrigin = ref('');

const query = reactive({
  agentId: '',
  cursor: 1,
  limit: 20,
  userId: '',
});

const columns = [
  { dataIndex: 'sysOrigin', key: 'sysOrigin', title: '系统', width: 100 },
  { dataIndex: 'userProfile', key: 'userProfile', title: '用户', width: 260 },
  { dataIndex: 'anchorQuantity', key: 'anchorQuantity', title: '主播数量', width: 100 },
  { dataIndex: 'createTime', key: 'createTime', title: '创建时间', width: 180 },
  { dataIndex: 'actions', key: 'actions', title: '操作', width: 80 },
];

watch(
  () => props.open,
  async (open) => {
    if (!open) {
      return;
    }
    query.cursor = 1;
    query.agentId = '';
    query.userId = String(props.row?.userId || props.row?.userProfile?.id || '');
    sysOrigin.value = String(
      props.row?.userProfile?.originSys || props.row?.sysOrigin || '',
    );
    await loadData(true);
  },
  { immediate: true },
);

function getUserText(profile?: Record<string, any>) {
  if (!profile) {
    return '-';
  }
  const nickname = profile.userNickname || profile.nickname || '-';
  const account = profile.actualAccount || profile.account || profile.id;
  return account ? `${nickname} / ${account}` : nickname;
}

function openUserDetails(userId?: number | string) {
  if (!userId) {
    return;
  }
  router.push(`/common/user/deatils/${userId}`);
}

async function loadData(reset = false) {
  if (reset) {
    query.cursor = 1;
  }
  loading.value = true;
  try {
    const result = await pageBdMemberTable({ ...query });
    list.value = result.records || [];
    total.value = result.total || 0;
  } finally {
    loading.value = false;
  }
}

function handlePageChange(page: number, pageSize: number) {
  query.cursor = page;
  query.limit = pageSize;
  loadData();
}

function handleDelete(record: Record<string, any>) {
  Modal.confirm({
    title: '您确定要删除吗？',
    async onOk() {
      await deleteBdMember(record.id);
      message.success('删除成功');
      await loadData(true);
    },
  });
}
</script>

<template>
  <Drawer
    :open="open"
    :title="`BD团队代理成员 · ${props.row?.userProfile?.userNickname || props.row?.userId || ''}`"
    destroy-on-close
    width="960"
    @close="$emit('close')"
  >
    <div class="toolbar">
      <Space wrap>
        <AccountInput
          v-model:value="query.agentId"
          :sys-origin="sysOrigin"
          placeholder="用户ID"
          style="width: 220px"
        />
        <Button :loading="loading" type="primary" @click="loadData(true)">
          搜索
        </Button>
      </Space>
    </div>

    <Table
      :columns="columns"
      :data-source="list"
      :loading="loading"
      :pagination="false"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'sysOrigin'">
          <SysOriginLabel :value="record.sysOrigin" />
        </template>
        <template v-else-if="column.key === 'userProfile'">
          <Button
            v-if="record.userProfile?.id"
            type="link"
            @click="openUserDetails(record.userProfile?.id)"
          >
            {{ getUserText(record.userProfile) }}
          </Button>
          <span v-else>{{ getUserText(record.userProfile) }}</span>
        </template>
        <template v-else-if="column.key === 'createTime'">
          {{ formatDate(record.createTime) }}
        </template>
        <template v-else-if="column.key === 'actions'">
          <Button danger size="small" type="link" @click="handleDelete(record)">
            删除
          </Button>
        </template>
      </template>
    </Table>

    <div class="pagination">
      <Pagination
        :current="query.cursor"
        :page-size="query.limit"
        :total="total"
        show-size-changer
        @change="handlePageChange"
        @showSizeChange="handlePageChange"
      />
    </div>
  </Drawer>
</template>

<style scoped>
.toolbar {
  margin-bottom: 16px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}
</style>
