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

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

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

import { useColumns, useGridFormSchema } from './data';
import DetailModal from './modules/detail-modal.vue';
import RefundModal from './modules/refund-modal.vue';

interface Props {
  agentId?: string;
}

const props = defineProps<Props>();

const queryParams = computed(() => ({
  ...(props.agentId ? { agent_id: props.agentId } : {}),
}));

// 详情弹窗
const [DetailModalComponent, detailModalApi] = useVbenModal({
  connectedComponent: DetailModal,
  destroyOnClose: true,
});

// 退款弹窗
const [RefundModalComponent, refundModalApi] = useVbenModal({
  connectedComponent: RefundModal,
  destroyOnClose: true,
});

const router = useRouter();

// 表格配置
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    fieldMappingTime: [
      ['create_time', ['create_time_start', 'create_time_end']],
      ['pay_time', ['pay_time_start', 'pay_time_end']],
    ],
    schema: useGridFormSchema(),
    submitOnChange: true,
  },
  gridEvents: {
    sortChange: () => {
      gridApi.query();
    },
  } as VxeGridListeners<AgentApi.AgentOrdersListItem>,
  gridOptions: {
    columns: useColumns(onActionClick),
    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 getAgentOrdersList({
            ...queryParams.value,
            page: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
            ...sortParams,
          });

          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.AgentOrdersListItem>,
});

// 操作处理
function onActionClick(
  e: OnActionClickParams<AgentApi.AgentOrdersListItem>,
) {
  switch (e.code) {
    case 'detail': {
      onDetail(e.row);
      break;
    }
    case 'query': {
      onQuery(e.row);
      break;
    }
    case 'refund': {
      onRefund(e.row);
      break;
    }
  }
}

// 详情处理
function onDetail(row: AgentApi.AgentOrdersListItem) {
  detailModalApi.setData(row).open();
}

// 报告结果处理
function onQuery(row: AgentApi.AgentOrdersListItem) {
  if (!row.query_id) {
    message.warning('该订单没有关联的查询记录');
    return;
  }
  router.push({
    name: 'OrderQueryDetail',
    params: {
      id: row.id, // 传递订单ID，后端API需要通过订单ID查询查询记录
    },
  });
}

// 退款处理
function onRefund(row: AgentApi.AgentOrdersListItem) {
  refundModalApi.setData(row).open();
}

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

<template>
  <Page :auto-content-height="!agentId">
    <DetailModalComponent />
    <RefundModalComponent @success="onRefresh" />
    <Grid :table-title="agentId ? '代理订单列表' : '代理订单列表'" />
  </Page>
</template>
