<template>
  <ElDialog
    v-model="visible"
    :title="dialogTitle"
    width="720px"
    :close-on-click-modal="false"
    destroy-on-close
    @closed="handleClosed"
  >
    <ElForm
      ref="formRef"
      :model="formModel"
      :rules="rules"
      label-width="120px"
      class="art-form-grid"
      :disabled="isView"
      v-loading="detailLoading"
    >
      <ElRow :gutter="12">
        <ElCol :span="12">
          <ElFormItem :label="t('tenantPackage.form.name')" prop="name">
            <ElInput
              v-model="formModel.name"
              :placeholder="t('tenantPackage.form.namePlaceholder')"
              clearable
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem :label="t('tenantPackage.form.packageType')" prop="packageType">
            <ElSelect
              v-model="formModel.packageType"
              :placeholder="t('tenantPackage.form.packageTypePlaceholder')"
              class="w-full"
            >
              <ElOption
                v-for="item in packageTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </ElSelect>
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem :label="t('tenantPackage.form.monthlyPrice')" prop="monthlyPrice">
            <ElInputNumber
              v-model="formModel.monthlyPrice"
              :placeholder="t('tenantPackage.form.pricePlaceholder')"
              :min="0"
              :precision="2"
              :controls="false"
              class="w-full"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem :label="t('tenantPackage.form.yearlyPrice')" prop="yearlyPrice">
            <ElInputNumber
              v-model="formModel.yearlyPrice"
              :placeholder="t('tenantPackage.form.pricePlaceholder')"
              :min="0"
              :precision="2"
              :controls="false"
              class="w-full"
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem :label="t('tenantPackage.form.maxStoreCount')" prop="maxStoreCount">
            <ElInputNumber
              v-model="formModel.maxStoreCount"
              :placeholder="t('tenantPackage.form.quotaPlaceholder')"
              :min="0"
              :controls="false"
              class="w-full"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem :label="t('tenantPackage.form.maxAccountCount')" prop="maxAccountCount">
            <ElInputNumber
              v-model="formModel.maxAccountCount"
              :placeholder="t('tenantPackage.form.quotaPlaceholder')"
              :min="0"
              :controls="false"
              class="w-full"
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem :label="t('tenantPackage.form.maxStorageGb')" prop="maxStorageGb">
            <ElInputNumber
              v-model="formModel.maxStorageGb"
              :placeholder="t('tenantPackage.form.quotaPlaceholder')"
              :min="0"
              :controls="false"
              class="w-full"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem :label="t('tenantPackage.form.maxSmsCredits')" prop="maxSmsCredits">
            <ElInputNumber
              v-model="formModel.maxSmsCredits"
              :placeholder="t('tenantPackage.form.quotaPlaceholder')"
              :min="0"
              :controls="false"
              class="w-full"
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem :label="t('tenantPackage.form.maxDeliveryOrders')" prop="maxDeliveryOrders">
            <ElInputNumber
              v-model="formModel.maxDeliveryOrders"
              :placeholder="t('tenantPackage.form.quotaPlaceholder')"
              :min="0"
              :controls="false"
              class="w-full"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem :label="t('tenantPackage.form.isActive')" prop="isActive">
            <ElSwitch
              v-model="formModel.isActive"
              :active-text="t('tenantPackage.status.enabled')"
              :inactive-text="t('tenantPackage.status.disabled')"
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem :label="t('tenantPackage.form.publicVisible')" prop="isPublicVisible">
            <ElSwitch v-model="formModel.isPublicVisible" />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem
            :label="t('tenantPackage.form.allowNewPurchase')"
            prop="isAllowNewTenantPurchase"
          >
            <ElSwitch v-model="formModel.isAllowNewTenantPurchase" />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem :label="t('tenantPackage.form.publishStatus')" prop="publishStatus">
            <ElTag :type="formModel.publishStatus === 1 ? 'success' : 'info'">
              {{
                formModel.publishStatus === 1
                  ? t('tenantPackage.publishStatus.published')
                  : t('tenantPackage.publishStatus.draft')
              }}
            </ElTag>
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem :label="t('tenantPackage.form.isRecommended')" prop="isRecommended">
            <ElSwitch v-model="formModel.isRecommended" />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem prop="sortOrder">
            <template #label>
              <span class="inline-flex items-center gap-1">
                <span>{{ t('tenantPackage.form.sortOrder') }}</span>
                <ElTooltip :content="t('tenantPackage.form.sortOrderPlaceholder')" placement="top">
                  <span class="cursor-help text-gray-400">
                    <ArtSvgIcon icon="ri:question-line" />
                  </span>
                </ElTooltip>
              </span>
            </template>
            <ElInputNumber
              v-model="formModel.sortOrder"
              :min="0"
              :controls="false"
              class="w-full"
              :placeholder="t('tenantPackage.form.sortOrderPlaceholder')"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElFormItem :label="t('tenantPackage.form.tags')" prop="tags">
        <ElSelect
          v-model="formModel.tags"
          multiple
          clearable
          filterable
          class="w-full"
          :placeholder="t('tenantPackage.form.tagsPlaceholder')"
        >
          <ElOption
            v-for="item in tagOptionsMerged"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </ElSelect>
      </ElFormItem>

      <ElFormItem :label="t('tenantPackage.form.description')" prop="description">
        <ElInput
          v-model="formModel.description"
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 5 }"
          :placeholder="t('tenantPackage.form.descriptionPlaceholder')"
          maxlength="500"
          show-word-limit
        />
      </ElFormItem>

      <ElFormItem :label="t('tenantPackage.form.featurePoliciesJson')" prop="featurePoliciesJson">
        <div class="w-full">
          <ElSpace wrap class="w-full">
            <ElButton type="primary" plain @click="openFeaturePolicyDialog">
              {{ t('tenantPackage.featurePolicy.open') }}
            </ElButton>
            <ElButton
              v-if="!isView && hasFeaturePolicy"
              type="danger"
              plain
              @click="handleClearFeaturePolicy"
            >
              {{ t('tenantPackage.featurePolicy.clear') }}
            </ElButton>
            <ElTag :type="hasFeaturePolicy ? 'success' : 'info'">
              {{
                hasFeaturePolicy
                  ? t('tenantPackage.featurePolicy.configured')
                  : t('tenantPackage.featurePolicy.notConfigured')
              }}
            </ElTag>
          </ElSpace>

          <div v-if="isView && hasFeaturePolicy" class="mt-3">
            <ElDivider content-position="left">
              {{ t('tenantPackage.detail.featureStrategy.title') }}
            </ElDivider>

            <ElAlert
              v-if="!featureStrategyIsValidJson"
              class="mb-2"
              :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">
              {{ t('tenantPackage.detail.featureStrategy.empty') }}
            </div>
          </div>
        </div>
      </ElFormItem>
    </ElForm>

    <template #footer>
      <ElButton @click="handleCancel">{{ t('common.cancel') }}</ElButton>
      <template v-if="!isView">
        <ElButton :loading="submitting" @click="handleSubmitDraft">
          {{ t('tenantPackage.form.submitDraft') }}
        </ElButton>
        <ElButton type="primary" :loading="submitting" @click="handleSubmitPublish">
          {{ t('tenantPackage.form.submitPublish') }}
        </ElButton>
      </template>
      <ElButton v-else type="primary" @click="handleCancel">
        {{ t('tenantPackage.actions.close') }}
      </ElButton>
    </template>
  </ElDialog>

  <PackageFeaturePolicyDialog
    v-model="featurePolicyDialogVisible"
    v-model:value="formModel.featurePoliciesJson"
    :readonly="isView"
  />
</template>

<script setup lang="ts">
  import { computed, reactive, ref, watch, nextTick } from 'vue'
  import { useI18n } from 'vue-i18n'
  import type { FormInstance, FormRules } from 'element-plus'
  import ArtSvgIcon from '@/components/core/base/art-svg-icon/index.vue'
  import {
    fetchCreateTenantPackage,
    fetchTenantPackageDetail,
    fetchUpdateTenantPackage
  } from '@/api/tenant-package'
  import { ElMessage, ElTag } from 'element-plus'
  import { TenantPackageTypeEnum } from '@/enums/TenantPackageType'
  import PackageFeaturePolicyDialog from './package-feature-policy-dialog.vue'
  import { useFeatureStrategyTable } from '../composables/useFeatureStrategyTable'

  interface Props {
    modelValue: boolean
    mode: 'create' | 'edit' | 'view' | 'copy'
    packageId?: string
  }

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

  type TenantPackageFormModel = Omit<
    Api.Tenant.CreateTenantPackageCommand,
    'packageType' | 'featurePoliciesJson'
  > & {
    packageType: TenantPackageTypeEnum
    featurePoliciesJson: string
  }

  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 detailLoading = ref(false)
  const submitting = ref(false)

  // 2. 表单模型
  const formRef = ref<FormInstance>()
  const formModel = reactive<TenantPackageFormModel>({
    name: '',
    description: '',
    packageType: TenantPackageTypeEnum.Standard,
    monthlyPrice: undefined,
    yearlyPrice: undefined,
    maxStoreCount: undefined,
    maxAccountCount: undefined,
    maxStorageGb: undefined,
    maxSmsCredits: undefined,
    maxDeliveryOrders: undefined,
    featurePoliciesJson: '',
    isActive: true,
    isPublicVisible: true,
    isAllowNewTenantPurchase: true,
    publishStatus: 0,
    isRecommended: false,
    tags: [],
    sortOrder: 0
  })

  // 3. 校验规则
  const rules: FormRules<TenantPackageFormModel> = {
    name: [
      { required: true, message: t('tenantPackage.form.validation.nameRequired'), trigger: 'blur' }
    ],
    packageType: [
      {
        required: true,
        message: t('tenantPackage.form.validation.packageTypeRequired'),
        trigger: 'change'
      }
    ],
    featurePoliciesJson: [
      {
        validator: (_rule, value, callback) => {
          // 1. 空值允许
          if (!value?.trim()) return callback()

          // 2. 非空必须是合法 JSON
          try {
            JSON.parse(value)
            return callback()
          } catch {
            return callback(new Error(t('tenantPackage.featurePolicy.invalidJson')))
          }
        },
        trigger: 'change'
      }
    ]
  }

  // 4. 枚举选项
  const packageTypeOptions = computed(() => [
    { value: TenantPackageTypeEnum.Free, label: t('tenantPackage.type.free') },
    { value: TenantPackageTypeEnum.Standard, label: t('tenantPackage.type.standard') },
    { value: TenantPackageTypeEnum.Professional, label: t('tenantPackage.type.professional') },
    { value: TenantPackageTypeEnum.Enterprise, label: t('tenantPackage.type.enterprise') }
  ])

  const tagOptions = computed(() => [
    // 1. 内置标签（与后端存储保持一致）
    { value: 'recommended', label: t('tenantPackage.tags.recommended') },
    { value: 'bestValue', label: t('tenantPackage.tags.bestValue') },
    { value: 'flagship', label: t('tenantPackage.tags.flagship') }
  ])

  const normalizeTagValue = (value: string) => {
    const normalized = value?.trim?.() || value
    const lower = normalized.toLowerCase()

    // 1. 兼容旧值/展示值（避免编辑页无法反选）
    const map: Record<string, string> = {
      recommended: 'recommended',
      bestvalue: 'bestValue',
      best_value: 'bestValue',
      'best-value': 'bestValue',
      flagship: 'flagship',
      推荐: 'recommended',
      性价比: 'bestValue',
      旗舰: 'flagship'
    }

    return map[normalized] || map[lower] || normalized
  }

  const normalizeTags = (values: string[]) => {
    const next = values.map((v) => normalizeTagValue(v)).filter(Boolean)
    return Array.from(new Set(next))
  }

  const tagOptionsMerged = computed(() => {
    const base = tagOptions.value
    const baseValueSet = new Set(base.map((item) => item.value))
    const extra = (formModel.tags || [])
      .map((v) => normalizeTagValue(v))
      .filter((v) => v && !baseValueSet.has(v))
      .map((v) => ({ value: v, label: v }))
    return [...base, ...extra]
  })

  const isView = computed(() => props.mode === 'view')
  const featurePolicyDialogVisible = ref(false)
  const hasFeaturePolicy = computed(() => !!formModel.featurePoliciesJson?.trim())

  // 5. 功能策略可视化（使用 composable）
  const featurePolicyJsonRef = computed(() => formModel.featurePoliciesJson || '')
  const { rows: featureStrategyRows, isValidJson: featureStrategyIsValidJson } =
    useFeatureStrategyTable(t, 'tenantPackage.detail.featureStrategy', featurePolicyJsonRef)

  const dialogTitle = computed(() => {
    if (props.mode === 'edit') return t('tenantPackage.form.editTitle')
    if (props.mode === 'view') return t('tenantPackage.form.viewTitle')
    if (props.mode === 'copy') return t('tenantPackage.form.copyTitle')
    return t('tenantPackage.form.createTitle')
  })

  // 6. 工具函数
  const toNumberOrUndefined = (value: unknown) => {
    if (value === null || value === undefined || value === '') return undefined
    const num = Number(value)
    return Number.isFinite(num) ? num : undefined
  }

  const resetForm = () => {
    formModel.name = ''
    formModel.description = ''
    formModel.packageType = TenantPackageTypeEnum.Standard
    formModel.monthlyPrice = undefined
    formModel.yearlyPrice = undefined
    formModel.maxStoreCount = undefined
    formModel.maxAccountCount = undefined
    formModel.maxStorageGb = undefined
    formModel.maxSmsCredits = undefined
    formModel.maxDeliveryOrders = undefined
    formModel.featurePoliciesJson = ''
    formModel.isActive = true
    formModel.isPublicVisible = true
    formModel.isAllowNewTenantPurchase = true
    formModel.publishStatus = 0
    formModel.isRecommended = false
    formModel.tags = []
    formModel.sortOrder = 0
  }

  const fillForm = (detail: Api.Tenant.TenantPackageDto) => {
    const packageTypeValue = detail.packageType ?? TenantPackageTypeEnum.Standard

    formModel.name = detail.name || ''
    formModel.description = detail.description || ''
    formModel.packageType = Number(packageTypeValue) as TenantPackageTypeEnum
    formModel.monthlyPrice = toNumberOrUndefined(detail.monthlyPrice)
    formModel.yearlyPrice = toNumberOrUndefined(detail.yearlyPrice)
    formModel.maxStoreCount = toNumberOrUndefined(detail.maxStoreCount)
    formModel.maxAccountCount = toNumberOrUndefined(detail.maxAccountCount)
    formModel.maxStorageGb = toNumberOrUndefined(detail.maxStorageGb)
    formModel.maxSmsCredits = toNumberOrUndefined(detail.maxSmsCredits)
    formModel.maxDeliveryOrders = toNumberOrUndefined(detail.maxDeliveryOrders)
    formModel.featurePoliciesJson = detail.featurePoliciesJson || ''
    formModel.isActive = !!detail.isActive
    formModel.isPublicVisible = !!detail.isPublicVisible
    formModel.isAllowNewTenantPurchase = !!detail.isAllowNewTenantPurchase
    formModel.publishStatus = Number(detail.publishStatus ?? 0) as 0 | 1
    formModel.isRecommended = !!detail.isRecommended
    formModel.tags = normalizeTags(Array.isArray(detail.tags) ? detail.tags : [])
    formModel.sortOrder = toNumberOrUndefined(detail.sortOrder) ?? 0
  }

  const openFeaturePolicyDialog = () => {
    featurePolicyDialogVisible.value = true
  }

  const handleClearFeaturePolicy = () => {
    formModel.featurePoliciesJson = ''
  }

  // 6. 监听弹窗打开加载详情
  const loadDetail = async () => {
    if (!props.packageId) return
    detailLoading.value = true
    try {
      // 1. 获取详情
      const detail = await fetchTenantPackageDetail(props.packageId)
      // 2. 回填表单
      fillForm(detail)
    } finally {
      detailLoading.value = false
    }
  }

  watch(
    () => visible.value,
    async (val) => {
      if (!val) return
      resetForm()
      await nextTick()
      if (props.mode === 'edit' || props.mode === 'view' || props.mode === 'copy') {
        await loadDetail()
      }

      if (props.mode === 'copy') {
        formModel.name = formModel.name ? `${formModel.name}-副本` : ''
        formModel.isActive = false
        formModel.isPublicVisible = false
        formModel.isAllowNewTenantPurchase = false
        formModel.publishStatus = 0
        formModel.isRecommended = false
        formModel.tags = []
      }
    }
  )

  // 7. 事件处理
  type TenantPackagePublishStatus = 0 | 1
  const TenantPackagePublishStatusEnum = {
    Draft: 0,
    Published: 1
  } as const

  const submitInternal = async (publishStatus: TenantPackagePublishStatus) => {
    if (!formRef.value) return
    if (submitting.value) return
    if (isView.value) {
      handleCancel()
      return
    }

    submitting.value = true
    try {
      const valid = await formRef.value.validate().catch(() => false)
      if (!valid) return

      const payload: Api.Tenant.CreateTenantPackageCommand = {
        ...formModel,
        publishStatus,
        packageType: Number(formModel.packageType) as unknown as Api.Tenant.TenantPackageType
      }

      if (props.mode === 'edit' && props.packageId) {
        await fetchUpdateTenantPackage(props.packageId, {
          ...payload,
          tenantPackageId: props.packageId
        })

        ElMessage.success(
          publishStatus === TenantPackagePublishStatusEnum.Draft
            ? t('tenantPackage.message.saveDraftSuccess')
            : t('tenantPackage.message.updateSuccess')
        )
      } else {
        await fetchCreateTenantPackage(payload)

        ElMessage.success(
          publishStatus === TenantPackagePublishStatusEnum.Draft
            ? t('tenantPackage.message.saveDraftSuccess')
            : t('tenantPackage.message.createSuccess')
        )
      }

      emit('success')
      handleCancel()
    } finally {
      submitting.value = false
    }
  }

  const handleSubmitDraft = async () => {
    formModel.publishStatus = TenantPackagePublishStatusEnum.Draft
    await submitInternal(TenantPackagePublishStatusEnum.Draft)
  }

  const handleSubmitPublish = async () => {
    formModel.publishStatus = TenantPackagePublishStatusEnum.Published
    await submitInternal(TenantPackagePublishStatusEnum.Published)
  }

  const handleCancel = () => {
    visible.value = false
  }

  const handleClosed = () => {
    resetForm()
    formRef.value?.clearValidate()
  }
</script>
