<template>
  <el-dialog title="绑定桌码" v-model="dialogVisible" width="30%" @close="reset">
    <el-form :model="form" :rules="rules" ref="refForm">
      <el-form-item label="桌码" prop="tableCode">
        <el-input
          autofocus
          ref="refTableCode"
          v-model="form.tableCode"
          placeholder="请输入桌码"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import shopTableApi from "@/api/account/table";
const dialogVisible = ref(false);

const form = reactive({
  id: "",
  tableCode: "",
});
const rules = {
  tableCode: [{ required: true, message: "请输入桌码", trigger: "blur" }],
};
const refForm = ref(null);

function reset() {
  refForm.value.resetFields();
  for (let i in form) {
    form[i] = "";
  }
}

const refTableCode = ref(null);
function open(item) {
  dialogVisible.value = true;
  nextTick(() => {
    setTimeout(() => {
      refTableCode.value.focus();
    }, 100);
  });
  form.tableCode = item.tableCode;
  form.id = item.id;
}

const emits = defineEmits(["refresh"]);
function submitForm() {
  refForm.value.validate((valid) => {
    if (valid) {
      shopTableApi
        .bindTableCode(form)
        .then((res) => {
          ElMessage({
            type: res ? "success" : "error",
            message: res ? "绑定成功" : "绑定失败",
          });
          if (res) {
            close();
            emits("refresh");
          }
        })
        .catch((error) => {
          console.log(error);
        });
    }
  });
}
function close() {
  dialogVisible.value = false;
}
defineExpose({
  open,
  close,
});
</script>