import { getBusiness } from "../api/business";

/* 
validators: function[] | {fn: function, tags: ['']}[]
*/
export function createValidator(validators) {
  return new Validator(validators);
}

class Validator {
  list = [];
  index = 0;
  _resolve = null;
  business = null;

  constructor(list) {
    if (Array.isArray(list)) this.list = list;
  }

  execute(data, options) {
    if (this.list.length == 0 || (options && options.notValid)) return Promise.resolve(true);
    return new Promise((resolve, reject) => {
      this._resolve = resolve;
      // 获取当前业务
      getBusiness().then((business) => {
        this.business = business;
        this.valid(data);
      });
    });
  }

  valid(data) {
    let fn = this.list[this.index];
    let result = null;
    if (typeof fn === "function") {
      result = fn(data);
    } else if (typeof fn === "object" && fn.fn) {
      if (Array.isArray(fn.tags) && fn.tags.length > 0) {
        if (fn.tags.includes(this.business)) {
          result = fn.fn(data);
        } else {
          result = true;
        }
      } else {
        result = fn.fn(data);
      }
    }
    // console.log('result',result)
    if (result instanceof Promise) {
      result.then((res) => {
        if (res) {
          this.sucess(data);
        } else {
          this.fail();
        }
      });
    } else if (typeof result === "boolean") {
      if (result) {
        this.sucess(data);
      } else {
        this.fail();
      }
    } else {
      console.warn(this.list[this.index], "验证函数的返回值有误，返回值应该为Boolean或Promise<Boolean>");
    }
  }

  sucess(data) {
    this.index++;
    if (this.index >= this.list.length) {
      this.index = 0;
      this._resolve(true);
      return;
    }
    this.valid(data);
  }

  fail() {
    this._resolve(false);
    this.index = 0;
  }
}
