<template>
  <ElDialog v-model="visible" title="套餐流量详单" width="900px" destroy-on-close>
    <div v-if="data">
      <!-- 套餐信息摘要 -->
      <ElDescriptions :column="2" border style="margin-bottom: 20px">
        <ElDescriptionsItem label="套餐名称">
          {{ data.package_name }}
        </ElDescriptionsItem>
        <ElDescriptionsItem label="总使用流量" :span="2">
          {{ formatDataSize(displayedTotalUsageMb) }}
        </ElDescriptionsItem>
      </ElDescriptions>

      <!-- 筛选器 -->
      <div style="display: flex; gap: 12px; align-items: center; margin-bottom: 16px">
        <span style="font-weight: 500">筛选方式：</span>
        <ElRadioGroup v-model="filterType" @change="handleFilterTypeChange">
          <ElRadio value="all">全部</ElRadio>
          <ElRadio value="day">按日</ElRadio>
          <ElRadio value="month">按月</ElRadio>
        </ElRadioGroup>
        <ElDatePicker
          v-if="filterType === 'day'"
          v-model="selectedDate"
          type="date"
          placeholder="选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          clearable
          @change="filterRecordsByDate"
          style="width: 200px"
        />
        <ElDatePicker
          v-if="filterType === 'month'"
          v-model="selectedMonth"
          type="month"
          placeholder="选择月份"
          format="YYYY-MM"
          value-format="YYYY-MM"
          clearable
          @change="filterRecordsByMonth"
          style="width: 200px"
        />
      </div>

      <!-- 每日流量记录表格 -->
      <ElTable :data="filteredRecords" border stripe max-height="400" v-loading="loading">
        <ElTableColumn prop="date" label="日期" width="120" align="center" />
        <ElTableColumn label="当日使用流量" width="150" align="center">
          <template #default="{ row }">
            {{ formatDataSize(row.daily_usage_mb) }}
          </template>
        </ElTableColumn>
        <ElTableColumn label="累计流量" width="150" align="center">
          <template #default="{ row }">
            {{ formatDataSize(row.cumulative_usage_mb) }}
          </template>
        </ElTableColumn>
        <ElTableColumn label="使用进度" min-width="200">
          <template #default="{ row }">
            <ElProgress
              :percentage="getUsageProgress(row.cumulative_usage_mb, displayedTotalUsageMb)"
              :color="
                getProgressColor(getUsageProgress(row.cumulative_usage_mb, displayedTotalUsageMb))
              "
            />
          </template>
        </ElTableColumn>
      </ElTable>
    </div>
    <div v-else-if="!loading" style="padding: 40px 0; text-align: center">
      <ElEmpty description="暂无流量详单数据" />
    </div>
  </ElDialog>
</template>

<script setup lang="ts">
  import { ref, computed, watch } from 'vue'
  import {
    ElDialog,
    ElDescriptions,
    ElDescriptionsItem,
    ElRadioGroup,
    ElRadio,
    ElDatePicker,
    ElTable,
    ElTableColumn,
    ElProgress,
    ElEmpty
  } from 'element-plus'
  import { CardService } from '@/api/modules'
  import type { PackageInfo } from '../../types'

  interface Props {
    modelValue: boolean
    packageUsageId?: number
    packageRow?: PackageInfo
  }

  interface DailyRecordItem {
    date: string
    daily_usage_mb: number
    cumulative_usage_mb: number
  }

  interface DailyRecordsResponseData {
    package_name: string
    package_usage_id: number
    total_usage_mb: number
    records: DailyRecordItem[]
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
  }

  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()

  const loading = ref(false)
  const data = ref<DailyRecordsResponseData | null>(null)
  const filterType = ref<'all' | 'day' | 'month'>('all')
  const selectedDate = ref<string>('')
  const selectedMonth = ref<string>('')
  const filteredRecords = ref<DailyRecordItem[]>([])

  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  })
  const displayedTotalUsageMb = computed(
    () => props.packageRow?.real_total_mb ?? data.value?.total_usage_mb ?? 0
  )

  // 监听对话框打开，加载数据
  watch(visible, async (newVal) => {
    if (newVal && props.packageUsageId) {
      await loadDailyRecords()
    } else if (!newVal) {
      // 关闭时重置数据
      data.value = null
      filterType.value = 'all'
      selectedDate.value = ''
      selectedMonth.value = ''
      filteredRecords.value = []
    }
  })

  const loadDailyRecords = async () => {
    if (!props.packageUsageId) return

    try {
      loading.value = true
      const res = await CardService.getPackageDailyRecords(props.packageUsageId)
      if (res.code === 0 && res.data) {
        data.value = res.data
        filteredRecords.value = res.data.records || []
      }
    } catch (error) {
      console.error('加载流量详单失败:', error)
      console.log('加载流量详单失败')
    } finally {
      loading.value = false
    }
  }

  const formatDataSize = (mb: number) => {
    if (mb >= 1024) {
      return `${(mb / 1024).toFixed(2)}GB`
    }
    return `${mb.toFixed(2)}MB`
  }

  const handleFilterTypeChange = () => {
    selectedDate.value = ''
    selectedMonth.value = ''
    filteredRecords.value = data.value?.records || []
  }

  const filterRecordsByDate = () => {
    if (!data.value?.records) return

    if (!selectedDate.value) {
      filteredRecords.value = data.value.records
      return
    }

    filteredRecords.value = data.value.records.filter((record) => {
      return record.date === selectedDate.value
    })
  }

  const filterRecordsByMonth = () => {
    if (!data.value?.records) return

    if (!selectedMonth.value) {
      filteredRecords.value = data.value.records
      return
    }

    filteredRecords.value = data.value.records.filter((record) => {
      return record.date.startsWith(selectedMonth.value)
    })
  }

  const getUsageProgress = (cumulative: number, total: number): number => {
    if (!total || total <= 0) return 0
    const percentage = (cumulative / total) * 100
    return Math.min(Math.round(percentage * 100) / 100, 100)
  }

  const getProgressColor = (percentage: number): string => {
    if (percentage < 50) return '#67c23a'
    if (percentage < 80) return '#e6a23c'
    return '#f56c6c'
  }
</script>

<style lang="scss" scoped></style>
