function compareVersion(v1, v2) {
  v1 = v1.split(".");
  v2 = v2.split(".");
  const len = Math.max(v1.length, v2.length);

  while (v1.length < len) {
    v1.push("0");
  }
  while (v2.length < len) {
    v2.push("0");
  }

  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i]);
    const num2 = parseInt(v2[i]);

    if (num1 > num2) {
      return 1;
    } else if (num1 < num2) {
      return -1;
    }
  }

  return 0;
}
/**
 * 时间转换
 * @param {String} time 需要转换的时间
 * @param {String} cFormat 格式 {y}-{m}-{d} {h}:{i}:{s}
 * @return: {String} timeStr 转换完成的时间
 */
function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return "-";
  }
  if (time == null) {
    return "-";
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (time == "") {
    date = new Date();
  } else if (typeof time === "object") {
    date = time;
  } else if (!isNaN(time) && ("" + time).length === 10) {
    time = parseInt(time) * 1000;
  } else {
    if (String(time).indexOf("T") > -1) {
      time = time.replace(/T/g, " ").replace(/\..*/g, "");
    }
    if (
      (String(time).indexOf("-") > -1 || String(time).indexOf(".") > -1) &&
      String(time).indexOf("T") == -1
    ) {
      time = time.replace(/-|\./g, "/");
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    if (result.length > 0 && value < 10) {
      value = "0" + value;
    }
    return value || 0;
  });
  return timeStr;
}
const downApp =
  "https://a.app.qq.com/o/simple.jsp?pkgname=com.financial.quantgroup";

function setSubMsg(tmplIds = [], callback = () => {}) {
  wx.getSetting({
    withSubscriptions: true,
    success(res) {
      let {
        subscriptionsSetting: { mainSwitch, itemSettings },
      } = res;
      if (mainSwitch) {
        itemSettings = itemSettings || {};
        const vaildTmplIds = tmplIds.filter(
          (item) => !itemSettings[item] || itemSettings[item] !== "ban"
        );
        console.log(vaildTmplIds);
        vaildTmplIds.length &&
          wx.requestSubscribeMessage({
            tmplIds: vaildTmplIds,
            success() {
              callback();
            },
            fail(err) {
              console.error("requestSubscribeMessage", err);
              callback();
            },
          });
      }
    },
  });
}

function cleanArray(actual) {
  const newArray = [];
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i]);
    }
  }
  return newArray;
}

function param(json, mark) {
  if (!json) return "";
  const temp = cleanArray(
    Object.keys(json).map((key) => {
      if (json[key] === undefined) return "";
      return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
    })
  ).join("&");
  const str = mark && temp.length ? "?" : "";
  return str + temp;
}

function param2Obj(url) {
  const search = decodeURIComponent(url.replace(/\+/g, " "));
  if (!search) {
    return {};
  }
  const obj = {};
  const searchArr = search.split("&");
  searchArr.forEach((v) => {
    const index = v.indexOf("=");
    if (index !== -1) {
      const name = v.substring(0, index);
      const val = v.substring(index + 1, v.length);
      obj[name] = val;
    }
  });
  return obj;
}

function debounce(fn, interval, immediate) {
  let flag = true;
  const time = interval || 1000;
  let timer = null;
  return function () {
    if (!immediate) {
      timer && clearTimeout(timer);
      timer = setTimeout(() => {
        fn.apply(this, arguments);
      }, time);
    } else {
      if (flag) {
        fn.apply(this, arguments);
        flag = false;
        return;
      }
      timer && clearTimeout(timer);
      timer = setTimeout(() => {
        fn.apply(this, arguments);
      }, time);
    }
  };
}

function throtte(fn, interval, immediate) {
  let time = 0;
  let flag = true;
  return function () {
    if (immediate) {
      if (flag) {
        fn.apply(this, arguments);
        flag = false;
        time = Date.now();
        return;
      }
      if (Date.now() - time > interval) {
        fn.apply(this, arguments);
        time = Date.now();
      }
    } else {
      if (Date.now() - time > interval) {
        time = Date.now();
        fn.apply(this, arguments);
      }
    }
  };
}

function isNull(str) {
  return str === undefined || str.length === 0 || str === null;
}

function isPhone(str) {
  if (!isNull(str)) {
    const reg = /^1[3456789]\d{9}$/;
    return reg.test(str);
  }
  return false;
}

function isHttpLink(url) {
  return /https?:\/\//gi.test(url);
}

function jumpWebViewUrl(url, wechatUrl) {
  const pageLink = wechatUrl || "/pages/webview/webview";
  return `${pageLink}?url=${encodeURIComponent(JSON.stringify(url))}`;
}

function getAppId() {
  let appId = uni.getStorageSync("appId") || "";
  if (appId) {
    return appId;
  }
  // #ifdef MP-ALIPAY
  appId = uni.getAppIdSync().appId;
  // #endif

  // #ifndef MP-ALIPAY || H5
  const accountInfo = uni.getAccountInfoSync();
  appId = accountInfo.miniProgram.appId;
  // #endif

  uni.setStorageSync("appId", appId);
  return appId;
}

// eslint-disable-next-line prettier/prettier
export {
  compareVersion,
  parseTime,
  downApp,
  setSubMsg,
  param,
  param2Obj,
  debounce,
  throtte,
  isPhone,
  isHttpLink,
  jumpWebViewUrl,
  getAppId,
};
