<template>
  <el-dialog :title="form.id ? '添加分类' : '编辑分类'" width="650px" v-model="visible" @close="closeHandle">
    <el-form ref="formRef" :rules="rules" :model="form" label-position="right" label-width="120px">
      <el-form-item label="分类名称" prop="name">
        <el-input placeholder="请输入分类名称" v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="分类图片">
        <SingleImageUpload v-model="form.pic" />
      </el-form-item>
      <el-form-item label="退菜是否退库存">
        <el-radio-group v-model="form.refundMode">
          <el-radio label="退菜退库存" :value="1"></el-radio>
          <el-radio label="仅退菜不退库存" :value="2"></el-radio>
          <el-radio label="每次询问-退菜后弹窗提示" :value="3"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="排序">
        <el-input-number v-model="form.sort" :min="1" :step="1"></el-input-number>
      </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="loading">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

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

const visible = ref(false)
const loading = ref(false)
const formRef = ref(null)
const form = ref({
  id: '',
  name: '',
  pic: '',
  refundMode: 1, // 退菜是否退库存 1退菜退库存 2仅退菜不退库存 3每次询问-退菜后弹窗提示
  sort: 1,
  status: 1
})
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>