<template>
  <!-- 添加或修改项目信息对话框 -->
  <el-dialog
      title="车间信息"
      v-model="visible"
      width="400px"
      append-to-body
      draggable
  >
    <div class="form-container">
      <el-form
          ref="workshopRef"
          class="master-container"
          :model="form"
          :rules="rules"
          label-width="100px"
      >
        <el-form-item label="车间名称" prop="name">
          <el-input v-model.trim="form.name" placeholder="请输入车间名称"/>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button type="primary" icon="Check" @click="submitForm"
      >确 定
      </el-button
      >
      <el-button icon="Close" @click="cancel">取 消</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import {getWorkshop, addWorkshop, updateWorkshop} from "@/api/business/workshop";

const {proxy} = getCurrentInstance();
const emit = defineEmits(["handleSaveSuccess"]);
/** 表单抽屉 页变量 */
const visible = ref(false);
const data = reactive({
  form: {},
  rules: {
    name: [
      {required: true, message: "车间名称不能为空", trigger: "blur"},
    ]
  },
});
const {form, rules} = toRefs(data);

/***********************  方法区  ****************************/
/** 打开抽屉 */
function open(row) {
  reset();
  visible.value = true;
  if (row) {
    getWorkshop(row.id).then((response) => {
      form.value = response.data;
    });
  }
}

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

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    name: "",

  };
  proxy.resetForm("workshopRef");
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["workshopRef"].validate((valid) => {
    if (valid) {
      if (form.value.id) {
        updateWorkshop(form.value).then((res) => {
          if (res.code === 200) {
            proxy.$modal.msgSuccess("保存成功");
            emit("handleSaveSuccess");
            visible.value = false;
          }
        });
      } else {
        addWorkshop(form.value).then((res) => {
          if (res.code === 200) {
            proxy.$modal.msgSuccess("添加成功");
            emit("handleSaveSuccess");
            visible.value = false;
          }
        });
      }
    }
  });
}

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