<template>
  <el-container class="withdraw-view panel-block">
    <el-header class="sa-header">
      <!-- 简化搜索组件 -->
      <div class="search-container">
        <sa-search-simple key="withdraw-search" :searchFields="searchFields" :defaultValues="defaultSearchValues"
          v-model="currentSearchParams" @search="handleSearch" @reset="handleReset" />
      </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.withdraw.processing')" name="1"></el-tab-pane>
        <el-tab-pane :label="t('modules.withdraw.approved')" name="2"></el-tab-pane>
        <el-tab-pane :label="t('modules.withdraw.rejected')" name="3"></el-tab-pane>
        <el-tab-pane :label="t('modules.withdraw.success')" name="4"></el-tab-pane>
        <el-tab-pane :label="t('modules.withdraw.failed')" name="5"></el-tab-pane>
        <el-tab-pane :label="t('modules.withdraw.timeout')" name="6"></el-tab-pane>
      </el-tabs>
      <div class="sa-title sa-flex sa-row-between">
        <div class="label sa-flex">{{ t('modules.withdraw.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.withdraw.exporting') : t('modules.withdraw.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.withdraw.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.withdraw.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.withdraw.phoneNo')" min-width="130" align="center">
            <template #default="scope">
              {{ scope.row.userPhone || '-' }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.withdraw.accountType')" min-width="100" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.accountType === 1 ? 'primary' : 'success'">
                {{ getAccountTypeText(scope.row.accountType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.withdraw.channel')" min-width="130" align="center">
            <template #default="scope">
              {{ scope.row.channel || '-' }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.withdraw.method')" min-width="130" align="center">
            <template #default="scope">
              {{ scope.row.bank || '-' }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.withdraw.currency')" min-width="80" align="center">
            <template #default="scope">
              {{ getCurrencyText(scope.row.currency) }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.withdraw.amount')" min-width="130" 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 :label="t('modules.withdraw.receivingAccountName')" min-width="130" align="center">
            <template #default="scope">
              {{ scope.row.bankAccountName || '-' }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.withdraw.receivingAccount')" min-width="160" align="center">
            <template #default="scope">
              {{ scope.row.bankAccount || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="transTime" :label="t('modules.withdraw.createTime')" min-width="160" sortable="custom">
            <template #default="scope">
              {{ scope.row.transTime || '-' }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.withdraw.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 WithdrawDetail from './detail.vue';

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

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

// 当前状态标签
const currentStatus = ref('all');

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

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

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

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

// 默认搜索值
const defaultSearchValues = reactive({
  userName: '',
  userPhone: '',
  orderNo: '',
  accountType: '',
  methodName: '',
  channel: '',
  timeType: 1, // 默认下单时间
  date_range: [],
});
// 列表
const table = reactive({
  data: [],
  order: '',
  sort: '',
  selected: [],
});
const loading = ref(true);

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

// 获取数据
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.withdraw.list(params, false);

    if (code == '200') {
      table.data = data.list || [];
      pageData.page = data.pageNum || 1;
      pageData.size = data.pageSize || 20;
      pageData.total = data.total || 0;
    }
  } 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 = {};
  // 获取当前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(
    WithdrawDetail,
    {
      title: t('modules.withdraw.detail'),
      type: 'view',
      id: row.id,
      size: '80%',
    },
    {
      confirm: () => {
        handleRefresh()
      },
      close: () => {
        handleRefresh()
      },
    },
  );
}

// 查看用户详情
function viewUserDetail(row) {
  useModal(
    UserDetail,
    {
      title: t('modules.withdraw.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.withdraw.report(exportParams, t('modules.withdraw.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();
  getData();
});
</script>
<style lang="scss" scoped>
.withdraw-view {
  .el-header {
    height: auto;
  }

  .el-main {
    .sa-table-wrap {
      height: 100%;
    }
  }
}
</style>
