<template>
  <ElDialog
    v-model="visible"
    :title="t('tenant.manualCreate.title')"
    width="1100px"
    top="4vh"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <ElForm ref="formRef" :model="formModel" :rules="rules" label-width="140px" v-loading="loading">
      <ElScrollbar max-height="72vh" class="pr-2">
        <ElDivider content-position="left">{{ t('tenant.manualCreate.section.tenant') }}</ElDivider>
        <ElRow :gutter="16">
          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.code')" prop="code">
              <ElInput
                v-model="formModel.code"
                :placeholder="t('tenant.manualCreate.placeholder.code')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.name')" prop="name">
              <ElInput
                v-model="formModel.name"
                :placeholder="t('tenant.manualCreate.placeholder.name')"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.shortName')" prop="shortName">
              <ElInput
                v-model="formModel.shortName"
                :placeholder="t('tenant.manualCreate.placeholder.shortName')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem
              :label="t('tenant.manualCreate.field.legalEntityName')"
              prop="legalEntityName"
            >
              <ElInput
                v-model="formModel.legalEntityName"
                :placeholder="t('tenant.manualCreate.placeholder.legalEntityName')"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.industry')" prop="industry">
              <ElInput
                v-model="formModel.industry"
                :placeholder="t('tenant.manualCreate.placeholder.industry')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.status')" prop="tenantStatus">
              <ElSelect v-model="formModel.tenantStatus" class="w-full">
                <ElOption
                  :value="TenantStatus.PendingReview"
                  :label="t('tenant.status.pendingReview')"
                />
                <ElOption :value="TenantStatus.Active" :label="t('tenant.status.active')" />
                <ElOption :value="TenantStatus.Suspended" :label="t('tenant.status.suspended')" />
                <ElOption :value="TenantStatus.Expired" :label="t('tenant.status.expired')" />
                <ElOption :value="TenantStatus.Closed" :label="t('tenant.status.closed')" />
              </ElSelect>
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.contactName')" prop="contactName">
              <ElInput
                v-model="formModel.contactName"
                :placeholder="t('tenant.manualCreate.placeholder.contactName')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.contactPhone')" prop="contactPhone">
              <ElInput
                v-model="formModel.contactPhone"
                :placeholder="t('tenant.manualCreate.placeholder.contactPhone')"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.contactEmail')" prop="contactEmail">
              <ElInput
                v-model="formModel.contactEmail"
                :placeholder="t('tenant.manualCreate.placeholder.contactEmail')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.website')" prop="website">
              <ElInput
                v-model="formModel.website"
                :placeholder="t('tenant.manualCreate.placeholder.website')"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.logoUrl')" prop="logoUrl">
              <ImageUploadField v-model="formModel.logoUrl" upload-type="merchant_logo" />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.coverImageUrl')" prop="coverImageUrl">
              <ImageUploadField v-model="formModel.coverImageUrl" upload-type="other" />
            </ElFormItem>
          </ElCol>

          <ElCol :span="24">
            <ElFormItem :label="t('tenant.manualCreate.field.region')" prop="region">
              <ElCascader
                v-model="regionCodes"
                class="w-full"
                filterable
                clearable
                :options="regionOptions"
                :props="regionProps"
                :placeholder="t('tenant.manualCreate.placeholder.region')"
                @change="handleRegionChange"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.country')" prop="country">
              <ElInput
                v-model="formModel.country"
                :placeholder="t('tenant.manualCreate.placeholder.country')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.province')" prop="province">
              <ElInput v-model="formModel.province" disabled />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.city')" prop="city">
              <ElInput v-model="formModel.city" disabled />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.district')" prop="district">
              <ElInput v-model="districtText" disabled />
            </ElFormItem>
          </ElCol>
          <ElCol :span="24">
            <ElFormItem :label="t('tenant.manualCreate.field.address')" prop="address">
              <ElInput
                v-model="formModel.address"
                :placeholder="t('tenant.manualCreate.placeholder.address')"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.tags')" prop="tags">
              <ElInput
                v-model="formModel.tags"
                :placeholder="t('tenant.manualCreate.placeholder.tags')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.remarks')" prop="remarks">
              <ElInput
                v-model="formModel.remarks"
                :placeholder="t('tenant.manualCreate.placeholder.remarks')"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.suspendedAt')" prop="suspendedAt">
              <ElDatePicker v-model="formModel.suspendedAt" type="datetime" class="w-full" />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem
              :label="t('tenant.manualCreate.field.suspensionReason')"
              prop="suspensionReason"
            >
              <ElInput
                v-model="formModel.suspensionReason"
                :placeholder="t('tenant.manualCreate.placeholder.suspensionReason')"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>

        <ElDivider content-position="left">{{
          t('tenant.manualCreate.section.subscription')
        }}</ElDivider>
        <ElRow :gutter="16">
          <ElCol :span="12">
            <ElFormItem
              :label="t('tenant.manualCreate.field.tenantPackageId')"
              prop="tenantPackageId"
            >
              <ElSelect v-model="formModel.tenantPackageId" class="w-full" filterable>
                <ElOption v-for="pkg in packages" :key="pkg.id" :label="pkg.name" :value="pkg.id" />
              </ElSelect>
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem
              :label="t('tenant.manualCreate.field.durationMonths')"
              prop="durationMonths"
            >
              <div class="flex w-full items-center gap-2">
                <ElInputNumber
                  v-model="formModel.durationMonths"
                  :min="1"
                  :max="1200"
                  class="w-full"
                />
                <span class="text-xs text-[var(--el-text-color-secondary)]">
                  {{ t('tenant.manualCreate.unit.month') }}
                </span>
              </div>
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem
              :label="t('tenant.manualCreate.field.subscriptionEffectiveFrom')"
              prop="subscriptionEffectiveFrom"
            >
              <ElDatePicker
                v-model="formModel.subscriptionEffectiveFrom"
                type="datetime"
                class="w-full"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.subscriptionEffectiveToPreview')">
              <ElInput :model-value="subscriptionEffectiveToPreview" disabled />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem
              :label="t('tenant.manualCreate.field.nextBillingDate')"
              prop="nextBillingDate"
            >
              <ElDatePicker v-model="formModel.nextBillingDate" type="datetime" class="w-full" />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.autoRenew')" prop="autoRenew">
              <ElSwitch v-model="formModel.autoRenew" />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem
              :label="t('tenant.manualCreate.field.subscriptionStatus')"
              prop="subscriptionStatus"
            >
              <ElSelect v-model="formModel.subscriptionStatus" class="w-full">
                <ElOption :value="0" :label="t('tenant.manualCreate.subscriptionStatus.pending')" />
                <ElOption :value="1" :label="t('tenant.manualCreate.subscriptionStatus.active')" />
                <ElOption
                  :value="2"
                  :label="t('tenant.manualCreate.subscriptionStatus.gracePeriod')"
                />
                <ElOption
                  :value="3"
                  :label="t('tenant.manualCreate.subscriptionStatus.cancelled')"
                />
                <ElOption
                  :value="4"
                  :label="t('tenant.manualCreate.subscriptionStatus.suspended')"
                />
              </ElSelect>
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem
              :label="t('tenant.manualCreate.field.scheduledPackageId')"
              prop="scheduledPackageId"
            >
              <ElInput
                v-model="formModel.scheduledPackageId"
                :placeholder="t('tenant.manualCreate.placeholder.scheduledPackageId')"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="24">
            <ElFormItem
              :label="t('tenant.manualCreate.field.subscriptionNotes')"
              prop="subscriptionNotes"
            >
              <ElInput
                v-model="formModel.subscriptionNotes"
                type="textarea"
                :rows="2"
                :placeholder="t('tenant.manualCreate.placeholder.subscriptionNotes')"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>

        <ElDivider content-position="left">{{
          t('tenant.manualCreate.section.verification')
        }}</ElDivider>
        <ElRow :gutter="16">
          <ElCol :span="12">
            <ElFormItem
              :label="t('tenant.manualCreate.field.verificationStatus')"
              prop="verificationStatus"
            >
              <ElSelect v-model="formModel.verificationStatus" class="w-full">
                <ElOption
                  :value="TenantVerificationStatus.Draft"
                  :label="t('tenant.verificationStatus.draft')"
                />
                <ElOption
                  :value="TenantVerificationStatus.Pending"
                  :label="t('tenant.verificationStatus.pending')"
                />
                <ElOption
                  :value="TenantVerificationStatus.Approved"
                  :label="t('tenant.verificationStatus.approved')"
                />
                <ElOption
                  :value="TenantVerificationStatus.Rejected"
                  :label="t('tenant.verificationStatus.rejected')"
                />
              </ElSelect>
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem
              :label="t('tenant.manualCreate.field.businessLicenseNumber')"
              prop="businessLicenseNumber"
            >
              <ElInput
                v-model="formModel.businessLicenseNumber"
                :placeholder="t('tenant.manualCreate.placeholder.businessLicenseNumber')"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem
              :label="t('tenant.manualCreate.field.businessLicenseUrl')"
              prop="businessLicenseUrl"
            >
              <ImageUploadField
                v-model="formModel.businessLicenseUrl"
                upload-type="business_license"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem
              :label="t('tenant.manualCreate.field.legalPersonName')"
              prop="legalPersonName"
            >
              <ElInput
                v-model="formModel.legalPersonName"
                :placeholder="t('tenant.manualCreate.placeholder.legalPersonName')"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem
              :label="t('tenant.manualCreate.field.legalPersonIdNumber')"
              prop="legalPersonIdNumber"
            >
              <ElInput
                v-model="formModel.legalPersonIdNumber"
                :placeholder="t('tenant.manualCreate.placeholder.legalPersonIdNumber')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem
              :label="t('tenant.manualCreate.field.bankAccountName')"
              prop="bankAccountName"
            >
              <ElInput
                v-model="formModel.bankAccountName"
                :placeholder="t('tenant.manualCreate.placeholder.bankAccountName')"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem
              :label="t('tenant.manualCreate.field.bankAccountNumber')"
              prop="bankAccountNumber"
            >
              <ElInput
                v-model="formModel.bankAccountNumber"
                :placeholder="t('tenant.manualCreate.placeholder.bankAccountNumber')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.bankName')" prop="bankName">
              <ElInput
                v-model="formModel.bankName"
                :placeholder="t('tenant.manualCreate.placeholder.bankName')"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem
              :label="t('tenant.manualCreate.field.legalPersonIdFrontUrl')"
              prop="legalPersonIdFrontUrl"
            >
              <ImageUploadField
                v-model="formModel.legalPersonIdFrontUrl"
                upload-type="business_license"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem
              :label="t('tenant.manualCreate.field.legalPersonIdBackUrl')"
              prop="legalPersonIdBackUrl"
            >
              <ImageUploadField
                v-model="formModel.legalPersonIdBackUrl"
                upload-type="business_license"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.reviewedBy')">
              <ElInput
                :placeholder="t('tenant.manualCreate.placeholder.systemAutoFill')"
                disabled
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem
              :label="t('tenant.manualCreate.field.reviewedByName')"
              prop="reviewedByName"
            >
              <ElInput
                v-model="formModel.reviewedByName"
                :placeholder="t('tenant.manualCreate.placeholder.reviewedByName')"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="24">
            <ElFormItem
              :label="t('tenant.manualCreate.field.additionalDataJson')"
              prop="additionalDataJson"
            >
              <ElInput
                v-model="formModel.additionalDataJson"
                type="textarea"
                :rows="2"
                :placeholder="t('tenant.manualCreate.placeholder.additionalDataJson')"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="24">
            <ElFormItem :label="t('tenant.manualCreate.field.reviewRemarks')" prop="reviewRemarks">
              <ElInput
                v-model="formModel.reviewRemarks"
                type="textarea"
                :rows="2"
                :placeholder="t('tenant.manualCreate.placeholder.reviewRemarks')"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>

        <ElDivider content-position="left">{{ t('tenant.manualCreate.section.admin') }}</ElDivider>
        <ElRow :gutter="16">
          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.adminAccount')" prop="adminAccount">
              <ElInput
                v-model="formModel.adminAccount"
                :placeholder="t('tenant.manualCreate.placeholder.adminAccount')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem
              :label="t('tenant.manualCreate.field.adminDisplayName')"
              prop="adminDisplayName"
            >
              <ElInput
                v-model="formModel.adminDisplayName"
                :placeholder="t('tenant.manualCreate.placeholder.adminDisplayName')"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.adminPassword')" prop="adminPassword">
              <ElInput
                v-model="formModel.adminPassword"
                type="password"
                show-password
                :placeholder="t('tenant.manualCreate.placeholder.adminPassword')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.adminAvatar')" prop="adminAvatar">
              <ImageUploadField v-model="formModel.adminAvatar" upload-type="user_avatar" />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem
              :label="t('tenant.manualCreate.field.adminMerchantId')"
              prop="adminMerchantId"
            >
              <ElInput
                v-model="formModel.adminMerchantId"
                :placeholder="t('tenant.manualCreate.placeholder.adminMerchantId')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.primaryOwnerUserId')">
              <ElInput
                :placeholder="t('tenant.manualCreate.placeholder.systemGenerated')"
                disabled
              />
            </ElFormItem>
          </ElCol>
        </ElRow>

        <ElDivider content-position="left">{{ t('tenant.manualCreate.section.system') }}</ElDivider>
        <ElRow :gutter="16">
          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.tenantId')">
              <ElInput
                :placeholder="t('tenant.manualCreate.placeholder.systemGenerated')"
                disabled
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.tenantCreatedAt')">
              <ElInput
                :placeholder="t('tenant.manualCreate.placeholder.systemGenerated')"
                disabled
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.tenantUpdatedAt')">
              <ElInput
                :placeholder="t('tenant.manualCreate.placeholder.systemGenerated')"
                disabled
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.tenantDeletedAt')">
              <ElInput
                :placeholder="t('tenant.manualCreate.placeholder.systemGenerated')"
                disabled
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.subscriptionId')">
              <ElInput
                :placeholder="t('tenant.manualCreate.placeholder.systemGenerated')"
                disabled
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.verificationId')">
              <ElInput
                :placeholder="t('tenant.manualCreate.placeholder.systemGenerated')"
                disabled
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.tenantCreatedBy')">
              <ElInput
                :placeholder="t('tenant.manualCreate.placeholder.systemGenerated')"
                disabled
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.tenantUpdatedBy')">
              <ElInput
                :placeholder="t('tenant.manualCreate.placeholder.systemGenerated')"
                disabled
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.tenantDeletedBy')">
              <ElInput
                :placeholder="t('tenant.manualCreate.placeholder.systemGenerated')"
                disabled
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem :label="t('tenant.manualCreate.field.subscriptionDeletedAt')">
              <ElInput
                :placeholder="t('tenant.manualCreate.placeholder.systemGenerated')"
                disabled
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </ElScrollbar>
    </ElForm>

    <template #footer>
      <ElButton @click="visible = false">{{ t('common.cancel') }}</ElButton>
      <ElButton type="primary" :loading="submitting" @click="handleSubmit">
        {{ t('common.confirm') }}
      </ElButton>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { computed, reactive, ref, watch } from 'vue'
  import { useI18n } from 'vue-i18n'
  import {
    ElMessage,
    type CascaderOption,
    type CascaderValue,
    type FormInstance,
    type FormRules
  } from 'element-plus'
  import { TenantStatus } from '@/enums/TenantStatus'
  import { TenantVerificationStatus } from '@/enums/TenantVerificationStatus'
  import { fetchCreateTenantManually, fetchGetTenantPackages } from '@/api/tenant'
  import ImageUploadField from './ImageUploadField.vue'
  import { regionData, codeToText } from 'element-china-area-data'

  defineOptions({ name: 'TenantManualCreateDialog' })

  const emit = defineEmits<{
    (e: 'success'): void
  }>()

  const { t } = useI18n()

  const visible = ref(false)
  const loading = ref(false)
  const submitting = ref(false)
  const formRef = ref<FormInstance>()
  const packages = ref<Api.Tenant.TenantPackageDto[]>([])
  const regionCodes = ref<CascaderValue>([])
  const districtText = ref('')

  const regionProps = {
    // 1. 使用 element-china-area-data 的 value/label/children 字段
    value: 'value',
    label: 'label',
    children: 'children'
  } as const
  const regionOptions = regionData as unknown as CascaderOption[]

  const formModel = reactive<Api.Tenant.CreateTenantManuallyCommand>({
    code: '',
    name: '',
    shortName: '',
    legalEntityName: '',
    industry: '',
    logoUrl: '',
    coverImageUrl: '',
    website: '',
    country: '',
    province: '',
    city: '',
    address: '',
    contactName: '',
    contactPhone: '',
    contactEmail: '',
    tags: '',
    remarks: '',
    suspendedAt: undefined,
    suspensionReason: '',
    tenantStatus: TenantStatus.Active,
    tenantPackageId: '',
    durationMonths: 12,
    autoRenew: false,
    subscriptionEffectiveFrom: new Date(),
    nextBillingDate: undefined,
    subscriptionStatus: 1,
    scheduledPackageId: '',
    subscriptionNotes: '',
    verificationStatus: TenantVerificationStatus.Approved,
    businessLicenseNumber: '',
    businessLicenseUrl: '',
    legalPersonName: '',
    legalPersonIdNumber: '',
    legalPersonIdFrontUrl: '',
    legalPersonIdBackUrl: '',
    bankAccountName: '',
    bankAccountNumber: '',
    bankName: '',
    additionalDataJson: '',
    submittedAt: undefined,
    reviewedAt: undefined,
    reviewedByName: '',
    reviewRemarks: '',
    adminAccount: '',
    adminDisplayName: '',
    adminPassword: '',
    adminAvatar: '',
    adminMerchantId: ''
  })

  const rules = reactive<FormRules>({
    // 1. 租户基础信息必填
    code: [{ required: true, message: t('tenant.manualCreate.rule.code'), trigger: 'blur' }],
    name: [{ required: true, message: t('tenant.manualCreate.rule.name'), trigger: 'blur' }],
    tenantStatus: [
      { required: true, message: t('tenant.manualCreate.rule.tenantStatus'), trigger: 'change' }
    ],

    // 2. 订阅信息必填
    tenantPackageId: [
      { required: true, message: t('tenant.manualCreate.rule.tenantPackageId'), trigger: 'change' }
    ],
    durationMonths: [
      { required: true, message: t('tenant.manualCreate.rule.durationMonths'), trigger: 'blur' }
    ],
    subscriptionEffectiveFrom: [
      {
        required: true,
        message: t('tenant.manualCreate.rule.subscriptionEffectiveFrom'),
        trigger: 'change'
      }
    ],
    subscriptionStatus: [
      {
        required: true,
        message: t('tenant.manualCreate.rule.subscriptionStatus'),
        trigger: 'change'
      }
    ],

    // 3. 认证信息必填
    verificationStatus: [
      {
        required: true,
        message: t('tenant.manualCreate.rule.verificationStatus'),
        trigger: 'change'
      }
    ],

    // 4. 管理员账号必填
    adminAccount: [
      { required: true, message: t('tenant.manualCreate.rule.adminAccount'), trigger: 'blur' }
    ],
    adminDisplayName: [
      { required: true, message: t('tenant.manualCreate.rule.adminDisplayName'), trigger: 'blur' }
    ],
    adminPassword: [
      { required: true, message: t('tenant.manualCreate.rule.adminPassword'), trigger: 'blur' }
    ]
  })

  const handleRegionChange = (value: CascaderValue | null | undefined) => {
    // 1. 解析省市县名称并回填到 Province/City（县区仅用于拼接 Address 展示）
    const codes = (Array.isArray(value) ? value : []) as string[]
    const [provinceCode, cityCode, districtCode] = codes
    formModel.province = provinceCode
      ? (codeToText as Record<string, string>)[provinceCode] || ''
      : ''
    formModel.city = cityCode ? (codeToText as Record<string, string>)[cityCode] || '' : ''
    districtText.value = districtCode
      ? (codeToText as Record<string, string>)[districtCode] || ''
      : ''
  }

  const subscriptionEffectiveToPreview = computed(() => {
    // 1. 读取生效时间与时长
    const from = formModel.subscriptionEffectiveFrom
    const months = Number(formModel.durationMonths ?? 0)
    if (!from || !Number.isFinite(months) || months <= 0) {
      return ''
    }

    // 2. 计算到期时间
    const fromDate = from instanceof Date ? from : new Date(from)
    if (Number.isNaN(fromDate.getTime())) {
      return ''
    }

    const effectiveTo = addMonths(fromDate, months)
    return formatDateTime(effectiveTo)
  })

  watch(
    () => [formModel.subscriptionEffectiveFrom, formModel.durationMonths],
    () => {
      // 1. 订阅变更时，若未填写 nextBillingDate，则默认跟随到期时间
      if (formModel.nextBillingDate) {
        return
      }

      const from = formModel.subscriptionEffectiveFrom
      const months = Number(formModel.durationMonths ?? 0)
      if (!from || !Number.isFinite(months) || months <= 0) {
        return
      }

      const fromDate = from instanceof Date ? from : new Date(from)
      if (Number.isNaN(fromDate.getTime())) {
        return
      }

      formModel.nextBillingDate = addMonths(fromDate, months)
    }
  )

  const loadPackages = async () => {
    // 1. 获取套餐列表（尽量拉多一点，便于下拉选择）
    const res = await fetchGetTenantPackages({ Page: 1, PageSize: 200, IsActive: true })
    packages.value = res.items || []
  }

  const resetForm = async () => {
    // 1. 重置表单校验状态
    formRef.value?.resetFields()

    // 2. 设置默认值
    Object.assign(formModel, {
      code: `t${Date.now()}`,
      name: '',
      shortName: '',
      legalEntityName: '',
      industry: '',
      logoUrl: '',
      coverImageUrl: '',
      website: '',
      country: '中国',
      province: '',
      city: '',
      address: '',
      contactName: '',
      contactPhone: '',
      contactEmail: '',
      tags: '',
      remarks: '',
      suspendedAt: undefined,
      suspensionReason: '',
      tenantStatus: TenantStatus.Active,
      tenantPackageId: '',
      durationMonths: 12,
      autoRenew: false,
      subscriptionEffectiveFrom: new Date(),
      nextBillingDate: undefined,
      subscriptionStatus: 1,
      scheduledPackageId: '',
      subscriptionNotes: '',
      verificationStatus: TenantVerificationStatus.Approved,
      businessLicenseNumber: '',
      businessLicenseUrl: '',
      legalPersonName: '',
      legalPersonIdNumber: '',
      legalPersonIdFrontUrl: '',
      legalPersonIdBackUrl: '',
      bankAccountName: '',
      bankAccountNumber: '',
      bankName: '',
      additionalDataJson: '',
      submittedAt: undefined,
      reviewedAt: undefined,
      reviewedByName: '',
      reviewRemarks: '',
      adminAccount: '',
      adminDisplayName: '',
      adminPassword: '',
      adminAvatar: '',
      adminMerchantId: ''
    })

    // 3. 同步清理省市县选择
    regionCodes.value = []
    districtText.value = ''
  }

  const open = async () => {
    visible.value = true
    loading.value = true
    try {
      // 1. 初始化表单默认值
      await resetForm()

      // 2. 预加载套餐
      if (packages.value.length === 0) {
        await loadPackages()
      }
    } finally {
      loading.value = false
    }
  }

  const handleClosed = () => {
    formRef.value?.resetFields()
  }

  const handleSubmit = async () => {
    if (!formRef.value) return

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

    // 2. 提交创建请求
    submitting.value = true
    try {
      await fetchCreateTenantManually(buildPayload())
      ElMessage.success(t('tenant.manualCreate.success'))
      visible.value = false
      emit('success')
    } catch (error) {
      console.error(error)
    } finally {
      submitting.value = false
    }
  }

  const formatDateTime = (date: Date) => {
    const pad2 = (value: number) => (value < 10 ? `0${value}` : `${value}`)
    return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())} ${pad2(
      date.getHours()
    )}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`
  }

  const addMonths = (date: Date, months: number) => {
    const result = new Date(date.getTime())
    const expectedMonth = result.getMonth() + months
    result.setMonth(expectedMonth)
    return result
  }

  const buildPayload = (): Api.Tenant.CreateTenantManuallyCommand => {
    // 1. 复制数据，避免直接修改表单响应式对象
    const payload: Api.Tenant.CreateTenantManuallyCommand = { ...formModel }

    // 2. 清理可空 long 字段：空字符串不传，避免后端反序列化失败
    if (payload.scheduledPackageId?.trim() === '') payload.scheduledPackageId = undefined
    if (payload.adminMerchantId?.trim() === '') payload.adminMerchantId = undefined

    // 3. 认证时间默认使用当前时间（不从表单传）
    payload.submittedAt = undefined
    payload.reviewedAt = undefined

    // 4. 将“县区 + 详细地址”合并写入 Address
    payload.address = [districtText.value, payload.address].filter(Boolean).join(' ')

    return payload
  }

  defineExpose({ open })
</script>
