<template>
  <el-dialog title="转运码新增" v-model="visible" width="400px" append-to-body draggable>
    <div class="form-container">
      <el-form ref="codeRef" class="master-container" :model="form" :rules="rules"
        label-width="80px">
        <el-form-item label="起始编码" prop="startCode">
          <el-input  v-model="form.startCode" style="width: 220px;" placeholder="请输入1-9或A-Z的一位字符"/>
        </el-form-item>
        <el-form-item label="生成数量" prop="num">
          <el-input-number  v-model="form.num" style="width: 220px;" min="1" max="999" :step="1" step-strictly
          :controls="false" placeholder="请输入1-999的数字" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button type="primary" icon="Check" @click="handleSave">确 定</el-button>
      <el-button icon="Close" @click="handleCancel">取 消</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { addTransferCode } from "@/api/business/transferCode";
const { proxy } = getCurrentInstance();
const emit = defineEmits(["handleSaveSuccess"]);
const visible = ref(false);
const data = reactive({
  form: {},
  rules: {
    startCode: [
          {
            validator: (rule, value, callback) => {
              console.log(!value);
              if (value === "") {
                callback(new Error('请输入内容')); // 空值提示
              } else if (!/^[1-9A-Z]$/.test(value)) {
                callback(new Error('只能输入1-9或A-Z的一位字符')); // 无效输入提示
              } else {
                callback(); // 校验通过
              }
            },
            trigger: 'blur'
          }
        ],
    num: [{ required: true, message: "生成数量不能为空", trigger: "blur" }]
  },
});
const { form, rules } = toRefs(data);

/***********************  方法区  ****************************/
/** 打开抽屉 */
function open(data) {
  reset();
  form.value.deptId = data
  visible.value = true;
}

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

/** 表单重置 */
function reset() {
  form.value = {
    deptId:null,
    startCode: null,
    num: null
  };
  proxy.resetForm("codeRef");
}

/** 提交按钮 */
function handleSave() {
  proxy.$refs["codeRef"].validate((valid) => {
    if (valid) {
      addTransferCode(form.value).then((res) => {
        if (res.code === 200) {
          proxy.$modal.msgSuccess("操作成功");
          emit("handleSaveSuccess");
        }
        visible.value = false;
      });
    }
  });
}

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