<template>
  <el-dialog
    :title="form.id ? '编辑考核指标' : '新增考核指标'"
    v-model="visible"
    :width="700"
    :close-on-click-modal="false"
    draggable>
    <el-form
      ref="dataFormRef"
      :model="form"
      :rules="dataRules"
      label-width="120px"
      v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="24" class="mb20">
          <el-form-item label="考核项" prop="categortyId">
            <el-select
              v-model="form.categortyId"
              placeholder="请选择考核项"
              clearable
              filterable
              style="width: 100%">
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.category"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="指标名称" prop="pointName">
            <el-input
              v-model="form.pointName"
              placeholder="请输入指标名称"
              clearable
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="评分标准" prop="standard">
            <el-input
              v-model="form.standard"
              type="textarea"
              :rows="4"
              placeholder="请输入评分标准"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="默认扣分值" prop="score">
            <el-input-number
              v-model="form.score"
              :min="0"
              :max="999"
              :precision="0"
              placeholder="请输入默认扣分值"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-model="form.remarks"
              type="textarea"
              :rows="4"
              placeholder="请输入备注"
              :maxlength="250"
              show-word-limit
              style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确 认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="AssessmentPointFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj, editObj, getDetail } from '/@/api/stuwork/assessmentpoint'
import { getList } from '/@/api/stuwork/assessmentcategory'

const emit = defineEmits(['refresh'])

// 定义变量内容
const dataFormRef = ref()
const visible = ref(false)
const loading = ref(false)
const operType = ref('add')
const categoryList = ref<any[]>([])

// 提交表单数据（与接口文档一致：edit 含 score 默认扣分值）
const form = reactive({
  id: '',
  categortyId: '',
  pointName: '',
  standard: '',
  score: undefined as number | undefined,
  remarks: ''
})

// 定义校验规则
const dataRules = {
  categortyId: [
    { required: true, message: '请选择考核项', trigger: 'change' }
  ],
  pointName: [
    { required: true, message: '请输入指标名称', trigger: 'blur' }
  ]
}

// 打开弹窗
const openDialog = async (type: string = 'add', row?: any) => {
  visible.value = true
  operType.value = type
  
    // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.id = ''
    form.categortyId = ''
    form.pointName = ''
    form.standard = ''
    form.score = undefined
    form.remarks = ''
    
    // 编辑时填充数据
    if (type === 'edit' && row) {
      form.id = row.id
      form.categortyId = row.categortyId || ''
      form.pointName = row.pointName || ''
      form.standard = row.standard || ''
      form.score = row.score !== undefined && row.score !== null ? Number(row.score) : undefined
      form.remarks = row.remarks || ''
      
      // 如果需要获取详情（含 score）
      if (row.id && (!row.pointName || row.standard === undefined || row.score === undefined)) {
        loading.value = true
        getDetail(row.id).then((res: any) => {
          if (res.data) {
            form.categortyId = res.data.categortyId || ''
            form.pointName = res.data.pointName || ''
            form.standard = res.data.standard || ''
            form.score = res.data.score !== undefined && res.data.score !== null ? Number(res.data.score) : undefined
            form.remarks = res.data.remarks || ''
          }
        }).catch(() => {}).finally(() => {
          loading.value = false
        })
      }
    }
  })
}

// 提交表单
const onSubmit = async () => {
  if (!dataFormRef.value) return
  
  await dataFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    loading.value = true
    try {
      // 与接口文档一致：categortyId, pointName, standard, score, remarks
      const submitData = {
        categortyId: form.categortyId,
        pointName: form.pointName,
        standard: form.standard || '',
        score: form.score !== undefined && form.score !== null ? Number(form.score) : 0,
        remarks: form.remarks || ''
      }
      
      if (operType.value === 'add') {
        await addObj(submitData)
        useMessage().success('新增成功')
      } else {
        await editObj({
          id: form.id,
          ...submitData
        })
        useMessage().success('编辑成功')
      }
      visible.value = false
      emit('refresh')
    } catch (err: any) {
      useMessage().error(err.msg || (operType.value === 'add' ? '新增失败' : '编辑失败'))
    } finally {
      loading.value = false
    }
  })
}

// 获取考核项列表
const getCategoryList = async () => {
  try {
    const res = await getList()
    if (res.data && Array.isArray(res.data)) {
      categoryList.value = res.data
    } else {
      categoryList.value = []
    }
  } catch (err) {
    categoryList.value = []
  }
}

// 初始化
onMounted(() => {
  getCategoryList()
})

// 暴露方法
defineExpose({
  openDialog
})
</script>

<style scoped lang="scss">
</style>

