<template>
  <!-- 添加或修改项目信息对话框 -->
  <el-dialog title="设备类别" height="400px" v-model="visible" width="400px" append-to-body draggable>
    <div class="form-container">
      <el-form ref="formCategoryRef" v-loading="loading" class="master-container" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="父级类别" prop="parentId">
          <el-tree-select v-model="form.parentId" :data="parentCategories" check-strictly :render-after-expand="false" />
        </el-form-item>
        <el-form-item label="设备类别名称" prop="name">
          <el-input v-model.trim="form.name" placeholder="请输入设备类别名称" />
        </el-form-item>
        <el-form-item label="设备类别编号" prop="code">
          <el-input v-model.trim="form.code" placeholder="请输入设备类别编号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="form.remark" placeholder="请输入设备类别状态" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="1" controls-position="right" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button type="primary" icon="Check" @click="handleSave">确 定</el-button>
      <el-button icon="Close" @click="handleCancel">取 消</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { getCategory, saveCategory } from '@/api/business/equipment'

const emit = defineEmits(['handleSaveSuccess'])
const { proxy } = getCurrentInstance()
/** 父类别 */
const loading = ref(false)
const parentCategories = ref([])
const visible = ref(false)
const data = reactive({
  form: {},
  rules: {
    name: [{ required: true, message: '设备类别名称不能为空', trigger: 'blur' }],
    code: [{ required: true, message: '设备类别编号不能为空', trigger: 'blur' }]
  }
})
const { form, rules } = toRefs(data)
/***********************  方法区  ****************************/
/** 打开抽屉 */
function open(id) {
  reset()
  visible.value = true
  loading.value = true
  getCategory(id || 0).then((res) => {
    if (res.data.formData) {
      form.value = res.data.formData
    }
    parentCategories.value = res.data.parentOptions
    parentCategories.value.unshift({
      value: '0',
      label: '一级分类'
    })
    loading.value = false
  })
}

/** 取消按钮 */
function handleCancel() {
  visible.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    parentId: '0',
    code: '',
    name: '',
    remark: '',
    sort: 1
  }
  proxy.resetForm('formCategoryRef')
}

/** 提交按钮 */
function handleSave() {
  proxy.$refs['formCategoryRef'].validate((valid) => {
    if (valid) {
      saveCategory(form.value).then((res) => {
        if (res.code === 200) {
          proxy.$modal.msgSuccess('操作成功')
          emit('handleSaveSuccess')
        }
        visible.value = false
      })
    }
  })
}

/** 暴露给父组件的方法 */
defineExpose({
  open
})
</script>
