import _ from "lodash";
import { customAlphabet } from "nanoid";
import config from "../constants/config";

export default {
  getAPI(module) {
    return `${config.BASE_URL}/${module}/v1`;
  },
  generateId() {
    // 生成随机id
    const nanoid = customAlphabet(
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
      10
    );
    return nanoid();
  },
  oneOf(value, validList) {
    return validList.includes(value)
  },
  // 拆分数据
  splitData(data) {
    let url = "";
    for (let k in data) {
      if (data.hasOwnProperty(k)) {
        let id = data[k].id || "";
        let value = data[k].value || "";
        url = url + "&" + id + "=" + encodeURIComponent(value);
      }
    }
    return url ? url.substring(1) : "";
  },
  // 拼接参数
  contractUrl(url, data) {
    return data.length > 0 ? url + "?" + this.splitData(data) : url;
  },
  readFile(file, readerType = "Text", unexpectedErrorMessage) {
    return new Promise((resolve, reject) => {
      const myUnexpectedErrorMessage =
        unexpectedErrorMessage || "Unexpected error";
      const reader = new FileReader();
      reader.addEventListener("load", (loadEvent) => {
        const result = _.get(loadEvent, ["target", "result"]);
        if (result) {
          resolve(result);
        } else {
          reject(new Error(myUnexpectedErrorMessage));
        }
      });
      reader.addEventListener("error", (errorEvent) => {
        reject(
          _.get(
            errorEvent,
            ["target", "error"],
            new Error(myUnexpectedErrorMessage)
          )
        );
      });
      if (readerType === "Text") {
        reader.readAsText(file);
      } else if (readerType === "ArrayBuffer") {
        reader.readAsArrayBuffer(file);
      }
    });
  },
  splitFileName: function (text) {
    var pattern = /\.{1}[a-z]{1,}$/;
    if (pattern.exec(text) !== null) {
      return text.slice(0, pattern.exec(text).index);
    } else {
      return text;
    }
  },
  getMouseDirection(e) {
    // 计算鼠标进入一个矩形div的方向，1，2，3，4分别代表上、右、下、左
    //表示左上角和右下角及中心点坐标
    var x1, y1, x4, y4, x0, y0;
    //表示左上角和右下角的对角线斜率
    var k;
    //用getBoundingClientRect比较省事，而且它的兼容性还不错
    var rect = e.target.getBoundingClientRect();
    if (!rect.width) {
      rect.width = rect.right - rect.left;
    }
    if (!rect.height) {
      rect.height = rect.bottom - rect.top;
    }
    //求各个点坐标 注意y坐标应该转换为负值，因为浏览器可视区域左上角为(0,0)，整个可视区域属于第四象限
    x1 = rect.left;
    y1 = -rect.top;
    x4 = rect.left + rect.width;
    y4 = -(rect.top + rect.height);
    x0 = rect.left + rect.width / 2;
    y0 = -(rect.top + rect.height / 2);
    //矩形不够大，不考虑
    if (Math.abs(x1 - x4) < 0.0001) return 4;
    //计算对角线斜率
    k = (y1 - y4) / (x1 - x4);
    var range = [k, -k];
    //表示鼠标当前位置的点坐标
    var x, y;
    x = e.clientX;
    y = -e.clientY;
    //表示鼠标当前位置的点与元素中心点连线的斜率
    var kk;
    kk = (y - y0) / (x - x0);
    //如果斜率在range范围内，则鼠标是从左右方向移入移出的
    if (isFinite(kk) && range[0] < kk && kk < range[1]) {
      //根据x与x0判断左右
      return x > x0 ? 1 : 3;
    } else {
      //根据y与y0判断上下
      return y > y0 ? 0 : 2;
    }
  },
  //格式化日期
  formatTime(date) {
    let json_date = new Date(date).toJSON();
    return new Date(new Date(json_date) + 8 * 3600 * 1000)
      .toISOString()
      .replace(/T/g, " ")
      .replace(/\.[\d]{3}Z/, "");
  },
  getStyle(element, styleName) {
    if (!isClient) return;
    if (!element || !styleName) return null;
    styleName = camelCase(styleName);
    if (styleName === "float") {
      styleName = "cssFloat";
    }
    try {
      const computed = document.defaultView.getComputedStyle(element, "");
      return element.style[styleName] || computed ? computed[styleName] : null;
    } catch (e) {
      return element.style[styleName];
    }
  },
};
