<template>
  <a-drawer
    :visible="visible"
    :width="760"
    :title="faq ? '编辑 FAQ' : '新建 FAQ'"
    :closable="!busy"
    :mask-closable="!busy"
    :esc-to-close="!busy"
    :on-before-cancel="canClose"
    unmount-on-close
    @cancel="close"
    @update:visible="handleVisibleChange"
  >
    <a-form ref="formRef" :model="form" layout="vertical">
      <section class="form-section">
        <h3>基本信息</h3>
        <a-form-item label="问题" field="question" :rules="[{ required: true, message: '请输入问题' }]">
          <a-textarea
            v-model="form.question"
            placeholder="请输入常见问题"
            :auto-size="{ minRows: 2, maxRows: 5 }"
            :max-length="1000"
            show-word-limit
          />
        </a-form-item>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="公共分类" field="category_id" :rules="[{ required: true, message: '请选择公共分类' }]">
              <a-select v-model="form.category_id" placeholder="请选择公共分类" allow-search>
                <a-option v-for="category in categories" :key="category.id" :value="category.id">
                  {{ category.label }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="优先级" field="priority">
              <a-select v-model="form.priority">
                <a-option v-for="option in faqPriorityOptions" :key="option.value" :value="option.value">
                  {{ option.label }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="问题类型" field="problem_type">
              <a-select v-model="form.problem_type" placeholder="请选择或输入" allow-clear allow-search allow-create>
                <a-option v-for="option in faqProblemTypeOptions" :key="option.value" :value="option.value">
                  {{ option.label }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="子分类" field="sub_category">
          <a-input v-model="form.sub_category" placeholder="请输入子分类或补充分类说明" :max-length="100" allow-clear />
        </a-form-item>
        <a-alert v-if="originalCategoryUnavailable" type="warning">原分类已停用或不可用，请重新选择</a-alert>
      </section>

      <section class="form-section">
        <h3>处理方案</h3>
        <a-form-item label="答案" field="answer" :rules="[{ required: true, message: '请输入答案' }]">
          <a-textarea v-model="form.answer" placeholder="请输入答案或处理方式" :auto-size="{ minRows: 4, maxRows: 10 }" />
        </a-form-item>
        <a-form-item label="详细解决方案" field="solution">
          <a-textarea v-model="form.solution" placeholder="补充完整的解决方案" :auto-size="{ minRows: 3, maxRows: 8 }" />
        </a-form-item>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="处理步骤" field="process_steps">
              <a-textarea v-model="form.process_steps" placeholder="请输入处理步骤" :auto-size="{ minRows: 3, maxRows: 8 }" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="前置条件" field="prerequisites">
              <a-textarea v-model="form.prerequisites" placeholder="请输入前置条件" :auto-size="{ minRows: 3, maxRows: 8 }" />
            </a-form-item>
          </a-col>
        </a-row>
      </section>

      <section class="form-section">
        <h3>使用范围</h3>
        <a-form-item label="适用范围" field="applicable_scope">
          <a-textarea
            v-model="form.applicable_scope"
            placeholder="说明适用的系统、角色或业务场景"
            :auto-size="{ minRows: 2, maxRows: 5 }"
            :max-length="200"
            show-word-limit
          />
        </a-form-item>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="关键词" field="keywords">
              <a-input v-model="form.keywords" placeholder="多个关键词用逗号分隔" :max-length="500" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="标签" field="tags">
              <a-input v-model="form.tags" placeholder="支持逗号分隔或 JSON 数组" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="检测点 ID" field="detection_point_ids">
          <a-input v-model="form.detection_point_ids" placeholder="支持逗号分隔或 JSON 数组" />
        </a-form-item>
        <a-form-item label="备注" field="remarks">
          <a-textarea v-model="form.remarks" placeholder="请输入备注" :auto-size="{ minRows: 2, maxRows: 5 }" />
        </a-form-item>
      </section>
    </a-form>

    <template #footer>
      <a-space>
        <a-button :disabled="busy" @click="close">取消</a-button>
        <a-button type="primary" :loading="busy" :disabled="busy" @click="handleSubmit">保存</a-button>
      </a-space>
    </template>
  </a-drawer>
</template>

<script lang="ts" setup>
import { computed, reactive, ref, watch } from 'vue'
import { Message, type FormInstance } from '@arco-design/web-vue'
import { faqPriorityOptions, faqProblemTypeOptions, type Faq, type FaqFormData } from '@/api/kb/faq'

/** 表单和筛选使用的扁平分类节点。 */
export interface FaqCategoryOption {
  id: number
  name: string
  label: string
  parentId: number
  level: number
  path: string
  status: 'active' | 'inactive'
}

interface Props {
  visible: boolean
  faq: Faq | null
  categories: FaqCategoryOption[]
  submitting?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  submitting: false,
})

const emit = defineEmits<{
  (event: 'update:visible', visible: boolean): void
  (event: 'submit', values: FaqFormData, done: () => void): void
}>()

const formRef = ref<FormInstance>()
const validating = ref(false)
const originalCategoryUnavailable = ref(false)
const busy = computed(() => validating.value || props.submitting)
type FaqEditorForm = Omit<FaqFormData, 'category_id'> & { category_id?: number }

const form = reactive<FaqEditorForm>(createEmptyForm())

/** 创建一份不共享引用的空表单。 */
function createEmptyForm(): FaqEditorForm {
  return {
    question: '',
    answer: '',
    priority: 'medium',
    category_id: undefined,
    sub_category: '',
    problem_type: '',
    solution: '',
    process_steps: '',
    prerequisites: '',
    keywords: '',
    tags: '',
    detection_point_ids: '',
    applicable_scope: '',
    remarks: '',
  }
}

/** 打开抽屉时载入当前 FAQ，关闭后由 unmount-on-close 清理视图。 */
function resetForm() {
  const faq = props.faq
  const categoryAvailable = Boolean(faq && props.categories.some((category) => category.id === faq.category_id))
  originalCategoryUnavailable.value = Boolean(faq && !categoryAvailable)
  Object.assign(
    form,
    faq
      ? {
          question: faq.question,
          answer: faq.answer,
          priority: faq.priority || 'medium',
          category_id: categoryAvailable ? faq.category_id : undefined,
          sub_category: faq.sub_category || '',
          problem_type: faq.problem_type || '',
          solution: faq.solution || '',
          process_steps: faq.process_steps || '',
          prerequisites: faq.prerequisites || '',
          keywords: faq.keywords || '',
          tags: faq.tags || '',
          detection_point_ids: faq.detection_point_ids || '',
          applicable_scope: faq.applicable_scope || '',
          remarks: faq.remarks || '',
        }
      : createEmptyForm()
  )
  validating.value = false
  formRef.value?.clearValidate()
}

watch(
  () => props.visible,
  (visible) => {
    if (visible) resetForm()
    else validating.value = false
  }
)

watch(
  () => props.categories,
  () => {
    const faq = props.faq
    if (!props.visible || !faq || !originalCategoryUnavailable.value) return
    if (props.categories.some((category) => category.id === faq.category_id)) {
      form.category_id = faq.category_id
      originalCategoryUnavailable.value = false
    }
  },
  { deep: true }
)

watch(
  () => form.category_id,
  (categoryId) => {
    if (categoryId && props.categories.some((category) => category.id === categoryId)) {
      originalCategoryUnavailable.value = false
    }
  }
)

/** 校验通过后交由父页面保存，接口成功前不关闭抽屉。 */
async function handleSubmit() {
  if (busy.value) return
  validating.value = true
  let handedOff = false
  try {
    const errors = await formRef.value?.validate()
    if (errors) return

    const question = form.question.trim()
    const answer = form.answer.trim()
    const categoryId = form.category_id
    if (!question || !answer || !categoryId) {
      Message.warning('问题、答案和公共分类为必填项')
      return
    }

    handedOff = true
    emit(
      'submit',
      {
        ...form,
        question,
        answer,
        category_id: categoryId,
        sub_category: form.sub_category.trim(),
        problem_type: form.problem_type.trim(),
        solution: form.solution.trim(),
        process_steps: form.process_steps.trim(),
        prerequisites: form.prerequisites.trim(),
        keywords: form.keywords.trim(),
        tags: form.tags.trim(),
        detection_point_ids: form.detection_point_ids.trim(),
        applicable_scope: form.applicable_scope.trim(),
        remarks: form.remarks.trim(),
      },
      () => {
        validating.value = false
      }
    )
  } finally {
    if (!handedOff) validating.value = false
  }
}

/** 提交中拒绝关闭，避免中断请求或丢失输入。 */
function close() {
  if (!busy.value) emit('update:visible', false)
}

function canClose() {
  return !busy.value
}

function handleVisibleChange(visible: boolean) {
  if (!visible) close()
}
</script>

<style scoped lang="less">
.form-section {
  & + & {
    margin-top: 28px;
    padding-top: 20px;
    border-top: 1px solid var(--color-neutral-3);
  }

  h3 {
    margin: 0 0 16px;
    color: var(--color-text-1);
    font-size: 16px;
  }
}
</style>
