<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, computed } 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'
  import { useUserStore } from '@/store/modules/user'

  defineOptions({ name: 'PackageDetail' })

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

  const currentUserType = computed(() => Number(userStore.info.user_type ?? 0))
  const isAgentAccount = computed(() => currentUserType.value === 3)
  const shouldHideVirtualTrafficFields = computed(() => [3, 4].includes(currentUserType.value))

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

  // 详情页配置
  const detailSections: DetailSection[] = [
    {
      title: '基本信息',
      fields: [
        { label: '套餐编码', prop: 'package_code' },
        { label: '套餐名称', prop: 'package_name' },
        { label: '套餐系列', prop: 'series_name' },
        {
          label: '套餐类型',
          formatter: (_: unknown, data: PackageResponse) => {
            const typeMap: Record<string, string> = {
              formal: '正式套餐',
              addon: '附加套餐'
            }
            return typeMap[data.package_type] || data.package_type
          }
        },
        {
          label: '成本价',
          formatter: (_: unknown, data: PackageResponse) => {
            return `¥${((data.cost_price || 0) / 100).toFixed(2)}`
          }
        },
        {
          label: '建议售价',
          formatter: (_: unknown, data: PackageResponse) => {
            if (data.suggested_retail_price === null || data.suggested_retail_price === undefined)
              return '-'
            return `¥${(data.suggested_retail_price / 100).toFixed(2)}`
          }
        },
        ...(isAgentAccount.value
          ? [
              {
                label: '代理零售价',
                formatter: (_: unknown, data: PackageResponse) => {
                  if (data.retail_price === null || data.retail_price === undefined) return '-'
                  return `¥${(data.retail_price / 100).toFixed(2)}`
                }
              },
              {
                label: '利润空间',
                formatter: (_: unknown, data: PackageResponse) => {
                  if (data.profit_margin === null || data.profit_margin === undefined) return '-'
                  return `¥${(data.profit_margin / 100).toFixed(2)}`
                }
              }
            ]
          : [
              {
                label: '价格配置状态',
                formatter: (_: unknown, data: PackageResponse) => {
                  return data.price_config_status_name || '-'
                }
              },
              {
                label: '生效零售价',
                formatter: (_: unknown, data: PackageResponse) => {
                  if (
                    data.effective_retail_price === null ||
                    data.effective_retail_price === undefined
                  )
                    return '-'
                  return `¥${(data.effective_retail_price / 100).toFixed(2)}`
                }
              },
              {
                label: '是否赠送',
                formatter: (_: unknown, data: PackageResponse) => {
                  return data.is_gift ? '是' : '否'
                }
              }
            ]),
        {
          label: '套餐时长',
          formatter: (_: unknown, data: PackageResponse) => {
            return `${data.duration_months} 个月`
          }
        },
        {
          label: '套餐周期类型',
          formatter: (_: unknown, data: PackageResponse) => {
            if (!data.calendar_type) return '-'
            const typeMap: Record<string, string> = {
              natural_month: '自然月',
              by_day: '按天'
            }
            return typeMap[data.calendar_type] || data.calendar_type
          }
        },
        {
          label: '套餐天数',
          formatter: (_: unknown, data: PackageResponse) => {
            if (data.calendar_type !== 'by_day' || !data.duration_days) return '-'
            return `${data.duration_days} 天`
          }
        },
        {
          label: '流量重置周期',
          formatter: (_: unknown, data: PackageResponse) => {
            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: (_: unknown, data: PackageResponse) => {
            if (!data.expiry_base) return '--'
            return data.expiry_base === 'from_activation' ? '实名激活时起算' : '购买时起算'
          }
        },
        {
          label: '状态',
          formatter: (_: unknown, data: PackageResponse) => {
            return getStatusLabel(data.status ?? 0)
          }
        },
        {
          label: '上架状态',
          formatter: (_: unknown, data: PackageResponse) => {
            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: (_: unknown, data: PackageResponse) => {
            const realDataMb = data.real_data_mb || 0
            if (realDataMb >= 1024) {
              return `${(realDataMb / 1024).toFixed(2)} GB`
            }
            return `${realDataMb} MB`
          }
        },
        ...(shouldHideVirtualTrafficFields.value
          ? []
          : [
              {
                label: '启用虚流量',
                formatter: (_: unknown, data: PackageResponse) => {
                  return data.enable_virtual_data ? '是' : '否'
                }
              },
              {
                label: '虚流量额度',
                formatter: (_: unknown, data: PackageResponse) => {
                  if (!data.enable_virtual_data) return '-'
                  const virtualDataMb = data.virtual_data_mb || 0
                  if (virtualDataMb >= 1024) {
                    return `${(virtualDataMb / 1024).toFixed(2)} GB`
                  }
                  return `${virtualDataMb} MB`
                }
              }
            ])
      ]
    },
    {
      title: '佣金配置',
      fields: [
        {
          label: '一次性佣金金额',
          formatter: (_: unknown, data: PackageResponse) => {
            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: (_: unknown, data: PackageResponse) => {
            if (!data.tier_info || !data.tier_info.current_rate) return '-'
            return data.tier_info.current_rate
          }
        },
        {
          label: '下一档位比例',
          formatter: (_: unknown, data: PackageResponse) => {
            if (!data.tier_info || !data.tier_info.next_rate) return '-'
            return String(data.tier_info.next_rate)
          }
        },
        {
          label: '下一档位阈值',
          formatter: (_: unknown, data: PackageResponse) => {
            if (
              !data.tier_info ||
              data.tier_info.next_threshold === null ||
              data.tier_info.next_threshold === undefined
            )
              return '-'
            return String(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>
