<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="800px" @close="cancel">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formData.itemType=='3'?formRules:formRules1"
      label-width="120px"
      v-loading="formLoading"
      :validate-on-rule-change="false"
      :key="formData.itemType"

    >
      <el-row :gutter="15">
        <el-col :span="12">
          <el-form-item label="编号" prop="itemNo">
            <el-input v-model="formData.itemNo" placeholder="请输入检验项编号" class="!w-240px"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="名称" prop="itemName">
            <el-input v-model="formData.itemName" placeholder="请输入名称" class="!w-240px"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="15">
        <el-col :span="12">
          <el-form-item label="性质" prop="nature">
            <el-radio-group v-model="formData.nature">
              <el-radio
                v-for="dict in getStrDictOptions(DICT_TYPE.NATURE)"
                :key="dict.value"
                :label="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位" prop="unitName">
            <el-input v-model="formData.unitName" placeholder="请输入单位" class="!w-240px"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="15">
        <el-col :span="12">
          <el-form-item label="检验值类型" prop="itemValueType">
            <el-select v-model="formData.itemValueType" placeholder="请选择检验值类型" @change="handleItemValueTypeChange">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.TEST_VALUE_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="适用类型" prop="itemType">
            <el-select v-model="formData.itemType" placeholder="请选择适用类型" @change="handleItemTypeChange">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.MAT_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="15">
        <el-col :span="12">
          <el-form-item label="检验值数量" prop="testNum">
            <el-input v-model="formData.testNum" placeholder="请输入检验值数量" class="!w-240px"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="绑定值" prop="itemContent">
            <el-input v-model="formData.itemContent" class="!w-240px" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="15">
        <el-col :span="12">
          <el-form-item label="是否取平均值" prop="printAvgValues">
            <el-radio-group v-model="formData.printAvgValues">
              <el-radio
                v-for="dict in getStrDictOptions(DICT_TYPE.SYSTEM_IS_CELL)"
                :key="dict.value"
                :label="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="小数位数" prop="floatNum">
            <el-input v-model="formData.floatNum" placeholder="请输入小数位数" class="!w-240px" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="15">
        <el-col :span="12">
          <el-form-item label="检验大类" prop="itemClass">
          <el-select v-model="formData.itemClass" placeholder="请选择检验大类" v-if="formData.itemType=='3'">
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.FINISHED_PRODUCT_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
          <el-select v-model="formData.itemClass" placeholder="请选择检验大类" v-if="formData.itemType=='1'">
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.RAW_MATERIALS_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
          <el-select v-model="formData.itemClass" placeholder="请选择检验大类" v-if="formData.itemType=='2'||!formData.itemType" disabled/>
        </el-form-item>
      </el-col>
      </el-row>
      <el-row :gutter="15">
        <el-col :span="24">
          <el-form-item label="检验方法" prop="checkMethod">
            <el-input type="textarea" :rows="4" v-model="formData.checkMethod" placeholder="请输入检验方法"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="15">
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" :rows="4" v-model="formData.remark" placeholder="请输入备注"/>
          </el-form-item>
        </el-col>
      </el-row>


    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {getStrDictOptions, DICT_TYPE, getIntDictOptions} from '@/utils/dict'
import * as CheckItemApi from '@/api/biz/checkitem'

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 formData = ref({
  id: undefined as number | undefined,
  itemNo: undefined as string | undefined,
  itemName: undefined as string | undefined,
  nature: undefined as string | undefined,
  unitName: undefined as string | undefined,
  checkMethod: undefined as string | undefined,
  remark: undefined as string | undefined,
  itemType: undefined as string | undefined,
  itemClass: undefined as string | undefined,
  itemValueType: undefined as string | undefined,
  itemContent: undefined as string | undefined,
  testNum: undefined as string | undefined,
  floatNum: undefined as number | string | undefined,
  printAvgValues: "0" as string | undefined,
})
const formRules = reactive({
  itemName: [
    { required: true, message: '请输入名称', trigger: 'blur' }
  ],
  nature: [
    { required: true, message: '性质不能为空', trigger: 'change' }
  ],
  itemType: [
    { required: true, message: '请选择适用类型', trigger: 'change' }
  ],
  itemContent: [
    { pattern: /^[\w\u4e00-\u9fa5]+(,[\w\u4e00-\u9fa5]+)*$/, message: '格式错误', trigger: 'blur' }
  ],
  itemClass: [
    { required: true, message: '检验大类', trigger: 'change' }
  ]
})
const formRules1 = reactive({
  itemName: [
    { required: true, message: '请输入名称', trigger: 'blur' }
  ],
  nature: [
    { required: true, message: '性质不能为空', trigger: 'change' }
  ],
  itemType: [
    { required: true, message: '请选择适用类型', trigger: 'change' }
  ],
  itemContent: [
    { pattern: /^[\w\u4e00-\u9fa5]+(,[\w\u4e00-\u9fa5]+)*$/, message: '格式错误', trigger: 'blur' }
  ]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
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 CheckItemApi.getCheckItem(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 适用类型变化 */
const handleItemTypeChange = () => {
  formData.value.itemClass = undefined
}

/** 检验值类型变化 */
const handleItemValueTypeChange = (row: string) => {
  if (row === 'I') {
    formData.value.floatNum = 2
  } else {
    formData.value.floatNum = ''
  }
}
const cancel = async () => {
  dialogVisible.value = false
  emit('success')
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 额外校验
  if (formData.value.itemValueType === 'I' && formData.value.itemContent != null && formData.value.itemContent !== '') {
    message.error('检验值类型为数字类型,绑定值必须为空,请确认')
    return
  }
  if (formData.value.itemValueType === 'T' && formData.value.floatNum != null && formData.value.floatNum !== '') {
    message.error('检验值类型为文本类型,小数位数必须为空,请确认')
    return
  }
  if (formData.value.itemValueType === 'I' && (formData.value.floatNum == null || formData.value.floatNum === '')) {
    message.error('检验值类型为数字类型,小数位数必须输入,请确认')
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CheckItemApi.CheckItemVO
    if (formType.value === 'create') {
      await CheckItemApi.createCheckItem(data)
      message.success(t('common.createSuccess'))
    } else {
      await CheckItemApi.updateCheckItem(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    itemNo: undefined,
    itemName: undefined,
    nature: undefined,
    unitName: undefined,
    checkMethod: undefined,
    remark: undefined,
    itemType: undefined,
    itemClass: undefined,
    itemValueType: undefined,
    itemContent: undefined,
    testNum: undefined,
    floatNum: undefined,
    printAvgValues: "0",
  }
  formRef.value?.resetFields()
}
</script>
