<template>
  <el-dialog :title="form.id ? '添加单位' : '编辑单位'" width="500px" v-model="visible" @close="closeHandle">
    <el-form ref="formRef" :rules="rules" :model="form" label-position="right" label-width="80px">
      <el-form-item label="单位名称" prop="name">
        <el-input placeholder="请输入单位名称" v-model="form.name"></el-input>
      </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="loading">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import _ from 'lodash'
import { ref } from 'vue'
import UserAPI from "@/api/product/commonUnits";

const visible = ref(false)
const loading = ref(false)
const formRef = ref(null)
const form = ref({
  id: '',
  name: ''
})
const rules = ref({
  name: [
    {
      required: true,
      message: '请输入单位名称',
      trigger: 'blur'
    }
  ]
})

const emit = defineEmits(['success'])
function handleOk() {
  formRef.value.validate(async (valid) => {
    try {
      if (valid) {
        loading.value = true
        if (form.value.id == '') {
          await UserAPI.addunit(form.value)
        } else {
          await UserAPI.update(form.value)
        }
        setTimeout(() => {
          visible.value = false
          ElMessage.success(form.value.id ? '添加成功' : '编辑成功')
          emit('success')
        }, 500);
      }
    } catch (error) {
      console.log(error);
    } finally {
      setTimeout(() => {
        loading.value = false
      }, 500);
    }
  })
}

function closeHandle() {
  form.value.name = ''
}

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

defineExpose({
  open
})
</script>