<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="罪犯" prop="prisonerId">
        <el-select
          v-model="formData.prisonerId"
          placeholder="请选择罪犯"
          filterable
          remote
          :remote-method="searchPrisoner"
          :loading="prisonerLoading"
          @change="handlePrisonerChange"
          style="width: 100%"
        >
          <el-option
            v-for="prisoner in prisonerList"
            :key="prisoner.id"
            :label="`${prisoner.name} (${prisoner.prisonerNo})`"
            :value="prisoner.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="评估类型" prop="assessmentType">
        <el-select v-model="formData.assessmentType" placeholder="请选择评估类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PRISON_RISK_ASSESSMENT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="评估日期" prop="assessmentDate">
        <el-date-picker
          v-model="formData.assessmentDate"
          type="date"
          value-format="x"
          placeholder="选择评估日期"
        />
      </el-form-item>
      <el-form-item label="暴力倾向得分" prop="violenceScore">
        <el-input v-model="formData.violenceScore" placeholder="请输入暴力倾向得分" />
      </el-form-item>
      <el-form-item label="脱逃倾向得分" prop="escapeScore">
        <el-input v-model="formData.escapeScore" placeholder="请输入脱逃倾向得分" />
      </el-form-item>
      <el-form-item label="自杀倾向得分" prop="suicideScore">
        <el-input v-model="formData.suicideScore" placeholder="请输入自杀倾向得分" />
      </el-form-item>
      <el-form-item label="综合得分" prop="totalScore">
        <el-input v-model="formData.totalScore" placeholder="请输入综合得分" />
      </el-form-item>
      <el-form-item label="风险等级" prop="riskLevel">
        <el-select v-model="formData.riskLevel" placeholder="请选择风险等级">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PRISON_RISK_LEVEL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="风险因素" prop="riskFactors">
        <el-input v-model="formData.riskFactors" placeholder="请输入风险因素" />
      </el-form-item>
      <el-form-item label="管控建议" prop="suggestions">
        <el-input v-model="formData.suggestions" placeholder="请输入管控建议" />
      </el-form-item>
      <el-form-item label="评估人ID" prop="assessorId">
        <el-input v-model="formData.assessorId" placeholder="请输入评估人ID" />
      </el-form-item>
      <el-form-item label="评估人姓名" prop="assessorName">
        <el-input v-model="formData.assessorName" placeholder="请输入评估人姓名" />
      </el-form-item>
      <el-form-item label="下次评估日期" prop="nextAssessmentDate">
        <el-date-picker
          v-model="formData.nextAssessmentDate"
          type="date"
          value-format="x"
          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_SCORE_STATUS)"
            :key="dict.value"
            :value="dict.value"
          >{{ dict.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { RiskAssessmentApi, RiskAssessment } from '@/api/prison/riskassessment'
import { PrisonerApi, PrisonerVO } from '@/api/prison/prisoner'

/** 危险评估 表单 */
defineOptions({ name: 'RiskAssessmentForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

// 罪犯选择相关
const prisonerLoading = ref(false)
const prisonerList = ref<PrisonerVO[]>([])

const formData = ref({
  id: undefined,
  prisonerId: undefined as number | undefined,
  prisonerNo: undefined as string | undefined,
  assessmentType: undefined as number | undefined,
  assessmentDate: undefined as number | undefined,
  violenceScore: undefined as number | undefined,
  escapeScore: undefined as number | undefined,
  suicideScore: undefined as number | undefined,
  totalScore: undefined as number | undefined,
  riskLevel: undefined as number | undefined,
  riskFactors: undefined as string | undefined,
  suggestions: undefined as string | undefined,
  assessorId: undefined as number | undefined,
  assessorName: undefined as string | undefined,
  nextAssessmentDate: undefined as number | undefined,
  status: 1 as number | undefined,
  remark: undefined as string | undefined
})
const formRules = reactive({
  prisonerId: [{ required: true, message: '罪犯不能为空', trigger: 'change' }],
  assessmentType: [{ required: true, message: '评估类型不能为空', trigger: 'change' }],
  assessmentDate: [{ required: true, message: '评估日期不能为空', trigger: 'change' }],
  riskLevel: [{ required: true, message: '风险等级不能为空', trigger: 'change' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 搜索罪犯 */
const searchPrisoner = async (query: string) => {
  if (!query) {
    prisonerList.value = []
    return
  }
  prisonerLoading.value = true
  try {
    const data = await PrisonerApi.getPage({
      pageNo: 1,
      pageSize: 20,
      name: query // 按姓名搜索
    } as any)
    prisonerList.value = data.list || []
  } catch (error) {
    console.error('搜索罪犯失败:', error)
    prisonerList.value = []
  } finally {
    prisonerLoading.value = false
  }
}

/** 罪犯选择变化 */
const handlePrisonerChange = async (prisonerId: number) => {
  const prisoner = prisonerList.value.find(p => p.id === prisonerId)
  if (prisoner) {
    formData.value.prisonerNo = prisoner.prisonerNo
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await RiskAssessmentApi.getRiskAssessment(id)
      // 加载已选罪犯信息
      if (formData.value.prisonerId) {
        const prisoner = await PrisonerApi.getPrisoner(formData.value.prisonerId)
        prisonerList.value = [prisoner]
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RiskAssessment
    if (formType.value === 'create') {
      await RiskAssessmentApi.createRiskAssessment(data)
      message.success(t('common.createSuccess'))
    } else {
      await RiskAssessmentApi.updateRiskAssessment(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    prisonerId: undefined,
    prisonerNo: undefined,
    assessmentType: undefined,
    assessmentDate: undefined,
    violenceScore: undefined,
    escapeScore: undefined,
    suicideScore: undefined,
    totalScore: undefined,
    riskLevel: undefined,
    riskFactors: undefined,
    suggestions: undefined,
    assessorId: undefined,
    assessorName: undefined,
    nextAssessmentDate: undefined,
    status: 1,
    remark: undefined
  }
  prisonerList.value = []
  formRef.value?.resetFields()
}
</script>