<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isCreate ? '新增评估模板' : '编辑评估模板'"
    width="700px"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="模板名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入模板名称" />
      </el-form-item>
      <el-form-item label="模板编码" prop="code">
        <el-input v-model="formData.code" placeholder="请输入模板编码，如：INCOMING_ASSESSMENT" />
      </el-form-item>
      <el-form-item label="模板类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择模板类型" class="!w-full">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PRISON_REPORT_TEMPLATE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="评估周期" prop="evaluationCycle">
        <el-select v-model="formData.evaluationCycle" placeholder="请选择评估周期" class="!w-full">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PRISON_EVALUATION_CYCLE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="适用人群" prop="applicableCrowd">
        <el-input v-model="formData.applicableCrowd" placeholder="请输入适用人群，如：新入监罪犯" />
      </el-form-item>
      <el-form-item label="模板描述" prop="description">
        <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入模板描述" />
      </el-form-item>
      <el-form-item label="AI提示词" prop="aiPrompt">
        <el-input v-model="formData.aiPrompt" type="textarea" :rows="4" placeholder="请输入AI提示词，用于AI生成报告时参考" />
      </el-form-item>
      <el-form-item label="允许AI生成" prop="aiEnabled">
        <el-switch v-model="formData.aiEnabled" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="formData.sort" :min="0" :max="999" controls-position="right" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" :rows="2" placeholder="请输入备注信息" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.PRISON_COMMON_STATUS)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { EvaluationTemplateApi } from '@/api/prison/evaluation'

defineOptions({ name: 'EvaluationTemplateForm' })

const emit = defineEmits(['success'])

// 保存当前编辑的模板ID，用于刷新数据
const currentTemplateId = ref<number | undefined>(undefined)

const dialogVisible = ref(false)
const isCreate = ref(true)
const submitLoading = ref(false)
const formRef = ref()

const formData = reactive({
  id: undefined,
  name: '',
  code: '',
  type: undefined as number | undefined,
  evaluationCycle: undefined as number | undefined,
  applicableCrowd: '',
  description: '',
  aiPrompt: '',
  aiEnabled: 1,
  sort: 0,
  remark: '',
  status: 1
})

const rules = {
  name: [{ required: true, message: '模板名称不能为空', trigger: 'blur' }],
  code: [{ required: true, message: '模板编码不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '模板类型不能为空', trigger: 'change' }],
  evaluationCycle: [{ required: true, message: '评估周期不能为空', trigger: 'change' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
}

/** 打开弹窗 */
const open = (type: string, id?: number) => {
  dialogVisible.value = true
  isCreate.value = type === 'create'
  currentTemplateId.value = id
  resetForm()
  if (id) {
    loadData(id)
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.id = undefined
  formData.name = ''
  formData.code = ''
  formData.type = undefined
  formData.evaluationCycle = undefined
  formData.applicableCrowd = ''
  formData.description = ''
  formData.aiPrompt = ''
  formData.aiEnabled = 1
  formData.sort = 0
  formData.remark = ''
  formData.status = 1
}

/** 加载数据 */
const loadData = async (id: number) => {
  const data = await EvaluationTemplateApi.getTemplate(id)
  if (data) {
    formData.id = data.id
    formData.name = data.name
    formData.code = data.code || ''
    formData.type = data.type
    formData.evaluationCycle = data.evaluationCycle
    formData.applicableCrowd = data.applicableCrowd || ''
    formData.description = data.description || ''
    formData.aiPrompt = data.aiPrompt || ''
    formData.aiEnabled = data.aiEnabled ?? 1
    formData.sort = data.sort ?? 0
    formData.remark = data.remark || ''
    formData.status = data.status
  }
}

/** 提交 */
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitLoading.value = true
    let updatedData = null
    if (isCreate.value) {
      await EvaluationTemplateApi.createTemplate(formData)
      message.success('创建成功')
    } else {
      await EvaluationTemplateApi.updateTemplate(formData)
      message.success('更新成功')
      // 获取更新后的模板数据
      if (currentTemplateId.value) {
        updatedData = await EvaluationTemplateApi.getTemplate(currentTemplateId.value)
      }
    }
    dialogVisible.value = false
    emit('success', updatedData)
  } finally {
    submitLoading.value = false
  }
}

defineExpose({ open })
</script>
