<template>
  <el-container class="user-detail" v-loading="loading">
    <el-main>
      <!-- 操作按钮 -->
      <!-- <div class="action-buttons sa-m-b-2"> -->
      <!-- <el-button @click="onSendSms">发短信</el-button> -->
      <!-- <el-button @click="onAppPush">APP推送</el-button> -->
      <!-- <el-button type="primary" @click="onEdit">{{ t('modules.user.editProfile') }}</el-button> -->
      <!-- </div> -->

      <!-- 基本信息 -->
      <div class="basic-info sa-m-b-10">
        <div class="sa-title sa-m-b-10 font-bold">{{ t('modules.user.basicInfo') }}</div>
        <div class="basic-info-tables">
          <!-- 第一行表格 -->
          <el-table class="sa-table basic-info-table-1" :data="[state.basicInfoTableData[0]]" stripe border
            :show-header="true">
            <el-table-column :label="t('modules.user.userName')" align="center">
              <template #default="{ row }">
                {{ row.field3 || '--' }}
              </template>
            </el-table-column>
            <el-table-column :label="t('modules.user.userId')" align="center">
              <template #default="{ row }">
                {{ row.field1 || '--' }}
              </template>
            </el-table-column>
            <el-table-column :label="t('modules.user.invitedCode')" align="center">
              <template #default="{ row }">
                {{ row.invitedCode || '--' }}
              </template>
            </el-table-column>
            <el-table-column :label="t('common.status')" align="center">
              <template #default="{ row }">
                {{ row.field2 || '--' }}
              </template>
            </el-table-column>
            <el-table-column :label="t('modules.user.accountName')" align="center">
              <template #default="{ row }">
                {{ state.userDetail.bankAccountName || '--' }}
              </template>
            </el-table-column>
            <el-table-column :label="t('modules.user.paymentBank')" align="center">
              <template #default="{ row }">
                {{ state.userDetail.bank || '--' }}
              </template>
            </el-table-column>
            <el-table-column :label="t('modules.user.paymentAccount')" align="center">
              <template #default="{ row }">
                {{ state.userDetail.bankAccount || '--' }}
              </template>
            </el-table-column>
          </el-table>

          <!-- 第二行表格 -->
          <el-table class="sa-table basic-info-table-2" :data="[state.basicInfoTableData[1]]" stripe border
            :show-header="true">
            <el-table-column :label="t('modules.user.vipLevel')" align="center" :rowspan="2">
              <template #default="{ row }">
                <div class="vip-section">
                  <div class="user-name">
                    <span class="user-level ml-4px">V{{ state.userDetail.vipLevel }}</span>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="t('modules.user.userPhone')" align="center">
              <template #default="{ row }">
                {{ state.basicInfoTableData[1]?.field1 || '--' }}
              </template>
            </el-table-column>
            <el-table-column :label="t('modules.user.registrationTime')" align="center">
              <template #default="{ row }">
                {{ state.basicInfoTableData[1]?.field2 || '--' }}
              </template>
            </el-table-column>
            <el-table-column label="" align="center">
              <template #default="{ row }">
                <!-- 空白，因为VIP等级已经在上面显示 -->
              </template>
            </el-table-column>
            <el-table-column label="" align="center">
              <template #default="{ row }">
                <!-- 空白列，对应用户ID -->
              </template>
            </el-table-column>
            <el-table-column label="" align="center">
              <template #default="{ row }">
                <!-- 空白列，对应状态 -->
              </template>
            </el-table-column>
            <el-table-column label="" align="center">
              <template #default="{ row }">
                <!-- 空白列，对应状态 -->
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 统计信息 -->
      <div class="stats-info sa-m-b-26">
        <div class="sa-title sa-m-b-10 font-bold">{{ t('modules.user.statisticsInfo') }}</div>
        <el-table class="sa-table" :data="state.statsTableData" stripe border>
          <el-table-column :label="t('modules.user.inviteFriends')" align="center">
            <template #default="{ row }">{{ row.inviteNum }}</template>
          </el-table-column>
          <el-table-column :label="t('modules.user.successOrders')" align="center">
            <template #default="{ row }">{{ row.successGroupNum }}</template>
          </el-table-column>
          <el-table-column :label="t('modules.user.availableBalance')" align="center">
            <template #default="{ row }">{{ formatCurrency(row.availableAmount) }}</template>
          </el-table-column>
          <el-table-column :label="t('modules.user.availableGroups')" align="center">
            <template #default="{ row }">{{ row.groupNum }}</template>
          </el-table-column>
          <el-table-column :label="t('modules.user.totalCommission')" align="center">
            <template #default="{ row }">{{ formatCurrency(row.totalEarnings) }}</template>
          </el-table-column>
          <el-table-column :label="t('modules.user.settledCommission')" align="center">
            <template #default="{ row }">{{ formatCurrency(row.settledEarnings) }}</template>
          </el-table-column>
          <el-table-column :label="t('modules.user.totalRecharge')" align="center">
            <template #default="{ row }">{{ formatCurrency(row.rechargeAmount) }}</template>
          </el-table-column>
        </el-table>

        <!-- 第二行统计数据 -->
        <el-table class="sa-table mt-2px" :data="state.statsTableData2" stripe border>
          <el-table-column :label="t('modules.user.teamMembers')" align="center">
            <template #default="{ row }">{{ row.teamNum }}</template>
          </el-table-column>
          <el-table-column :label="t('modules.user.accountBalance')" align="center">
            <template #default="{ row }">{{ formatCurrency(row.walletBalance) }}</template>
          </el-table-column>
          <el-table-column :label="t('modules.user.frozenBalance')" align="center">
            <template #default="{ row }">{{ formatCurrency(row.freezeAmount) }}</template>
          </el-table-column>
          <el-table-column :label="t('modules.user.commissionBalance')" align="center">
            <template #default="{ row }">{{ formatCurrency(row.earningsBalance) }}</template>
          </el-table-column>
          <el-table-column :label="t('modules.user.last7DaysCommission')" align="center">
            <template #default="{ row }">{{ formatCurrency(row.l7DEarnings) }}</template>
          </el-table-column>
          <el-table-column :label="t('modules.user.pendingCommission')" align="center">
            <template #default="{ row }">{{ formatCurrency(row.pendingEarnings) }}</template>
          </el-table-column>
          <el-table-column :label="t('modules.user.totalWithdraw')" align="center">
            <template #default="{ row }">{{ formatCurrency(row.withdrawAmount) }}</template>
          </el-table-column>
        </el-table>
      </div>

      <!-- Tab切换内容 -->
      <div class="tab-content">
        <el-tabs v-model="state.activeTab" @tab-change="handleTabChange">
          <el-tab-pane :label="t('modules.user.orderRecords')" name="orders">
            <el-skeleton v-if="state.loading.orders" :rows="5" animated />
            <el-table v-else class="sa-table" :data="state.orders" stripe border>
              <el-table-column sortable="custom" prop="orderId" :label="t('modules.order.orderNumber')" min->
                <template #default="{ row }">
                  <div class="order-info">
                    <div class="order-sn">{{ row.orderId }}</div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.goods.goodsInfo')" min-width="300">
                <template #default="{ row }">
                  <div class="sa-flex" v-if="row.productName">
                    <el-image :src="row.image" style="width: 60px; height: 60px; margin-right: 12px" fit="cover" />
                    <div>
                      <div class="goods-title">{{ row.productName }}</div>
                    </div>
                  </div>
                  <div v-else>-</div>
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.goods.specification')" align="center">
                <template #default="{ row }">
                  <div v-if="row.sku">
                    {{ row.sku || '-' }}
                  </div>
                  <div v-else>-</div>
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.order.quantity')" min-width="80" align="center">
                <template #default="{ row }">
                  <div v-if="row.payNum">
                    {{ row.payNum || 0 }}
                  </div>
                  <div v-else>0</div>
                </template>
              </el-table-column>
              <el-table-column prop="payPrice" :label="t('modules.order.paymentAmount')" min-width="130" align="center">
                <template #default="{ row }">
                  <div>{{ formatCurrency(row.payPrice) }}</div>
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.order.orderStatus')" min-width="100" align="center">
                <template #default="{ row }">
                  <el-tag :type="getStatusType('order', row.status)">
                    {{ getStatusText('order', row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.order.groupStatusLabel')" min-width="110" align="center">
                <template #default="{ row }">
                  <el-tag :type="getStatusType('pink', row.storePinkStatus)">
                    {{ getStatusText('pink', row.storePinkStatus) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.order.logistics')" min- align="center">
                <template #default="{ row }">
                  <div v-if="row.deliveryId">
                    <div class="delivery-name">{{ row.deliveryName || t('modules.order.courier') }}：{{ row.deliveryId }}
                    </div>
                  </div>
                  <div v-else>{{ t('modules.order.notShipped') }}</div>
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.order.orderTime')" min- align="center">
                <template #default="{ row }">
                  <div>{{ row.createTime }}</div>
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.order.payTime')" min- align="center">
                <template #default="{ row }">
                  <div>{{ row.payTime || '-' }}</div>
                </template>
              </el-table-column>
              <el-table-column :label="t('common.actions')" align="center">
                <template #default="{ row }">
                  <el-button type="primary" link @click="viewOrder(row)">{{ t('common.detail') }}</el-button>
                  <el-button v-if="row.status === 3 && row.pinkStatus === 1" type="danger" link
                    @click="handleRefund(row)" class="ml-2">
                    {{ t('common.refund') }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <el-tab-pane :label="t('modules.user.subordinateUsers')" name="subordinates">
            <el-skeleton v-if="state.loading.subordinates" :rows="5" animated />
            <el-table v-else class="sa-table" :data="state.subordinates" stripe border>
              <el-table-column :label="t('modules.user.userName')" prop="name" align="center">
                <template #default="{ row }">
                  {{ row.name || '--' }}
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.user.userPhone')" prop="phoneNo" align="center" />
              <el-table-column :label="t('modules.user.registrationTime')" prop="createTime" align="center" />
              <el-table-column :label="t('modules.user.userLevel')" width="100" align="center">
                <template #default="{ row }"> V{{ row.vipLevel }} </template>
              </el-table-column>
              <el-table-column :label="t('common.actions')" width="80" align="center">
                <template #default="{ row }">
                  <el-button type="primary" link @click="viewSubordinateUser(row)">{{ t('common.view') }}</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <el-tab-pane :label="t('modules.user.commissionRecords')" name="commissions">
            <el-skeleton v-if="state.loading.commissions" :rows="5" animated />
            <el-table v-else class="sa-table" :data="state.commissions" stripe border>
              <el-table-column :label="t('modules.user.commissionId')" prop="id" align="center" />
              <el-table-column :label="t('modules.user.commissionType')" min->
                <template #default="{ row }">
                  <span class="sa-table-line-1">{{ getBizTypeTextFromOptions(row.bizType) }}</span>
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.user.commissionAmount')" align="center">
                <template #default="{ row }"> {{ formatCurrency(row.amount) }} </template>
              </el-table-column>
              <el-table-column :label="t('modules.user.commissionStatus')" min-width="100" align="center">
                <template #default="{ row }">
                  <el-tag :type="getStatusType('commission', row.status)">
                    {{ getStatusText('commission', row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" :label="t('modules.user.commissionTime')" min-width="160"
                sortable="custom">
                <template #default="{ row }">
                  {{ row.createTime || '-' }}
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <el-tab-pane :label="t('modules.user.rechargeRecords')" name="recharges">
            <el-skeleton v-if="state.loading.recharges" :rows="5" animated />
            <el-table v-else class="sa-table" :data="state.recharges" stripe border>
              <el-table-column prop="orderNo" :label="t('modules.user.rechargeOrderNo')" min-width="100"
                sortable="custom">
                <template #default="{ row }">
                  <span class="sa-table-line-1">{{ row.orderNo || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.user.rechargeChannel')" align="center">
                <template #default="{ row }">
                  {{ row.channelName || '-' }}
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.user.rechargeMethod')" min-width="100" align="center">
                <template #default="{ row }">
                  {{ row.methodName || '-' }}
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.user.currency')" min-width="80" align="center">
                <template #default="{ row }">
                  {{ getCurrencyText(row.currency) }}
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.user.amount')" align="center">
                <template #default="{ row }"> {{ formatCurrency(row.amount) }} </template>
              </el-table-column>
              <el-table-column :label="t('common.status')" min-width="100" align="center">
                <template #default="{ row }">
                  <el-tag :type="getStatusType('recharge', row.status)">
                    {{ getStatusText('recharge', row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" :label="t('modules.order.orderTime')" min-width="160"
                sortable="custom">
                <template #default="{ row }">
                  {{ row.createTime || '-' }}
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.user.successTime')" min-width="160">
                <template #default="{ row }">
                  {{ row.successTime || '--' }}
                </template>
              </el-table-column>
              <el-table-column fixed="right" :label="t('common.actions')" min-width="80">
                <template #default="{ row }">
                  <el-button link type="primary" @click="viewRecharge(row)">{{ t('common.detail') }}</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <el-tab-pane :label="t('modules.user.withdrawRecords')" name="withdraws">
            <el-skeleton v-if="state.loading.withdraws" :rows="5" animated />
            <el-table v-else class="sa-table" :data="state.withdraws" stripe border>
              <el-table-column prop="orderNo" :label="t('modules.user.withdrawOrderNo')" min-width="150"
                sortable="custom">
                <template #default="{ row }">
                  <span class="sa-table-line-1">{{ row.orderNo || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.user.withdrawType')" min-width="100" align="center">
                <template #default="{ row }">
                  <el-tag :type="row.accountType === 1 ? 'primary' : 'success'">
                    {{ getAccountTypeText(row.accountType) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.withdraw.channel')" min-width="130" align="center">
                <template #default="{ row }">
                  {{ row.channel || '-' }}
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.withdraw.method')" min-width="130" align="center">
                <template #default="{ row }">
                  {{ row.bank || '-' }}
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.user.currency')" min-width="80" align="center">
                <template #default="{ row }">
                  {{ getCurrencyText(row.currency) }}
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.user.withdrawAmount')" align="center">
                <template #default="{ row }"> {{ formatCurrency(row.amount) }} </template>
              </el-table-column>
              <el-table-column :label="t('common.status')" min-width="100" align="center">
                <template #default="{ row }">
                  <el-tag :type="getStatusType('withdraw', row.status)">
                    {{ getStatusText('withdraw', row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.user.accountName')" min-width="130" align="center">
                <template #default="{ row }">
                  {{ row.bankAccountName || '-' }}
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.user.paymentAccount')" min-width="160" align="center">
                <template #default="{ row }">
                  {{ row.bankAccount || '-' }}
                </template>
              </el-table-column>
              <el-table-column prop="transTime" :label="t('modules.order.orderTime')" min-width="160" sortable="custom">
                <template #default="{ row }">
                  {{ row.transTime || '-' }}
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.user.successTime')" min-width="160">
                <template #default="{ row }">
                  {{ row.successTime || '--' }}
                </template>
              </el-table-column>
              <el-table-column fixed="right" :label="t('common.actions')" min-width="80">
                <template #default="{ row }">
                  <el-button link type="primary" @click="viewWithdraw(row)">{{ t('common.detail') }}</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <el-tab-pane :label="t('modules.user.shippingAddresses')" name="addresses">
            <el-skeleton v-if="state.loading.addresses" :rows="5" animated />
            <el-table v-else class="sa-table" :data="state.addresses" stripe border>
              <el-table-column :label="t('modules.user.recipient')" prop="realName" align="center" />
              <el-table-column :label="t('modules.user.userPhone')" prop="phone" min-width="130" align="center" />
              <el-table-column :label="t('modules.user.detailedAddress')" min-width="400">
                <template #default="{ row }">
                  {{ row.province }}/{{ row.city }}/{{ row.district }}/{{ row.detail }}
                  {{ row.postCode }}
                </template>
              </el-table-column>
              <el-table-column :label="t('modules.user.isDefault')" min-width="100" align="center">
                <template #default="{ row }">
                  <el-tag :type="row.isDefault === 1 ? 'success' : 'info'">
                    {{ row.isDefault === 1 ? t('modules.user.defaultAddress') : t('modules.user.normalAddress') }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>

        <!-- 统一分页组件 -->
        <div class="sa-m-t-20 flex justify-end">
          <sa-pagination layout="total, prev, pager, next" :pageData="pageData"
            @updateFn="() => loadTabData(state.activeTab)" />
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useModal, usePagination } from '@/sheep/hooks';
import { api, userUtils } from '../user.service';

const { t } = useI18n();
import {
  api as orderApi,
  getOrderStatusInfo,
  getRefundStatusInfo,
  getPinkStatusInfo,
} from '../../order/order.service';
import { api as financeApi, financeUtils } from '../../finance/finance.service';
import userEdit from './edit.vue';
import OrderDetail from '../../order/order/detail.vue';
import userDetail from './detail.vue';
import RechargeDetail from '../../finance/recharge/detail.vue';
import WithdrawDetail from '../../finance/withdraw/detail.vue';

const props = defineProps({
  modal: {
    type: Object,
    default: () => ({}),
  },
});

// 分页数据
const { pageData } = usePagination();
// 设置默认每页20条
pageData.size = 20;

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

const state = reactive({
  userDetail: {},
  basicInfoTableData: [],
  statsTableData: [],
  statsTableData2: [],
  orders: [],
  subordinates: [],
  commissions: [],
  recharges: [],
  withdraws: [],
  addresses: [],
  activeTab: 'orders',
  loading: {
    orders: false,
    subordinates: false,
    commissions: false,
    recharges: false,
    withdraws: false,
    addresses: false,
  },
});

// 初始化基本信息表格数据
const initBasicInfoTableData = () => {
  state.basicInfoTableData = [
    {
      field1: state.userDetail.userNo || '--', // 用户ID
      invitedCode: state.userDetail.invitedCode || '--', // 邀请码
      field2: getStatusText('user', state.userDetail.status) || '--', // 状态
      field3: state.userDetail.name || '--', // 昵称
      field4: state.userDetail.bank || '--', // 收款银行
      field5: state.userDetail.bankAccountName || '--', // 账户名称
    },
    {
      field1: state.userDetail.phoneNo || '--', // 手机号
      field2: state.userDetail.createTime || '--', // 注册时间
      field3: state.userDetail.bankAccount || '--', // 收款账户
    },
  ];
  // 初始化统计信息表格数据
  state.statsTableData = [
    {
      inviteNum: state.userDetail.inviteNum || 0, // 邀请好友数
      successGroupNum: state.userDetail.successGroupNum || 0, // 成团数
      groupNum: state.userDetail.groupNum || 0, // 可参团数
      totalEarnings: state.userDetail.totalEarnings || 0, // 总收益
      availableAmount: state.userDetail.availableAmount || 0, // 可用余额
      settledEarnings: state.userDetail.settledEarnings || 0, // 已结算收益
      rechargeAmount: state.userDetail.rechargeAmount || 0, // 充值
    },
  ];

  state.statsTableData2 = [
    {
      teamNum: state.userDetail.teamNum || 0, // 团队人数
      walletBalance: state.userDetail.walletBalance || 0, // 钱包余额
      earningsBalance: state.userDetail.earningsBalance || 0, // 收益余额
      freezeAmount: state.userDetail.freezeAmount || 0, // 冻结金额
      l7DEarnings: state.userDetail.l7DEarnings || 0, // 近7天收益
      pendingEarnings: state.userDetail.pendingEarnings || 0, // 待结算金额
      withdrawAmount: state.userDetail.withdrawAmount || 0, // 提现总金额
    },
  ];
};

// 通用状态处理函数
const getStatusText = (type, value) => {
  const statusMap = {
    user: userUtils.getUserStatusText,
    order: getOrderStatusInfo,
    refund: getRefundStatusInfo,
    pink: getPinkStatusInfo,
    commission: financeUtils.getCommissionStatusText,
    recharge: financeUtils.getRechargeStatusText,
    withdraw: financeUtils.getWithdrawStatusText,
  };

  // 对于用户状态和财务状态，直接调用函数
  if (['user', 'commission', 'recharge', 'withdraw'].includes(type)) {
    return statusMap[type]?.(value) || '未知';
  }

  // 对于订单相关状态，返回text属性
  return statusMap[type]?.(value)?.text || '未知';
};

const getStatusType = (type, value) => {
  const statusMap = {
    order: getOrderStatusInfo,
    refund: getRefundStatusInfo,
    pink: getPinkStatusInfo,
    commission: financeUtils.getCommissionStatusType,
    recharge: (status) => financeUtils.getStatusType(status, 'recharge'),
    withdraw: (status) => financeUtils.getStatusType(status, 'withdraw'),
  };
  return statusMap[type]?.(value) || 'info';
};

// 财务相关工具函数（保持不变，因为这些是工具函数而非状态函数）
const getCurrencyText = financeUtils.getCurrencyText;
const getAccountTypeText = financeUtils.getAccountTypeText;
const getBizTypeText = financeUtils.getBizTypeText;
const formatCurrency = financeUtils.formatCurrency;

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

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

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

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

  if (matchedOption) {
    return matchedOption.label;
  }

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

// 获取用户详情
const loading = ref(false);
const getUserDetail = async () => {
  try {
    loading.value = true;
    const { code, data } = await api.list.userDetail(props.modal.params.id);
    if (code == '200') {
      state.userDetail = data;
      initBasicInfoTableData();
      // 用户详情获取完成后，加载当前激活的tab数据
      await loadTabData(state.activeTab);
    }
  } catch (error) {
    console.error('获取用户详情失败:', error);
  }
  loading.value = false;
};

// 统一数据获取函数
const fetchTabData = async (tabType, page = 1) => {
  try {
    // 确保用户详情已获取，特别是手机号
    if (!state.userDetail.phoneNo) {
      console.warn('用户手机号未获取，跳过数据请求');
      return;
    }

    const requestData = {
      page,
      size: pageData.size,
    };

    let response;
    let stateKey;

    switch (tabType) {
      case 'orders':
        // 获取用户订单记录 - 使用订单API，添加用户手机号筛选
        response = await orderApi.order.list({
          ...requestData,
          userPhone: state.userDetail.phoneNo, // 使用用户手机号筛选
        });
        stateKey = 'orders';
        break;
      case 'subordinates':
        response = await api.list.myUsers({
          ...requestData,
          type: 1,
          userId: props.modal.params.id,
        });
        stateKey = 'subordinates';
        break;
      case 'commissions':
        // 获取用户佣金记录 - 使用佣金API，添加用户手机号筛选
        response = await financeApi.commission.list(
          {
            ...requestData,
            phoneNo: state.userDetail.phoneNo, // 使用用户手机号筛选
          },
          false,
        );
        stateKey = 'commissions';
        break;
      case 'recharges':
        // 获取用户充值记录 - 使用充值API，添加用户手机号筛选
        response = await financeApi.recharge.list(
          {
            ...requestData,
            userPhone: state.userDetail.phoneNo, // 使用用户手机号筛选
          },
          false,
        );
        stateKey = 'recharges';
        break;
      case 'withdraws':
        // 获取用户提现记录 - 使用提现API，添加用户手机号筛选
        response = await financeApi.withdraw.list(
          {
            ...requestData,
            userPhone: state.userDetail.phoneNo, // 使用用户手机号筛选
          },
          false,
        );
        stateKey = 'withdraws';
        break;
      case 'addresses':
        // 获取用户收货地址
        response = await api.getUserAddresses(props.modal.params.id, requestData);
        stateKey = 'addresses';
        break;
      default:
        return;
    }

    if (response && response.code == '200') {
      // 处理不同的数据结构：充值和提现记录多嵌套一层 data.list
      const isNestedData = ['recharges', 'withdraws'].includes(tabType);
      const dataSource = isNestedData ? response.data.list : response.data;

      state[stateKey] = dataSource?.list || [];
      // 更新分页信息
      pageData.page = dataSource?.pageNum || page;
      pageData.total = dataSource?.total || 0;

      console.log(`${tabType}数据加载成功:`, {
        list: dataSource?.list,
        total: dataSource?.total,
        pageNum: dataSource?.pageNum,
      });
    } else {
      console.error('API响应错误:', response);
      // 确保即使出错也设置为空数组
      state[stateKey] = [];
      pageData.total = 0;
    }
  } catch (error) {
    console.error(`获取${tabType}数据失败:`, error);
    // 确保出错时也设置为空数组，避免表格组件报错
    state[tabType] = [];
    pageData.total = 0;
  }
};

// Tab切换处理
const handleTabChange = (tabName) => {
  state.activeTab = tabName;
  // 切换tab时重置页码为1
  pageData.page = 1;
  // 每次切换都重新加载数据
  loadTabData(tabName);
};

// 加载Tab数据
const loadTabData = async (tabName) => {
  state.loading[tabName] = true;

  try {
    // 从 pageData 获取当前页码
    await fetchTabData(tabName, pageData.page);
  } catch (error) {
    console.error(`加载${tabName}数据失败:`, error);
  } finally {
    state.loading[tabName] = false;
  }
};

// 编辑资料
const onEdit = () => {
  useModal(
    userEdit,
    {
      title: '编辑用户资料',
      width: '80%',
      id: state.userDetail.id,
      type: 'edit',
    },
    {
      confirm: () => {
        // 编辑成功后刷新数据
        getUserDetail();
      },
    },
  );
};

// 统一模态框打开函数
const openDetailModal = (type, row) => {
  console.log(row);
  const modalConfigs = {
    order: {
      component: OrderDetail,
      title: '订单详情',
      width: '90%',
      orderNo: row.orderId,
    },
    subordinateUser: {
      component: userDetail,
      title: '用户详情',
      width: '1200px',
      type: 'view',
      id: row.id,
      hasConfirm: true,
    },
    recharge: {
      component: RechargeDetail,
      title: '充值详情',
      width: '80%',
      id: row.id,
    },
    withdraw: {
      component: WithdrawDetail,
      title: '提现详情',
      width: '80%',
      id: row.id,
    },
  };

  const config = modalConfigs[type];
  if (!config) return;

  const { component, hasConfirm, ...modalOptions } = config;

  if (hasConfirm) {
    useModal(component, modalOptions, {
      confirm: () => getUserDetail(),
    });
  } else {
    useModal(component, modalOptions);
  }
};

// 各类详情查看函数（保持向后兼容）
const viewOrder = (row) => openDetailModal('order', row);
const viewSubordinateUser = (row) => openDetailModal('subordinateUser', row);
const viewRecharge = (row) => openDetailModal('recharge', row);
const viewWithdraw = (row) => openDetailModal('withdraw', row);

// 处理退款
const handleRefund = async (row) => {
  try {
    // 确认退款操作
    await ElMessageBox.confirm(
      `确定要对订单 ${row.orderId} 进行退款吗？`,
      '退款确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    // 调用退款API
    const { code, message } = await orderApi.order.refund(row.id);
    if (code === '200' || code === 200) {
      ElMessage.success('退款操作成功');
      // 刷新订单数据
      await loadTabData('orders');
    } else {
      ElMessage.error(message || '退款操作失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('退款操作失败:', error);
      ElMessage.error('退款操作失败');
    }
  }
};

onMounted(() => {
  // 先初始化基本信息表格数据（防止模板报错）
  initBasicInfoTableData();
  // 获取佣金类型枚举
  getCommissionTypes();
  // 初始化用户详情和基本信息（会在获取完成后自动加载tab数据）
  getUserDetail();
});
</script>

<style lang="scss" scoped>
.user-detail {
  padding: 0px 20px;

  .action-buttons {
    text-align: right;
    margin-bottom: 26px;

    .el-button {
      margin-right: 12px;
    }
  }

  .basic-info {
    h3 {
      font-size: 16px;
      font-weight: 600;
      color: var(--sa-title);
    }

    .avatar-section,
    .vip-section {
      text-align: center;

      .user-name {
        font-weight: 600;
        font-size: 16px;
        color: var(--sa-title);
      }

      .user-level {
        // 使用会员黄
        color: rgba(252, 202, 0, 1);
        font-size: 14px;
      }
    }

    .payment-info {
      text-align: center;
      line-height: 1.6;

      div {
        margin-bottom: 4px;
        font-size: 13px;

        &:last-child {
          margin-bottom: 0;
        }
      }
    }

    .info-item {
      display: flex;
      align-items: center;
      margin-bottom: 8px;

      .label {
        flex-shrink: 0;
        color: var(--sa-subfont);
        font-size: 14px;
      }

      .value {
        color: var(--sa-subtitle);
        font-size: 14px;
        font-weight: 500;
      }
    }
  }

  .goods-info {
    display: flex;
    align-items: center;

    .goods-detail {
      flex: 1;

      .goods-name {
        font-size: 14px;
        color: #333;
        line-height: 1.4;
        word-break: break-word;
      }
    }
  }

  // 基本信息表格特殊样式
  .basic-info-tables {
    .basic-info-table-1 {
      margin-bottom: 0;

      .sa-table {
        border-bottom: none;
        border-radius: 8px 8px 0 0;
      }
    }

    .basic-info-table-2 {
      margin-top: -1px;

      .sa-table {
        border-top: none;
        border-radius: 0 0 8px 8px;
      }

      // 隐藏第一列的内容，但保持宽度
      :deep(.el-table__body-wrapper) {
        .el-table__body tr td:first-child {
          border-left: none;
          background: transparent;
        }
      }
    }
  }

  // 表格边框样式 - 参考order/detail.vue
  .basic-info,
  .stats-info,
  .tab-content {
    .sa-table {
      overflow: hidden;
      border: 1px solid #dcdfe6;

      :deep(.el-table) {
        border: none;
        border-radius: 0;
      }

      :deep(.el-table__header-wrapper) {
        background: var(--sa-table-header-bg, #f5f7fa);

        .el-table__header {
          background: var(--sa-table-header-bg, #f5f7fa);

          th {
            background: var(--sa-table-header-bg, #f5f7fa) !important;
            font-weight: 600;
            color: var(--sa-title, #303133);
            border-bottom: 1px solid #dcdfe6;
            border-right: 1px solid #dcdfe6;

            &:first-child {
              border-left: none;
            }

            &:last-child {
              border-right: none;
            }
          }
        }
      }

      :deep(.el-table__body-wrapper) {
        .el-table__body {
          tr {
            &:hover {
              background: #f5f7fa !important;
            }

            td {
              border-bottom: 1px solid #dcdfe6;
              border-right: 1px solid #dcdfe6;
              border-left: none;

              &:first-child {
                border-left: none;
              }

              &:last-child {
                border-right: none;
              }
            }

            &:last-child td {
              border-bottom: none;
            }
          }
        }
      }

      // 确保边框完整性
      :deep(.el-table--border) {
        border: none;

        &::after {
          display: none;
        }

        &::before {
          display: none;
        }
      }

      :deep(.el-table--border .el-table__cell) {
        border-right: 1px solid #dcdfe6;
        border-left: none;

        &:first-child {
          border-left: none;
        }

        &:last-child {
          border-right: none;
        }
      }

      // 修复表格底部和左侧边框
      :deep(.el-table__body) {
        border-left: none;
        border-bottom: none;
      }

      :deep(.el-table__header) {
        border-left: none;
      }
    }
  }

  .stats-info {
    h3 {
      font-size: 16px;
      font-weight: 600;
      color: var(--sa-title);
    }

    .stat-item {
      text-align: center;
      padding: 16px;
      border: 1px solid #dcdfe6;
      border-radius: 8px;
      background: var(--sa-table-header-bg, #f5f7fa);

      .stat-label {
        color: var(--sa-subfont);
        font-size: 14px;
        margin-bottom: 8px;
      }

      .stat-value {
        color: var(--sa-title);
        font-size: 18px;
        font-weight: 600;
      }
    }
  }

  .orders-content,
  .subordinates-content,
  .commissions-content,
  .addresses-content {
    .sa-title {
      font-size: 16px;
      font-weight: 600;
      color: var(--sa-title);
    }

    .sa-table {
      border-radius: 8px;
      overflow: hidden;
      border: 1px solid #dcdfe6;

      :deep(.el-table) {
        border: none;
        border-radius: 0;
      }

      :deep(.el-table__header-wrapper) {
        background: var(--sa-table-header-bg, #f5f7fa);

        .el-table__header {
          background: var(--sa-table-header-bg, #f5f7fa);

          th {
            background: var(--sa-table-header-bg, #f5f7fa) !important;
            font-weight: 600;
            color: var(--sa-title, #303133);
            border-bottom: 1px solid #dcdfe6;
            border-right: 1px solid #dcdfe6;

            &:first-child {
              border-left: none;
            }

            &:last-child {
              border-right: none;
            }
          }
        }
      }

      :deep(.el-table__body-wrapper) {
        .el-table__body {
          tr {
            &:hover {
              background: #f5f7fa !important;
            }

            td {
              border-bottom: 1px solid #dcdfe6;
              border-right: 1px solid #dcdfe6;
              border-left: none;

              &:first-child {
                border-left: none;
              }

              &:last-child {
                border-right: none;
              }
            }

            &:last-child td {
              border-bottom: none;
            }
          }
        }
      }

      :deep(.el-table--border) {
        border: none;

        &::after {
          display: none;
        }

        &::before {
          display: none;
        }
      }

      :deep(.el-table--border .el-table__cell) {
        border-right: 1px solid #dcdfe6;
        border-left: none;

        &:first-child {
          border-left: none;
        }

        &:last-child {
          border-right: none;
        }
      }

      :deep(.el-table__body) {
        border-left: none;
        border-bottom: none;
      }

      :deep(.el-table__header) {
        border-left: none;
      }
    }
  }

  .goods-title {
    font-size: 14px;
    color: var(--sa-subtitle);
    line-height: 1.4;
  }
}

.sa-title {
  line-height: 32px;
}
</style>
