<template>
  <div class="art-page-view">
    <!-- 1. 筛选区 -->
    <ElCard shadow="never" class="mb-4">
      <div class="flex flex-wrap items-center justify-between gap-3">
        <div class="text-base font-semibold">{{ $t('billing.statistics.title') }}</div>

        <div class="flex flex-wrap items-center gap-2">
          <ElDatePicker
            v-model="dateRange"
            type="daterange"
            value-format="YYYY-MM-DD"
            :start-placeholder="$t('billing.statistics.startDate')"
            :end-placeholder="$t('billing.statistics.endDate')"
          />

          <ElSelect v-model="groupBy" class="w-[120px]">
            <ElOption value="Day" :label="$t('billing.statistics.groupBy.day')" />
            <ElOption value="Week" :label="$t('billing.statistics.groupBy.week')" />
            <ElOption value="Month" :label="$t('billing.statistics.groupBy.month')" />
          </ElSelect>

          <ElButton type="primary" :loading="loading" @click="handleRefresh" v-ripple>
            <ArtSvgIcon icon="ri:refresh-line" />
            {{ $t('worktab.btn.refresh') }}
          </ElButton>
        </div>
      </div>
    </ElCard>

    <!-- 2. 收入概览卡片 -->
    <ElRow :gutter="16" class="mb-4">
      <ElCol :span="6">
        <ElCard shadow="hover" class="statistics-card">
          <div class="card-content">
            <div class="card-icon revenue">
              <ArtSvgIcon icon="ri:money-dollar-circle-line" :size="32" />
            </div>
            <div class="card-info">
              <div class="card-label">{{ $t('billing.statistics.totalRevenue') }}</div>
              <div class="card-value">￥{{ formatMoney(totalRevenue) }}</div>
            </div>
          </div>
        </ElCard>
      </ElCol>
      <ElCol :span="6">
        <ElCard shadow="hover" class="statistics-card">
          <div class="card-content">
            <div class="card-icon pending">
              <ArtSvgIcon icon="ri:wallet-3-line" :size="32" />
            </div>
            <div class="card-info">
              <div class="card-label">{{ $t('billing.statistics.pendingAmount') }}</div>
              <div class="card-value">￥{{ formatMoney(pendingAmount) }}</div>
            </div>
          </div>
        </ElCard>
      </ElCol>
      <ElCol :span="6">
        <ElCard shadow="hover" class="statistics-card">
          <div class="card-content">
            <div class="card-icon overdue">
              <ArtSvgIcon icon="ri:error-warning-line" :size="32" />
            </div>
            <div class="card-info">
              <div class="card-label">{{ $t('billing.statistics.overdueAmount') }}</div>
              <div class="card-value">￥{{ formatMoney(overdueAmount) }}</div>
            </div>
          </div>
        </ElCard>
      </ElCol>
      <ElCol :span="6">
        <ElCard shadow="hover" class="statistics-card">
          <div class="card-content">
            <div class="card-icon monthly">
              <ArtSvgIcon icon="ri:bar-chart-2-line" :size="32" />
            </div>
            <div class="card-info">
              <div class="card-label">{{ $t('billing.statistics.totalAmountDue') }}</div>
              <div class="card-value">￥{{ formatMoney(totalAmountDue) }}</div>
            </div>
          </div>
        </ElCard>
      </ElCol>
    </ElRow>

    <!-- 3. 图表：状态分布 + 支付方式占比 -->
    <ElRow :gutter="16" class="mb-4">
      <ElCol :span="12">
        <ElCard shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">{{ $t('billing.statistics.statusDistribution') }}</span>
            </div>
          </template>
          <ArtRingChart :height="'320px'" :data="statusPieData" :show-legend="true" />
        </ElCard>
      </ElCol>
      <ElCol :span="12">
        <ElCard shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">{{
                $t('billing.statistics.paymentMethodDistribution')
              }}</span>
            </div>
          </template>
          <ArtRingChart
            v-if="paymentMethodPieData.length > 0"
            :height="'320px'"
            :data="paymentMethodPieData"
            :show-legend="true"
          />
          <ElEmpty v-else :description="$t('billing.statistics.paymentMethodNoData')" />
        </ElCard>
      </ElCol>
    </ElRow>

    <!-- 4. 图表：收入趋势 + 欠款排行 -->
    <ElRow :gutter="16">
      <ElCol :span="16">
        <ElCard shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">{{ $t('billing.statistics.revenueTrend') }}</span>
            </div>
          </template>
          <ArtLineChart
            :height="'320px'"
            :x-axis-data="trendXAxis"
            :data="trendSeries"
            :show-area-color="true"
          />
        </ElCard>
      </ElCol>
      <ElCol :span="8">
        <ElCard shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">{{ $t('billing.statistics.topDebtors') }}</span>
            </div>
          </template>

          <ElTable :data="topDebtors" size="small" height="320">
            <ElTableColumn prop="tenantName" :label="$t('billing.field.tenantName')" />
            <ElTableColumn
              prop="overdueAmount"
              :label="$t('billing.statistics.overdueAmount')"
              width="120"
            >
              <template #default="{ row }">￥{{ formatMoney(row.overdueAmount) }}</template>
            </ElTableColumn>
            <ElTableColumn
              prop="overdueDays"
              :label="$t('billing.statistics.overdueDays')"
              width="100"
            >
              <template #default="{ row }">{{ row.overdueDays }}</template>
            </ElTableColumn>
          </ElTable>
        </ElCard>
      </ElCol>
    </ElRow>
  </div>
</template>

<script setup lang="ts">
  import { computed, onMounted, ref } from 'vue'
  import {
    ElButton,
    ElCard,
    ElCol,
    ElDatePicker,
    ElEmpty,
    ElOption,
    ElRow,
    ElSelect,
    ElTable,
    ElTableColumn
  } from 'element-plus'
  import ArtSvgIcon from '@/components/core/base/art-svg-icon/index.vue'
  import ArtLineChart from '@/components/core/charts/art-line-chart/index.vue'
  import ArtRingChart from '@/components/core/charts/art-ring-chart/index.vue'
  import { fetchBillingStatistics, fetchOverdueBillings } from '@/api/billing'
  import { TenantBillingStatus } from '@/enums/Billing'
  import { calculateDaysOverdue, formatBillingStatus, formatPaymentMethod } from '@/utils/billing'

  defineOptions({ name: 'TenantBillingStatistics' })

  // ==================== State ====================

  // 1. 查询条件
  const dateRange = ref<[string, string] | []>([])
  const groupBy = ref<Api.Billing.BillingStatisticsParams['GroupBy']>('Day')

  // 2. 页面状态
  const loading = ref(false)
  const statistics = ref<Api.Billing.BillingStatisticsDto | null>(null)
  const topDebtors = ref<
    Array<{ tenantId: string; tenantName: string; overdueAmount: number; overdueDays: number }>
  >([])

  // ==================== Computed ====================

  // 3. 计算展示数据（兼容不同后端返回）
  const totalRevenue = computed(() => {
    return statistics.value?.totalRevenue ?? statistics.value?.totalAmountPaid ?? 0
  })

  const totalAmountDue = computed(() => {
    return statistics.value?.totalAmountDue ?? 0
  })

  const pendingAmount = computed(() => {
    return statistics.value?.pendingAmount ?? statistics.value?.totalAmountUnpaid ?? 0
  })

  const overdueAmount = computed(() => {
    return statistics.value?.overdueAmount ?? statistics.value?.totalOverdueAmount ?? 0
  })

  // 4. 图表：状态分布（饼图数据）
  const statusPieData = computed(() => {
    // 4.1 优先使用增强统计的 statusDistribution
    const dist = statistics.value?.statusDistribution
    if (dist && dist.length > 0) {
      return dist.map((x) => ({
        name: formatBillingStatus(x.status),
        value: x.count
      }))
    }

    // 4.2 回退到基础统计的 count 字段
    const pending = statistics.value?.pendingBillCount ?? statistics.value?.pendingCount ?? 0
    const paid = statistics.value?.paidBillCount ?? statistics.value?.paidCount ?? 0
    const overdue = statistics.value?.overdueBillCount ?? statistics.value?.overdueCount ?? 0
    const cancelled = statistics.value?.cancelledCount ?? 0

    return [
      { name: formatBillingStatus(TenantBillingStatus.Pending), value: pending },
      { name: formatBillingStatus(TenantBillingStatus.Paid), value: paid },
      { name: formatBillingStatus(TenantBillingStatus.Overdue), value: overdue },
      { name: formatBillingStatus(TenantBillingStatus.Cancelled), value: cancelled }
    ]
  })

  // 5. 图表：支付方式占比（饼图数据）
  const paymentMethodPieData = computed(() => {
    const dist = statistics.value?.paymentMethodDistribution
    if (!dist || dist.length === 0) return []

    return dist.map((x) => ({
      name: formatPaymentMethod(x.method),
      value: x.count
    }))
  })

  // 6. 图表：收入趋势（折线图数据）
  const trendXAxis = computed(() => {
    const trend = statistics.value?.revenueTrend
    if (trend && trend.length > 0) return trend.map((x) => x.date)

    const daily = statistics.value?.dailyStats
    if (daily && daily.length > 0) return daily.map((x) => x.date)

    return []
  })

  const trendSeries = computed(() => {
    const trend = statistics.value?.revenueTrend
    if (trend && trend.length > 0) return trend.map((x) => x.amount)

    const daily = statistics.value?.dailyStats
    if (daily && daily.length > 0) return daily.map((x) => x.paidAmount ?? x.totalAmount ?? 0)

    return []
  })

  // ==================== Methods ====================

  // 7. 工具：金额格式化（保持 UI 一致）
  const formatMoney = (amount: number) => {
    return (Number.isFinite(amount) ? amount : 0).toFixed(2)
  }

  // 8. 初始化默认日期范围（本月）
  const initDefaultDateRange = () => {
    const now = new Date()
    const firstDay = new Date(now.getFullYear(), now.getMonth(), 1)
    const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0)
    dateRange.value = [firstDay.toISOString().split('T')[0], lastDay.toISOString().split('T')[0]]
  }

  // 9. 加载统计数据
  const loadStatistics = async () => {
    if (!dateRange.value || dateRange.value.length !== 2) return

    // 1. 拉取统计数据
    const data = await fetchBillingStatistics({
      StartDate: dateRange.value[0],
      EndDate: dateRange.value[1],
      GroupBy: groupBy.value
    })

    statistics.value = data
  }

  // 10. 拉取逾期列表并聚合欠款排行（用于补足 topDebtors 数据）
  const loadTopDebtors = async () => {
    // 1. 拉取逾期账单（仅用于排名展示）
    const res = await fetchOverdueBillings({ PageNumber: 1, PageSize: 500 })
    const rows = res.items || []

    // 2. 按租户聚合欠款金额与逾期天数
    const map = new Map<
      string,
      { tenantId: string; tenantName: string; overdueAmount: number; overdueDays: number }
    >()

    rows.forEach((b) => {
      const tenantId = b.tenantId || ''
      if (!tenantId) return

      const remain = Math.max((b.amountDue || 0) - (b.amountPaid || 0), 0)
      const days = Math.max(calculateDaysOverdue(b.dueDate), 0)

      const prev = map.get(tenantId)
      if (!prev) {
        map.set(tenantId, {
          tenantId,
          tenantName: b.tenantName || '-',
          overdueAmount: remain,
          overdueDays: days
        })
        return
      }

      map.set(tenantId, {
        tenantId,
        tenantName: prev.tenantName || b.tenantName || '-',
        overdueAmount: prev.overdueAmount + remain,
        overdueDays: Math.max(prev.overdueDays, days)
      })
    })

    // 3. Top 10
    topDebtors.value = Array.from(map.values())
      .sort((a, b) => b.overdueAmount - a.overdueAmount)
      .slice(0, 10)
  }

  // 11. 刷新入口
  const handleRefresh = async () => {
    if (!dateRange.value || dateRange.value.length !== 2) return

    loading.value = true
    try {
      await Promise.all([loadStatistics(), loadTopDebtors()])
    } finally {
      loading.value = false
    }
  }

  onMounted(() => {
    initDefaultDateRange()
    handleRefresh()
  })
</script>

<style scoped lang="scss">
  .statistics-card {
    .card-content {
      display: flex;
      gap: 16px;
      align-items: center;

      .card-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 56px;
        height: 56px;
        color: var(--el-color-white);
        border-radius: 12px;

        &.revenue {
          background: linear-gradient(
            135deg,
            var(--el-color-primary-light-5) 0%,
            var(--el-color-primary) 100%
          );
        }

        &.pending {
          background: linear-gradient(
            135deg,
            var(--el-color-warning-light-5) 0%,
            var(--el-color-warning) 100%
          );
        }

        &.overdue {
          background: linear-gradient(
            135deg,
            var(--el-color-danger-light-5) 0%,
            var(--el-color-danger) 100%
          );
        }

        &.monthly {
          background: linear-gradient(
            135deg,
            var(--el-color-success-light-5) 0%,
            var(--el-color-success) 100%
          );
        }
      }

      .card-info {
        flex: 1;

        .card-label {
          margin-bottom: 8px;
          font-size: 14px;
          color: var(--el-text-color-secondary);
        }

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

  .card-header {
    .card-title {
      font-size: 16px;
      font-weight: 600;
    }
  }
</style>
