<template>
  <div class="package-series-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, h } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ElCard, ElButton, ElIcon, ElMessage, ElTag } 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 { PackageSeriesService } from '@/api/modules'
  import type { PackageSeriesResponse } from '@/types/api'
  import { formatDateTime } from '@/utils/business/format'
  import { getEnableStatusText } from '@/config/constants'

  defineOptions({ name: 'PackageSeriesDetail' })

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

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

  // 详情页配置
  const detailSections: DetailSection[] = [
    {
      title: '基本信息',
      fields: [
        { label: '系列编码', prop: 'series_code' },
        { label: '系列名称', prop: 'series_name' },
        {
          label: '状态',
          formatter: (_, data) => {
            return data.status === 1 ? '启用' : '禁用'
          }
        },
        {
          label: '描述',
          prop: 'description'
        },
        { label: '创建时间', prop: 'created_at', formatter: (value) => formatDateTime(value) },
        { label: '更新时间', prop: 'updated_at', formatter: (value) => formatDateTime(value) }
      ]
    },
    {
      title: '一次性佣金配置',
      fields: [
        {
          label: '启用状态',
          formatter: (_, data) => {
            return getEnableStatusText(data.one_time_commission_config?.enable || false)
          }
        },
        {
          label: '佣金类型',
          formatter: (_, data) => {
            const config = data.one_time_commission_config
            if (!config?.commission_type) return '-'
            return config.commission_type === 'fixed' ? '固定佣金' : '梯度佣金'
          }
        },
        {
          label: '固定佣金金额',
          formatter: (_, data) => {
            const config = data.one_time_commission_config
            if (config?.commission_type !== 'fixed' || !config.commission_amount) return '-'
            return `¥${(config.commission_amount / 100).toFixed(2)}`
          }
        },
        {
          label: '触发阈值',
          formatter: (_, data) => {
            const config = data.one_time_commission_config
            if (!config?.threshold) return '-'
            return `¥${(config.threshold / 100).toFixed(2)}`
          }
        },
        {
          label: '触发类型',
          formatter: (_, data) => {
            const config = data.one_time_commission_config
            if (!config?.trigger_type) return '-'
            return config.trigger_type === 'first_recharge' ? '首次充值' : '累计充值'
          }
        },
        {
          label: '梯度配置',
          render: (data) => {
            const config = data.one_time_commission_config
            if (
              config?.commission_type !== 'tiered' ||
              !config.tiers ||
              config.tiers.length === 0
            ) {
              return h('span', '-')
            }

            return h(
              'div',
              { style: 'display: flex; flex-direction: column; gap: 8px;' },
              config.tiers.map((tier: any, index: number) => {
                const dimensionText = tier.dimension === 'sales_count' ? '销量' : '销售额'
                const thresholdText =
                  tier.dimension === 'sales_amount'
                    ? `¥${(tier.threshold / 100).toFixed(2)}`
                    : tier.threshold
                const amountText = `¥${(tier.amount / 100).toFixed(2)}`
                const scopeText = tier.stat_scope === 'self' ? '仅自己' : '自己+下级'
                const operatorText = tier.operator || '>='

                return h(
                  ElTag,
                  { type: 'info', size: 'default' },
                  () =>
                    `档位${index + 1}: ${dimensionText} ${operatorText} ${thresholdText}, 佣金 ${amountText}, ${scopeText}`
                )
              })
            )
          }
        }
      ]
    },
    {
      title: '强充配置',
      fields: [
        {
          label: '启用状态',
          formatter: (_, data) => {
            return getEnableStatusText(
              data.one_time_commission_config?.enable_force_recharge || false
            )
          }
        },
        {
          label: '强充金额',
          formatter: (_, data) => {
            const config = data.one_time_commission_config
            if (!config?.force_amount) return '-'
            return `¥${(config.force_amount / 100).toFixed(2)}`
          }
        },
        {
          label: '强充计算类型',
          formatter: (_, data) => {
            const config = data.one_time_commission_config
            if (!config?.force_calc_type) return '-'
            return config.force_calc_type === 'fixed' ? '固定' : '动态'
          }
        }
      ]
    },
    {
      title: '时效配置',
      fields: [
        {
          label: '时效类型',
          formatter: (_, data) => {
            const config = data.one_time_commission_config
            if (!config?.validity_type) return '-'
            const typeMap: Record<string, string> = {
              permanent: '永久',
              fixed_date: '固定日期',
              relative: '相对时长'
            }
            return typeMap[config.validity_type] || '-'
          }
        },
        {
          label: '时效值',
          formatter: (_, data) => {
            const config = data.one_time_commission_config
            if (!config?.validity_value) return '-'
            if (config.validity_type === 'relative') {
              return `${config.validity_value}个月`
            } else if (config.validity_type === 'fixed_date') {
              return config.validity_value
            }
            return '-'
          }
        }
      ]
    }
  ]

  // 返回上一页
  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 PackageSeriesService.getPackageSeriesDetail(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-series-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>
