<template>
  <div>
    <el-form ref="ruleFormRef" :rules="rules" :model="formData" label-width="120px">
      <el-form-item label="分类名称" prop="categoryName">
        <el-input v-model="formData.categoryName" placeholder="请输入分类名称" />
      </el-form-item>
      <el-form-item label="排列序号">
        <el-input v-model="formData.sort" placeholder="请输入排列序号" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
  import { ref } from 'vue'
  import { createPageData, editPageData } from '@/api/main/system/system';
  const { proxy } = getCurrentInstance();
  const props = defineProps({
    getDefaultInfo: {
      type: Object,
      default: () => ({}),
    }
  });
  const ruleFormRef = ref()
  const formData = ref({
    categoryName: '',
    sort: '',
  })
  const categoryId = ref()
  const rules = reactive({
    categoryName: [
      { required: true, message: '请输入分类名称', trigger: 'blur' },
    ]
  })
  watch(props, (nweProps) => {
    init(nweProps)
  });
  
  onMounted(() => {
    init(props)
  });
  function init(props) {
    categoryId.value = props.getDefaultInfo.categoryId
    if (categoryId.value) {
      getDetail(props.getDefaultInfo)
    } else {
      resetForm()
    }
  }
  const emit = defineEmits(["updateSuccess"]);
  function submitForm(formEl) {
    formEl.validate((valid, fields) => {
      if (valid) {
        if (categoryId.value) {
          editPageData('/quality/category', formData.value).then((data) => {
            proxy.$modal.msgSuccess('编辑成功！');
            emit('updateSuccess');
          })
        } else {
          createPageData('/quality/category', formData.value).then((data) => {
            proxy.$modal.msgSuccess('新增成功！');
            emit('updateSuccess');
          })
        }

      } else {
        console.log('error submit!', fields)
      }
    })
  }
  function getDetail(item) {
    formData.value.categoryId = item.categoryId
    formData.value.categoryName = item.categoryName
    formData.value.sort = item.sort
  }
  function resetForm() {
    formData.value.categoryId = ''
    formData.value.categoryName = ''
    formData.value.sort = ''
  }
</script>

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