<template>
  <div class="agent-dashboard">
    <!-- 头部 -->
    <div class="dashboard-header">
      <div class="header-content">
        <div class="agent-info">
          <div class="avatar">
            <el-icon><User /></el-icon>
          </div>
          <div class="info-text">
            <h2>{{ agentInfo?.real_name }}</h2>
            <p>{{ agentInfo?.city_name }}{{ agentInfo?.district_name }}代理</p>
            <span class="phone">{{ agentInfo?.phone }}</span>
          </div>
        </div>
        <el-button 
          class="logout-btn"
          @click="handleLogout"
        >
          <el-icon><SwitchButton /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- 核心数据概览 -->
    <div class="overview-section">
      <div class="overview-card main-stats">
        <div class="card-header">
          <h3>今日概览</h3>
          <el-icon class="refresh-icon" @click="refreshData"><Refresh /></el-icon>
        </div>
        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-icon merchant">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ stats.total_merchants || 0 }}</div>
              <div class="stat-label">总商户</div>
              <div class="stat-trend">+{{ stats.weekly_new_merchants || 0 }} 本周新增</div>
            </div>
          </div>
          
          <div class="stat-item">
            <div class="stat-icon commission">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">¥{{ (Number(stats.total_commission) || 0).toFixed(2) }}</div>
              <div class="stat-label">总佣金</div>
              <div class="stat-trend">¥{{ (Number(stats.monthly_commission) || 0).toFixed(2) }} 本月</div>
            </div>
          </div>
          
          <div class="stat-item">
            <div class="stat-icon available">
              <el-icon><Wallet /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">¥{{ (Number(stats.daily_commission) || 0).toFixed(2) }}</div>
              <div class="stat-label">今日佣金</div>
              <div class="stat-trend">{{ stats.daily_commission_records || 0 }} 笔记录</div>
            </div>
          </div>
          
          <div class="stat-item">
            <div class="stat-icon approved">
              <el-icon><Select /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ stats.approved_merchants || 0 }}</div>
              <div class="stat-label">已审核</div>
              <div class="stat-trend">{{ stats.pending_merchants || 0 }} 待审核</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 数据可视化图表 -->
    <div class="charts-section">
      <!-- 佣金趋势图 -->
      <div class="chart-card">
        <div class="card-header">
          <h3>佣金趋势</h3>
          <el-select v-model="chartPeriod" size="small" @change="loadChartData">
            <el-option label="近7天" value="7d" />
            <el-option label="近30天" value="30d" />
            <el-option label="近3个月" value="3m" />
          </el-select>
        </div>
        <div class="chart-container">
          <v-chart :option="commissionTrendOption" :loading="chartLoading" />
        </div>
      </div>
      
      <!-- 商户状态分布 -->
      <div class="chart-card">
        <div class="card-header">
          <h3>商户状态分布</h3>
        </div>
        <div class="chart-container">
          <v-chart :option="merchantStatusOption" :loading="chartLoading" />
        </div>
      </div>
    </div>

    <!-- 快速操作 -->
    <div class="quick-actions">
      <div class="action-card" @click="goToWithdrawals">
        <div class="action-icon withdraw">
          <el-icon><CreditCard /></el-icon>
        </div>
        <div class="action-content">
          <div class="action-title">佣金提现</div>
          <div class="action-desc">快速提现到账</div>
        </div>
        <el-icon class="arrow"><ArrowRight /></el-icon>
      </div>
    </div>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" class="main-tabs">
      <!-- 商户管理 -->
      <el-tab-pane label="商户管理" name="merchants">
        <div class="merchants-section">
          <div class="section-header">
            <h3>我的商户</h3>
            <el-button @click="loadMerchants" :loading="loadingMerchants">
              刷新
            </el-button>
          </div>
          
          <!-- 商户统计信息 -->
          <div class="merchant-stats" v-if="stats.total_merchants">
            <div class="stat-item">
              <span class="stat-label">总商户数：</span>
              <span class="stat-value">{{ stats.total_merchants || 0 }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">正常商户：</span>
              <span class="stat-value normal">{{ stats.normal_merchants || 0 }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">早期商户：</span>
              <span class="stat-value early">{{ stats.early_merchants || 0 }}</span>
              <el-tooltip content="注册时间早于代理加入时间的商户，不参与佣金计算" placement="top">
                <el-icon class="info-icon"><InfoFilled /></el-icon>
              </el-tooltip>
            </div>
          </div>
          
          <el-table 
            :data="merchants" 
            v-loading="loadingMerchants"
            stripe
            style="width: 100%"
            :row-class-name="({ row }) => row.is_early_merchant ? 'early-merchant' : ''"
            border
            size="small"
            class="responsive-table"
          >
            <el-table-column prop="username" label="用户名" min-width="80" :width="null">
              <template #default="{ row }">
                {{ maskUsername(row.username) }}
              </template>
            </el-table-column>
            <el-table-column prop="real_name" label="真实姓名" min-width="80" :width="null" class-name="hide-on-mobile" />
            <el-table-column prop="phone" label="手机号" min-width="100" :width="null" class-name="hide-on-small-mobile">
              <template #default="{ row }">
                {{ maskUsername(row.phone) }}
              </template>
            </el-table-column>
            <el-table-column prop="audit_status" label="审核状态" min-width="80" :width="null">
              <template #default="{ row }">
                <el-tag size="small" :type="getAuditStatusType(row.audit_status)">
                  {{ getAuditStatusText(row.audit_status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="merchant_status" label="商户类型" min-width="100" :width="null">
              <template #default="{ row }">
                <el-tag 
                  size="small"
                  :type="row.is_early_merchant ? 'warning' : 'success'"
                  :icon="row.is_early_merchant ? 'Warning' : 'Check'"
                >
                  {{ row.is_early_merchant ? '早期商户' : '正常商户' }}
                </el-tag>
                <el-tooltip 
                  v-if="row.is_early_merchant" 
                  content="该商户注册时间早于代理加入时间，不参与佣金计算" 
                  placement="top"
                >
                  <el-icon class="info-icon"><InfoFilled /></el-icon>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="completed_matches" label="完成匹配" min-width="80" :width="null" class-name="hide-on-mobile" />
            <el-table-column prop="joined_at" label="加入时间" min-width="100" :width="null" class-name="hide-on-small-mobile">
              <template #default="{ row }">
                {{ formatDateTime(row.joined_at) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="100" :width="null">
              <template #default="{ row }">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="viewMerchantTransfers(row)"
                >
                  转账记录
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination-wrapper">
            <el-pagination
              v-model:current-page="merchantsPage"
              v-model:page-size="merchantsPageSize"
              :total="merchantsTotal"
              :page-sizes="[10, 20, 50]"
              layout="total, sizes"
              @current-change="loadMerchants"
              @size-change="loadMerchants"
            />
          </div>
          <div class="pagination-wrapper">
            <el-pagination
              v-model:current-page="merchantsPage"
              v-model:page-size="merchantsPageSize"
              :total="merchantsTotal"
              :page-sizes="[10, 20, 50]"
              layout="prev, pager, next, jumper"
              @current-change="loadMerchants"
              @size-change="loadMerchants"
            />
          </div>
        </div>
      </el-tab-pane>
      
      <!-- 佣金记录 -->
      <el-tab-pane label="佣金记录" name="commissions">
        <div class="commissions-section">
          <div class="section-header">
            <h3>佣金记录</h3>
            <el-button @click="loadCommissions" :loading="loadingCommissions">
              刷新
            </el-button>
          </div>
          
          <div class="responsive-table">
            <el-table 
              :data="commissions" 
              v-loading="loadingCommissions"
              stripe
              border
              size="small"
              class="responsive-table"
              style="width: 100%"
            >
              <el-table-column prop="username" label="商户" :width="null" min-width="80">
                <template #default="{ row }">
                  {{ maskUsername(row.username) }}
                </template>
              </el-table-column>
              <el-table-column prop="real_name" label="真实姓名" :width="null" min-width="80" class-name="hide-on-small-mobile" />
              <el-table-column prop="commission_amount" label="佣金金额" :width="null" min-width="90">
                <template #default="{ row }">
                  ¥{{ (Number(row.commission_amount) || 0).toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column prop="commission_type" label="佣金类型" :width="null" min-width="90">
                <template #default="{ row }">
                  <el-tag size="small" :type="getCommissionTypeTagType(row.commission_type)">
                    {{ getCommissionTypeText(row.commission_type) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" :width="null" min-width="70">
                <template #default="{ row }">
                  <el-tag size="small" :type="getCommissionStatusType(row.status)">
                    {{ getCommissionStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="created_at" label="生成时间" :width="null" min-width="120" class-name="hide-on-mobile">
                <template #default="{ row }">
                  {{ formatDateTime(row.created_at) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <div class="pagination-wrapper">
            <el-pagination
              v-model:current-page="commissionsPage"
              v-model:page-size="commissionsPageSize"
              :total="commissionsTotal"
              :page-sizes="[10, 20, 50]"
              layout="total, sizes"
              @current-change="loadCommissions"
              @size-change="loadCommissions"
            />
          </div>
          <div class="pagination-wrapper">
            <el-pagination
              v-model:current-page="commissionsPage"
              v-model:page-size="commissionsPageSize"
              :total="commissionsTotal"
              :page-sizes="[10, 20, 50]"
              layout="prev, pager, next, jumper"
              @current-change="loadCommissions"
              @size-change="loadCommissions"
            />
          </div>
        </div>
      </el-tab-pane>
      

      
      <!-- 佣金提现 -->
      <el-tab-pane label="佣金提现" name="withdrawals">
        <div class="withdrawals-section">
          <div class="section-header">
            <h3>佣金提现</h3>
            <el-button type="primary" @click="goToWithdrawals">
              进入提现页面
            </el-button>
          </div>
          
          <div class="withdrawal-summary">
            <div class="summary-card">
              <div class="summary-item">
                <span class="label">可提现金额：</span>
                <span class="value amount">¥{{ (Number(stats.available_amount) || 0).toFixed(2) }}</span>
              </div>
              <div class="summary-item">
                <span class="label">提现中金额：</span>
                <span class="value">¥{{ (Number(stats.pending_withdrawal) || 0).toFixed(2) }}</span>
              </div>
              <div class="summary-item">
                <span class="label">已提现金额：</span>
                <span class="value">¥{{ (Number(stats.withdrawn_amount) || 0).toFixed(2) }}</span>
              </div>
            </div>
            
            <div class="quick-actions">
              <el-button type="primary" size="large" @click="goToWithdrawals">
                立即提现
              </el-button>
            </div>
          </div>
        </div>
      </el-tab-pane>
      
      <!-- 商户转账记录 -->
      <el-tab-pane label="商户转账记录" name="transfers">
        <div class="transfers-section">
          <div class="section-header">
            <h3>商户转账记录</h3>
            <div class="header-actions">
              <el-select 
                v-model="selectedMerchantId" 
                placeholder="选择商户" 
                size="small" 
                style="width: 200px; margin-right: 10px"
                clearable
                @change="loadTransfers"
              >
                <el-option 
                  v-for="merchant in merchants" 
                  :key="merchant.id" 
                  :label="`${merchant.real_name} (${maskUsername(merchant.phone)})`" 
                  :value="merchant.id"
                />
              </el-select>
              <el-button @click="loadTransfers" :loading="loadingTransfers">
                刷新
              </el-button>
            </div>
          </div>
          
          <el-table 
            :data="transfers" 
            v-loading="loadingTransfers"
            stripe
            border
            size="small"
            class="responsive-table"
            style="width: 100%"
          >
            <el-table-column prop="id" label="转账ID" min-width="80" :width="null" />
            <el-table-column prop="from_real_name" label="发送方" min-width="100" :width="null" />
            <el-table-column prop="to_real_name" label="接收方" min-width="100" :width="null" />
            <el-table-column prop="amount" label="金额" min-width="100" :width="null">
              <template #default="{ row }">
                ¥{{ row.amount }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" min-width="80" :width="null">
              <template #default="{ row }">
                <el-tag :type="getTransferStatusType(row.status)" size="small">
                  {{ getTransferStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="transfer_type" label="类型" min-width="100" :width="null">
              <template #default="{ row }">
                <el-tag :type="getTransferTypeType(row.transfer_type)" size="small">
                  {{ getTransferTypeText(row.transfer_type) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="创建时间" min-width="160" :width="null" class-name="hide-on-small-mobile">
              <template #default="{ row }">
                {{ formatDateTime(row.created_at) }}
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" min-width="150" :width="null" class-name="hide-on-mobile" />
          </el-table>
          
          <div class="pagination-wrapper">
            <el-pagination
              v-model:current-page="transfersPage"
              v-model:page-size="transfersPageSize"
              :total="transfersTotal"
              :page-sizes="[10, 20, 50]"
              layout="total, sizes"
              @current-change="loadTransfers"
              @size-change="loadTransfers"
            />
          </div>
          <div class="pagination-wrapper">
            <el-pagination
              v-model:current-page="transfersPage"
              v-model:page-size="transfersPageSize"
              :total="transfersTotal"
              :page-sizes="[10, 20, 50]"
              layout="prev, pager, next, jumper"
              @current-change="loadTransfers"
              @size-change="loadTransfers"
            />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, 
  Money, 
  Wallet, 
  Select, 
  SwitchButton, 
  Refresh, 
  CreditCard, 
  Management, 
  ArrowRight,
  InfoFilled,
  Warning,
  Check
} from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import api, { transferAPI } from '@/utils/api'

// 注册ECharts组件
use([
  CanvasRenderer,
  LineChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const router = useRouter()

// 响应式数据
const agentInfo = ref(null)
const stats = ref({})
const activeTab = ref('merchants')

// 商户数据
const merchants = ref([])
const loadingMerchants = ref(false)
const merchantsPage = ref(1)
const merchantsPageSize = ref(10)
const merchantsTotal = ref(0)

// 佣金数据
const commissions = ref([])
const loadingCommissions = ref(false)
const commissionsPage = ref(1)
const commissionsPageSize = ref(10)
const commissionsTotal = ref(0)

// 转账记录数据
const transfers = ref([])
const loadingTransfers = ref(false)
const transfersPage = ref(1)
const transfersPageSize = ref(10)
const transfersTotal = ref(0)
const selectedMerchantId = ref(null)

// 图表相关数据
const chartPeriod = ref('7d')
const chartLoading = ref(false)
const commissionTrendOption = ref({})
const merchantStatusOption = ref({})
const chartData = ref({
  commissionTrend: [],
  merchantStatus: []
})

// 方法
const loadAgentInfo = () => {
  const stored = localStorage.getItem('agentInfo')
  if (stored) {
    agentInfo.value = JSON.parse(stored)
  } else {
    router.push('/agent/login')
  }
}

const loadStats = async () => {
  if (!agentInfo.value) return
  
  try {
    // 使用详细统计接口获取更多维度的数据
    const { data } = await api.get(`/agents/detailed-stats/${agentInfo.value.id}`)
    if (data.success) {
      stats.value = data.data
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
    ElMessage.error('加载统计数据失败')
    // 如果详细统计接口失败，回退到基础统计接口
    try {
      const { data: fallbackData } = await api.get(`/agents/stats/${agentInfo.value.id}`)
      if (fallbackData.success) {
        stats.value = fallbackData.data
      }
    } catch (fallbackError) {
      console.error('回退统计数据加载也失败:', fallbackError)
    }
  }
}

const loadMerchants = async () => {
  if (!agentInfo.value) return
  
  loadingMerchants.value = true
  try {
    const { data } = await api.get(`/agents/merchants/${agentInfo.value.id}`, {
      params: {
        page: merchantsPage.value,
        limit: merchantsPageSize.value
      }
    })
    
    merchants.value = data.data.merchants
    merchantsTotal.value = data.data.total
    
    // 更新商户相关的统计信息（如果返回了统计数据）
    if (data.data.stats) {
      // 只更新商户相关的统计字段，保留其他统计数据
      stats.value = { 
        ...stats.value, 
        total_merchants: data.data.stats.total_merchants,
        early_merchants: data.data.stats.early_merchants,
        normal_merchants: data.data.stats.normal_merchants
      }
    }
  } catch (error) {
    ElMessage.error('加载商户列表失败')
  } finally {
    loadingMerchants.value = false
  }
}

const loadCommissions = async () => {
  if (!agentInfo.value) return
  
  loadingCommissions.value = true
  try {
    const { data } = await api.get(`/agents/commissions/${agentInfo.value.id}`, {
      params: {
        page: commissionsPage.value,
        limit: commissionsPageSize.value
      }
    })
    
    commissions.value = data.data.commissions
    commissionsTotal.value = data.data.summary.total_records
  } catch (error) {
    ElMessage.error('加载佣金记录失败')
  } finally {
    loadingCommissions.value = false
  }
}

const loadTransfers = async () => {
  if (!agentInfo.value) return
  
  loadingTransfers.value = true
  try {
    // 构建请求参数
    const params = {
      page: transfersPage.value,
      limit: transfersPageSize.value
    }
    
    // 如果选择了特定商户，则添加到请求参数中
    let userId = selectedMerchantId.value
    
    // 如果没有选择特定商户，则获取代理下所有商户的转账记录
    if (!userId) {
      // 使用代理ID获取所有相关商户的转账记录
      const { data } = await api.get(`/agents/merchants/${agentInfo.value.id}/transfers`, {
        params
      })
      console.log(data,'data1');
      
      transfers.value = data.data.transfers
      transfersTotal.value = data.data.pagination.total
    } else {
      // 获取特定商户的转账记录
      const { data } = await transferAPI.getUserTransfersByUserId(userId, params)
      
      transfers.value = data.data.transfers
      transfersTotal.value = data.data.pagination.total
    }
  } catch (error) {
    console.error('加载转账记录失败:', error)
    ElMessage.error('加载转账记录失败')
  } finally {
    loadingTransfers.value = false
  }
}

const viewMerchantTransfers = (merchant) => {
  // 设置选中的商户ID
  selectedMerchantId.value = merchant.id
  // 切换到转账记录标签页
  activeTab.value = 'transfers'
  // 加载该商户的转账记录
  loadTransfers()
}

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '确认退出', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    localStorage.removeItem('agentInfo')
    router.push('/agent/login')
  } catch (error) {
    // 用户取消
  }
}

const getAuditStatusType = (status) => {
  const types = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return types[status] || 'info'
}

const getAuditStatusText = (status) => {
  const texts = {
    pending: '待审核',
    approved: '已审核',
    rejected: '已拒绝'
  }
  return texts[status] || status
}

/**
 * 获取佣金类型标签类型
 * @param {string} type - 佣金类型
 * @returns {string} 标签类型
 */
const getCommissionTypeTagType = (type) => {
  const types = {
    registration: 'primary',
    matching: 'success'
  }
  return types[type] || 'info'
}

/**
 * 获取佣金类型文本
 * @param {string} type - 佣金类型
 * @returns {string} 显示文本
 */
const getCommissionTypeText = (type) => {
  const texts = {
    registration: '注册佣金',
    matching: '匹配佣金'
  }
  return texts[type] || type
}

/**
 * 获取佣金状态标签类型
 * @param {string} status - 佣金状态
 * @returns {string} 标签类型
 */
const getCommissionStatusType = (status) => {
  // 由于agent_commission_records表没有status字段，所有佣金记录都是已生成状态
  return 'success'
}

/**
 * 获取佣金状态文本
 * @param {string} status - 佣金状态
 * @returns {string} 显示文本
 */
const getCommissionStatusText = (status) => {
  // 由于agent_commission_records表没有status字段，所有佣金记录都是已生成状态
  return '已生成'
}

/**
 * 获取转账状态标签类型
 * @param {string} status - 转账状态
 * @returns {string} 标签类型
 */
const getTransferStatusType = (status) => {
  const types = {
    pending: 'warning',
    confirmed: 'success',
    rejected: 'danger',
    received: 'success',
    cancelled: 'info'
  }
  return types[status] || 'info'
}

/**
 * 获取转账状态文本
 * @param {string} status - 转账状态
 * @returns {string} 显示文本
 */
const getTransferStatusText = (status) => {
  const texts = {
    pending: '待确认',
    confirmed: '已确认',
    rejected: '已拒绝',
    received: '已收到',
    cancelled: '已取消'
  }
  return texts[status] || status
}

/**
 * 获取转账类型标签类型
 * @param {string} type - 转账类型
 * @returns {string} 标签类型
 */
const getTransferTypeType = (type) => {
  const types = {
    deposit: 'success',
    withdraw: 'warning',
    transfer: 'primary',
    commission: 'success',
    refund: 'info',
    penalty: 'danger',
    initial: 'primary',
    return: 'info',
    user_to_user: 'primary',
    user_to_public: 'warning',
    public_to_user: 'success'
  }
  return types[type] || 'info'
}

/**
 * 获取转账类型文本
 * @param {string} type - 转账类型
 * @returns {string} 显示文本
 */
const getTransferTypeText = (type) => {
  const texts = {
    deposit: '充值',
    withdraw: '提现',
    transfer: '转账',
    commission: '佣金',
    refund: '退款',
    penalty: '罚金',
    initial: '初始转账',
    return: '返还转账',
    user_to_user: '用户转账',
    user_to_public: '用户转公户',
    public_to_user: '公户转用户'
  }
  return texts[type] || type
}

/**
 * 格式化日期时间
 * @param {string|Date} date - 需要格式化的日期
 * @returns {string} - 格式化后的日期字符串或原文本
 */
const formatDateTime = (date) => {
  if (!date) return ''
  
  // 使用dayjs进行格式化
  const dayjsDate = dayjs(date)
  
  // 检查是否为有效日期
  if (!dayjsDate.isValid()) {
    // 如果不是有效日期，返回原文本
    return date
  }
  
  // 如果是有效日期，进行格式化
  return dayjsDate.format('YYYY-MM-DD HH:mm:ss')
}

/**
 * 用户名脱敏处理
 * @param {string} username - 原始用户名
 * @returns {string} 脱敏后的用户名
 */
const maskUsername = (username) => {
  if (!username || username.length <= 2) {
    return username
  }
  
  // 如果是手机号格式（11位数字）
  if (/^\d{11}$/.test(username)) {
    return username.replace(/(\d{3})\d{5}(\d{3})/, '$1*****$2')
  }
  
  // 如果是邮箱格式
  if (username.includes('@')) {
    const [localPart, domain] = username.split('@')
    if (localPart.length <= 2) {
      return `${localPart[0]}*@${domain}`
    }
    const maskedLocal = localPart[0] + '*'.repeat(localPart.length - 2) + localPart[localPart.length - 1]
    return `${maskedLocal}@${domain}`
  }
  
  // 普通用户名：保留首尾字符，中间用*替换
  if (username.length <= 3) {
    return username[0] + '*'.repeat(username.length - 1)
  }
  
  return username[0] + '*'.repeat(username.length - 2) + username[username.length - 1]
}

/**
 * 跳转到提现页面
 */
const goToWithdrawals = () => {
  router.push('/agent/withdrawals')
}

/**
 * 刷新所有数据
 */
const refreshData = async () => {
  await Promise.all([
    loadStats(),
    loadChartData(),
    loadMerchants(),
    loadCommissions()
  ])
  ElMessage.success('数据刷新成功')
}

/**
 * 加载图表数据
 */
const loadChartData = async () => {
  if (!agentInfo.value) return
  
  chartLoading.value = true
  try {
    // 从后端API获取数据
    const [trendResponse, statusResponse] = await Promise.all([
      api.get(`/agents/commission-trend/${agentInfo.value.id}`, {
        params: { period: chartPeriod.value }
      }),
      api.get(`/agents/merchant-status/${agentInfo.value.id}`)
    ])
    
    if (trendResponse.data.success && statusResponse.data.success) {
      chartData.value = {
        commissionTrend: trendResponse.data.data,
        merchantStatus: statusResponse.data.data
      }
    } else {
      throw new Error('API返回失败')
    }
    
    updateChartOptions()
  } catch (error) {
    console.error('加载图表数据失败:', error)
    ElMessage.warning('图表数据加载失败，使用模拟数据')
    generateMockChartData()
  } finally {
    chartLoading.value = false
  }
}

/**
 * 生成模拟图表数据（用于演示）
 */
const generateMockChartData = () => {
  // 模拟佣金趋势数据
  const days = chartPeriod.value === '7d' ? 7 : chartPeriod.value === '30d' ? 30 : 90
  const trendData = []
  const today = new Date()
  
  for (let i = days - 1; i >= 0; i--) {
    const date = new Date(today)
    date.setDate(date.getDate() - i)
    trendData.push({
      date: date.toISOString().split('T')[0],
      amount: Math.random() * 100 + 20
    })
  }
  
  // 模拟商户状态分布数据
  const statusData = [
    { status: '已审核', count: stats.value.approved_merchants || 15 },
    { status: '待审核', count: (stats.value.total_merchants || 20) - (stats.value.approved_merchants || 15) },
    { status: '已拒绝', count: Math.floor(Math.random() * 5) }
  ]
  
  chartData.value.commissionTrend = trendData
  chartData.value.merchantStatus = statusData
  updateChartOptions()
}

/**
 * 更新图表配置
 */
const updateChartOptions = () => {
  // 确保数据存在
  if (!chartData.value.commissionTrend || !Array.isArray(chartData.value.commissionTrend)) {
    return
  }
  
  // 佣金趋势图配置
  commissionTrendOption.value = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>佣金: ¥{c}'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: chartData.value.commissionTrend.map(item => {
        const date = dayjs(item.date)
        return date.format('M/D')
      }),
      axisLabel: {
        fontSize: 10
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: 10,
        formatter: '¥{value}'
      }
    },
    series: [{
      data: chartData.value.commissionTrend.map(item => parseFloat(item.amount || 0).toFixed(2)),
      type: 'line',
      smooth: true,
      lineStyle: {
        color: '#409EFF',
        width: 3
      },
      itemStyle: {
        color: '#409EFF'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: 'rgba(64, 158, 255, 0.3)'
          }, {
            offset: 1, color: 'rgba(64, 158, 255, 0.1)'
          }]
        }
      }
    }]
  }
  
  // 确保商户状态数据存在
  if (!chartData.value.merchantStatus || !Array.isArray(chartData.value.merchantStatus)) {
    return
  }
  
  // 商户状态分布饼图配置
  merchantStatusOption.value = {
    tooltip: {
      trigger: 'item',
      formatter: '{a}<br/>{b}: {c} ({d}%)'
    },
    legend: {
      bottom: '5%',
      left: 'center',
      textStyle: {
        fontSize: 10
      }
    },
    series: [{
      name: '商户状态',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['50%', '45%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '14',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: chartData.value.merchantStatus.map((item, index) => ({
        value: item.count,
        name: item.status,
        itemStyle: {
          color: ['#67C23A', '#E6A23C', '#F56C6C'][index] || '#909399'
        }
      }))
    }]
  }
}

// 生命周期
onMounted(async () => {
  loadAgentInfo()
  if (agentInfo.value) {
    // 先加载基础统计数据
    await loadStats()
    // 然后并行加载其他数据
    await Promise.all([
      loadChartData(),
      loadMerchants(),
      loadCommissions(),
      loadTransfers()
    ])
  }
})
</script>

<style scoped>
.agent-dashboard {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding-bottom: 20px;
}

/* 头部样式 */
.dashboard-header {
  padding: 20px 16px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.agent-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.avatar {
  width: 48px;
  height: 48px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.info-text h2 {
  margin: 0;
  font-size: 18px;
  color: white;
  font-weight: 600;
}

.info-text p {
  margin: 2px 0;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

.phone {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
}

.logout-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.logout-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

/* 概览区域 */
.overview-section {
  padding: 0 16px;
  margin-top: -10px;
}

.overview-card {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
  font-weight: 600;
}

.refresh-icon {
  font-size: 20px;
  color: #409EFF;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.refresh-icon:hover {
  transform: rotate(180deg);
}

/* 统计网格 */
.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: linear-gradient(135deg, #f8f9ff 0%, #f0f4ff 100%);
  border-radius: 12px;
  border: 1px solid rgba(64, 158, 255, 0.1);
}

.stat-icon {
  width: 44px;
  height: 44px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
  flex-shrink: 0;
}

.stat-icon.merchant {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.commission {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.available {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.approved {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-content {
  flex: 1;
  min-width: 0;
}

.stat-number {
  font-size: 16px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 2px;
  word-break: break-all;
}

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

.stat-trend {
  font-size: 11px;
  color: #909399;
  margin-top: 2px;
}

/* 图表区域 */
.charts-section {
  padding: 0 16px;
  margin-bottom: 20px;
}

.chart-card {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
  white-space: nowrap;
  flex-shrink: 0;
}

.chart-container {
  height: 200px;
  width: 100%;
}

/* 快速操作区域 */
.quick-actions {
  padding: 0 16px;
  margin-bottom: 20px;
}

.action-card {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.action-card:active {
  transform: translateY(0);
}

.action-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
  flex-shrink: 0;
}

.action-icon.withdraw {
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
}

.action-icon.manage {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
}

.action-content {
  flex: 1;
}

.action-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.action-desc {
  font-size: 14px;
  color: #606266;
}

.arrow {
  font-size: 18px;
  color: #C0C4CC;
}

/* 标签页样式 */
.main-tabs {
  padding: 0 16px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

:deep(.el-tabs__content) {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  margin-top: 16px;
}

:deep(.el-tabs__header) {
  margin: 0;
  background: white;
  border-radius: 16px;
  padding: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

:deep(.el-tabs__nav-wrap) {
  padding: 0;
}

:deep(.el-tabs__item) {
  padding: 12px 20px;
  border-radius: 12px;
  margin: 0 4px;
  transition: all 0.3s ease;
}

:deep(.el-tabs__item.is-active) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

:deep(.el-tabs__active-bar) {
  display: none;
}

/* 提现相关样式 */
.withdrawals-section {
  min-height: 300px;
}

.withdrawal-summary {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.summary-card {
  background: linear-gradient(135deg, #f8f9ff 0%, #f0f4ff 100%);
  border-radius: 16px;
  padding: 20px;
  border: 1px solid rgba(64, 158, 255, 0.1);
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid rgba(64, 158, 255, 0.1);
}

.summary-item:last-child {
  border-bottom: none;
}

.summary-item .label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.summary-item .value {
  font-size: 16px;
  font-weight: 700;
  color: #303133;
}

.summary-item .value.amount {
  color: #f56c6c;
  font-size: 18px;
}

.withdrawals-section .quick-actions {
  padding: 0;
  margin: 0;
  background: none;
  box-shadow: none;
}

.withdrawals-section .quick-actions .el-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

/* 表格样式 */
:deep(.el-table) {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

:deep(.el-table__header) {
  background: linear-gradient(135deg, #f8f9ff 0%, #f0f4ff 100%);
}

:deep(.el-table th) {
  background: transparent;
  border-bottom: 1px solid rgba(64, 158, 255, 0.1);
  font-weight: 600;
  color: #303133;
}

:deep(.el-table td) {
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

:deep(.el-table__row:hover > td) {
  background: rgba(64, 158, 255, 0.05);
}

/* 分页样式 */
:deep(.el-pagination) {
  justify-content: center;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 8px;
  margin: 0 2px;
}

:deep(.el-pagination .el-pager li.is-active) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

/* 商户统计信息样式 */
.merchant-stats {
  display: flex;
  gap: 24px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 16px;
  border: 1px solid #e9ecef;
}

.merchant-stats .stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.merchant-stats .stat-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.merchant-stats .stat-value {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.merchant-stats .stat-value.normal {
  color: #67C23A;
}

.merchant-stats .stat-value.early {
  color: #E6A23C;
}

/* 商户类型相关样式 */
.info-icon {
  margin-left: 4px;
  color: #E6A23C;
  cursor: help;
  font-size: 14px;
}

.text-muted {
  color: #909399;
  font-style: italic;
}

.merchant-status-tag {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

/* 早期商户行样式 */
.el-table .el-table__row.early-merchant {
  background-color: #fdf6ec;
}

.el-table .el-table__row.early-merchant:hover {
  background-color: #faecd8;
}

/* 移动端响应式 */
@media (max-width: 768px) {
  .dashboard-header {
    padding: 16px 12px;
  }
  
  .overview-section,
  .charts-section,
  .quick-actions,
  .main-tabs {
    padding: 0 12px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }
  
  .stat-item {
    padding: 12px;
  }
  
  .stat-number {
    font-size: 14px;
  }
  
  .stat-label {
    font-size: 11px;
  }
  
  .chart-container {
    height: 180px;
  }
  
  .action-card {
    padding: 16px;
  }
  
  .action-icon {
    width: 40px;
    height: 40px;
    font-size: 20px;
  }
  
  .action-title {
    font-size: 14px;
  }
  
  .action-desc {
    font-size: 12px;
  }
  
  :deep(.el-tabs__item) {
    padding: 8px 12px;
    font-size: 14px;
  }
  
  :deep(.el-table) {
    font-size: 12px;
  }
  
  :deep(.el-table th),
  :deep(.el-table td) {
    padding: 8px 4px;
  }
}

/* 响应式表格样式 */
.responsive-table {
  width: 100%;
  overflow-x: auto;
}

@media (max-width: 768px) {
  .hide-on-mobile {
    display: none;
  }
  
  :deep(.el-table .cell) {
    padding-left: 5px;
    padding-right: 5px;
  }
  
  :deep(.el-table) {
    font-size: 12px;
  }
  
  :deep(.el-tag) {
    transform: scale(0.9);
    transform-origin: left center;
  }
}

@media (max-width: 480px) {
  .hide-on-small-mobile {
    display: none;
  }
  
  .stats-grid {
    grid-template-columns: 1fr 1fr;
    gap: 8px;
  }
  
  .stat-item {
    padding: 8px;
    flex-direction: column;
    text-align: center;
    gap: 8px;
  }
  
  .stat-icon {
    width: 32px;
    height: 32px;
    font-size: 16px;
  }
  
  .stat-number {
    font-size: 12px;
  }
  
  .stat-label {
    font-size: 10px;
  }
  
  .chart-container {
    height: 160px;
  }
  
  .action-card {
    padding: 12px;
    gap: 12px;
  }
  
  .card-header h3 {
    font-size: 16px;
  }
  
  .overview-card,
  .chart-card {
    padding: 16px;
  }
  
  :deep(.el-pagination) {
    justify-content: center;
    flex-wrap: wrap;
    row-gap: 8px;
  }
}
</style>