import sa from "sa-sdk-javascript";
import { isAndroid, isIOS } from "./validation";
import localStorage from "@/service/localStorage";
import settings from "@/api/settings";

/**
 * 替换邮箱字符
 * @param {String} email 输入字符串
 * @return: {Function} new_email 邮箱
 */
export function regEmail(email) {
  if (String(email).indexOf("@") > 0) {
    const str = email.split("@");
    let _s = "";
    if (str[0].length > 3) {
      for (var i = 0; i < str[0].length - 3; i++) {
        _s += "*";
      }
    }
    var new_email = str[0].substr(0, 3) + _s + "@" + str[1];
  }
  return new_email;
}

/**
 * 替换手机字符
 * @param {String} mobile 输入字符串
 * @return: {Function} new_email 邮箱
 */
export function regMobile(mobile) {
  if (mobile.length > 7) {
    var new_mobile = mobile.substr(0, 3) + "****" + mobile.substr(7);
  }
  return new_mobile;
}

/**
 * 去除两侧空格
 * @param {String} s 输入字符串
 * @return: {Function} new_email 邮箱
 */
export function stringTrim(s) {
  s = stringTrimLeft(s);
  return stringTrimRight(s);
}

/**
 * 去除左侧空格
 * @param {String} s 输入字符串
 * @return: {Function} new_email 邮箱
 */
export function stringTrimLeft(s) {
  return s.replace(/^[\s\n\t]+/g, "");
}

/**
 * 去除右侧空格
 * @param {String} s 输入字符串
 * @return: {Function} new_email 邮箱
 */
export function stringTrimRight(s) {
  return s.replace(/[\s\n\t]+$/g, "");
}

/**
 * 只能输入中文、英文、数字
 * @param {String} str 输入字符串
 * @return: {String} new_stremail 中文、英文、数字
 */
export function filterSc(str) {
  // eslint-disable-next-line
  return str.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g, "");
}

/**
 * 字符长度（中文）
 * @param  {String} str 输入字符串
 * @return: {Number} len 长度
 */
export function strLen(str) {
  var len = 0;
  for (var i = 0; i < str.length; i++) {
    var c = str.charCodeAt(i);
    //单字节加1
    if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
      len++;
    } else {
      len += 2;
    }
  }
  return len;
}

/**
 * 替换emoji表情
 * @param {String} name 输入字符串
 * @return: {String} str 字符串
 */
export function filterEmoji(name) {
  // eslint-disable-next-line
  let str = name.replace(
    // eslint-disable-next-line
    /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/gi,
    ""
  );
  return str;
}

/**
 * hash路由获取url参数
 * @param {String} searchString  输入字符串
 * @return: {String} str 字符串
 */
export function parseSearch(searchString) {
  if (!searchString) {
    return {};
  }
  if (!searchString.includes("?")) {
    return {};
  }
  return searchString
    .split("?")[1]
    .split("#")[0]
    .split("&")
    .reduce((result, next) => {
      const pair = next.split("=");
      try {
        result[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
      } catch (e) {
        // eslint-disable-next-line
        //   result[decodeURIComponent(pair[0])] = window.$URL.decode(pair[1]);
      }
      return result;
    }, {});
}
/**
 * 时间转换
 * @param {String} time 需要转换的时间
 * @param {String} cFormat 格式 {y}-{m}-{d} {h}:{i}:{s}
 * @return: {String} timeStr 转换完成的时间
 */
export 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;
}

/**
 * @description: 根据日期获取真实年龄，精确到天
 * @param {String} strBirthday 日期“1990-01-01”
 * @return {String} returnAge 返回年龄
 */
export function getRealAge(strBirthday) {
  var returnAge,
    strBirthdayArr = strBirthday.split("-"),
    birthYear = +strBirthdayArr[0],
    birthMonth = +strBirthdayArr[1],
    birthDay = +strBirthdayArr[2],
    d = new Date(),
    nowYear = d.getFullYear(),
    nowMonth = d.getMonth() + 1,
    nowDay = d.getDate();
  if (nowYear == birthYear) {
    returnAge = 0; //同年 则为0周岁
  } else {
    var ageDiff = nowYear - birthYear; //年之差
    if (ageDiff > 0) {
      if (nowMonth == birthMonth) {
        var dayDiff = nowDay - birthDay; //日之差
        if (dayDiff < 0) {
          returnAge = ageDiff - 1;
        } else {
          returnAge = ageDiff;
        }
      } else {
        var monthDiff = nowMonth - birthMonth; //月之差
        if (monthDiff < 0) {
          returnAge = ageDiff - 1;
        } else {
          returnAge = ageDiff;
        }
      }
    } else {
      returnAge = -1; //返回-1 表示出生日期输入错误 晚于今天
    }
  }
  return returnAge; //返回周岁年龄
}

/**
 * @description: 根据身份证号获取生日日期
 * @param {String} idCard 身份证号
 * @return {String} birthday 生日日期
 */
export function getBirthDate(idCard) {
  let birthday = "";
  if (idCard) {
    if (idCard.length == 15) {
      birthday = "19" + idCard.substr(6, 6);
    } else if (idCard.length == 18) {
      birthday = idCard.substr(6, 8);
    }

    birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-");
  }

  if (birthday && !isValidDate(new Date(birthday))) {
    birthday = "";
  }

  return birthday;
}

/**
 * @description: 移动端监听软键盘弹起或收起，IOS，android
 * @param  {Boolean} off 是否销毁
 * @return {Function} callback 软键盘弹起或收取回调, true => 弹起， false => 隐藏
 */

export function onKeyboardStateChange(callback = () => {}, off = false) {
  if (isIOS) {
    let isReset = true; //是否归位

    const focusinHandler = () => {
      isReset = false; //聚焦时键盘弹出，焦点在输入框之间切换时，会先触发上一个输入框的失焦事件，再触发下一个输入框的聚焦事件
      callback(true);
    };

    const focusoutHandler = () => {
      isReset = true;
      setTimeout(() => {
        //当焦点在弹出层的输入框之间切换时先不归位
        if (isReset) {
          // window.scroll(0, 0); // 【暂时取掉】确定延时后没有聚焦下一元素，是由收起键盘引起的失焦，则强制让页面归位
          callback(false);
        }
      }, 30);
    };
    if (off) {
      document.body.removeEventListener("focusin", focusinHandler);
      document.body.removeEventListener("focusout", focusoutHandler);
    } else {
      document.body.addEventListener("focusin", focusinHandler);
      document.body.addEventListener("focusout", focusoutHandler);
    }
  }

  if (isAndroid) {
    const originHeight = document.documentElement.clientHeight || document.body.clientHeight;
    const resizeHandler = () => {
      const resizeHeight = document.documentElement.clientHeight || document.body.clientHeight;
      const activeElement = document.activeElement;
      if (resizeHeight < originHeight) {
        // 键盘弹起后逻辑
        if (
          activeElement &&
          (activeElement.tagName === "INPUT" || activeElement.tagName === "TEXTAREA")
        ) {
          setTimeout(() => {
            activeElement.scrollIntoView({ block: "center" }); //焦点元素滚到可视区域的问题
          }, 0);
          callback(true);
        }
      } else {
        // 键盘收起后逻辑
        callback(false);
      }
    };
    if (off) {
      window.removeEventListener("resize", resizeHandler);
    } else {
      window.addEventListener("resize", resizeHandler);
    }
  }
}

// 校验是否合法日期
export function isValidDate(date) {
  return date instanceof Date && !isNaN(date.getTime());
}

// 神策注册公共属性
export function registerSa() {
  const saObj = { platformType: "H5" };

  // 获取distinctId
  sa.quick("isReady", function() {
    const distinctId = sa.quick("getAnonymousID");
    localStorage.set("distinctId", distinctId);
  });

  // 添加公共属性
  sa.registerPage(saObj);
  // 登陆埋点
  loginSa();
}

// 用户登录神策埋点
export function loginSa(uuid = localStorage.get("uuid")) {
  if (!uuid) return;
  localStorage.set("uuid", uuid);
  sa.login(uuid);
}

export function getSobot() {
  const distinctId = localStorage.get("distinctId");
  return distinctId ? `${settings.sobot}&partnerid=${distinctId}` : settings.sobot;
}
