<template>
  <div class="art-page-view space-y-4">
    <ElCard shadow="never">
      <div class="flex flex-wrap items-start justify-between gap-4">
        <div class="space-y-1">
          <div class="text-lg font-semibold">{{ t('announcement.create.title') }}</div>
          <div class="text-sm text-[var(--el-text-color-secondary)]">
            {{ draftStatusText }}
          </div>
        </div>
        <div class="flex items-center gap-2">
          <ElButton @click="handleCancel">
            {{ t('common.cancel') }}
          </ElButton>
          <ElButton type="primary" :loading="loading" @click="handleSubmit">
            {{ t('announcement.action.create') }}
          </ElButton>
        </div>
      </div>
    </ElCard>

    <ElCard shadow="never" v-loading="pageLoading">
      <ElForm ref="formRef" :model="formModel" :rules="formRules" label-position="top">
        <div class="grid grid-cols-1 gap-4 lg:grid-cols-2">
          <ElFormItem class="lg:col-span-2" prop="title" :label="t('announcement.form.title')">
            <ElInput
              v-model="formModel.title"
              maxlength="128"
              show-word-limit
              :placeholder="t('announcement.form.titlePlaceholder')"
            />
          </ElFormItem>

          <ElFormItem prop="announcementType" :label="t('announcement.form.type')">
            <ElSelect
              v-model="formModel.announcementType"
              clearable
              :placeholder="t('announcement.form.typePlaceholder')"
            >
              <ElOption
                v-for="option in typeOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </ElSelect>
          </ElFormItem>

          <ElFormItem prop="priority" :label="t('announcement.form.priority')">
            <ElInputNumber v-model="formModel.priority" :min="1" :max="5" class="w-full" />
          </ElFormItem>

          <ElFormItem prop="effectiveFrom" :label="t('announcement.form.effectiveFrom')">
            <ElDatePicker
              v-model="formModel.effectiveFrom"
              type="datetime"
              class="w-full"
              :value-format="dateTimeFormat"
              :placeholder="t('announcement.form.effectiveFromPlaceholder')"
            />
          </ElFormItem>

          <ElFormItem prop="effectiveTo" :label="t('announcement.form.effectiveTo')">
            <ElDatePicker
              v-model="formModel.effectiveTo"
              type="datetime"
              clearable
              class="w-full"
              :value-format="dateTimeFormat"
              :placeholder="t('announcement.form.effectiveToPlaceholder')"
            />
          </ElFormItem>

          <ElFormItem
            class="lg:col-span-2"
            prop="targetType"
            :label="t('announcement.form.target')"
          >
            <AudienceSelector
              :model-value="{
                targetType: formModel.targetType,
                targetRules: formModel.targetRules,
                targetUserIds: formModel.targetUserIds
              }"
              @update:model-value="
                (value) => {
                  formModel.targetType = value.targetType
                  formModel.targetRules = value.targetRules
                  formModel.targetUserIds = value.targetUserIds
                }
              "
            />
          </ElFormItem>

          <ElFormItem class="lg:col-span-2" prop="content" :label="t('announcement.form.content')">
            <RichTextEditor
              v-model="formModel.content"
              :height="'360px'"
              :placeholder="t('announcement.form.contentPlaceholder')"
            />
          </ElFormItem>
        </div>
      </ElForm>
    </ElCard>
  </div>
</template>

<script setup lang="ts">
  import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { useRoute, useRouter } from 'vue-router'
  import { storeToRefs } from 'pinia'
  import type { FormInstance, FormItemRule, FormRules } from 'element-plus'
  import {
    ElButton,
    ElCard,
    ElDatePicker,
    ElForm,
    ElFormItem,
    ElInput,
    ElInputNumber,
    ElMessage,
    ElOption,
    ElSelect
  } from 'element-plus'
  import RichTextEditor from '@/components/common/RichTextEditor.vue'
  import AudienceSelector from '@/components/announcement/AudienceSelector.vue'
  import { useAnnouncementStore } from '@/store/modules/announcement'
  import type {
    AnnouncementDraft,
    AnnouncementFormData,
    AnnouncementTargetType,
    AnnouncementTypeOption,
    TenantAnnouncementType
  } from '@/types/announcement'
  import { TenantAnnouncementType as TenantAnnouncementTypeEnum } from '@/types/announcement'

  defineOptions({ name: 'PlatformAnnouncementCreate' })

  const { t } = useI18n()
  const route = useRoute()
  const router = useRouter()

  // 1. 初始化 Store 与加载状态
  const announcementStore = useAnnouncementStore()
  const { loading } = storeToRefs(announcementStore)
  const pageLoading = ref(false)

  // 2. 表单模型（对齐 AnnouncementFormData）
  const formModel = reactive<AnnouncementFormData>({
    title: '',
    content: '',
    announcementType: TenantAnnouncementTypeEnum.System,
    priority: 1,
    effectiveFrom: new Date().toISOString(),
    effectiveTo: null,
    targetType: 'All',
    targetRules: undefined,
    targetUserIds: [],
    rowVersion: undefined
  })

  // 3. 日期格式（UTC ISO）
  const dateTimeFormat = 'YYYY-MM-DDTHH:mm:ss.SSSZ'

  // 4. 下拉选项（公告类型）
  const typeOptions = computed<AnnouncementTypeOption[]>(() => {
    const values = Object.values(TenantAnnouncementTypeEnum).filter(
      (value) => typeof value === 'number'
    ) as TenantAnnouncementType[]

    return values.map((value) => ({
      value,
      label: getTypeLabel(value)
    }))
  })

  // 6. FluentValidation 风格校验规则构建器
  const createRuleBuilder = () => {
    const rules: FormItemRule[] = []

    const withValidator = (
      validator: (value: unknown) => string | null,
      trigger: FormItemRule['trigger']
    ) => {
      rules.push({
        trigger,
        validator: (_rule, value, callback) => {
          const message = validator(value)
          if (message) {
            callback(new Error(message))
            return
          }
          callback()
        }
      })
    }

    return {
      required(message: string, trigger: FormItemRule['trigger'] = 'blur') {
        rules.push({ required: true, message, trigger })
        return this
      },
      maxLength(max: number, message: string, trigger: FormItemRule['trigger'] = 'blur') {
        withValidator((value) => {
          if (!value) {
            return null
          }
          return String(value).length > max ? message : null
        }, trigger)
        return this
      },
      numberRange(
        min: number,
        max: number,
        message: string,
        trigger: FormItemRule['trigger'] = 'change'
      ) {
        withValidator((value) => {
          if (value === null || value === undefined || value === '') {
            return null
          }
          const num = Number(value)
          if (Number.isNaN(num)) {
            return message
          }
          return num < min || num > max ? message : null
        }, trigger)
        return this
      },
      custom(
        validator: (value: unknown) => string | null,
        trigger: FormItemRule['trigger'] = 'change'
      ) {
        withValidator(validator, trigger)
        return this
      },
      build() {
        return rules
      }
    }
  }

  // 7. 表单校验规则（FluentValidation 组合）
  const formRules = computed<FormRules<AnnouncementFormData>>(() => ({
    title: createRuleBuilder()
      .required(t('announcement.validation.titleRequired'))
      .maxLength(128, t('announcement.validation.titleMax'))
      .build(),
    content: createRuleBuilder().required(t('announcement.validation.contentRequired')).build(),
    announcementType: createRuleBuilder()
      .required(t('announcement.validation.typeRequired'), 'change')
      .build(),
    priority: createRuleBuilder()
      .required(t('announcement.validation.priorityRequired'), 'change')
      .numberRange(1, 5, t('announcement.validation.priorityRange'))
      .build(),
    effectiveFrom: createRuleBuilder()
      .required(t('announcement.validation.effectiveFromRequired'), 'change')
      .build(),
    effectiveTo: createRuleBuilder().custom(validateEffectiveTo, 'change').build(),
    targetType: createRuleBuilder()
      .required(t('announcement.validation.targetTypeRequired'), 'change')
      .custom(validateAudience, 'change')
      .build()
  }))

  const formRef = ref<FormInstance>()
  const autoSaveCleanup = ref<(() => void) | null>(null)

  // 8. 草稿状态提示
  const draftStatusText = computed(() => {
    const lastSaved = announcementStore.currentDraft?.lastSaved
    if (!lastSaved) {
      return t('announcement.draft.notSaved')
    }

    return t('announcement.draft.savedAt', { time: formatTime(lastSaved) })
  })

  // 9. 初始化草稿并启动自动保存
  const initDraft = () => {
    // 1. 从路由参数读取草稿
    const draftId = route.query.draftId ? String(route.query.draftId) : ''
    if (draftId) {
      const draft = announcementStore.loadDraft(draftId)
      if (draft) {
        applyDraft(draft)
      }
    }

    // 2. 启动自动保存
    autoSaveCleanup.value?.()
    autoSaveCleanup.value = announcementStore.autoSaveDraft(formModel, 30000)
  }

  const applyDraft = (draft: AnnouncementDraft) => {
    // 1. 合并草稿数据
    formModel.title = draft.title ?? ''
    formModel.content = draft.content ?? ''
    formModel.announcementType = draft.announcementType ?? TenantAnnouncementTypeEnum.System
    formModel.priority = draft.priority ?? 1
    formModel.effectiveFrom = draft.effectiveFrom ?? new Date().toISOString()
    formModel.effectiveTo = draft.effectiveTo ?? null
    formModel.targetType = draft.targetType ?? 'All'
    formModel.targetRules = draft.targetRules
    formModel.targetUserIds = draft.targetUserIds ?? []
  }

  const validateEffectiveTo = (value: unknown) => {
    if (!value) {
      return null
    }

    const start = Date.parse(formModel.effectiveFrom)
    const end = Date.parse(String(value))
    if (Number.isNaN(start) || Number.isNaN(end)) {
      return t('announcement.validation.effectiveToAfter')
    }

    return end < start ? t('announcement.validation.effectiveToAfter') : null
  }

  const validateAudience = (value: unknown) => {
    const targetType = value as AnnouncementTargetType
    if (!targetType) {
      return t('announcement.validation.targetTypeRequired')
    }

    if ((targetType === 'Rules' || targetType === 'Roles') && !formModel.targetRules) {
      return t('announcement.validation.targetRulesRequired')
    }

    if (
      (targetType === 'Users' || targetType === 'Manual') &&
      (!formModel.targetUserIds || formModel.targetUserIds.length === 0)
    ) {
      return t('announcement.validation.targetUsersRequired')
    }

    return null
  }

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

    try {
      // 1. 触发表单校验
      await formRef.value.validate()
    } catch {
      ElMessage.warning(t('announcement.message.validationFailed'))
      return
    }

    try {
      // 2. 构建提交参数
      const payload: AnnouncementFormData = {
        title: formModel.title.trim(),
        content: formModel.content,
        announcementType: formModel.announcementType,
        priority: formModel.priority,
        effectiveFrom: formModel.effectiveFrom,
        effectiveTo: formModel.effectiveTo || null,
        targetType: formModel.targetType,
        targetRules: formModel.targetRules,
        targetUserIds: formModel.targetUserIds
      }

      // 3. 提交创建请求
      const result = await announcementStore.createAnnouncement(payload, { scope: 'platform' })
      if (result) {
        ElMessage.success(t('announcement.message.createSuccess'))

        // 4. 清理草稿并跳转详情
        if (announcementStore.currentDraft?.draftId) {
          announcementStore.clearDraft(announcementStore.currentDraft.draftId)
        }
        void router.push(`/platform/announcements/${result.id}`)
      }
    } catch {
      ElMessage.error(t('announcement.message.createFailed'))
    }
  }

  const handleCancel = () => {
    // 1. 返回上一页
    router.back()
  }

  const formatTime = (value: string) => {
    const date = new Date(value)
    if (Number.isNaN(date.getTime())) {
      return value
    }
    return date.toLocaleTimeString()
  }

  const getTypeLabel = (type: TenantAnnouncementType) => {
    switch (type) {
      case TenantAnnouncementTypeEnum.System:
        return t('announcement.type.system')
      case TenantAnnouncementTypeEnum.Billing:
        return t('announcement.type.billing')
      case TenantAnnouncementTypeEnum.Operation:
        return t('announcement.type.operation')
      case TenantAnnouncementTypeEnum.SYSTEM_PLATFORM_UPDATE:
        return t('announcement.type.platformUpdate')
      case TenantAnnouncementTypeEnum.SYSTEM_SECURITY_NOTICE:
        return t('announcement.type.security')
      case TenantAnnouncementTypeEnum.SYSTEM_COMPLIANCE:
        return t('announcement.type.compliance')
      case TenantAnnouncementTypeEnum.TENANT_INTERNAL:
        return t('announcement.type.tenantInternal')
      case TenantAnnouncementTypeEnum.TENANT_FINANCE:
        return t('announcement.type.tenantFinance')
      case TenantAnnouncementTypeEnum.TENANT_OPERATION:
        return t('announcement.type.tenantOperation')
      default:
        return t('announcement.type.unknown')
    }
  }

  onMounted(() => {
    // 1. 初始化草稿
    initDraft()
  })

  onBeforeUnmount(() => {
    // 1. 清理草稿定时器
    autoSaveCleanup.value?.()
  })
</script>
