<template>
  <!-- 添加或修改项目信息对话框 -->
  <el-dialog title="设备档案" height="400px" v-model="visible" width="400px" append-to-body draggable>
    <div class="form-container">
      <el-form ref="formEquipmentRef" v-loading="loading" class="master-container" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备名称" prop="equipmentName">
          <el-input v-model.trim="form.equipmentName" placeholder="请输入设备名称" required />
        </el-form-item>
        <el-form-item label="设备规格" prop="standard">
          <el-input v-model.trim="form.standard" placeholder="请输入规格型号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button type="primary" icon="Check" @click="handleSave">确 定</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { getEquipment, saveEquipment } from '@/api/business/equipment'

const { proxy } = getCurrentInstance()
const emit = defineEmits(['handleSaveSuccess'])

/** 表单抽屉 页变量 */
const loading = ref(false)
const visible = ref(false)
const data = reactive({
  form: {},
  rules: {
    equipmentName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
    standard: [{ required: true, message: '设备规格不能为空', trigger: 'blur' }]
  }
})
const { form, rules } = toRefs(data)

/** 设备类别id */
const categoryId = ref(0)
/***********************  方法区  ****************************/
/** 打开抽屉 */
function open(data) {
  reset()
  visible.value = true
  categoryId.value = data.categoryId
  getEquipment(data.id || 0).then((res) => {
    if (res.data) {
      form.value = res.data
    }
  })
}

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

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    equipmentName: '',
    standard: '',
    remark: ''
  }
  proxy.resetForm('formEquipmentRef')
}

/** 提交按钮 */
function handleSave() {
  proxy.$refs['formEquipmentRef'].validate((valid) => {
    if (valid) {
      form.value.equipmentCategoryId = categoryId.value
      saveEquipment(form.value).then((res) => {
        proxy.$modal.msgSuccess('修改成功')
        visible.value = false
        emit('handleSaveSuccess')
      })
    }
  })
}

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