<template>
  <el-dialog title="设备清单表单" v-model="visible" width="400px" height="500px" append-to-body draggable>
    <div class="form-container">
      <el-form ref="formDetailRef" v-loading="loading" class="master-container" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备编码" prop="equipmentCode">
          <el-input v-model="form.equipmentCode" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="使用部门" prop="usageDeptAlias">
          <el-input v-model="form.usageDeptAlias" placeholder="请选择使用部门">
            <template #append>
              <el-button icon="Search" @click="handleSelectDeptSingle" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button type="primary" @click="handleSave">确 定</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </template>

    <select-dept-dialog ref="selectDeptRef" @handleSelectDept="handleSelectDept" />
  </el-dialog>
</template>
<script setup>
import { getDetails, saveDetails } from '@/api/business/equipment'
import selectDeptDialog from '@/components/Dialog/Department'
const emit = defineEmits(['handleSaveSuccess'])

const { proxy } = getCurrentInstance()
/** 字典数组区 */
/** 表单抽屉 页变量 */
const loading = ref(false)
const visible = ref(false)
const data = reactive({
  form: {},
  rules: {
    equipmentCode: [{ required: true, message: '设备编码不能为空', trigger: 'blur' }],
    usageDeptAlias: [{ required: true, message: '使用部门不能为空', trigger: 'blur' }]
  }
})
const { form, rules } = toRefs(data)
/***********************  方法区  ****************************/
/** 打开抽屉 */
const open = (data) => {
  reset()
  visible.value = true
  form.value.equipmentId = data.equipmentId
  if (data.id) {
    getDetails(data.id).then((res) => {
      form.value = res.data
    })
  }
}

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

/** 表单重置 */
const reset = () => {
  form.value = {
    id: null,
    equipmentId: 0,
    equipmentCode: '',
    usageDeptId: 0,
    usageDeptCode: '',
    usageDeptAlias: '',
    equipmentStatusId: 0,
    equipmentStatusCode: '',
    remark: ''
  }
  proxy.resetForm('formDetailRef')
}

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

const handleSelectDeptSingle = () => {
  proxy.$refs['selectDeptRef'].open()
}

/** 选择部门回调 */
const handleSelectDept = (data) => {
  form.value.usageDeptId = data.deptId
  form.value.usageDeptCode = data.deptCode
  form.value.usageDeptAlias = data.deptName
}

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