<template>
  <el-container class="recharge-view panel-block">
    <el-header class="sa-header">
      <!-- 简化搜索组件 -->
      <div class="search-container">
        <sa-search-simple key="recharge-search" :searchFields="searchFields" :defaultValues="defaultSearchValues"
          v-model="currentSearchParams" @search="handleSearch" @reset="handleReset" :defaultExpand="true" />
      </div>
      <!-- 状态Tab切换 -->
      <el-tabs class="sa-tabs" v-model="currentStatus" @tab-change="handleTabChange">
        <el-tab-pane :label="t('common.all')" name="all"></el-tab-pane>
        <el-tab-pane :label="t('modules.recharge.processing')" name="1"></el-tab-pane>
        <el-tab-pane :label="t('modules.recharge.success')" name="2"></el-tab-pane>
        <el-tab-pane :label="t('modules.recharge.failed')" name="3"></el-tab-pane>
        <el-tab-pane :label="t('modules.recharge.timeout')" name="4"></el-tab-pane>
      </el-tabs>
      <!-- 统计数据展示 -->
      <div class="statistics-container">
        <div class="stat-item">
          <div class="stat-label">{{ t('modules.recharge.orderNum') }}</div>
          <div class="stat-value">{{ statistics.orderNum || 0 }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">{{ t('modules.recharge.orderAmount') }}</div>
          <div class="stat-value">৳{{ statistics.orderAmount || 0 }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">{{ t('modules.recharge.successOrderNum') }}</div>
          <div class="stat-value">{{ statistics.successNum || 0 }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">{{ t('modules.recharge.successAmount') }}</div>
          <div class="stat-value">৳{{ statistics.successAmount || 0 }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">{{ t('modules.recharge.successRate') }}</div>
          <div class="stat-value">{{ statistics.successRate || 0 }}%</div>
        </div>
      </div>
      <div class="sa-title sa-flex sa-row-between">
        <div class="label sa-flex">{{ t('modules.recharge.title') }}</div>
        <div>
          <el-button class="sa-button-refresh" icon="RefreshRight" @click="handleRefresh"></el-button>
          <el-button icon="Download" type="primary" :loading="exportLoading" :disabled="exportLoading"
            @click="exportRecords">
            {{ exportLoading ? t('modules.recharge.exporting') : t('modules.recharge.exportRecords') }}
          </el-button>
        </div>
      </div>
    </el-header>
    <el-main class="sa-p-0">
      <div class="sa-table-wrap panel-block panel-block--bottom" v-loading="loading">
        <el-table height="100%" class="sa-table" :data="table.data" @sort-change="fieldFilter" row-key="id" stripe>
          <template #empty>
            <sa-empty />
          </template>
          <el-table-column prop="orderNo" :label="t('modules.recharge.orderNo')" min-width="180" sortable="custom">
            <template #default="scope">
              <span class="sa-table-line-1">{{ scope.row.orderNo || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.recharge.userName')" min-width="120">
            <template #default="scope">
              <el-link type="primary" :underline="true" @click="viewUserDetail(scope.row)">
                {{ scope.row.userName || '-' }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="userPhone" :label="t('modules.recharge.phoneNo')" min-width="130" align="center">
            <template #default="scope">
              {{ scope.row.userPhone || '-' }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.recharge.channel')" min-width="100" align="center">
            <template #default="scope">
              {{ scope.row.channelName || '-' }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.recharge.method')" min-width="100" align="center">
            <template #default="scope">
              {{ scope.row.methodName || '-' }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.recharge.currency')" min-width="80" align="center">
            <template #default="scope">
              {{ getCurrencyText(scope.row.currency) }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.recharge.amount')" min-width="120" align="center">
            <template #default="scope"> ৳{{ scope.row.amount || 0 }} </template>
          </el-table-column>
          <el-table-column :label="t('common.status')" min-width="100" align="center">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" :label="t('modules.recharge.createTime')" min-width="160"
            sortable="custom">
            <template #default="scope">
              {{ scope.row.createTime || '-' }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.recharge.successTime')" min-width="160">
            <template #default="scope">
              {{ scope.row.successTime || '--' }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" :label="t('common.actions')" min-width="80">
            <template #default="scope">
              <el-button link type="primary" @click="viewDetail(scope.row)">{{ t('common.detail') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-main>
    <sa-view-bar>
      <template #right>
        <sa-pagination :pageData="pageData" @updateFn="getData" />
      </template>
    </sa-view-bar>
  </el-container>
</template>
<script setup>
import { onMounted, reactive, ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useModal, usePagination } from '@/sheep/hooks';
import { api, financeUtils } from '../finance.service';
import adminApi from '../../../../admin/api';
import UserDetail from '../../user/list/detail.vue';
import RechargeDetail from './detail.vue';

const { t } = useI18n();
const { pageData } = usePagination();

// 设置默认每页20条
pageData.size = 20;

// 支付通道列表
const channelList = ref([]);
const channelLoading = ref(false);

// 搜索字段配置 - 使用计算属性以支持语言切换
const searchFields = computed(() => ({
  userName: {
    type: 'input',
    label: t('modules.recharge.userName'),
    placeholder: t('modules.recharge.enterUserName'),
    width: 150,
  },
  userPhone: {
    type: 'input',
    label: t('modules.recharge.phoneNo'),
    placeholder: t('modules.recharge.enterPhoneNo'),
    width: 150,
  },
  orderNo: {
    type: 'input',
    label: t('modules.recharge.orderNo'),
    placeholder: t('modules.recharge.enterOrderNo'),
    width: 180,
  },
  methodName: {
    type: 'select',
    label: t('modules.recharge.method'),
    placeholder: t('form.pleaseSelect') + t('modules.recharge.method'),
    width: 120,
    options: [
      { label: 'BKASH', value: 'BKASH' },
      { label: 'NAGAD', value: 'NAGAD' },
      { label: 'ROCKET', value: 'ROCKET' },
    ],
  },
  channel: {
    type: 'select',
    label: t('modules.recharge.channel'),
    placeholder: t('form.pleaseSelect') + t('modules.recharge.channel'),
    width: 150,
    options: channelList.value.map(channel => ({
      label: channel.channel,
      value: channel.channelName,
    })),
  },
  timeType: {
    type: 'select',
    label: t('modules.recharge.timeType'),
    placeholder: t('modules.recharge.selectTimeType'),
    width: 120,
    options: [
      { label: t('modules.recharge.createTime'), value: 1 },
      { label: t('modules.recharge.successTime'), value: 2 },
    ],
  },
  date_range: {
    type: 'daterange',
    label: t('modules.recharge.timeRange'),
    placeholder: t('modules.recharge.selectTimeRange'),
    width: 400,
  },
}));

// 默认搜索值
const defaultSearchValues = reactive({
  userName: '',
  userPhone: '',
  orderNo: '',
  methodName: '',
  channel: '',
  timeType: 1, // 默认下单时间
  date_range: getTodayRange(), // 默认当天
});
// 当前状态标签
const currentStatus = ref('all');

// 当前搜索条件
const currentSearchParams = ref({});

// 获取当天日期范围
function getTodayRange() {
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, '0');
  const day = String(today.getDate()).padStart(2, '0');
  const dateStr = `${year}-${month}-${day}`;
  return [dateStr + ' 00:00:00', dateStr + ' 23:59:59'];
}

// 导出loading状态
const exportLoading = ref(false);

// 统计数据
const statistics = ref({
  orderNum: 0,
  orderAmount: 0,
  successNum: 0,
  successAmount: 0,
  successRate: 0
});

// 列表
const table = reactive({
  data: [],
  order: '',
  sort: '',
  selected: [],
});
const loading = ref(true);

// 使用公共配置的函数
const getStatusType = (status) => financeUtils.getStatusType(status, 'recharge');
const getStatusText = financeUtils.getRechargeStatusText;
const getCurrencyText = financeUtils.getCurrencyText;

// 获取数据
async function getData(page, searchParams = {}) {
  if (page) pageData.page = page;
  loading.value = true;

  try {
    // 构建请求参数
    let params = {
      page: pageData.page,
      size: pageData.size,
      ...searchParams,
    };

    // 处理日期范围
    if (searchParams.date_range && searchParams.date_range.length === 2) {
      params.startTime = searchParams.date_range[0];
      params.endTime = searchParams.date_range[1];
      delete params.date_range;
    }
    if (currentStatus.value !== 'all') {
      params.status = parseInt(currentStatus.value);
    }

    // 调用真实API
    const { code, data } = await api.recharge.list(params, false);

    if (code == '200') {
      // 适配新的数据结构
      const listData = data.list?.list || data.list || [];
      table.data = listData;
      pageData.page = data.list?.pageNum || data.pageNum || 1;
      pageData.size = data.list?.pageSize || data.pageSize || 20;
      pageData.total = data.list?.total || data.total || 0;

      // 更新统计数据，successRate需要乘以100
      statistics.value = {
        orderNum: data.orderNum || 0,
        orderAmount: data.orderAmount || 0,
        successNum: data.successNum || 0,
        successAmount: data.successAmount || 0,
        successRate: ((data.successRate || 0) * 100).toFixed(2)
      };
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error(t('common.fetchDataFailed'));
  } finally {
    loading.value = false;
  }
}
// 标签切换处理
const handleTabChange = (status) => {
  currentStatus.value = status;

  // 根据不同状态设置不同的筛选参数
  let statusParams = {};

  if (status !== 'all') {
    statusParams.status = parseInt(status);
  }

  // 整合搜索条件和状态筛选
  const allParams = { ...currentSearchParams.value, ...statusParams };
  getData(1, allParams);
};

// 搜索处理
const handleSearch = (searchParams) => {
  // 由于使用了 v-model，currentSearchParams 会自动更新
  // 获取当前tab的状态参数
  let statusParams = {};
  if (currentStatus.value !== 'all') {
    statusParams.status = parseInt(currentStatus.value);
  }

  // 整合搜索条件和状态筛选
  const allParams = { ...currentSearchParams.value, ...statusParams };
  getData(1, allParams);
};

// 重置处理
const handleReset = () => {
  // 清空搜索参数,包括时间范围
  currentSearchParams.value = {
    userName: '',
    userPhone: '',
    orderNo: '',
    methodName: '',
    channel: '',
    timeType: 1,
    date_range: [], // 重置时清空时间范围
  };
  // 获取当前tab的状态参数
  let statusParams = {};
  if (currentStatus.value !== 'all') {
    statusParams.status = parseInt(currentStatus.value);
  }

  getData(1, statusParams);
};

// 刷新处理 - 保持当前筛选条件
const handleRefresh = () => {
  // 获取当前tab的状态参数
  let statusParams = {};
  if (currentStatus.value !== 'all') {
    statusParams.status = parseInt(currentStatus.value);
  }

  // 整合搜索条件和状态筛选
  const allParams = { ...currentSearchParams.value, ...statusParams };
  getData(pageData.page, allParams);
};

// table 字段排序
function fieldFilter({ prop, order }) {
  table.order = order == 'ascending' ? 'asc' : 'desc';
  table.sort = prop;

  // 获取当前tab的状态参数
  let statusParams = {};
  if (currentStatus.value !== 'all') {
    statusParams.status = parseInt(currentStatus.value);
  }

  // 整合搜索条件和状态筛选
  const allParams = { ...currentSearchParams.value, ...statusParams };
  getData(pageData.page, allParams);
}
// 查看详情
function viewDetail(row) {
  useModal(
    RechargeDetail,
    {
      title: t('modules.recharge.detail'),
      width: '1500px',
      type: 'view',
      id: row.id,
    },
    {
      confirm: () => {
        // 详情页面通常不需要确认回调
      },
    },
  );
}

// 查看用户详情
function viewUserDetail(row) {
  useModal(
    UserDetail,
    {
      title: t('modules.recharge.userDetail'),
      type: 'view',
      id: row.userId,
    },
    {
      confirm: () => {
        // 用户详情页面通常不需要确认回调
      },
    },
  );
}

// 导出记录
async function exportRecords() {
  if (exportLoading.value) return; // 防止重复点击

  exportLoading.value = true;
  try {
    // 构建导出参数，与列表请求参数保持一致，但排除分页相关数据
    const exportParams = {
      ...currentSearchParams.value, // 当前搜索参数
    };

    // 添加当前状态筛选
    if (currentStatus.value !== 'all') {
      exportParams.status = parseInt(currentStatus.value);
    }

    // 处理时间范围搜索（与 getData 函数保持一致）
    if (exportParams.date_range && exportParams.date_range.length === 2) {
      exportParams.startTime = exportParams.date_range[0];
      exportParams.endTime = exportParams.date_range[1];
      delete exportParams.date_range;
    }

    // 调用导出API，所有下载逻辑都在REPORT函数中处理
    await api.recharge.report(exportParams, t('modules.recharge.records'));
  } finally {
    exportLoading.value = false;
  }
}

// 获取支付通道列表
async function getChannelList() {
  channelLoading.value = true;
  try {
    const { code, data } = await adminApi.payment.channel.list({});
    if (code === '200') {
      channelList.value = data || [];
    }
  } catch (error) {
    console.error('获取支付通道失败:', error);
  } finally {
    channelLoading.value = false;
  }
}

onMounted(() => {
  getChannelList();
  // 初始化时使用默认搜索参数(包含默认时间范围)
  currentSearchParams.value = { ...defaultSearchValues };
  getData(1, currentSearchParams.value);
});
</script>
<style lang="scss" scoped>
.recharge-view {
  .el-header {
    height: auto;
  }

  .el-main {
    .sa-table-wrap {
      height: 100%;
    }
  }

  // 统计数据容器样式
  .statistics-container {
    display: flex;
    gap: 16px;
    margin: 14px 0 0 0;
    border-radius: 6px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);

    .stat-item {
      flex: 1;
      text-align: center;
      padding: 10px 12px;
      background: #ffffff;
      border-radius: 4px;
      border-left: 3px solid #409eff;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
      transition: all 0.2s ease;

      &:hover {
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
        transform: translateY(-1px);
      }

      &:nth-child(2) {
        border-left-color: #67c23a;
      }

      &:nth-child(3) {
        border-left-color: #e6a23c;
      }

      &:nth-child(4) {
        border-left-color: #f56c6c;
      }

      &:nth-child(5) {
        border-left-color: #909399;
      }

      .stat-label {
        font-size: 12px;
        color: #606266;
        margin-bottom: 6px;
        font-weight: 500;
      }

      .stat-value {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
    }
  }
}
</style>
