<template>
  <ElCard shadow="never" class="daily-commission-stats-widget">
    <template #header>
      <div class="card-header">
        <div class="header-left">
          <span class="header-title">每日佣金统计</span>
        </div>
        <div class="header-right" v-if="statsList.length > 0">
          <span class="date-range"
            >{{ formatDateRange(startDate) }} ~ {{ formatDateRange(endDate) }}</span
          >
        </div>
      </div>
    </template>
    <div v-if="statsList.length > 0" class="stats-info">
      <div class="stats-card">
        <div
          class="stats-icon"
          style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%)"
        >
          <i class="el-icon">💰</i>
        </div>
        <div class="stats-content">
          <div class="stats-label">总收入</div>
          <div class="stats-value">{{ formatMoney(totalAmount) }}</div>
        </div>
      </div>
      <div class="stats-card">
        <div
          class="stats-icon"
          style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)"
        >
          <i class="el-icon">📊</i>
        </div>
        <div class="stats-content">
          <div class="stats-label">总笔数</div>
          <div class="stats-value">{{ totalCount }} 笔</div>
        </div>
      </div>
    </div>
    <div class="stats-chart" v-if="statsList.length > 0">
      <div class="chart-bar" v-for="item in statsList" :key="item.date">
        <div class="bar-label">{{ formatDateShort(item.date) }}</div>
        <div class="bar-value" :style="{ height: getBarHeight(item.total_amount) + 'px' }">
          <ElTooltip :content="formatMoney(item.total_amount)" placement="top">
            <div class="bar-fill"></div>
          </ElTooltip>
        </div>
      </div>
    </div>
    <div v-if="statsList.length === 0" class="empty-content">
      <i class="el-icon-info" style="font-size: 48px; color: var(--el-text-color-placeholder)"></i>
      <p>暂无佣金统计数据</p>
    </div>
  </ElCard>
</template>

<script setup lang="ts">
  import { CommissionService } from '@/api/modules'
  import { ElTooltip } from 'element-plus'
  import type { DailyCommissionStatsItem } from '@/types/api/commission'
  import { useUserStore } from '@/store/modules/user'
  import { formatMoney } from '@/utils/business/format'
  import { usePermission } from '@/composables/usePermission'

  defineOptions({ name: 'DailyCommissionStatsWidget' })

  const { hasPermission } = usePermission()
  const userStore = useUserStore()
  const currentShopId = computed(() => userStore.info?.shop_id)

  const statsList = ref<DailyCommissionStatsItem[]>([])
  const loading = ref(false)

  const startDate = ref('')
  const endDate = ref('')

  const totalAmount = computed(() =>
    statsList.value.reduce((sum, item) => sum + item.total_amount, 0)
  )
  const totalCount = computed(() =>
    statsList.value.reduce((sum, item) => sum + item.total_count, 0)
  )

  const maxAmount = computed(() => {
    if (statsList.value.length === 0) return 0
    return Math.max(...statsList.value.map((item) => item.total_amount))
  })

  const getBarHeight = (amount: number) => {
    if (maxAmount.value === 0) return 0
    return Math.max(4, (amount / maxAmount.value) * 100)
  }

  const formatDateShort = (dateStr: string) => {
    if (!dateStr) return '-'
    return dateStr.slice(5) // MM-DD
  }

  const formatDateRange = (dateStr: string) => {
    if (!dateStr) return '-'
    return dateStr // API already returns YYYY-MM-DD format
  }

  const loadDailyStats = async () => {
    // 检查权限，没有权限不调用接口
    if (!hasPermission('dashboard_analysis:withdrawal_settings')) {
      return
    }

    if (!currentShopId.value) return

    loading.value = true
    try {
      const res = await CommissionService.getShopDailyCommissionStats(currentShopId.value, {
        days: 30
      })
      if (res.code === 0 && res.data) {
        statsList.value = res.data
        if (res.data.length > 0) {
          startDate.value = res.data[res.data.length - 1]?.date || ''
          endDate.value = res.data[0]?.date || ''
        }
      }
    } catch (error) {
      console.error('获取每日佣金统计失败:', error)
    } finally {
      loading.value = false
    }
  }

  onMounted(() => {
    loadDailyStats()
  })
</script>

<style lang="scss" scoped>
  .daily-commission-stats-widget {
    :deep(.el-card__header) {
      padding: 18px 20px;
      background: var(--el-fill-color-light);
      border-bottom: 1px solid var(--el-border-color-lighter);
    }

    :deep(.el-card__body) {
      padding: 20px;
    }

    .card-header {
      display: flex;
      flex-wrap: wrap;
      gap: 12px;
      align-items: center;
      justify-content: space-between;

      .header-left {
        display: flex;
        gap: 10px;
        align-items: center;

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

      .header-right {
        .date-range {
          font-size: 13px;
          color: var(--el-text-color-secondary);
        }
      }
    }

    .stats-info {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
      gap: 16px;
      margin-bottom: 20px;

      .stats-card {
        display: flex;
        gap: 12px;
        align-items: center;
        padding: 16px;
        background: var(--el-fill-color-blank);
        border-radius: 8px;

        .stats-icon {
          display: flex;
          flex-shrink: 0;
          align-items: center;
          justify-content: center;
          width: 40px;
          height: 40px;
          font-size: 20px;
          border-radius: 8px;
        }

        .stats-content {
          flex: 1;
          min-width: 0;

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

          .stats-value {
            overflow: hidden;
            font-size: 16px;
            font-weight: 600;
            color: var(--el-text-color-primary);
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }
    }

    .stats-chart {
      display: flex;
      gap: 8px;
      align-items: flex-end;
      height: 120px;
      padding-top: 10px;

      .chart-bar {
        display: flex;
        flex: 1;
        flex-direction: column;
        gap: 4px;
        align-items: center;

        .bar-label {
          font-size: 11px;
          color: var(--el-text-color-secondary);
        }

        .bar-value {
          display: flex;
          justify-content: center;
          width: 100%;

          .bar-fill {
            width: 80%;
            max-width: 24px;
            cursor: pointer;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 4px 4px 0 0;
            transition: opacity 0.2s;

            &:hover {
              opacity: 0.8;
            }
          }
        }
      }
    }

    &.empty-state {
      .empty-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 40px 20px;
        color: var(--el-text-color-secondary);

        p {
          margin-top: 12px;
          font-size: 14px;
        }
      }
    }
  }

  @media (width <= 768px) {
    .daily-commission-stats-widget {
      .card-header {
        .header-left,
        .header-right {
          width: 100%;
        }
      }

      .stats-info {
        grid-template-columns: 1fr;
        gap: 12px;
      }

      .stats-chart {
        padding-bottom: 10px;
        overflow-x: auto;
      }
    }
  }
</style>
