<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="70px">
        <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="form.name" placeholder="请输入设备类别名称" />
        </el-form-item>
        <el-form-item label="类别编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入设备类别名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="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" @click="handleSave">确 定</el-button>
      <el-button @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: {}
})
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>
