<template>
  <a-page-header :title="getPageTitle()" @back="() => $router.go(-1)">
    <template #extra>
      <a-space>
        <a-button @click="reload()">
          <template #icon>
            <ReloadOutlined />
          </template>
          刷新
        </a-button>
      </a-space>
    </template>

    <a-card :bordered="false" :body-style="{ padding: '16px' }">
      <!-- 搜索区域 -->
      <div class="search-container">
        <a-form layout="inline" :model="searchForm" class="search-form">
          <a-form-item label="关键字">
            <a-input
              v-model:value="searchForm.keywords"
              placeholder="用户ID/兑换码"
              allow-clear
              style="width: 200px"
              @pressEnter="handleSearch"
            />
          </a-form-item>
          <a-form-item label="兑换码">
            <a-input
              v-model:value="searchForm.code"
              placeholder="兑换码"
              allow-clear
              style="width: 200px"
              @pressEnter="handleSearch"
            />
          </a-form-item>
          <a-form-item label="用户ID">
            <a-input-number
              v-model:value="searchForm.userId"
              placeholder="用户ID"
              allow-clear
              style="width: 150px"
              :min="1"
            />
          </a-form-item>
          <a-form-item>
            <a-space>
              <a-button type="primary" @click="handleSearch">
                <template #icon>
                  <SearchOutlined />
                </template>
                搜索
              </a-button>
              <a-button @click="handleReset">
                <template #icon>
                  <ClearOutlined />
                </template>
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>

      <!-- 统计卡片 -->
      <a-row :gutter="16" style="margin-bottom: 16px">
        <a-col :span="8">
          <a-statistic
            title="总充值笔数"
            :value="statistics.totalCount"
            :value-style="{ color: '#1890ff' }"
          />
        </a-col>
        <a-col :span="8">
          <a-statistic
            title="总充值金额"
            :value="statistics.totalAmount"
            :precision="2"
            prefix="¥"
            :value-style="{ color: '#52c41a' }"
          />
        </a-col>
        <a-col :span="8">
          <a-statistic
            title="今日充值金额"
            :value="statistics.todayAmount"
            :precision="2"
            prefix="¥"
            :value-style="{ color: '#faad14' }"
          />
        </a-col>
      </a-row>

      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="id"
        :columns="columns"
        :datasource="datasource"
        :scroll="{ x: 1000 }"
        tool-class="ele-toolbar-form"
      >
        <template #bodyCell="{ column, record }">
          <!-- 金额 -->
          <template v-if="column.key === 'amount'">
            <span class="amount-value">+¥{{ formatAmount(record.amount) }}</span>
          </template>

          <!-- 兑换码 -->
          <template v-if="column.key === 'code'">
            <a-typography-text copyable>{{ record.code }}</a-typography-text>
          </template>

          <!-- 余额变化 -->
          <template v-if="column.key === 'balanceChange'">
            <div class="balance-change">
              <span class="balance-before">{{ formatAmount(record.balanceBefore) }}</span>
              <ArrowRightOutlined />
              <span class="balance-after">{{ formatAmount(record.balanceAfter) }}</span>
            </div>
          </template>

          <!-- 创建时间 -->
          <template v-if="column.key === 'createTime'">
            {{ formatDate(record.createTime) }}
          </template>
        </template>
      </ele-pro-table>
    </a-card>
  </a-page-header>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import {
  ReloadOutlined,
  SearchOutlined,
  ClearOutlined,
  ArrowRightOutlined
} from '@ant-design/icons-vue';
import { toDateString } from 'ele-admin-pro';
import { pageRechargeRecord } from '@/api/shop/shopRechargeRecord';
import type { ShopRechargeRecord } from '@/api/shop/shopRechargeRecord/model';

// 搜索表单
const searchForm = reactive({
  keywords: '',
  code: '',
  userId: undefined as number | undefined
});

// 表格引用
const tableRef = ref(null);

// 统计数据
const statistics = reactive({
  totalCount: 0,
  totalAmount: 0,
  todayAmount: 0
});

// 表格列配置
const columns = ref([
  {
    title: '记录ID',
    dataIndex: 'id',
    key: 'id',
    width: 100
  },
  {
    title: '用户ID',
    dataIndex: 'userId',
    key: 'userId',
    width: 120
  },
  {
    title: '兑换码',
    key: 'code',
    width: 180
  },
  {
    title: '充值金额',
    key: 'amount',
    width: 120,
    align: 'center'
  },
  {
    title: '余额变化',
    key: 'balanceChange',
    width: 200,
    align: 'center'
  },
  {
    title: '充值时间',
    key: 'createTime',
    width: 180,
    align: 'center'
  }
]);

// 数据源
const datasource = ({ page, limit, where, orders }) => {
  const params = {
    ...where,
    ...searchForm,
    ...orders,
    page,
    limit
  };
  return pageRechargeRecord(params).then((res) => {
    // 更新统计数据
    if (res.list && res.list.length > 0) {
      updateStatistics(res.list);
    }
    return res;
  });
};

// 更新统计数据
const updateStatistics = (list: ShopRechargeRecord[]) => {
  statistics.totalCount = list.length;
  statistics.totalAmount = list.reduce((sum, item) => {
    return sum + (Number(item.amount) || 0);
  }, 0);
  
  // 计算今日金额
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  statistics.todayAmount = list
    .filter(item => {
      if (!item.createTime) return false;
      const createDate = new Date(item.createTime);
      return createDate >= today;
    })
    .reduce((sum, item) => {
      return sum + (Number(item.amount) || 0);
    }, 0);
};

// 格式化金额
const formatAmount = (amount: string | number | undefined) => {
  if (amount === null || amount === undefined) return '0.00';
  return Number(amount).toFixed(2);
};

// 格式化日期
const formatDate = (dateStr: string | undefined) => {
  if (!dateStr) return '-';
  return toDateString(dateStr, 'yyyy-MM-dd HH:mm:ss');
};

// 搜索
const handleSearch = () => {
  tableRef.value?.reload();
};

// 重置
const handleReset = () => {
  searchForm.keywords = '';
  searchForm.code = '';
  searchForm.userId = undefined;
  tableRef.value?.reload();
};

// 刷新
const reload = () => {
  tableRef.value?.reload();
};

// 获取页面标题
const getPageTitle = () => {
  return '充值兑换记录';
};

onMounted(() => {
  // 初始加载
});
</script>

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

.amount-value {
  font-weight: bold;
  color: #52c41a;
  font-size: 16px;
}

.balance-change {
  display: flex;
  align-items: center;
  gap: 8px;
}

.balance-before {
  color: #999;
  text-decoration: line-through;
}

.balance-after {
  color: #52c41a;
  font-weight: bold;
}
</style>
