<template>
  <div class="commissions-container">
    <!-- Statistics Cards -->
    <el-row :gutter="16" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card rmb-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ stats.totalCommissionPaidRmb || stats.totalCommissionPaid }}</div>
              <div class="stat-label">累计佣金支出(人民币)</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card peso-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Coin /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">₱{{ stats.totalCommissionPaidPeso || '0.00' }}</div>
              <div class="stat-label">累计佣金支出(比索)</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card count-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.totalCommissionCount }}</div>
              <div class="stat-label">佣金记录数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card pending-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Wallet /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value dual">
                <span class="rmb">¥{{ stats.pendingWithdrawalRmb || stats.pendingWithdrawal }}</span>
                <span class="divider">/</span>
                <span class="peso">₱{{ stats.pendingWithdrawalPeso || '0.00' }}</span>
              </div>
              <div class="stat-label">待提现金额</div>
            </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>
      
      <!-- 系统默认比例 -->
      <div class="config-section">
        <h4>系统默认比例</h4>
        <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>

      <el-divider />

      <!-- 用户专属比例 -->
      <div class="config-section">
        <h4>用户专属比例设置</h4>
        <p class="section-desc">为特定用户设置专属佣金比例，未设置的用户将使用系统默认比例</p>
        
        <!-- 添加用户专属比例 -->
        <el-form :inline="true" class="user-rate-form">
          <el-form-item label="用户UID">
            <el-input v-model="userRateForm.uid" placeholder="输入用户UID" style="width: 120px" />
          </el-form-item>
          <el-form-item label="佣金比例">
            <el-input-number
              v-model="userRateForm.rate"
              :min="0"
              :max="100"
              :precision="2"
              :step="0.5"
            />
            <span class="rate-suffix">%</span>
          </el-form-item>
          <el-form-item>
            <el-button type="success" :loading="savingUserRate" @click="handleAddUserRate">
              <el-icon><Plus /></el-icon>
              添加
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 已设置专属比例的用户列表 -->
        <el-table :data="usersWithCustomRates" stripe border size="small" style="margin-top: 16px">
          <el-table-column prop="uid" label="UID" width="100" />
          <el-table-column prop="nickname" label="昵称" width="150" />
          <el-table-column prop="percentage" label="专属比例" width="120">
            <template #default="{ row }">
              <el-tag type="success">{{ row.percentage }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <el-button type="primary" link size="small" @click="handleEditUserRate(row)">
                <el-icon><Edit /></el-icon>
                修改
              </el-button>
              <el-button type="danger" link size="small" @click="handleRemoveUserRate(row)">
                <el-icon><Delete /></el-icon>
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="usersWithCustomRates.length === 0" class="empty-tip">
          暂无用户设置专属比例
        </div>
      </div>

      <div class="config-hint">
        <el-alert
          title="注意：修改佣金比例仅对新创建的支付订单生效，不影响已计入的历史佣金记录。用户专属比例优先于系统默认比例。"
          type="warning"
          :closable="false"
          show-icon
        />
      </div>
    </el-card>

    <!-- Edit User Rate Dialog -->
    <el-dialog v-model="editUserRateDialogVisible" title="修改用户佣金比例" width="400px">
      <el-form label-width="100px">
        <el-form-item label="用户">
          <span>{{ editingUser?.nickname }} (UID: {{ editingUser?.uid }})</span>
        </el-form-item>
        <el-form-item label="佣金比例">
          <el-input-number
            v-model="editUserRateValue"
            :min="0"
            :max="100"
            :precision="2"
            :step="0.5"
          />
          <span class="rate-suffix">%</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editUserRateDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="savingUserRate" @click="handleSaveEditUserRate">保存</el-button>
      </template>
    </el-dialog>

    <!-- 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.currency === 'PHP' ? '₱' : '¥' }}{{ row.paymentAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="costAmount" label="成本金额" width="120">
          <template #default="{ row }">
            <span class="cost-amount">{{ row.currency === 'PHP' ? '₱' : '¥' }}{{ row.costAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="profitAmount" label="营利金额" width="120">
          <template #default="{ row }">
            <span class="profit-amount">{{ row.currency === 'PHP' ? '₱' : '¥' }}{{ row.profitAmount }}</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.currency === 'PHP' ? '₱' : '¥' }}{{ row.commissionAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="currency" label="货币" width="80">
          <template #default="{ row }">
            <el-tag :type="row.currency === 'PHP' ? 'success' : 'warning'" size="small">
              {{ row.currency === 'PHP' ? '比索' : '人民币' }}
            </el-tag>
          </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, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Money, Coin, Document, Wallet } from '@element-plus/icons-vue'
import api from '@/utils/api'

// State
const loading = ref(false)
const savingRate = ref(false)
const savingUserRate = ref(false)
const commissions = ref([])
const newRate = ref(2)
const usersWithCustomRates = ref([])
const editUserRateDialogVisible = ref(false)
const editingUser = ref(null)
const editUserRateValue = ref(0)

const userRateForm = reactive({
  uid: '',
  rate: 5,
})

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 fetchUsersWithCustomRates() {
  try {
    const response = await api.get('/api/v1/admin/commissions/config/user-commission-rates')
    if (response.data.code === 0) {
      usersWithCustomRates.value = response.data.data.users || []
    }
  } catch (error) {
    console.error('Failed to fetch users with custom rates:', 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
  }
}

async function handleAddUserRate() {
  if (!userRateForm.uid) {
    ElMessage.error('请输入用户UID')
    return
  }
  if (userRateForm.rate < 0 || userRateForm.rate > 100) {
    ElMessage.error('佣金比例必须在 0-100% 之间')
    return
  }

  savingUserRate.value = true
  try {
    // First find user by UID
    const userResponse = await api.get('/api/v1/admin/users', {
      params: { search: userRateForm.uid, limit: 1 }
    })
    
    if (userResponse.data.code !== 0 || !userResponse.data.data.users?.length) {
      ElMessage.error('未找到该用户')
      return
    }

    const user = userResponse.data.data.users[0]
    
    // Set user commission rate
    const response = await api.put(`/api/v1/admin/commissions/config/user-commission-rate/${user.id}`, {
      rate: userRateForm.rate / 100,
    })
    
    if (response.data.code === 0) {
      ElMessage.success('用户专属比例设置成功')
      userRateForm.uid = ''
      userRateForm.rate = 5
      fetchUsersWithCustomRates()
    } else {
      ElMessage.error(response.data.error?.message || '设置失败')
    }
  } catch (error) {
    console.error('Failed to add user rate:', error)
    ElMessage.error(error.response?.data?.error?.message || '设置失败')
  } finally {
    savingUserRate.value = false
  }
}

function handleEditUserRate(row) {
  editingUser.value = row
  editUserRateValue.value = row.commissionRate * 100
  editUserRateDialogVisible.value = true
}

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

  savingUserRate.value = true
  try {
    const response = await api.put(`/api/v1/admin/commissions/config/user-commission-rate/${editingUser.value.userId}`, {
      rate: editUserRateValue.value / 100,
    })
    
    if (response.data.code === 0) {
      ElMessage.success('用户专属比例已更新')
      editUserRateDialogVisible.value = false
      fetchUsersWithCustomRates()
    } else {
      ElMessage.error(response.data.error?.message || '更新失败')
    }
  } catch (error) {
    console.error('Failed to save user rate:', error)
    ElMessage.error('更新失败')
  } finally {
    savingUserRate.value = false
  }
}

async function handleRemoveUserRate(row) {
  try {
    await ElMessageBox.confirm(
      `确定要移除用户 "${row.nickname}" (UID: ${row.uid}) 的专属佣金比例吗？移除后将使用系统默认比例。`,
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const response = await api.put(`/api/v1/admin/commissions/config/user-commission-rate/${row.userId}`, {
      rate: null,
    })
    
    if (response.data.code === 0) {
      ElMessage.success('已移除用户专属比例')
      fetchUsersWithCustomRates()
    } else {
      ElMessage.error(response.data.error?.message || '移除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to remove user rate:', error)
      ElMessage.error('移除失败')
    }
  }
}

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()
  fetchUsersWithCustomRates()
  fetchCommissions()
})
</script>

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

  .stat-card {
    border-radius: 12px;
    overflow: hidden;
    transition: transform 0.3s ease;

    &:hover {
      transform: translateY(-4px);
    }

    .stat-content {
      display: flex;
      align-items: center;
      padding: 8px 0;

      .stat-icon {
        width: 56px;
        height: 56px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;
        flex-shrink: 0;

        .el-icon {
          font-size: 28px;
          color: #fff;
        }
      }

      .stat-info {
        flex: 1;
        min-width: 0;

        .stat-value {
          font-size: 24px;
          font-weight: 600;
          line-height: 1.2;
          margin-bottom: 4px;
          
          &.dual {
            font-size: 18px;
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            gap: 4px;
            
            .rmb {
              color: #e6a23c;
            }
            
            .peso {
              color: #67c23a;
            }
            
            .divider {
              color: #c0c4cc;
              font-weight: normal;
            }
          }
        }

        .stat-label {
          font-size: 13px;
          color: #909399;
        }
      }
    }

    &.rmb-card {
      .stat-icon {
        background: linear-gradient(135deg, #f6d365 0%, #e6a23c 100%);
      }
      .stat-value {
        color: #e6a23c;
      }
    }

    &.peso-card {
      .stat-icon {
        background: linear-gradient(135deg, #84fab0 0%, #67c23a 100%);
      }
      .stat-value {
        color: #67c23a;
      }
    }

    &.count-card {
      .stat-icon {
        background: linear-gradient(135deg, #667eea 0%, #409eff 100%);
      }
      .stat-value {
        color: #409eff;
      }
    }

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

  .config-card {
    margin-bottom: 20px;
    border-radius: 12px;

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

      h4 {
        margin: 0 0 16px 0;
        font-size: 16px;
        color: #303133;
        font-weight: 600;
      }

      .section-desc {
        font-size: 13px;
        color: #909399;
        margin: -8px 0 16px 0;
      }

      .user-rate-form {
        background: linear-gradient(135deg, #f5f7fa 0%, #e4e7ed 100%);
        padding: 20px;
        border-radius: 10px;
        border: 1px solid #ebeef5;
      }

      .empty-tip {
        text-align: center;
        color: #909399;
        padding: 30px;
        font-size: 14px;
        background: #fafafa;
        border-radius: 8px;
        margin-top: 16px;
      }
    }

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

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

  .table-card {
    border-radius: 12px;

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

    .payment-amount {
      color: #e6a23c;
      font-weight: 500;
    }

    .cost-amount {
      color: #f56c6c;
      font-weight: 500;
    }

    .profit-amount {
      color: #67c23a;
      font-weight: 600;
    }

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

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

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