<template>
  <el-card class="income-summary-card" v-loading="loading">
    <template #header>
      <div class="card-header">
        <span class="card-title">今日收入汇总</span>
        <el-button 
          type="primary" 
          link 
          :icon="Refresh" 
          @click="handleRefresh"
          :loading="loading"
        >
          刷新
        </el-button>
      </div>
    </template>
    
    <el-table :data="tableData" border stripe class="income-table">
      <el-table-column prop="category" label="类别" width="120" />
      <el-table-column prop="item" label="项目" min-width="150" />
      <el-table-column prop="value" label="金额" min-width="120" align="right">
        <template #default="{ row }">
          <span :class="{ 'negative-value': row.isNegative }">
            {{ row.value }}
          </span>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 利润计算公式 -->
    <div class="formula-section">
      <div class="formula-label">利润计算公式：</div>
      <div class="formula-content">{{ data.formula || '收入 - 发货金额 - 用户剩余达达券 - 盒柜剩余' }}</div>
    </div>
    
    <!-- 错误提示 -->
    <div v-if="error" class="error-message">
      <el-icon><WarningFilled /></el-icon>
      <span>{{ error }}</span>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { Refresh, WarningFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getIncomeSummaryStats, type IncomeSummaryStats } from '@/api/business/statistics'
import { formatCurrency } from '@/utils/format'

// ==================== 状态定义 ====================

const loading = ref(false)
const error = ref<string | null>(null)

// 默认数据（降级展示）
const defaultData: IncomeSummaryStats = {
  todayIncome: 0,
  rmbIncome: 0,
  diamondIncome: 0,
  otherIncome: 0,
  shippedToday: 0,
  expenses: 0,
  todayShipped: 0,
  remainingCoupon: 0,
  boxRemaining: 0,
  profit: 0,
  formula: '收入 - 发货金额 - 用户剩余达达券 - 盒柜剩余'
}

const data = reactive<IncomeSummaryStats>({ ...defaultData })

// ==================== 计算属性 ====================

/**
 * 表格数据
 */
const tableData = computed(() => [
  { category: '收入', item: '订单收入（RMB+钻石）', value: formatCurrency(data.todayIncome), isNegative: false },
  { category: '收入', item: 'RMB收入', value: formatCurrency(data.rmbIncome), isNegative: false },
  { category: '收入', item: '钻石商城收入', value: formatCurrency(data.diamondIncome), isNegative: false },
  { category: '收入', item: '其他收入', value: formatCurrency(data.otherIncome), isNegative: false },
  { category: '出货', item: '订单出货', value: formatCurrency(data.shippedToday), isNegative: false },
  { category: '支出', item: '支出', value: formatCurrency(data.expenses), isNegative: false },
  { category: '支出', item: '当天发货金额', value: formatCurrency(data.todayShipped), isNegative: false },
  { category: '支出', item: '当天用户剩余达达券', value: formatCurrency(data.remainingCoupon), isNegative: false },
  { category: '支出', item: '盒柜剩余价值', value: formatCurrency(data.boxRemaining), isNegative: false },
  { category: '利润', item: '利润', value: formatCurrency(data.profit), isNegative: data.profit < 0 }
])

// ==================== 数据加载 ====================

/**
 * 加载收入汇总统计数据
 */
async function loadData() {
  loading.value = true
  error.value = null
  
  try {
    const response = await getIncomeSummaryStats()
    if (response.code === 0 && response.data) {
      Object.assign(data, response.data)
    } else {
      error.value = response.message || '获取数据失败'
      Object.assign(data, defaultData)
    }
  } catch (err: unknown) {
    console.error('加载收入汇总数据失败:', err)
    
    // 根据错误类型显示不同提示
    if (err instanceof Error) {
      if (err.message.includes('403') || err.message.includes('权限')) {
        error.value = '无权限访问此页面'
      } else if (err.message.includes('network') || err.message.includes('Network')) {
        error.value = '网络连接失败，请检查网络'
      } else {
        error.value = '服务器繁忙，请稍后重试'
      }
    } else {
      error.value = '获取数据失败'
    }
    
    // 降级展示默认值
    Object.assign(data, defaultData)
  } finally {
    loading.value = false
  }
}

/**
 * 刷新数据
 */
function handleRefresh() {
  loadData()
  ElMessage.info('正在刷新数据...')
}

// ==================== 生命周期 ====================

onMounted(() => {
  loadData()
})

// ==================== 暴露方法 ====================

defineExpose({
  refresh: loadData
})
</script>

<style scoped>
.income-summary-card {
  height: 100%;
}

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

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.income-table {
  width: 100%;
}

.income-table :deep(.el-table__row) {
  transition: background-color 0.3s ease;
}

.income-table :deep(.el-table__row:hover) {
  background-color: var(--el-fill-color-light);
}

.negative-value {
  color: var(--el-color-danger);
  font-weight: 600;
}

.formula-section {
  margin-top: 16px;
  padding: 12px;
  background: var(--el-fill-color-light);
  border-radius: 8px;
}

.formula-label {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-bottom: 4px;
}

.formula-content {
  font-size: 14px;
  color: var(--el-text-color-primary);
  font-family: 'Courier New', monospace;
}

.error-message {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-top: 16px;
  padding: 12px;
  background: var(--el-color-danger-light-9);
  border-radius: 4px;
  color: var(--el-color-danger);
  font-size: 14px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .income-table :deep(.el-table__cell) {
    padding: 8px 4px;
    font-size: 12px;
  }
}
</style>
