<template>
  <ElDrawer
    v-model="visible"
    :title="dialogTitle"
    size="min(920px, 92vw)"
    :close-on-click-modal="false"
    destroy-on-close
    @closed="handleClosed"
  >
    <ElForm
      ref="formRef"
      :model="formModel"
      :rules="rules"
      label-width="120px"
      class="art-form-grid"
      v-loading="loading"
    >
      <ElRow :gutter="12">
        <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>
      </ElRow>

      <ElFormItem :label="t('tenantPackage.form.featurePoliciesJson')" prop="featurePoliciesJson">
        <div class="w-full">
          <ElInput
            v-model="formModel.featurePoliciesJson"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 8 }"
            :placeholder="t('tenantPackage.form.featurePlaceholder')"
          />

          <div class="mt-3">
            <ElDivider content-position="left">
              {{ t('quotaPackage.benefit.featureStrategy.title') }}
            </ElDivider>

            <ElAlert
              v-if="hasFeaturePolicy && !featureStrategyIsValidJson"
              class="mb-2"
              :title="t('quotaPackage.benefit.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('quotaPackage.benefit.featureStrategy.columns.name')"
                min-width="220"
              />
              <ElTableColumn
                prop="valueText"
                :label="t('quotaPackage.benefit.featureStrategy.columns.value')"
                min-width="160"
              />
              <ElTableColumn
                prop="isEnabled"
                :label="t('quotaPackage.benefit.featureStrategy.columns.status')"
                width="110"
              >
                <template #default="{ row }">
                  <ElTag :type="row.isEnabled ? 'success' : 'info'">
                    {{
                      row.isEnabled
                        ? t('quotaPackage.benefit.featureStrategy.status.enabled')
                        : t('quotaPackage.benefit.featureStrategy.status.disabled')
                    }}
                  </ElTag>
                </template>
              </ElTableColumn>
              <ElTableColumn
                prop="conditionsText"
                :label="t('quotaPackage.benefit.featureStrategy.columns.conditions')"
                min-width="240"
              />
            </ElTable>

            <div v-else class="text-xs text-gray-500">
              {{
                hasFeaturePolicy
                  ? t('quotaPackage.benefit.featureStrategy.empty')
                  : t('quotaPackage.benefit.featureStrategy.notConfigured')
              }}
            </div>
          </div>
        </div>
      </ElFormItem>
    </ElForm>

    <div class="drawer-footer">
      <ElButton @click="handleCancel">{{ t('common.cancel') }}</ElButton>
      <ElButton type="primary" :loading="submitting" @click="handleSubmit">
        {{ t('tenantPackage.form.submit') }}
      </ElButton>
    </div>
  </ElDrawer>
</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 { ElMessage } from 'element-plus'
  import { fetchTenantPackageDetail, fetchUpdateTenantPackage } 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
    (e: 'success'): void
  }

  type QuotaFormModel = Pick<
    Api.Tenant.CreateTenantPackageCommand,
    | 'maxStoreCount'
    | 'maxAccountCount'
    | 'maxStorageGb'
    | 'maxSmsCredits'
    | 'maxDeliveryOrders'
    | 'featurePoliciesJson'
  >

  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 dialogTitle = computed(() =>
    t('tenantPackage.dialog.quotaTitle', { name: props.packageName || '--' })
  )

  const loading = ref(false)
  const submitting = ref(false)
  const formRef = ref<FormInstance>()
  const packageDetail = ref<Api.Tenant.TenantPackageDto>()

  // 2. 表单模型（只编辑配额相关字段）
  const formModel = reactive<QuotaFormModel>({
    maxStoreCount: undefined,
    maxAccountCount: undefined,
    maxStorageGb: undefined,
    maxSmsCredits: undefined,
    maxDeliveryOrders: undefined,
    featurePoliciesJson: ''
  })

  // 3. 校验规则
  const rules: FormRules<QuotaFormModel> = {
    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'
      }
    ]
  }

  const hasFeaturePolicy = computed(() => !!formModel.featurePoliciesJson?.trim())

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

  const resetForm = () => {
    formModel.maxStoreCount = undefined
    formModel.maxAccountCount = undefined
    formModel.maxStorageGb = undefined
    formModel.maxSmsCredits = undefined
    formModel.maxDeliveryOrders = undefined
    formModel.featurePoliciesJson = ''
    packageDetail.value = undefined
  }

  const fillForm = (detail: Api.Tenant.TenantPackageDto) => {
    formModel.maxStoreCount = detail.maxStoreCount
    formModel.maxAccountCount = detail.maxAccountCount
    formModel.maxStorageGb = detail.maxStorageGb
    formModel.maxSmsCredits = detail.maxSmsCredits
    formModel.maxDeliveryOrders = detail.maxDeliveryOrders
    formModel.featurePoliciesJson = detail.featurePoliciesJson || ''
  }

  const loadDetail = async () => {
    if (!props.packageId) return
    loading.value = true
    try {
      // 1. 获取套餐详情
      const detail = await fetchTenantPackageDetail(props.packageId)
      packageDetail.value = detail

      // 2. 回填配额
      fillForm(detail)
    } finally {
      loading.value = false
    }
  }

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

  // 5. 事件处理
  const handleSubmit = async () => {
    if (!props.packageId) return
    if (!packageDetail.value) return

    // 1. 表单校验
    if (!formRef.value) return
    const valid = await formRef.value.validate().catch(() => false)
    if (!valid) return

    submitting.value = true
    try {
      const detail = packageDetail.value

      // 2. 组装全量更新 payload（避免 PUT 覆盖字段）
      const payload: Api.Tenant.UpdateTenantPackageCommand = {
        tenantPackageId: detail.id,
        name: detail.name,
        description: detail.description,
        packageType: detail.packageType,
        monthlyPrice: detail.monthlyPrice,
        yearlyPrice: detail.yearlyPrice,
        maxStoreCount: formModel.maxStoreCount,
        maxAccountCount: formModel.maxAccountCount,
        maxStorageGb: formModel.maxStorageGb,
        maxSmsCredits: formModel.maxSmsCredits,
        maxDeliveryOrders: formModel.maxDeliveryOrders,
        featurePoliciesJson: formModel.featurePoliciesJson || undefined,
        isActive: detail.isActive,
        isPublicVisible: detail.isPublicVisible,
        isAllowNewTenantPurchase: detail.isAllowNewTenantPurchase,
        publishStatus: detail.publishStatus,
        isRecommended: detail.isRecommended,
        tags: detail.tags || [],
        sortOrder: detail.sortOrder
      }

      // 3. 执行更新
      await fetchUpdateTenantPackage(props.packageId, payload)
      ElMessage.success(t('tenantPackage.message.updateSuccess'))

      // 4. 通知刷新
      emit('success')
      handleCancel()
    } finally {
      submitting.value = false
    }
  }

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

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

<style scoped>
  .drawer-footer {
    position: sticky;
    bottom: 0;
    z-index: 1;
    display: flex;
    gap: 12px;
    justify-content: flex-end;
    padding: 12px 0 0;
    margin-top: 12px;
    background: var(--el-bg-color);
    border-top: 1px solid var(--el-border-color-lighter);
  }
</style>
