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

import { useVbenModal } from '@vben/common-ui';
import { Card, Statistic, Row, Col, DatePicker, Button, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getAgentCommissionList } from '#/api/agent';
import type { AgentApi } from '#/api';
import dayjs, { Dayjs } from 'dayjs';

interface ModalData {
  agentId: number;
}

const [Modal, modalApi] = useVbenModal({
  title: '历史佣金记录',
  destroyOnClose: true,
  footer: false,
});

const modalData = computed(() => modalApi.getData<ModalData>());

// 时间范围选择
const dateRange = ref<[Dayjs, Dayjs] | undefined>(undefined);

// 统计数据
const statistics = ref({
  totalAmount: 0,
  settledAmount: 0,
  frozenAmount: 0,
  refundedAmount: 0,
  totalCount: 0,
  settledCount: 0,
  frozenCount: 0,
  refundedCount: 0,
});

// 快捷时间范围选择
function selectTimeRange(range: string) {
  const now = dayjs();
  let startDate: Dayjs;

  switch (range) {
    case '7d':
      startDate = now.subtract(7, 'day');
      break;
    case '1m':
      startDate = now.subtract(1, 'month');
      break;
    case '3m':
      startDate = now.subtract(3, 'month');
      break;
    case '1y':
      startDate = now.subtract(1, 'year');
      break;
    default:
      dateRange.value = undefined;
      return;
  }

  dateRange.value = [startDate, now];
}

// 重置时间范围
function resetTimeRange() {
  dateRange.value = undefined;
}

// 表格配置
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    fieldMappingTime: [['create_time', ['create_time_start', 'create_time_end']]],
    schema: [
      {
        component: 'InputNumber',
        fieldName: 'order_id',
        label: '订单ID',
        componentProps: {
          placeholder: '请输入订单ID',
          style: { width: '100%' },
        },
      },
      {
        component: 'Input',
        fieldName: 'product_name',
        label: '产品名称',
        componentProps: {
          placeholder: '请输入产品名称',
        },
      },
      {
        component: 'Select',
        fieldName: 'status',
        label: '状态',
        componentProps: {
          allowClear: true,
          placeholder: '请选择状态',
          options: [
            { label: '已结算', value: 0 },
            { label: '冻结中', value: 1 },
            { label: '已退款', value: 2 },
          ],
        },
      },
    ],
    submitOnChange: true,
  },
  gridOptions: {
    columns: [
      {
        field: 'id',
        title: 'ID',
        width: 80,
      },
      {
        field: 'order_id',
        title: '订单ID',
        width: 100,
      },
      {
        field: 'amount',
        title: '佣金金额',
        width: 120,
        formatter: ({ cellValue }: { cellValue: number }) =>
          `¥${cellValue.toFixed(2)}`,
      },
      {
        field: 'product_name',
        title: '产品名称',
        width: 180,
      },
      {
        field: 'status',
        title: '状态',
        width: 100,
        formatter: ({ cellValue }: { cellValue: number }) => {
          const statusMap: Record<number, string> = {
            0: '已结算',
            1: '冻结中',
            2: '已退款',
          };
          return statusMap[cellValue] || '未知';
        },
        className: ({ cellValue }: { cellValue: number }) => {
          if (cellValue === 0) return 'text-green-600';
          if (cellValue === 1) return 'text-orange-600';
          if (cellValue === 2) return 'text-red-600';
          return '';
        },
      },
      {
        field: 'create_time',
        title: '创建时间',
        width: 160,
        sortable: true,
      },
    ],
    height: 600,
    maxHeight: 800,
    keepSource: true,
    pagerConfig: {
      enabled: true,
      pageSize: 20,
      pageSizes: [10, 20, 50, 100],
      layouts: ['Total', 'Sizes', 'PrevJump', 'Number', 'NextJump', 'FullJump'],
    },
    rowConfig: {
      keyField: 'id',
    },
    toolbarConfig: {
      custom: true,
      export: false,
      refresh: { code: 'query' },
      search: true,
      zoom: true,
    },
    proxyConfig: {
      ajax: {
        query: async ({ page }: { page: { currentPage: number; pageSize: number } }, formValues: Record<string, any>) => {
          const params: any = {
            agent_id: modalData.value?.agentId,
            ...formValues,
            page: page.currentPage,
            pageSize: page.pageSize,
          };

          // 添加时间范围参数
          if (dateRange.value && dateRange.value[0] && dateRange.value[1]) {
            params.create_time_start = dateRange.value[0].format('YYYY-MM-DD HH:mm:ss');
            params.create_time_end = dateRange.value[1].format('YYYY-MM-DD HH:mm:ss');
          }

          const result = await getAgentCommissionList(params);

          // 更新统计数据
          updateStatistics(result.items || []);

          return result;
        },
      },
      props: {
        result: 'items',
        total: 'total',
      },
      autoLoad: true,
    },
  },
});

// 更新统计数据
function updateStatistics(items: AgentApi.AgentCommissionListItem[]) {
  statistics.value = {
    totalCount: items.length,
    totalAmount: items.reduce((sum, item) => sum + item.amount, 0),
    settledCount: items.filter(item => item.status === 0).length,
    settledAmount: items.filter(item => item.status === 0).reduce((sum, item) => sum + item.amount, 0),
    frozenCount: items.filter(item => item.status === 1).length,
    frozenAmount: items.filter(item => item.status === 1).reduce((sum, item) => sum + item.amount, 0),
    refundedCount: items.filter(item => item.status === 2).length,
    refundedAmount: items.filter(item => item.status === 2).reduce((sum, item) => sum + item.amount, 0),
  };
}

// 监听时间范围变化，自动刷新表格
watch(dateRange, () => {
  if (gridApi) {
    gridApi.query();
  }
});
</script>

<template>
  <Modal class="w-[calc(100vw-200px)]">
    <div class="commission-history-modal">
      <!-- 时间范围选择 -->
      <Card class="mb-4" title="时间范围选择">
        <Space :size="12">
          <span class="text-sm text-gray-600">快速选择：</span>
          <Button size="small" @click="selectTimeRange('7d')">近7日</Button>
          <Button size="small" @click="selectTimeRange('1m')">近1月</Button>
          <Button size="small" @click="selectTimeRange('3m')">近3月</Button>
          <Button size="small" @click="selectTimeRange('1y')">近1年</Button>
          <Button size="small" type="default" @click="resetTimeRange">全部</Button>
          <span class="text-sm text-gray-400 ml-4">|</span>
          <span class="text-sm text-gray-600">自定义：</span>
          <DatePicker.RangePicker
            v-model:value="dateRange"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
            :placeholder="['开始时间', '结束时间']"
            style="width: 380px"
          />
        </Space>
      </Card>

      <!-- 统计卡片 -->
      <Card class="mb-4" title="统计信息">
        <Row :gutter="[16, 16]">
          <Col :span="6">
            <Statistic title="总记录数" :value="statistics.totalCount" />
          </Col>
          <Col :span="6">
            <Statistic
              title="总佣金金额"
              :value="statistics.totalAmount"
              :precision="2"
              prefix="¥"
              :value-style="{ color: '#1890ff' }"
            />
          </Col>
          <Col :span="6">
            <Statistic
              title="已结算金额"
              :value="statistics.settledAmount"
              :precision="2"
              prefix="¥"
              :value-style="{ color: '#52c41a' }"
            />
            <div class="text-sm text-gray-500 mt-1">
              {{ statistics.settledCount }} 条记录
            </div>
          </Col>
          <Col :span="6">
            <Statistic
              title="冻结中金额"
              :value="statistics.frozenAmount"
              :precision="2"
              prefix="¥"
              :value-style="{ color: '#fa8c16' }"
            />
            <div class="text-sm text-gray-500 mt-1">
              {{ statistics.frozenCount }} 条记录
            </div>
          </Col>
        </Row>
        <Row :gutter="[16, 16]" class="mt-4">
          <Col :span="12">
            <Statistic
              title="已退款金额"
              :value="statistics.refundedAmount"
              :precision="2"
              prefix="¥"
              :value-style="{ color: '#f5222d' }"
            />
            <div class="text-sm text-gray-500 mt-1">
              {{ statistics.refundedCount }} 条记录
            </div>
          </Col>
        </Row>
      </Card>

      <!-- 佣金记录列表 -->
      <Grid :table-title="`代理商 ID: ${modalData?.agentId} 的历史佣金记录`" />
    </div>
  </Modal>
</template>

<style lang="less" scoped>
.commission-history-modal {
  padding: 16px;
}
</style>
