<template>
  <div class="package-detail">
    <ElCard shadow="never">
      <!-- 页面头部 -->
      <div class="detail-header">
        <ElButton @click="handleBack">
          <template #icon>
            <ElIcon><ArrowLeft /></ElIcon>
          </template>
          返回
        </ElButton>
        <h2 class="detail-title">套餐详情</h2>
      </div>

      <!-- 详情内容 -->
      <DetailPage v-if="detailData" :sections="detailSections" :data="detailData" />

      <!-- 加载中 -->
      <div v-if="loading" class="loading-container">
        <ElIcon class="is-loading"><Loading /></ElIcon>
        <span>加载中...</span>
      </div>
    </ElCard>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ElCard, ElButton, ElIcon, ElMessage } from 'element-plus'
  import { ArrowLeft, Loading } from '@element-plus/icons-vue'
  import DetailPage from '@/components/common/DetailPage.vue'
  import type { DetailSection } from '@/components/common/DetailPage.vue'
  import { PackageManageService } from '@/api/modules'
  import type { PackageResponse } from '@/types/api'
  import { formatDateTime } from '@/utils/business/format'
  import { getStatusLabel, getShelfStatusText } from '@/config/constants'

  defineOptions({ name: 'PackageDetail' })

  const route = useRoute()
  const router = useRouter()

  const loading = ref(false)
  const detailData = ref<PackageResponse | null>(null)

  // 详情页配置
  const detailSections: DetailSection[] = [
    {
      title: '基本信息',
      fields: [
        { label: 'ID', prop: 'id' },
        { label: '套餐编码', prop: 'package_code' },
        { label: '套餐名称', prop: 'package_name' },
        { label: '套餐系列', prop: 'series_name' },
        {
          label: '套餐类型',
          formatter: (_, data) => {
            const typeMap: Record<string, string> = {
              formal: '正式套餐',
              addon: '附加套餐'
            }
            return typeMap[data.package_type] || data.package_type
          }
        },
        {
          label: '套餐时长',
          formatter: (_, data) => {
            return `${data.duration_months} 个月`
          }
        },
        {
          label: '套餐周期类型',
          formatter: (_, data) => {
            if (!data.calendar_type) return '-'
            const typeMap: Record<string, string> = {
              natural_month: '自然月',
              by_day: '按天'
            }
            return typeMap[data.calendar_type] || data.calendar_type
          }
        },
        {
          label: '套餐天数',
          formatter: (_, data) => {
            if (data.calendar_type !== 'by_day' || !data.duration_days) return '-'
            return `${data.duration_days} 天`
          }
        },
        {
          label: '流量重置周期',
          formatter: (_, data) => {
            if (!data.data_reset_cycle) return '-'
            const cycleMap: Record<string, string> = {
              daily: '每日',
              monthly: '每月',
              yearly: '每年',
              none: '不重置'
            }
            return cycleMap[data.data_reset_cycle] || data.data_reset_cycle
          }
        },
        {
          label: '到期计时基准',
          formatter: (_, data) => {
            if (!data.expiry_base) return '--'
            return data.expiry_base === 'from_activation' ? '实名激活时起算' : '购买时起算'
          }
        },
        {
          label: '状态',
          formatter: (_, data) => {
            return getStatusLabel(data.status ?? 0)
          }
        },
        {
          label: '上架状态',
          formatter: (_, data) => {
            return getShelfStatusText(data.shelf_status ?? 0)
          }
        },
        { label: '创建时间', prop: 'created_at', formatter: (value) => formatDateTime(value) },
        { label: '更新时间', prop: 'updated_at', formatter: (value) => formatDateTime(value) }
      ]
    },
    {
      title: '流量配置',
      fields: [
        {
          label: '真流量额度',
          formatter: (_, data) => {
            if (data.real_data_mb >= 1024) {
              return `${(data.real_data_mb / 1024).toFixed(2)} GB`
            }
            return `${data.real_data_mb} MB`
          }
        },
        {
          label: '启用虚流量',
          formatter: (_, data) => {
            return data.enable_virtual_data ? '是' : '否'
          }
        },
        {
          label: '虚流量额度',
          formatter: (_, data) => {
            if (!data.enable_virtual_data) return '-'
            if (data.virtual_data_mb >= 1024) {
              return `${(data.virtual_data_mb / 1024).toFixed(2)} GB`
            }
            return `${data.virtual_data_mb} MB`
          }
        }
      ]
    },
    {
      title: '价格信息',
      fields: [
        {
          label: '成本价',
          formatter: (_, data) => {
            return `¥${(data.cost_price / 100).toFixed(2)}`
          }
        },
        {
          label: '建议售价',
          formatter: (_, data) => {
            return `¥${(data.suggested_retail_price / 100).toFixed(2)}`
          }
        },
        {
          label: '利润空间',
          formatter: (_, data) => {
            if (data.profit_margin === null || data.profit_margin === undefined) return '-'
            return `¥${(data.profit_margin / 100).toFixed(2)}`
          }
        }
      ]
    },
    {
      title: '佣金配置',
      fields: [
        {
          label: '一次性佣金金额',
          formatter: (_, data) => {
            if (
              data.one_time_commission_amount === null ||
              data.one_time_commission_amount === undefined
            )
              return '-'
            return `¥${(data.one_time_commission_amount / 100).toFixed(2)}`
          }
        },
        {
          label: '当前返佣比例',
          formatter: (_, data) => {
            if (!data.tier_info || !data.tier_info.current_rate) return '-'
            return data.tier_info.current_rate
          }
        },
        {
          label: '下一档位比例',
          formatter: (_, data) => {
            if (!data.tier_info || !data.tier_info.next_rate) return '-'
            return data.tier_info.next_rate
          }
        },
        {
          label: '下一档位阈值',
          formatter: (_, data) => {
            if (
              !data.tier_info ||
              data.tier_info.next_threshold === null ||
              data.tier_info.next_threshold === undefined
            )
              return '-'
            return data.tier_info.next_threshold
          }
        }
      ]
    }
  ]

  // 返回上一页
  const handleBack = () => {
    router.back()
  }

  // 获取详情数据
  const fetchDetail = async () => {
    const id = Number(route.params.id)
    if (!id) {
      ElMessage.error('缺少ID参数')
      return
    }

    loading.value = true
    try {
      const res = await PackageManageService.getPackageDetail(id)
      if (res.code === 0) {
        detailData.value = res.data
      }
    } catch (error) {
      console.error(error)
      console.log('获取详情失败')
    } finally {
      loading.value = false
    }
  }

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

<style scoped lang="scss">
  .package-detail {
    padding: 20px;
  }

  .detail-header {
    display: flex;
    gap: 16px;
    align-items: center;
    padding-bottom: 16px;

    .detail-title {
      margin: 0;
      font-size: 20px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
  }

  .loading-container {
    display: flex;
    flex-direction: column;
    gap: 12px;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
    color: var(--el-text-color-secondary);

    .el-icon {
      font-size: 32px;
    }
  }
</style>
