<script lang="ts" setup>
import type {
  OnActionClickParams,
  VxeGridListeners,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { AgentApi } from '#/api/agent';

import { computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';

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

import { Button, Card, Dropdown, Menu } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getAgentList } from '#/api/agent';

import { useColumns, useGridFormSchema } from './data';
import CommissionModal from './modules/commission-modal.vue';
import Form from './modules/form.vue';
import LinkModal from './modules/link-modal.vue';
import OrderModal from './modules/order-modal.vue';
import RebateModal from './modules/rebate-modal.vue';
import UpgradeModal from './modules/upgrade-modal.vue';
import WithdrawalModal from './modules/withdrawal-modal.vue';

const route = useRoute();
const router = useRouter();

// 表单抽屉
const [FormDrawer, formDrawerApi] = useVbenDrawer({
  connectedComponent: Form,
  destroyOnClose: true,
});

// 推广链接弹窗
const [LinkModalComponent, linkModalApi] = useVbenModal({
  connectedComponent: LinkModal,
  destroyOnClose: true,
});

// 佣金记录弹窗
const [CommissionModalComponent, commissionModalApi] = useVbenModal({
  connectedComponent: CommissionModal,
  destroyOnClose: true,
});

// 返佣记录弹窗
const [RebateModalComponent, rebateModalApi] = useVbenModal({
  connectedComponent: RebateModal,
  destroyOnClose: true,
});

// 升级记录弹窗
const [UpgradeModalComponent, upgradeModalApi] = useVbenModal({
  connectedComponent: UpgradeModal,
  destroyOnClose: true,
});

// 订单记录弹窗
const [OrderModalComponent, orderModalApi] = useVbenModal({
  connectedComponent: OrderModal,
  destroyOnClose: true,
});

// 提现记录弹窗
const [WithdrawalModalComponent, withdrawalModalApi] = useVbenModal({
  connectedComponent: WithdrawalModal,
  destroyOnClose: true,
});

// 表格配置
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    fieldMappingTime: [
      ['create_time', ['create_time_start', 'create_time_end']],
    ],
    schema: useGridFormSchema(),
    submitOnChange: true,
  },
  gridEvents: {
    sortChange: () => {
      gridApi.query();
    },
  } as VxeGridListeners<AgentApi.AgentListItem>,
  gridOptions: {
    columns: useColumns(),
    height: 'auto',
    keepSource: true,
    sortConfig: {
      remote: true,
      multiple: false,
      trigger: 'default',
      orders: ['asc', 'desc', null],
      resetPage: true,
    },
    proxyConfig: {
      ajax: {
        query: async ({ page, sort }, formValues) => {
          const sortParams = sort
            ? {
              order_by: sort.field,
              order_type: sort.order,
            }
            : {};

          const res = await getAgentList({
            page: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
            ...sortParams,
            team_leader_id: route.query.team_leader_id
              ? Number(route.query.team_leader_id)
              : undefined,
          });

          return {
            ...res,
            sort: sort || null,
          };
        },
      },
      props: {
        result: 'items',
        total: 'total',
      },
      autoLoad: true,
    },
    rowConfig: {
      keyField: 'id',
    },
    toolbarConfig: {
      custom: true,
      export: false,
      refresh: { code: 'query' },
      search: true,
      zoom: true,
    },
  } as VxeTableGridOptions<AgentApi.AgentListItem>,
});

// 更多操作菜单项
const moreMenuItems = [
  {
    key: 'links',
    label: '推广链接',
  },
  {
    key: 'rebate',
    label: '返佣记录',
  },
  {
    key: 'upgrade',
    label: '升级记录',
  },
  {
    key: 'order',
    label: '订单记录',
  },
  {
    key: 'withdrawal',
    label: '提现记录',
  },
];

// 团队首领信息
const teamLeaderId = computed(() => route.query.team_leader_id);

// 返回团队首领列表
function onBackToParent() {
  router.replace({
    query: {
      ...route.query,
      team_leader_id: undefined,
    },
  });
}

// 操作处理函数
function onActionClick(
  e:
    | OnActionClickParams<AgentApi.AgentListItem>
    | { code: string; row: AgentApi.AgentListItem },
) {
  switch (e.code) {
    case 'commission': {
      onViewCommission(e.row);
      break;
    }
    case 'edit': {
      onEdit(e.row);
      break;
    }
    case 'links': {
      onViewLinks(e.row);
      break;
    }
    case 'rebate': {
      onViewRebate(e.row);
      break;
    }
    case 'upgrade': {
      onViewUpgrade(e.row);
      break;
    }
    case 'order': {
      onViewOrder(e.row);
      break;
    }
    case 'view-sub-agent': {
      router.replace({
        query: {
          ...route.query,
          team_leader_id: e.row.id,
        },
      });
      break;
    }
    case 'withdrawal': {
      onViewWithdrawal(e.row);
      break;
    }
  }
}

// 编辑处理
function onEdit(row: AgentApi.AgentListItem) {
  formDrawerApi.setData(row).open();
}

// 查看推广链接
function onViewLinks(row: AgentApi.AgentListItem) {
  linkModalApi.setData({ agentId: row.id }).open();
}

// 查看佣金记录
function onViewCommission(row: AgentApi.AgentListItem) {
  commissionModalApi.setData({ agentId: row.id }).open();
}

// 查看返佣记录
function onViewRebate(row: AgentApi.AgentListItem) {
  rebateModalApi.setData({ agentId: row.id }).open();
}

// 查看升级记录
function onViewUpgrade(row: AgentApi.AgentListItem) {
  upgradeModalApi.setData({ agentId: row.id }).open();
}

// 查看订单记录
function onViewOrder(row: AgentApi.AgentListItem) {
  orderModalApi.setData({ agentId: row.id }).open();
}

// 查看提现记录
function onViewWithdrawal(row: AgentApi.AgentListItem) {
  withdrawalModalApi.setData({ agentId: row.id }).open();
}

// 刷新处理
function onRefresh() {
  gridApi.query();
}
</script>

<template>
  <Page auto-content-height>
    <FormDrawer @success="onRefresh" />
    <LinkModalComponent />
    <CommissionModalComponent />
    <RebateModalComponent />
    <UpgradeModalComponent />
    <OrderModalComponent />
    <WithdrawalModalComponent />

    <!-- 团队首领信息卡片 -->
    <Card v-if="teamLeaderId" class="mb-4">
      <div class="flex items-center gap-4">
        <Button @click="onBackToParent">返回上级列表</Button>
        <div>团队首领ID：{{ teamLeaderId }}</div>
      </div>
    </Card>

    <Grid table-title="代理列表">
      <template #operation="{ row }">
        <div class="operation-buttons">
          <Button type="link" @click="onActionClick({ code: 'edit', row })">
            编辑
          </Button>
          <Button type="link" @click="onActionClick({ code: 'view-sub-agent', row })">
            查看下级
          </Button>
          <!-- <Button
            type="link"
            @click="onActionClick({ code: 'order-record', row })"
          >
            订单记录
          </Button> -->
          <Dropdown>
            <Button type="link">更多操作</Button>
            <template #overlay>
              <Menu :items="moreMenuItems" @click="(e) => onActionClick({ code: String(e.key), row })" />
            </template>
          </Dropdown>
        </div>
      </template>
    </Grid>
  </Page>
</template>

<style lang="less" scoped>
.parent-agent-card {
  margin-bottom: 16px;
  background-color: #fafafa;
}

.operation-buttons {
  display: flex;
  align-items: center;
  justify-content: space-around;
  gap: 4px;

  :deep(.ant-btn-link) {
    padding: 0 4px;
  }
}
</style>
