<template>
  <el-dialog :title="form.id ? '编辑耗材类型' : '添加耗材类型'" width="600px" v-model="visible" @close="onClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120" label-position="right">
      <el-form-item label="耗材类型名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入耗材类型名称" :maxlength="20"></el-input>
      </el-form-item>
      <el-form-item label="启用">
        <el-switch v-model="form.status" :active-value="1" :inactive-value="0"></el-switch>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="handleOk" :loading="confirmLoading">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import _ from 'lodash'
import { ref } from 'vue'
import Api from "@/api/product/cons-group";

const visible = ref(false)
const formRef = ref(null)
const form = ref({
  name: '',
  status: 1
})

const rules = ref({
  name: [
    {
      required: true,
      message: '请输入耗材类型名称',
      trigger: 'blur'
    }
  ]
})

const emit = defineEmits(['success'])
const confirmLoading = ref(false)
function handleOk() {
  formRef.value.validate(async vaild => {
    try {
      if (vaild) {
        confirmLoading.value = true
        if (form.value.id) {
          await Api.edit(form.value)
          ElMessage.success('编辑成功')
        } else {
          await Api.add(form.value)
          ElMessage.success('添加成功')
        }
        emit('success')
        visible.value = false
      }
    } catch (error) {
      console.log(error);
    } finally {
      confirmLoading.value = false
    }
  })
}

function onClose() {
  formRef.value.resetFields()
  form.value.name = ''
  form.value.status = 1
}

function open(obj) {
  visible.value = true
  if (obj && obj.id) {
    form.value = _.cloneDeep(obj)
  }
}

defineExpose({ open })
</script>