/* eslint-disable prettier/prettier */
import { isAndroid, isIOS } from './validation.service';
import Cookies from './cookieStorage.service';
import 'dingtalk-jsapi/entry/mobile'; // 只引入移动端（支持小程序）
import ddSetTitle from 'dingtalk-jsapi/api/biz/navigation/setTitle'; // 按需引入方法
import localStorage from './localStorage.service';
import Vue from 'vue';

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;
}
export function formatMaskPhone(phone) {
  const reg = /(\d{3})\d{4}(\d{4})/;
  return phone.replace(reg, '$1****$2') || '';
}

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

export function onKeyboardStateChange(
  callback = () => {
    return;
  },
  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 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) {
  // eslint-disable-next-line prettier/prettier
  // eslint-disable-next-line space-before-function-paren
  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;
}

export const getMonthAdd0 = m => {
  return m < 10 ? '0' + m : m;
};

export const isPhone = str => {
  if (str) {
    const reg = new RegExp('^1[3456789]\\d{9}$');
    return reg.test(str);
  }
  return false;
};

export function throttle(fn, wait) {
  let flag = true;
  return function() {
    if (flag) {
      fn.apply(this, arguments);
      flag = false;
      setTimeout(() => {
        flag = true;
      }, wait);
    }
  };
}

export function getType(n) {
  const str = Object.prototype.toString.call(n);
  return str.slice(8, str.length - 1);
}

// 深拷贝
export function deepCopy(d) {
  let obj = {};
  let _type = getType(d);
  if (_type === 'Date') {
    return new Date(d);
  } else if (_type === 'RegExp') {
    return new RegExp(d.source, d.flags);
  } else if (_type === 'Function') {
    return function() {
      return d.apply(this, arguments);
    };
  } else if (_type === 'NodeList') {
    return d.cloneNode(true);
  } else if (_type === 'Object') {
    for (let o in d) {
      obj[o] = deepCopy(d[o]);
    }
  } else if (_type === 'Array') {
    obj = [];
    for (let i in d) {
      obj[i] = deepCopy(d[i]);
    }
  } else {
    return d;
  }
  return obj;
}

// 链接跳转，增加参数，app跳转
const localStorageParams = ['vccToken', 'vccChannel', 'sonVccChannel', 'tenantId'];
const cookiesParams = ['h'];
let navTimer = null;
export function locationHrefPatchDelay(url = '', from = '') {
  if (navTimer) clearTimeout(navTimer);
  navTimer = setTimeout(() => {
    locationHrefPatch(url, from);
  }, 300);
}
const H5_URL_MAP = {
  home: '/',
  goodDetail: 'goodDetail',
  landPage: 'search',
  shopCart: 'shopCart',
  cashier: 'pay',
  activityGoodsList: 'activityProduct'
};
export function locationHrefPatch(url = '', router) {
  if (!url) return;
  let params = parseSearch(url);
  localStorageParams.forEach(item => {
    const itemVal = localStorage.get(item);
    if (itemVal) params[item] = itemVal;
  });
  cookiesParams.forEach(item => {
    const itemVal = Cookies.get(item);
    if (itemVal) params[item] = itemVal;
  });
  params.fromHost = /(https|http):\/\//gi.test(url) ? window.location.origin : '';
  let paramsStr = '';
  Object.keys(params).forEach(item => {
    paramsStr += `&${item}=${params[item]}`;
  });
  const targetUrl = `${url.split('?')[0]}?${paramsStr.slice(1)}`;
  if (/(https|http):\/\//gi.test(targetUrl)) {
    window.location.href = targetUrl;
  } else if (/xyqb:\/\//gi.test(targetUrl)) {
    let urlTag = '';
    if (/goodsdetail|goodsDetail/gi.test(targetUrl)) {
      urlTag = 'goodDetail';
    } else if (/goodsList|search/g.test(targetUrl)) {
      urlTag = 'landPage';
    } else if (/activityGoodsList/gi.test(targetUrl)) {
      urlTag = 'activityGoodsList';
    } else if (/shopCart|shoppingCart/gi.test(targetUrl)) {
      urlTag = 'shopCart';
    } else if (/cashier/gi.test(targetUrl)) {
      urlTag = 'cashier';
    } else if (/discover|homepage/g.test(targetUrl)) {
      urlTag = 'home';
    } else {
      urlTag = 'home';
    }
    if (urlTag) {
      const url = `${H5_URL_MAP[urlTag]}?${targetUrl.split('?')[1]}`;
      console.log(url);
      if (router) {
        router.push({ path: url });
      } else {
        window.location.href = window.location.origin + '/' + url;
      }
    }
  } else {
    window.location.href = window.location.origin + '/' + targetUrl;
  }
}
export function loadScript(url, globalName) {
  return new Promise((resolve, reject) => {
    if (window[globalName] || process.env.NODE_ENV === 'development') {
      resolve();
    }
    const head = document.getElementsByTagName('head')[0];
    const script = document.createElement('script');
    // script.charset = 'UTF-8';
    script.async = true;
    script.onerror = function() {
      // eslint-disable-next-line
      reject();
    };
    let loaded = false;
    script.onload = script.onreadystatechange = function() {
      if (
        !loaded &&
        (!script.readyState || script.readyState === 'loaded' || script.readyState === 'complete')
      ) {
        loaded = true;
        setTimeout(function() {
          // eslint-disable-next-line
          resolve();
        }, 0);
      }
    };
    script.src = url;
    head.appendChild(script);
  });
}

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

export function queryStringify(json) {
  if (!json) return '';
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return '';
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key]);
    })
  ).join('&');
}

export const clearLoginInfo = () => {
  localStorage.remove('userInfo');
  localStorage.remove('historyArr');
  // localStorage.remove('vccChannel');
  localStorage.remove('vccToken');
  localStorage.remove('orderData');
  localStorage.remove('token');
  localStorage.remove('uuid');
  localStorage.remove('userPhoneNo');
};
export const replaceFavicon = icon => {
  const link = document.querySelector("link[rel*='icon']") || document.createElement('link');
  link.type = 'image/x-icon';
  link.rel = 'icon';
  link.href = icon;
  document.getElementsByTagName('head')[0].appendChild(link);
};

export const changeDocumentTitle = title => {
  // 钉钉浏览器内部，使用钉钉提供的JSAPI中的接口dd.biz.navigation.setTitle设置导航栏标题
  if (window.navigator.userAgent.includes('DingTalk')) {
    ddSetTitle({
      title,
      onSuccess: result => {
        console.log(result);
      },
      onFail: err => {
        console.log(err);
      }
    });
    return;
  }
  document.title = title;
  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 const formatPrice = v => {
  return `¥${v || '0.00'}`;
};
// 判断是否为0
export const checkEqualZero = v => Number(v) === 0;

export function isDef(val) {
  return val !== undefined && val !== null && val !== 'null' && val !== 'undefined';
}

export 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);
    }
  };
}

export 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);
      }
    }
  };
}
// 0是相等， 1是v1>v2, -1是v1<v2, -2  不存在
export function compareVersion(v1, v2) {
  if (!v1 || !v2) return -2;
  const v1Arr = v1.split('.');
  const v2Arr = v2.split('.');
  const len = Math.max(v1Arr.length, v2Arr.length);

  while (v1Arr.length < len) {
    v1Arr.push('0');
  }
  while (v2Arr.length < len) {
    v2Arr.push('0');
  }

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

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

  return 0;
}

export const getServiceHeaders = () => ({
  'living-service': JSON.stringify({ citycode: localStorage.get('citycode') || 1 })
});

export const cleanUndefinedOrNull = (params = {}) => {
  return Object.keys(params).reduce((origin, key) => {
    const item = params[key];
    if (!(item === null || item === undefined)) {
      origin[key] = item;
    }
    return origin;
  }, {});
};
/**
 * 将数组切割n的二维数组
 * @param {*} array
 * @param {*} n
 * @returns
 */
export const getNewArray = (list, n) => {
  const arr = [];
  let index = 0;
  while (list.length > index) {
    arr.push(list.slice(index, index + n));
    index += n;
  }
  return arr;
};

/**
 *
 * @param {*} arr old arr
 * @returns new arr
 */
export const exportNewArr = arr => {
  const odd = [];
  const even = [];
  arr.forEach(function(item, index) {
    if ((index + 1) % 2 === 0) even.push(item);
    else odd.push(item);
  });
  return odd.concat(even);
};
export const pick = (obj, arr) =>
  arr.reduce((iter, val) => (val in obj && (iter[val] = obj[val]), iter), {});

export const sub = (arg1, arg2) => {
  arg1 = arg1 || "";
  arg2 = arg2 || "";
  let r1, r2;
  try {
    r1 = arg1.toString().split(".")[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split(".")[1].length;
  } catch (e) {
    r2 = 0;
  }
  const c = Math.abs(r1 - r2);
  const m = Math.pow(10, Math.max(r1, r2));
  if (c > 0) {
    const cm = Math.pow(10, c);
    if (r1 > r2) {
      arg1 = Number(arg1.toString().replace(".", ""));
      arg2 = Number(arg2.toString().replace(".", "")) * cm;
    } else {
      arg1 = Number(arg1.toString().replace(".", "")) * cm;
      arg2 = Number(arg2.toString().replace(".", ""));
    }
  } else {
    arg1 = Number(arg1.toString().replace(".", ""));
    arg2 = Number(arg2.toString().replace(".", ""));
  }
  return (arg1 - arg2) / m;
};
