import { message } from 'antd';
import { parse } from 'querystring';
import moment from 'moment';

/* 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: string): boolean => reg.test(path);

export const isAntDesignPro = (): boolean => {
  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 = (): boolean => {
  const { NODE_ENV } = process.env;
  if (NODE_ENV === 'development') {
    return true;
  }
  return isAntDesignPro();
};

export const getPageQuery = () => {
  const { href } = window.location;
  const qsIndex = href.indexOf('?');
  const sharpIndex = href.indexOf('#');

  if (qsIndex !== -1) {
    if (qsIndex > sharpIndex) {
      return parse(href.split('?')[1]);
    }

    return parse(href.slice(qsIndex + 1, sharpIndex));
  }

  return {};
};

// 排序这是比较函数
export const compare = (field: string, order: 'descend' | 'ascend') => {
  // descend 降序 大到小  ascend 升序 小到大
  if (order === 'ascend') {
    return function (m: any, n: any) {
      var a = m[field];
      var b = n[field];
      return a - b; //升序
    }
  } else {
    return function (m: any, n: any) {
      var a = m[field];
      var b = n[field];
      return b - a; //降序
    }
  }
}

// 返回别名
export const getChannelName = (name: string) => {
  let newName = name
  let abridgeServer: string[] = ['知定', '巨网', '广联', '太古', '云广', '傲星', '弘捷', '开域']
  let asName = abridgeServer.find((item: string) => name?.indexOf(item) !== -1)
  if (asName) {
    newName = asName
  } else if (newName?.length > 5) {
    newName = newName?.slice(2, 5) + '...'
  }
  return newName
}

// 输入文案时判断
export const txtLength = (value?: string) => {
  if (value) {
    let length = value?.length
    let text = value?.replace(/[\x00-\xff]/g, '')
    return text?.length + Number(((length - text?.length) / 2).toFixed())
  } else {
    return 0
  }
}

// 点击复制
export const copy = (str: string) => {
  let element = document.createElement("textarea");
  element.id = 'myTextarea'
  element.textContent = str
  document.body.append(element);
  (document.getElementById('myTextarea') as any).select();
  document.execCommand("Copy")
  document.body.removeChild(element);
  message.success(`复制成功：${str}`)
}

type Type = "day" | "week" | "month" | "year" | "years" | "y" | "months" | "M" | "weeks" | "w" | "days" | "d" | "hour" | "hours" | "h" | "minute"
type Format = 'YYYY-MM-DD' | 'YYYY-MM-DD HH' | 'YYYY-MM-DD HH:mm' | 'YYYY-MM-DD HH:mm:ss'
/**往后日期 */
export function useAddTime(num: number, type: Type, format?: Format, date?: Date | string): string {
  return moment(date || new Date()).add(num, type).format(format || 'YYYY-MM-DD')
}


/**
 * 精度
 * @param num1 number
 * @param num2 number
 * @param operator '+' | '-' | '*' | '/'
 * @returns 
 */
export const getNumber = (num1: number, num2: number, operator: '+' | '-' | '*' | '/') => {
  if (!num1) {
    return '0.00'
  }
  return Number(eval(`${num1.toFixed(10)}${operator}${num2.toFixed(10)}`).toFixed(10))
}

/**
 * 数组分组
 * @param array 
 * @param f 
 * @param isObject 
 * @returns 
 */
export const groupBy = (array: any[], f: (item: any) => any[], isObject?: boolean) => {
  const groups: any = {};
  array.forEach(function (o) { //注意这里必须是forEach 大写
    const group = JSON.stringify(f(o));
    groups[group] = groups[group] || [];
    groups[group].push(o);
  });
  if (isObject) {
    return groups
  }
  return Object.keys(groups).map(function (group) {
    return groups[group];
  });
}