import { isAndroid, isIOS, isXyqb } from './validation.service';
import Bridge from '@qg/js-bridge';
const jsBridge = new Bridge();
import Vue from 'vue';
import config from '@/config';
export const EventBus = new Vue();
/**
 * 替换邮箱字符
 * @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;
}

//返回拨打标签
export function regPhone(data) {
  const regExp = new RegExp(/((0\d{2,3}-\d{7,8})|(1[358674]\d{9}))/, 'g'); //匹配电话，以便能直接拨打
  const newData = data.replace(regExp, "<a class='tel' href='tel:$1'>$1</a>");
  return newData;
}

export function formatPhone(phone) {
  const reg = /^(\d{3})(\d{4})(\d{4})$/;
  const matches = reg.exec(phone);
  const newPhone = matches[1] + ' ' + matches[2] + ' ' + matches[3];
  return newPhone;
}

/**
 * @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); // 【暂时取掉】确定延时后没有聚焦下一元素，是由收起键盘引起的失焦，则强制让页面归位
          document.body.scrollTop = 0;
          document.documentElement.scrollTop = 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 throttle(fn, wait) {
  let flag = true;
  return function() {
    if (flag) {
      fn.apply(this, arguments);
      flag = false;
      setTimeout(() => {
        flag = true;
      }, wait);
    }
  };
}

export function changeTitleOfIOS() {
  if (isIOS) {
    const hackIframe = document.createElement('iframe');
    hackIframe.style.display = 'none';
    hackIframe.src = '/fixIosTitle.html?r=' + Math.random();
    document.body.appendChild(hackIframe);
    setTimeout(() => {
      document.body.removeChild(hackIframe);
    }, 300);
  }
}

export function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  // eslint-disable-next-line no-useless-escape
  name = name.replace(/[\[\]]/g, '\\$&');
  var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

// 清除键盘
export function clearKeyboard() {
  var input = document.getElementsByTagName('input');
  for (let i = 0; i < input.length; i++) {
    input[i].blur();
  }
  var textarea = document.getElementsByTagName('textarea');
  for (let i = 0; i < textarea.length; i++) {
    textarea[i].blur();
  }
}

export function idNoFormat(value) {
  return value.replace(/(\d{6})(\d{0,8})?(\d{0,4})?/, function(res, $1, $2, $3) {
    if (res.length <= 6) {
      return $1;
    }
    if (res.length <= 14) {
      return $1 + ' ' + $2;
    }
    return $1 + ' ' + $2 + ' ' + $3;
  });
}
export function dateFormat(value) {
  return value.replace(/(\d{4})(\d{2})(\d{2})/, '$1.$2.$3');
}

export function getQueryString(name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
  var r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}

// HEX转RGB
export function hexToRgb(hex) {
  var rgb = [];
  for (let i = 1; i < 7; i += 2) {
    rgb.push(parseInt('0x' + hex.slice(i, i + 2)));
  }
  return rgb;
}

export function setAppTitleColor(bgcolor = '#fff') {
  if (!isXyqb) return;
  const isGradient = Array.isArray(bgcolor);
  let rgbColor = isGradient ? bgcolor[0] : bgcolor;
  if (rgbColor.toLocaleLowerCase().indexOf('#') > -1) rgbColor = hexToRgb(rgbColor);
  const isDarkContent = 0.213 * rgbColor[0] + 0.715 * rgbColor[1] + 0.072 * rgbColor[2] <= 255 / 2;
  const colors = isGradient
    ? [bgcolor[0].substr(1), bgcolor[1].substr(1)]
    : [bgcolor.substr(1), bgcolor.substr(1)];
  jsBridge.run({
    event: 'resetNavigationBarColor',
    data: {
      isDarkContent,
      colors
    }
  });
}

export function getQueryParams(key) {
  var search = window.location.search;
  var regExp = new RegExp('[\\?\\&]([^\\?\\&]+)=([^\\?\\&]+)', 'ig');
  var queryStringList = {};
  var parttern;
  while ((parttern = regExp.exec(search))) {
    if (!queryStringList[parttern[1].toLowerCase()]) {
      queryStringList[parttern[1].toLowerCase()] = parttern[2];
    }
  }

  //返回指定键的值
  if (key) {
    return queryStringList[key.toLowerCase()] || '';
  }

  //返回所有查询参数
  return queryStringList;
}

export function paramsParentheses() {
  let paramsObj = getQueryParams();
  let tempString = '';
  // !h=0$activityId=39"
  for (let key in paramsObj) {
    let option = `${key}=${paramsObj[key]}`;
    tempString += `$${option}`;
  }
  if (tempString.length) {
    tempString = `${config.localHost}!` + tempString.slice(1);
  }
  return tempString;
}
