<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="罪犯编号" prop="prisonerCode">
            <el-input v-model="formData.prisonerCode" placeholder="请输入罪犯编号" :disabled="formType === 'view'" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="罪犯姓名" prop="prisonerName">
            <el-input v-model="formData.prisonerName" placeholder="请输入罪犯姓名" :disabled="formType === 'view'" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="评估人" prop="assessor">
            <el-input v-model="formData.assessor" placeholder="请输入评估人" :disabled="formType === 'view'" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="评估类型" prop="assessmentType">
            <el-select v-model="formData.assessmentType" placeholder="请选择评估类型" :disabled="formType === 'view'">
              <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-col>
        <el-col :span="8">
          <el-form-item label="评估日期" prop="assessmentDate">
            <el-date-picker
              v-model="formData.assessmentDate"
              type="date"
              placeholder="请选择评估日期"
              value-format="YYYY-MM-DD"
              :disabled="formType === 'view'"
              class="!w-full"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="评估方式" prop="assessMethod">
            <el-select v-model="formData.assessMethod" placeholder="请选择评估方式" :disabled="formType === 'view'">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.PRISON_RISK_ASSESS_METHOD)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">风险评估</el-divider>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="综合得分" prop="overallScore">
            <el-input-number v-model="formData.overallScore" :min="0" :max="100" placeholder="0-100" :disabled="formType === 'view'" class="!w-full" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="风险等级" prop="riskLevel">
            <el-select v-model="formData.riskLevel" placeholder="请选择风险等级" :disabled="formType === 'view'">
              <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-col>
        <el-col :span="8">
          <el-form-item label="精神状态" prop="mentalState">
            <el-select v-model="formData.mentalState" placeholder="请选择精神状态" :disabled="formType === 'view'">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.PRISON_RISK_MENTAL_STATE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">风险指标</el-divider>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="脱逃风险" prop="escapeRisk">
            <el-select v-model="formData.escapeRisk" placeholder="请选择脱逃风险等级" :disabled="formType === 'view'">
              <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-col>
        <el-col :span="8">
          <el-form-item label="暴力倾向" prop="violenceRisk">
            <el-select v-model="formData.violenceRisk" placeholder="请选择暴力倾向等级" :disabled="formType === 'view'">
              <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-col>
        <el-col :span="8">
          <el-form-item label="抗改风险" prop="revoltRisk">
            <el-select v-model="formData.revoltRisk" placeholder="请选择抗改风险等级" :disabled="formType === 'view'">
              <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-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="自杀自伤" prop="selfHarmRisk">
            <el-select v-model="formData.selfHarmRisk" placeholder="请选择自杀自伤等级" :disabled="formType === 'view'">
              <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-col>
      </el-row>

      <el-divider content-position="left">评估结果</el-divider>

      <el-form-item label="结论" prop="conclusion">
        <el-input
          v-model="formData.conclusion"
          type="textarea"
          placeholder="请输入评估结论"
          :rows="3"
          :disabled="formType === 'view'"
        />
      </el-form-item>
      <el-form-item label="建议" prop="recommendation">
        <el-input
          v-model="formData.recommendation"
          type="textarea"
          placeholder="请输入管理建议"
          :rows="3"
          :disabled="formType === 'view'"
        />
      </el-form-item>
      <el-form-item label="项目得分" prop="itemScores">
        <el-input
          v-model="formData.itemScores"
          type="textarea"
          placeholder="请输入各评估项目得分，JSON格式"
          :rows="3"
          :disabled="formType === 'view'"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          placeholder="请输入备注"
          :rows="2"
          :disabled="formType === 'view'"
        />
      </el-form-item>
    </el-form>

    <!-- 查看详情时的信息展示 -->
    <template v-if="formType === 'view'">
      <el-divider content-position="left">详细信息</el-divider>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="创建时间">
          {{ formData.createTime ? formatDateTime(formData.createTime) : '-' }}
        </el-descriptions-item>
      </el-descriptions>
    </template>

    <template #footer>
      <el-button v-if="formType !== 'view'" @click="submitForm" type="primary" :disabled="formLoading">
        {{ formType === 'create' ? '新增' : '修改' }}
      </el-button>
      <el-button @click="dialogVisible = false">关闭</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { formatDateTime } from '@/utils/formatTime'
import { RiskApi, RiskSaveReqVO } from '@/api/prison/risk'

/** 风险评估 表单 */
defineOptions({ name: 'PrisonRiskForm' })

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

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

const formData = ref({
  id: undefined,
  prisonerId: undefined,
  prisonerCode: undefined,
  prisonerName: undefined,
  assessmentType: undefined,
  assessmentDate: undefined,
  assessMethod: undefined,
  overallScore: undefined,
  riskLevel: undefined,
  mentalState: undefined,
  escapeRisk: undefined,
  violenceRisk: undefined,
  revoltRisk: undefined,
  selfHarmRisk: undefined,
  recommendation: undefined,
  assessor: undefined,
  conclusion: undefined,
  itemScores: undefined,
  remark: undefined,
  createTime: undefined
})

const formRules = reactive({
  prisonerCode: [{ required: true, message: '请输入罪犯编号', trigger: 'blur' }],
  prisonerName: [{ required: true, message: '请输入罪犯姓名', trigger: 'blur' }],
  assessmentType: [{ required: true, message: '请选择评估类型', trigger: 'change' }],
  assessmentDate: [{ required: true, message: '请选择评估日期', trigger: 'change' }],
  riskLevel: [{ required: true, message: '请选择风险等级', trigger: 'change' }]
})

const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: 'create' | 'update' | 'view', id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'view' ? '查看详情' : t('action.' + type)
  formType.value = type

  resetForm()

  // 修改/查看时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await RiskApi.getRisk(id)
      formData.value = {
        id: data.id,
        prisonerId: data.prisonerId,
        prisonerCode: data.prisonerCode,
        prisonerName: data.prisonerName,
        assessmentType: data.assessmentType,
        assessmentDate: data.assessmentDate,
        assessMethod: data.assessMethod,
        overallScore: data.overallScore,
        riskLevel: data.riskLevel,
        mentalState: data.mentalState,
        escapeRisk: data.escapeRisk,
        violenceRisk: data.violenceRisk,
        revoltRisk: data.revoltRisk,
        selfHarmRisk: data.selfHarmRisk,
        recommendation: data.recommendation,
        assessor: data.assessor,
        conclusion: data.conclusion,
        itemScores: data.itemScores,
        remark: data.remark,
        createTime: data.createTime
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

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

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    prisonerId: undefined,
    prisonerCode: undefined,
    prisonerName: undefined,
    assessmentType: undefined,
    assessmentDate: undefined,
    assessMethod: undefined,
    overallScore: undefined,
    riskLevel: undefined,
    mentalState: undefined,
    escapeRisk: undefined,
    violenceRisk: undefined,
    revoltRisk: undefined,
    selfHarmRisk: undefined,
    recommendation: undefined,
    assessor: undefined,
    conclusion: undefined,
    itemScores: undefined,
    remark: undefined,
    createTime: undefined
  }
  formRef.value?.resetFields()
}
</script>
