import * as FETCH from "api/virtual/fetch";
import PinyinEngine from "pinyin-engine";

export default {
  data() {
    return {
      completeCompanyInitialized: false,
      completeCompaniesPinyinEngine: null,
      completeCompanies: [],
      completeHandledCompanies: [],
      completePackageInitialized: false,
      completePackagesPinyinEngine: null,
      completePackages: [],
      completeHandledPackages: []
    };
  },
  methods: {
    handleComplete(array, value = "", key = "name", indexKey = "id") {
      if (value === "" || value === null) {
        return array;
      }

      const pinyinEngine = new PinyinEngine(array, [key]);

      let res = [];

      res = pinyinEngine.query(value);

      res = array.filter(item => {
        return (
          item.name.toLowerCase().indexOf(value.toLowerCase()) !== -1 ||
          res.find(element => {
            return element[indexKey] === item[indexKey];
          })
        );
      });

      return res;
    },
    initCompleteCompanies() {
      return new Promise((resolve, reject) => {
        if (!this.completeCompanyInitialized) {
          this.completeCompanyInitialized = true;
          FETCH.companies().then(res => {
            if (res.code === 0) {
              this.completeCompanies = res.data;
              resolve(res.data);
            }

            reject(res);
          });
        } else {
          resolve(this.completeCompanies);
        }
      });
    },
    handleCompleteCompanies(value) {
      return new Promise((resolve, reject) => {
        this.initCompleteCompanies().then(() => {
          this.completeHandledCompanies = this.handleComplete(
            this.completeCompanies,
            value
          );
          resolve(this.completeHandledCompanies);
        });
      });
    },
    initCompletePackages(type = null) {
      return new Promise((resolve, reject) => {
        if (!this.completePackageInitialized) {
          FETCH.packages().then(res => {
            if (res.code === 0) {
              this.completePackageInitialized = true;

              type = type instanceof Array ? type : [type];
              this.completePackages = res.data.filter(el => {
                if (type !== null && type.indexOf(el.type) === -1) {
                  return false;
                }
                return true;
              });
              resolve(this.completePackages);
            }

            reject(res);
          });
        } else {
          resolve(this.completePackages);
        }
      });
    },
    handleCompletePackages(type = 0, value) {
      type = type == 1 ? 0 : type;

      return new Promise((resolve, reject) => {
        this.initCompletePackages(type).then(() => {
          this.completeHandledPackages = this.handleComplete(
            this.completePackages,
            value
          );
          resolve(this.completeHandledPackages);
        });
      });
    }
  }
};
