import Taro, { getStorageSync } from "@tarojs/taro";
import Schema, { Rules } from "async-validator";

export const TOKEN_KEY = "token";
export const NICKNAME_key = "nickname";

export const getSceneUrl = (scene?: number) => {
  const name = getStorageSync(NICKNAME_key);
  const token = getStorageSync(TOKEN_KEY);

  return `https://app.4dage.com/projects/wxcs/web/index.html?platform=wx&name=${name}&token=${token}${
    typeof scene === "number" ? `&scene=${scene}` : ""
  }`;
};

export const createRandomString = () => {
  const characters =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let randomString = "";
  for (let i = 0; i < 2; i++) {
    randomString += characters.charAt(
      Math.floor(Math.random() * characters.length)
    );
  }
  return randomString;
};

export const onValidateField = (value: any, rules: Rules) => {
  const validator = new Schema(rules);
  return new Promise<any>((resolve) => {
    validator.validate(value, (errors) => {
      if (errors) {
        resolve(errors);
      } else {
        const errMsg = Object.keys(rules).map((key) => {
          return {
            field: key,
            message: undefined,
          };
        });
        resolve(errMsg);
      }
    });
  });
};

export const handleValidate = async (params, formRules) => {
  const errors = await onValidateField(params, formRules);
  let valid = !errors || errors.filter((error) => error.message).length <= 0;

  if (!valid) {
    Taro.showToast({
      icon: "none",
      title: errors[0].message,
    });
    return false;
  }

  return true;
};

export function debounce(func: Function, time: number, immediate = false) {
  let timer: number | null = null;
  return (...args: any) => {
    if (timer) clearInterval(timer);
    if (immediate) {
      if (!timer) func.apply(this, args);
      timer = window.setTimeout(() => {
        timer = null;
      }, time);
    } else {
      timer = window.setTimeout(() => {
        func.apply(this, args);
      }, time);
    }
  };
}
