/* eslint-disable prefer-destructuring */
import { parse } from 'querystring';
import pathRegexp from 'path-to-regexp';
import moment from 'moment';
import localStorage from './localStorage';
/* eslint no-useless-escape:0 import/prefer-default-export:0 */

const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
export const isUrl = path => reg.test(path);
export const isAntDesignPro = () => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }

  return window.location.hostname === 'preview.pro.ant.design';
}; // 给官方演示站点用，用于关闭真实开发环境不需要使用的特性

export const isAntDesignProOrDev = () => {
  const { NODE_ENV } = process.env;

  if (NODE_ENV === 'development') {
    return true;
  }

  return isAntDesignPro();
};
export const getPageQuery = () => parse(window.location.href.split('?')[1]);
/**
 * props.route.routes
 * @param router [{}]
 * @param pathname string
 */

export const getAuthorityFromRouter = (router = [], pathname) => {
  const authority = router.find(({ path }) => path && pathRegexp(path).exec(pathname));
  if (authority) return authority;
  return undefined;
};

export function toThousands(data, num) {
  // 千位分隔符
  let value = Number(data || 0).toFixed(num);
  const int = Number.isInteger(value);
  let result = '';
  if (!int) {
    result = `.${value.split('.')[1]}`;
    value = `${Number.parseInt(value, 10).toString()}`;
  }
  while (value.length > 3) {
    result = `,${value.slice(-3)}${result}`;
    value = value.slice(0, value.length - 3);
  }
  if (value) {
    result = value + result;
  }
  return result;
}

export const formatTime = (time, crm = 'YYYY-MM-DD HH:mm:ss') => time.format(crm);
export const resetTime = (time, crm = 'YYYY-MM-DD HH:mm:ss') => moment(time, crm);

// 返回传递给他的任意对象的类
export function isClass(o) {
  if (o === null) return 'Null';
  if (o === undefined) return 'Undefined';
  return Object.prototype.toString.call(o).slice(8, -1);
}

export function debounce(fn, delay = 500) {
  let timer = null;

  return function fun(...args) {
    if (timer) {
      clearTimeout(timer);
    }

    timer = setTimeout(() => {
      timer = null;
      fn.apply(this, args);
    }, delay);
  };
}

// 深拷贝
export function deepClone(obj) {
  let result;
  const oClass = isClass(obj);

  // 确定result的类型
  if (oClass === 'Object') {
    result = {};
  } else if (oClass === 'Array') {
    result = [];
  } else {
    return obj;
  }
  // eslint-disable-next-line no-restricted-syntax
  for (const key in obj) {
    if ({}.hasOwnProperty.call(obj, key)) {
      const copy = obj[key];
      if (isClass(copy) === 'Object') {
        result[key] = deepClone(copy); // 递归调用
      } else if (isClass(copy) === 'Array') {
        result[key] = deepClone(copy);
      } else {
        result[key] = obj[key];
      }
    }
  }
  return result;
}
export const getClientInfo = () => {
  if (window.innerHeight !== undefined) {
    return {
      width: window.innerWidth,
      height: window.innerHeight,
    };
  }
  if (document.compatMode === 'CSS1Compat') {
    return {
      width: document.documentElement.clientWidth,
      height: document.documentElement.clientHeight,
    };
  }
  return {
    width: document.body.clientWidth,
    height: document.body.clientHeight,
  };
};

// 字符串或json去空格
export const stringOrObjectTrim = params => {
  if (isClass(params) === 'String') {
    return params.trim();
  }
  if (isClass(params) === 'Object') {
    Object.keys(params).forEach(key => {
      if (isClass(params[key]) === 'String') {
        params[key] = params[key].trim();
      } else if (isClass(params[key]) === 'Object') {
        stringOrObjectTrim(params[key]);
      } else if (isClass(params[key]) === 'Array') {
        params[key].forEach((item, i) => {
          params[key][i] = stringOrObjectTrim(item);
        });
      }
    });
  }
  return params;
};

// json转数组用于[Radio/Select/Checkbox]的options
export const jsonToArray = (obj, valueType) =>
  Object.keys(obj).map(key => ({
    label: obj[key],
    value: valueType === 'number' ? +key : key,
  }));

export const getObjectType = v => Object.prototype.toString.call(v).replace(/\[object |]/g, '');

// 获取长表单错误提示
export const getErrorMessage = err => {
  const message = '请检查表单数据！';
  // eslint-disable-next-line wrap-iife
  (function getMsg(v) {
    if (Array.isArray(v)) {
      getMsg(v[0]);
    } else {
      const keys = Object.keys(v);
      if (Array.isArray(v[keys[0]])) {
        getMsg(v[keys[0]][0]);
      } else if (v[keys[0]].errors && v[keys[0]].errors.length) {
        // eslint-disable-next-line no-const-assign
        message = v[keys[0]].errors[0].message;
      } else {
        getMsg(v);
      }
    }
  })(err);
  return message;
};

// 获取地址栏参数，name:参数名称
export const getUrlParams = name => {
  const regArg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
  const r = window.location.search.substring(1).match(regArg);
  if (r != null) return decodeURIComponent(r[2]);
  return null;
};

// 获取地址栏所有参数
export const getUrlSearchParams = () => {
  const newObj = {};
  const url = window.location.search; // 获取url中"?"符后的字符串
  if (url.indexOf('?') !== -1) {
    const strs = url.replace('?', '').split('&');
    for (let i = 0; i < strs.length; i++) {
      newObj[strs[i].split('=')[0]] = strs[i].split('=')[1] || '';
    }
  }
  return newObj;
};

// 获取token
export const getToken = () => {
  // 从消费地图后管过来
  if (getUrlParams('source') === 'tob' && localStorage.get('tobToken')) {
    return localStorage.get('tobToken');
  }
  return localStorage.get('token');
};

// 获取跳转参数
export const getToUrlQuery = () => {
  const params = getUrlSearchParams();
  // 从消费地图后管过来
  if (params.source) {
    return {
      source: params.source,
      token: params.token,
      isMaster: params.isMaster,
    };
  }
  return {};
};
