<template>
  <ElDrawer
    v-model="visible"
    :title="drawerTitle"
    size="min(920px, 92vw)"
    :close-on-click-modal="false"
    destroy-on-close
    @closed="handleClosed"
  >
    <div class="detail-body" v-loading="loading">
      <ElDescriptions :column="2" border>
        <ElDescriptionsItem :label="t('common.id')">
          {{ detail?.id || '--' }}
        </ElDescriptionsItem>
        <ElDescriptionsItem :label="t('tenantPackage.form.name')">
          {{ detail?.name || '--' }}
        </ElDescriptionsItem>

        <ElDescriptionsItem :label="t('tenantPackage.form.packageType')">
          <ElTag :type="getPackageTypeTag(detail?.packageType)">
            {{ getPackageTypeLabel(detail?.packageType) }}
          </ElTag>
        </ElDescriptionsItem>
        <ElDescriptionsItem :label="t('tenantPackage.form.publishStatus')">
          <ElTag :type="detail?.publishStatus === 1 ? 'success' : 'info'">
            {{
              detail?.publishStatus === 1
                ? t('tenantPackage.publishStatus.published')
                : t('tenantPackage.publishStatus.draft')
            }}
          </ElTag>
        </ElDescriptionsItem>

        <ElDescriptionsItem :label="t('tenantPackage.form.monthlyPrice')">
          {{ renderPrice(detail?.monthlyPrice) }}
        </ElDescriptionsItem>
        <ElDescriptionsItem :label="t('tenantPackage.form.yearlyPrice')">
          {{ renderPrice(detail?.yearlyPrice) }}
        </ElDescriptionsItem>

        <ElDescriptionsItem :label="t('tenantPackage.form.sortOrder')">
          {{ detail?.sortOrder ?? '--' }}
        </ElDescriptionsItem>
        <ElDescriptionsItem :label="t('tenantPackage.form.isRecommended')">
          <ElTag :type="detail?.isRecommended ? 'success' : 'info'">
            {{ detail?.isRecommended ? t('common.yes') : t('common.no') }}
          </ElTag>
        </ElDescriptionsItem>

        <ElDescriptionsItem :label="t('tenantPackage.form.isActive')">
          <ElTag :type="detail?.isActive ? 'success' : 'danger'">
            {{
              detail?.isActive
                ? t('tenantPackage.status.enabled')
                : t('tenantPackage.status.disabled')
            }}
          </ElTag>
        </ElDescriptionsItem>
        <ElDescriptionsItem :label="t('tenantPackage.form.publicVisible')">
          <ElTag :type="detail?.isPublicVisible ? 'success' : 'info'">
            {{ detail?.isPublicVisible ? t('common.yes') : t('common.no') }}
          </ElTag>
        </ElDescriptionsItem>

        <ElDescriptionsItem :label="t('tenantPackage.form.allowNewPurchase')">
          <ElTag :type="detail?.isAllowNewTenantPurchase ? 'success' : 'info'">
            {{ detail?.isAllowNewTenantPurchase ? t('common.yes') : t('common.no') }}
          </ElTag>
        </ElDescriptionsItem>
        <ElDescriptionsItem :label="t('tenantPackage.form.tags')">
          <ElSpace v-if="detail?.tags?.length" wrap>
            <ElTag v-for="tag in detail.tags" :key="tag" :type="getPackageTagType(tag)">
              {{ getPackageTagLabel(tag) }}
            </ElTag>
          </ElSpace>
          <span v-else>--</span>
        </ElDescriptionsItem>

        <ElDescriptionsItem :label="t('tenantPackage.form.maxStoreCount')">
          {{ renderQuota(detail?.maxStoreCount) }}
        </ElDescriptionsItem>
        <ElDescriptionsItem :label="t('tenantPackage.form.maxAccountCount')">
          {{ renderQuota(detail?.maxAccountCount) }}
        </ElDescriptionsItem>
        <ElDescriptionsItem :label="t('tenantPackage.form.maxStorageGb')">
          {{ renderQuota(detail?.maxStorageGb) }}
        </ElDescriptionsItem>
        <ElDescriptionsItem :label="t('tenantPackage.form.maxSmsCredits')">
          {{ renderQuota(detail?.maxSmsCredits) }}
        </ElDescriptionsItem>
        <ElDescriptionsItem :label="t('tenantPackage.form.maxDeliveryOrders')">
          {{ renderQuota(detail?.maxDeliveryOrders) }}
        </ElDescriptionsItem>

        <ElDescriptionsItem :label="t('tenantPackage.form.description')" :span="2">
          {{ detail?.description || '--' }}
        </ElDescriptionsItem>
      </ElDescriptions>

      <div class="feature-body">
        <ElDivider content-position="left">
          {{ t('tenantPackage.form.featurePoliciesJson') }}
        </ElDivider>

        <ElInput
          :model-value="detail?.featurePoliciesJson || ''"
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 12 }"
          readonly
        />

        <ElDivider content-position="left">
          {{ t('tenantPackage.detail.featureStrategy.title') }}
        </ElDivider>

        <ElAlert
          v-if="hasFeaturePolicy && !featureStrategyIsValidJson"
          :title="t('tenantPackage.detail.featureStrategy.invalidJson')"
          type="warning"
          show-icon
          :closable="false"
        />

        <ElTable
          v-if="featureStrategyRows.length"
          :data="featureStrategyRows"
          border
          size="small"
          class="w-full"
        >
          <ElTableColumn
            prop="name"
            :label="t('tenantPackage.detail.featureStrategy.columns.name')"
            min-width="220"
          />
          <ElTableColumn
            prop="valueText"
            :label="t('tenantPackage.detail.featureStrategy.columns.value')"
            min-width="160"
          />
          <ElTableColumn
            prop="isEnabled"
            :label="t('tenantPackage.detail.featureStrategy.columns.status')"
            width="110"
          >
            <template #default="{ row }">
              <ElTag :type="row.isEnabled ? 'success' : 'info'">
                {{
                  row.isEnabled
                    ? t('tenantPackage.detail.featureStrategy.status.enabled')
                    : t('tenantPackage.detail.featureStrategy.status.disabled')
                }}
              </ElTag>
            </template>
          </ElTableColumn>
          <ElTableColumn
            prop="conditionsText"
            :label="t('tenantPackage.detail.featureStrategy.columns.conditions')"
            min-width="240"
          />
        </ElTable>

        <div v-else class="text-xs text-gray-500">
          {{
            hasFeaturePolicy
              ? t('tenantPackage.detail.featureStrategy.empty')
              : t('tenantPackage.featurePolicy.notConfigured')
          }}
        </div>
      </div>
    </div>
  </ElDrawer>
</template>

<script setup lang="ts">
  import { computed, nextTick, ref, watch } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { TenantPackageTypeEnum } from '@/enums/TenantPackageType'
  import { fetchTenantPackageDetail } from '@/api/tenant-package'
  import { useFeatureStrategyTable } from '../composables/useFeatureStrategyTable'

  interface Props {
    modelValue: boolean
    packageId?: string
    packageName?: string
  }

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

  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()
  const { t } = useI18n()

  // 1. 抽屉状态
  const visible = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
  })

  const drawerTitle = computed(() =>
    t('tenantPackage.drawer.detailTitle', { name: props.packageName || '--' })
  )

  // 2. 详情数据
  const loading = ref(false)
  const detail = ref<Api.Tenant.TenantPackageDto>()

  const hasFeaturePolicy = computed(() => !!detail.value?.featurePoliciesJson?.trim())
  const featurePolicyJsonRef = computed(() => detail.value?.featurePoliciesJson || '')
  const { rows: featureStrategyRows, isValidJson: featureStrategyIsValidJson } =
    useFeatureStrategyTable(t, 'tenantPackage.detail.featureStrategy', featurePolicyJsonRef)

  // 3. 展示辅助
  type ElTagType = 'primary' | 'success' | 'warning' | 'info' | 'danger'
  type PackageTypeOption = { value: number; label: string; tag: ElTagType }

  const packageTypeOptions = computed<PackageTypeOption[]>(() => [
    { value: TenantPackageTypeEnum.Free, label: t('tenantPackage.type.free'), tag: 'info' },
    {
      value: TenantPackageTypeEnum.Standard,
      label: t('tenantPackage.type.standard'),
      tag: 'warning'
    },
    {
      value: TenantPackageTypeEnum.Professional,
      label: t('tenantPackage.type.professional'),
      tag: 'primary'
    },
    {
      value: TenantPackageTypeEnum.Enterprise,
      label: t('tenantPackage.type.enterprise'),
      tag: 'success'
    }
  ])

  const getPackageTypeLabel = (value?: number) =>
    packageTypeOptions.value.find((item) => item.value === value)?.label ||
    t('tenantPackage.type.standard')

  const getPackageTypeTag = (value?: number): ElTagType =>
    packageTypeOptions.value.find((item) => item.value === value)?.tag || 'info'

  const renderPrice = (value?: number) => {
    if (value === null || value === undefined) return '--'
    return `${'\u00A5'}${Number(value).toFixed(2)}`
  }

  const renderQuota = (value?: number) => {
    if (value === null || value === undefined) return t('tenantPackage.table.quotaEmpty')
    return String(value)
  }

  const getPackageTagLabel = (tag: string) => {
    switch (tag) {
      case 'recommended':
        return t('tenantPackage.tags.recommended')
      case 'bestValue':
        return t('tenantPackage.tags.bestValue')
      case 'flagship':
        return t('tenantPackage.tags.flagship')
      default:
        return tag
    }
  }

  const getPackageTagType = (tag: string): ElTagType => {
    switch (tag) {
      case 'recommended':
        return 'success'
      case 'bestValue':
        return 'warning'
      case 'flagship':
        return 'danger'
      default:
        return 'info'
    }
  }

  // 4. 生命周期：打开时加载详情
  const loadDetail = async () => {
    if (!props.packageId) return
    loading.value = true
    try {
      detail.value = await fetchTenantPackageDetail(props.packageId)
    } finally {
      loading.value = false
    }
  }

  watch(
    () => visible.value,
    async (val) => {
      if (!val) return
      detail.value = undefined
      await nextTick()
      await loadDetail()
    }
  )

  const handleClosed = () => {
    detail.value = undefined
  }
</script>

<style scoped>
  .detail-body {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .feature-body {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
</style>
