<template>
  <div class="commissions-container">
    <!-- Statistics Cards -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-value">¥{{ stats.totalCommissionPaid }}</div>
            <div class="stat-label">累计佣金支出</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-value">{{ stats.totalCommissionCount }}</div>
            <div class="stat-label">佣金记录数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-value">¥{{ stats.pendingWithdrawal }}</div>
            <div class="stat-label">待提现金额</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- Commission Rate Config -->
    <el-card class="config-card">
      <template #header>
        <div class="card-header">
          <span>佣金比例配置</span>
        </div>
      </template>
      <el-form :inline="true">
        <el-form-item label="当前佣金比例">
          <el-tag type="primary" size="large">{{ rateConfig.percentage }}</el-tag>
        </el-form-item>
        <el-form-item label="设置新比例">
          <el-input-number
            v-model="newRate"
            :min="0"
            :max="100"
            :precision="2"
            :step="0.5"
          />
          <span class="rate-suffix">%</span>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="savingRate" @click="handleSaveRate">保存</el-button>
        </el-form-item>
      </el-form>
      <div class="config-hint">
        <el-alert
          title="注意：修改佣金比例仅对新创建的支付订单生效，不影响已计入的历史佣金记录。"
          type="warning"
          :closable="false"
          show-icon
        />
      </div>
    </el-card>

    <!-- Commissions Table -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>佣金记录</span>
        </div>
      </template>

      <el-table v-loading="loading" :data="commissions" stripe border>
        <el-table-column label="邀请人" width="150">
          <template #default="{ row }">
            <span>{{ row.inviter?.nickname || '-' }}</span>
            <br />
            <small class="text-muted">UID: {{ row.inviter?.uid || '-' }}</small>
          </template>
        </el-table-column>
        <el-table-column label="被邀请人" width="150">
          <template #default="{ row }">
            <span>{{ row.invitee?.nickname || '-' }}</span>
            <br />
            <small class="text-muted">UID: {{ row.invitee?.uid || '-' }}</small>
          </template>
        </el-table-column>
        <el-table-column label="支付订单" width="180">
          <template #default="{ row }">
            {{ row.paymentOrder?.orderNo || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentAmount" label="支付金额" width="120">
          <template #default="{ row }">
            <span class="payment-amount">¥{{ row.paymentAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="commissionRate" label="佣金比例" width="100" />
        <el-table-column prop="commissionAmount" label="佣金金额" width="120">
          <template #default="{ row }">
            <span class="commission-amount">¥{{ row.commissionAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'credited' ? 'success' : 'danger'">
              {{ row.status === 'credited' ? '已入账' : '已取消' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/utils/api'

// State
const loading = ref(false)
const savingRate = ref(false)
const commissions = ref([])
const newRate = ref(2)

const stats = reactive({
  totalCommissionPaid: '0.00',
  totalCommissionCount: 0,
  pendingWithdrawal: '0.00',
})

const rateConfig = reactive({
  value: 0.02,
  percentage: '2.00%',
  isDefault: true,
})

const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0,
})

// Methods
async function fetchStats() {
  try {
    const response = await api.get('/api/v1/admin/commissions/stats')
    if (response.data.code === 0) {
      Object.assign(stats, response.data.data)
    }
  } catch (error) {
    console.error('Failed to fetch stats:', error)
  }
}

async function fetchRateConfig() {
  try {
    const response = await api.get('/api/v1/admin/commissions/config/commission-rate')
    if (response.data.code === 0) {
      Object.assign(rateConfig, response.data.data)
      newRate.value = rateConfig.value * 100
    }
  } catch (error) {
    console.error('Failed to fetch rate config:', error)
  }
}

async function fetchCommissions() {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
    }

    const response = await api.get('/api/v1/admin/commissions', { params })
    if (response.data.code === 0) {
      commissions.value = response.data.data.records
      pagination.total = response.data.data.pagination.total
    }
  } catch (error) {
    console.error('Failed to fetch commissions:', error)
    ElMessage.error('获取佣金列表失败')
  } finally {
    loading.value = false
  }
}

async function handleSaveRate() {
  if (newRate.value < 0 || newRate.value > 100) {
    ElMessage.error('佣金比例必须在 0-100% 之间')
    return
  }

  savingRate.value = true
  try {
    const response = await api.put('/api/v1/admin/commissions/config/commission-rate', {
      rate: newRate.value / 100,
    })
    
    if (response.data.code === 0) {
      ElMessage.success('佣金比例已更新')
      fetchRateConfig()
    } else {
      ElMessage.error(response.data.error?.message || '更新失败')
    }
  } catch (error) {
    console.error('Failed to save rate:', error)
    ElMessage.error('更新失败')
  } finally {
    savingRate.value = false
  }
}

function handlePageChange(page) {
  pagination.page = page
  fetchCommissions()
}

function handleSizeChange(size) {
  pagination.limit = size
  pagination.page = 1
  fetchCommissions()
}

function formatDate(date) {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

// Initialize
onMounted(() => {
  fetchStats()
  fetchRateConfig()
  fetchCommissions()
})
</script>

<style lang="scss" scoped>
.commissions-container {
  .stats-row {
    margin-bottom: 20px;
  }

  .stat-card {
    .stat-content {
      text-align: center;
      padding: 10px 0;

      .stat-value {
        font-size: 28px;
        font-weight: bold;
        color: #409eff;
      }

      .stat-label {
        font-size: 14px;
        color: #909399;
        margin-top: 8px;
      }
    }
  }

  .config-card {
    margin-bottom: 20px;

    .rate-suffix {
      margin-left: 8px;
      font-size: 14px;
      color: #606266;
    }

    .config-hint {
      margin-top: 16px;
    }
  }

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

    .payment-amount {
      color: #e6a23c;
    }

    .commission-amount {
      color: #67c23a;
      font-weight: bold;
    }

    .text-muted {
      color: #909399;
      font-size: 12px;
    }
  }

  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
