<template>
  <ElDialog
    v-model="visible"
    :title="title"
    width="600px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <ElForm ref="formRef" :model="formModel" :rules="rules" label-width="100px" v-loading="loading">
      <ElFormItem :label="t('tenant.table.code')" prop="code">
        <ElInput
          v-model="formModel.code"
          :placeholder="t('tenant.edit.placeholder.code')"
          :disabled="isEdit"
        />
      </ElFormItem>
      <ElFormItem :label="t('tenant.table.name')" prop="name">
        <ElInput v-model="formModel.name" :placeholder="t('tenant.edit.placeholder.name')" />
      </ElFormItem>
      <ElFormItem :label="t('tenant.detail.shortName')" prop="shortName">
        <ElInput
          v-model="formModel.shortName"
          :placeholder="t('tenant.edit.placeholder.shortName')"
        />
      </ElFormItem>
      <ElFormItem :label="t('tenant.detail.industry')" prop="industry">
        <ElInput
          v-model="formModel.industry"
          :placeholder="t('tenant.edit.placeholder.industry')"
        />
      </ElFormItem>
      <ElFormItem :label="t('tenant.table.contactName')" prop="contactName">
        <ElInput
          v-model="formModel.contactName"
          :placeholder="t('tenant.edit.placeholder.contactName')"
        />
      </ElFormItem>
      <ElFormItem :label="t('tenant.table.contactPhone')" prop="contactPhone">
        <ElInput
          v-model="formModel.contactPhone"
          :placeholder="t('tenant.edit.placeholder.contactPhone')"
        />
      </ElFormItem>
      <ElFormItem :label="t('tenant.detail.contactEmail')" prop="contactEmail">
        <ElInput
          v-model="formModel.contactEmail"
          :placeholder="t('tenant.edit.placeholder.contactEmail')"
        />
      </ElFormItem>

      <template v-if="!isEdit">
        <ElDivider content-position="left">{{ t('tenant.edit.package.title') }}</ElDivider>
        <ElFormItem :label="t('tenant.edit.package.select')" prop="tenantPackageId">
          <ElSelect
            v-model="formModel.tenantPackageId"
            :placeholder="t('tenant.edit.placeholder.tenantPackageId')"
            class="w-full"
          >
            <ElOption v-for="pkg in packages" :key="pkg.id" :label="pkg.name" :value="pkg.id">
              <span style="float: left">{{ pkg.name }}</span>
              <span style="float: right; font-size: 13px; color: var(--el-text-color-secondary)">
                {{
                  pkg.packageType === 0
                    ? t('tenant.edit.packageType.free')
                    : t('tenant.edit.packageType.paid')
                }}
              </span>
            </ElOption>
          </ElSelect>
        </ElFormItem>
        <ElFormItem :label="t('tenant.edit.package.durationMonths')" prop="durationMonths">
          <ElInputNumber
            v-model="formModel.durationMonths"
            :min="1"
            :max="120"
            :label="t('tenant.edit.unit.month')"
          />
          <span class="ml-2">{{ t('tenant.edit.unit.month') }}</span>
        </ElFormItem>
        <ElFormItem :label="t('tenant.detail.autoRenew')" prop="autoRenew">
          <ElSwitch v-model="formModel.autoRenew" />
        </ElFormItem>
        <ElFormItem :label="t('tenant.detail.effectiveFrom')" prop="effectiveFrom">
          <ElDatePicker
            v-model="formModel.effectiveFrom"
            type="datetime"
            :placeholder="t('tenant.edit.placeholder.effectiveFrom')"
            class="w-full"
          />
        </ElFormItem>
      </template>
    </ElForm>
    <template #footer>
      <span class="dialog-footer">
        <ElButton @click="visible = false">{{ t('common.cancel') }}</ElButton>
        <ElButton type="primary" :loading="submitting" @click="handleSubmit">
          {{ t('common.confirm') }}
        </ElButton>
      </span>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { ref, computed, reactive } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
  import {
    fetchGetTenantDetail,
    fetchGetTenantPackages,
    fetchRegisterTenant,
    fetchUpdateTenant
  } from '@/api/tenant'
  import type { UpdateTenantCommand } from '@/types/tenant'

  defineOptions({ name: 'TenantEdit' })

  const { t } = useI18n()

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

  const visible = ref(false)
  const loading = ref(false)
  const submitting = ref(false)
  const isEdit = ref(false)
  const formRef = ref<FormInstance>()
  const packages = ref<Api.Tenant.TenantPackageDto[]>([])
  const tenantId = ref<string>('')

  const formModel = reactive<Api.Tenant.RegisterTenantCommand>({
    code: '',
    name: '',
    shortName: '',
    industry: '',
    contactName: '',
    contactPhone: '',
    contactEmail: '',
    tenantPackageId: '', // long -> string
    durationMonths: 12,
    autoRenew: false,
    effectiveFrom: undefined
  })

  const rules = computed<FormRules>(() => {
    return {
      code: [
        { required: true, message: t('tenant.edit.validation.codeRequired'), trigger: 'blur' }
      ],
      name: [
        { required: true, message: t('tenant.edit.validation.nameRequired'), trigger: 'blur' }
      ],
      tenantPackageId: isEdit.value
        ? []
        : [
            {
              required: true,
              message: t('tenant.edit.validation.tenantPackageIdRequired'),
              trigger: 'change'
            }
          ]
    }
  })

  const title = computed(() =>
    isEdit.value ? t('tenant.edit.titleEdit') : t('tenant.edit.titleCreate')
  )

  const loadPackages = async () => {
    try {
      const res = await fetchGetTenantPackages()
      packages.value = res.items ?? []
    } catch (error) {
      console.error(error)
    }
  }

  const open = async (row?: Api.Tenant.TenantDto) => {
    visible.value = true
    isEdit.value = !!row

    if (formRef.value) {
      formRef.value.resetFields()
    }

    // 1. 重置当前租户ID
    tenantId.value = row?.id ?? ''

    // 2. 初始化表单默认值
    Object.assign(formModel, {
      code: '',
      name: '',
      shortName: '',
      industry: '',
      contactName: '',
      contactPhone: '',
      contactEmail: '',
      tenantPackageId: '',
      durationMonths: 12,
      autoRenew: false,
      effectiveFrom: undefined
    })

    // 3. 新增模式：仅加载套餐
    if (!isEdit.value) {
      if (packages.value.length === 0) {
        loading.value = true
        try {
          await loadPackages()
        } finally {
          loading.value = false
        }
      }
      return
    }

    // 4. 编辑模式：拉取详情并反填表单
    if (!tenantId.value) return

    loading.value = true
    try {
      const detail = await fetchGetTenantDetail(tenantId.value, { showErrorMessage: false })
      const tenant = detail.tenant

      Object.assign(formModel, {
        code: tenant.code ?? '',
        name: tenant.name ?? '',
        shortName: tenant.shortName ?? '',
        industry: tenant.industry ?? '',
        contactName: tenant.contactName ?? '',
        contactPhone: tenant.contactPhone ?? '',
        contactEmail: tenant.contactEmail ?? ''
      })
    } catch (error) {
      console.error(error)
      ElMessage.error(t('tenant.error.loadDetailFailed'))
      visible.value = false
    } finally {
      loading.value = false
    }
  }

  const handleClosed = () => {
    // 1. 关闭时清理状态
    formRef.value?.resetFields()
    tenantId.value = ''
    isEdit.value = false
  }

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

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

    submitting.value = true
    try {
      if (isEdit.value) {
        // 2. 编辑模式：更新租户
        if (!tenantId.value) return

        const updateData: UpdateTenantCommand = {
          tenantId: tenantId.value,
          name: formModel.name,
          shortName: formModel.shortName,
          industry: formModel.industry,
          contactName: formModel.contactName,
          contactPhone: formModel.contactPhone,
          contactEmail: formModel.contactEmail
        }

        // TD-001 已完成：PUT /api/admin/v1/tenants/{tenantId}
        // 响应：BaseResponse<void>
        // 错误码：400（参数错误）、404（租户不存在）、409（name/contactPhone 冲突）
        await fetchUpdateTenant(tenantId.value, updateData)

        ElMessage.success(t('tenant.success.updateSuccess'))
      } else {
        // 3. 新增模式：注册租户
        await fetchRegisterTenant(formModel)
        ElMessage.success(t('tenant.success.registerSuccess'))
      }

      // 4. 通知父组件并关闭
      emit('success')
      visible.value = false
    } catch (error) {
      console.error(error)
      if (isEdit.value) {
        ElMessage.error(t('tenant.error.updateFailed'))
      }
    } finally {
      submitting.value = false
    }
  }

  defineExpose({ open })
</script>
