import { ElMessage } from "element-plus";
import { getDataType } from "@/assets/js/utils.js";

export default function (ref, message = "请补全必填项!") {
  const type = ["Function", "AsyncFunction"];
  if (!type.includes(getDataType(ref?.value?.validate)))
    throw new Error("不是有效的Element-Plus Form组件ref!");
  return new Promise((resolve, reject) => {
    ref.value.validate((valid) => {
      if (valid) {
        resolve(valid);
      } else {
        reject(valid);
        ElMessage.warning(message);
        setTimeout(() => {
          const element = document.querySelectorAll(".el-form-item__error")[0];
          element.scrollIntoView({
            behavior: "smooth",
            block: "center",
          });
        }, 100);
      }
    });
  });
}
