<template>
  <el-container class="commission-view panel-block">
    <el-header class="sa-header">
      <!-- 简化搜索组件 -->
      <div class="search-container">
        <sa-search-simple :searchFields="searchFields" :defaultValues="defaultSearchValues"
          v-model="currentSearchParams" @search="handleSearch" @reset="handleReset">
        </sa-search-simple>
      </div>
      <div class="sa-title sa-flex sa-row-between">
        <div class="label sa-flex">{{ t('modules.commission.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.commission.exporting') : t('modules.commission.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="tranNo" :label="t('modules.commission.commissionNo')" min-width="180"
            sortable="custom">
            <template #default="scope">
              <span class="sa-table-line-1">{{ scope.row.tranNo || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.commission.userName')" min-width="120">
            <template #default="scope">
              <el-link type="primary" :underline="true" @click="viewUserDetail(scope.row)">
                {{ scope.row.name || '-' }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="phoneNo" :label="t('modules.commission.phoneNo')" min-width="130" align="center">
            <template #default="scope">
              {{ scope.row.phoneNo || '-' }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.commission.commissionAmount')" min-width="120" align="center">
            <template #default="scope"> ৳{{ scope.row.amount || 0 }} </template>
          </el-table-column>
          <el-table-column :label="t('modules.commission.commissionType')" min-width="150">
            <template #default="scope">
              <span class="sa-table-line-1">{{ getBizTypeTextFromOptions(scope.row.bizType) }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.commission.orderNo')" min-width="150">
            <template #default="scope">
              <el-link v-if="scope.row.orderNo && scope.row.orderNo.startsWith('BH')" type="primary" :underline="true"
                @click="viewOrderDetail(scope.row)">
                {{ scope.row.orderNo }}
              </el-link>
              <span v-else-if="scope.row.orderNo">{{ scope.row.orderNo }}</span>
              <span v-else>--</span>
            </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.commission.issueTime')" min-width="160"
            sortable="custom">
            <template #default="scope">
              {{ scope.row.createTime || '-' }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.commission.settleTime')" min-width="160">
            <template #default="scope">
              {{ scope.row.settleTime || '--' }}
            </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 UserDetail from '../../user/list/detail.vue';
import OrderDetail from '../../order/order/detail.vue';

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

// 业务类型选项 - 响应式数据
const bizTypeOptions = ref([]);

// 搜索字段配置 - 使用计算属性以支持语言切换
const searchFields = computed(() => ({
  name: {
    type: 'input',
    label: t('modules.commission.userName'),
    placeholder: t('modules.commission.enterUserName'),
    width: 150,
  },
  phoneNo: {
    type: 'input',
    label: t('modules.commission.phoneNo'),
    placeholder: t('modules.commission.enterPhoneNo'),
    width: 150,
  },
  orderNo: {
    type: 'input',
    label: t('modules.commission.orderNo'),
    placeholder: t('modules.commission.enterOrderNo'),
    width: 180,
  },
  status: {
    type: 'select',
    label: t('common.status'),
    placeholder: t('modules.commission.selectStatus'),
    width: 120,
    options: [
      { label: t('common.all'), value: '' },
      { label: t('modules.commission.unsettled'), value: 1 },
      { label: t('modules.commission.settled'), value: 2 },
    ],
  },
  bizType: {
    type: 'select',
    label: t('modules.commission.commissionType'),
    placeholder: t('modules.commission.selectType'),
    width: 150,
    options: bizTypeOptions.value, // 使用响应式的选项
  },
  date_range: {
    type: 'daterange',
    label: t('modules.finance.timeRange'),
    placeholder: t('modules.commission.selectTimeRange'),
    width: 240,
  },
}));

// 默认搜索值
const defaultSearchValues = reactive({
  name: '',
  phoneNo: '',
  orderNo: '',
  status: '',
  bizType: '',
  date_range: [],
});

// 当前搜索参数状态
const currentSearchParams = ref({});

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

// 搜索处理函数
function handleSearch(searchParams) {
  // 由于使用了 v-model，currentSearchParams 会自动更新
  // 直接调用 getData，会自动使用当前的搜索条件
  getData(1);
}

// 重置搜索参数处理函数
function handleReset() {
  // 手动清空搜索参数
  currentSearchParams.value = {};
  // 传递空参数重新请求数据
  getData(1, {});
}

// 刷新处理 - 保持当前筛选条件
function handleRefresh() {
  // 使用当前搜索条件刷新数据
  const finalSearchParams = currentSearchParams.value || {};
  getData(pageData.page, finalSearchParams);
}

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

// 状态处理函数
const getStatusType = financeUtils.getCommissionStatusType;

// 状态文本需要前端国际化（固定枚举值）
const getStatusText = (status) => {
  const statusMap = {
    1: t('modules.commission.unsettled'),
    2: t('modules.commission.settled'),
  };
  return statusMap[status] || t('modules.commission.unknown');
};

// 业务类型文本由后端处理国际化，这里保留原函数作为后备
const getBizTypeText = financeUtils.getBizTypeText;

// 根据后端返回的佣金类型选项数据匹配显示文本
const getBizTypeTextFromOptions = (bizType) => {
  if (!bizType) return '--';

  // 从 bizTypeOptions 中查找匹配的类型
  const matchedOption = bizTypeOptions.value.find(option => option.value === bizType);

  if (matchedOption) {
    return matchedOption.label;
  }

  // 如果没有匹配到，使用后备函数
  return getBizTypeText(bizType);
};

// 获取佣金类型枚举
async function getCommissionTypes() {
  try {
    const { code, data } = await api.commission.getTypes();

    if (code == '200' && data) {
      const options = [{ label: t('common.all'), value: '' }]; // 前端国际化的"全部"选项
      data.forEach((item) => {
        options.push({
          label: item.name, // 后端返回的已国际化文本
          value: item.code,
        });
      });
      bizTypeOptions.value = options;
    }
  } catch (error) {
    console.error('获取佣金类型枚举失败:', error);
  }
}

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

  try {
    // 构建请求参数 - 优先使用传入的参数，否则使用双向绑定的搜索条件
    const finalSearchParams = searchParams !== null ? searchParams : currentSearchParams.value;

    let params = {
      page: pageData.page,
      size: pageData.size,
      ...finalSearchParams,
    };

    // 处理日期范围
    if (finalSearchParams.date_range && finalSearchParams.date_range.length === 2) {
      params.startTime = finalSearchParams.date_range[0];
      params.endTime = finalSearchParams.date_range[1];
      delete params.date_range;
    }

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

    if (code == '200') {
      table.data = data.list || [];
      pageData.page = data.pageNum || 1;
      pageData.size = data.pageSize || 10;
      pageData.total = data.total || 0;
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error(t('common.fetchDataFailed'));
  } finally {
    loading.value = false;
  }
}
// table 字段排序
function fieldFilter({ prop, order }) {
  table.order = order == 'ascending' ? 'asc' : 'desc';
  table.sort = prop;
  // 使用当前搜索条件进行排序
  const finalSearchParams = currentSearchParams.value || {};
  getData(pageData.page, finalSearchParams);
}

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

// 查看订单详情
function viewOrderDetail(row) {
  if (!row.orderNo || !row.orderNo.startsWith('BH')) return;
  useModal(
    OrderDetail,
    {
      title: t('modules.commission.orderDetail'),
      type: 'view',
      orderNo: row.orderNo,
    },
    {
      confirm: () => {
        // 订单详情页面通常不需要确认回调
      },
    },
  );
}

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

  exportLoading.value = true;
  try {
    // 构建导出参数，与列表请求参数保持一致，但排除分页相关数据
    const exportParams = {
      ...currentSearchParams.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.commission.report(exportParams, t('modules.commission.commissionRecords'));
  } finally {
    exportLoading.value = false;
  }
}

onMounted(() => {
  getCommissionTypes(); // 获取佣金类型枚举
  getData();
});
</script>
<style lang="scss" scoped>
.commission-view {
  .el-header {
    height: auto;
  }

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