/*
 * @Author: walker.liu
 * @Date: 2022-03-07 16:37:46
 * @Copyright（C）:  2019-2020 ZP Inc.   All rights reserved.
 */
import dayjs from 'dayjs';
export const commafy = function (num, fixedNum) {
  num = parseFloat(num);
  if (fixedNum != 0 && !fixedNum) fixedNum = 2;
  if (num || 0 == num) {
    num = num.toFixed(fixedNum) + '';
    var re = /\d{1,3}(?=(\d{3})+(\.\d*)?$)/g;
    num = num.replace(re, '$&,');

    return num;
  }
  return '';
};

export const selectMonthList = function (initMonth = 202203) {
  let monthOptions = [
    {
      label: '最近30天',
      value: 30,
    },
  ];
  let currentMonth = parseInt(dayjs().format('YYYYMM'));
  while (currentMonth > initMonth) {
    currentMonth = parseInt(
      dayjs(String(currentMonth)).subtract(1, 'month').format('YYYYMM')
    );
    monthOptions.push({
      label: dayjs(String(currentMonth)).format('YYYY-MM'),
      value: currentMonth,
    });
  }
  return monthOptions;
};

/**
 * 分转成千分位元展示
 * @param {*} value
 * @returns
 */
export const thousandthMoney = function (value, unit = '') {
  if (value !== '') {
    value = (Number(value) / 100000).toFixed(2);
    value = String(value);
    const match = value.split('.');
    const res = match
      .map((item) => item.replace(/(\d)(?=(\d{3})+$)/g, '$1,'))
      .join('.');
    return unit ? unit + res : res;
  }
  return '';
};

// 转换成美式数字展示---并展示两位小数
export const conversionNum = (value: string) => {
  let num;
  try {
    //先保留两位小数
    num = parseFloat(value).toFixed(2);
    num = num.toString().replace(/\B(?=(\d{3})+\b)/g, ',');
    return num;
  } catch (e) {
    return value;
  }
};

// 去除字符串之间的空格
export const RemoveSpaces = (value: string) => {
  let newVal = value.replace(/\s*/g, '');
  return newVal;
};

export const parseCoinAmount = function (value) {
  let res = '';
  if (!value) {
    return res;
  }
  let valueStr = '';
  let str = String(value).toLowerCase();
  if (str.indexOf('e') >= 1) {
    let precision = str.substring(str.indexOf('e') + 2);
    valueStr = Number(value).toFixed(~~precision + 3);
  } else {
    valueStr = value + '';
  }
  // 大于1时， 展示2位小数
  if (value >= 1) {
    res = parseFloat(parseFloat(valueStr).toFixed(2)) + '';
  } else if (value * 10000 >= 1) {
    res = parseFloat(parseFloat(valueStr).toFixed(6)) + '';
  } else {
    let match = valueStr.match(/\.(\d+?)[1-9]/g);
    if (match) {
      if (match[0]) {
        res =
          '0.0{' +
          (match[0].length - 2) +
          '}' +
          valueStr.substring(match[0].length, match[0].length + 4);
      }
    } else {
      return value;
    }
  }
  return res;
};

export const parsePercent = function (
  value: string | number,
  prefix: boolean = false
) {
  if (value === undefined || value === null) {
    return 'N/A';
  }
  let result = (parseFloat(value + '') * 100).toFixed(1);
  let prefixStr = '';
  if (prefix) {
    prefixStr = value >= 0 ? '+' : '';
    return prefixStr + result + '%';
  }
  return result + '%';
};

export const parseScore = function (value: string | number) {
  if (value === undefined || value === null) {
    return 'N/A';
  }
  return parseFloat((~~value / 10).toFixed(2));
};

export const parseUrlQuery = function (url: string) {
  const parseResult = url.split('?');
  let result = {
    path: parseResult[0],
    query: {},
  };
  if (!parseResult[1]) {
    return result;
  }
  const vars = parseResult[1].split('&');
  for (var i = 0; i < vars.length; i++) {
    const pair = vars[i].split('=');
    result.query[pair[0]] = pair[1];
  }
  return result;
};

//获取元素是否在可视区域
export function isElementInViewport(el) {
  let rect = el.getBoundingClientRect();
  return (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <=
      (window.innerHeight || document.documentElement.clientHeight) &&
    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
  );
}

export function parseNumberToK(num, fixed = 1) {
  if (!num) {
    return '0';
  }
  if (num < 1000) {
    return parseFloat(parseFloat(num).toFixed(1));
  } else if (num >= 1000 && num < 1000000) {
    return parseFloat((num / 1000).toFixed(fixed)) + 'K';
  } else {
    return parseFloat((num / 1000000).toFixed(fixed)) + 'M';
  }
}

//
export const filterEmptyParams = (params) => {
  const result = {};
  for (const index in params) {
    if (
      params[index] === undefined ||
      params[index] === '' ||
      params[index] === null ||
      (Array.isArray(params[index]) && params[index].length === 0)
    ) {
    } else {
      result[index] = params[index];
    }
  }
  return result;
};

/**
 * 函数节流处理
 */
export function throttle(func, delay) {
  let timer = null;
  let startTime = Date.now();
  return function (...args) {
    const curTime = Date.now();
    const remaining = delay - (curTime - startTime);
    const context = this;
    clearTimeout(timer);
    if (remaining <= 0) {
      func.call(context, ...args);
      startTime = Date.now();
    } else {
      timer = setTimeout(() => {
        func.call(context, ...args);
      }, remaining);
    }
  };
}

/**
 * 防抖--可选择首次是否执行
 * @param func -fn
 * @param delay -time
 * @param Immediate -首次立即执行
 * @returns
 */
export function debounce(func, delay, Immediate = false) {
  let timer = null;
  let closeImmed = null;
  let immed = Immediate;
  return function (...args) {
    const context = this;
    if (Immediate) {
      if (closeImmed) {
        clearTimeout(closeImmed);
      }
      if (immed) {
        func.call(context, ...args);
        immed = false;
        closeImmed = setTimeout(() => {
          immed = true;
        }, delay);
        return;
      }
    }
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      func.call(context, ...args);
      immed = true;
    }, delay);
  };
}

/**
 * 科学计数法转换
 */
// 将科学计数法转换成小数
export const scientificToNumber = function (num: number) {
  let m: any = num.toExponential().match(/\d(?:\.(\d*))?e([+-]\d+)/);
  return num.toFixed(Math.max(0, (m[1] || '').length - m[2]));
};

// 获取k线图价格精度
export const PriceAccuracy = (number: number) => {
  let num = number + '';
  // 有的数据是科学计数法展示的
  let StrValue = num.toString().replace('$', '');
  let numLength = 0;
  // 判断数据是否有{}
  if (StrValue.indexOf('{') !== -1) {
    let par = /{(.+?)}/g;
    let zeroNum: any = StrValue.match(par);
    let ThisZero = zeroNum[0].replace('{', '');
    ThisZero = ThisZero.replace('}', '');
    if (parseInt(ThisZero) <= 10) {
      let newValue = StrValue.replace(zeroNum[0], '');
      let newArr: any = newValue.split('.')[1];
      // 在小数点后面添0
      for (let i = 0; i <= parseInt(ThisZero); i++) {
        // 拆分后的
        newArr = '0' + newArr;
      }
      newArr = newArr.match('[0]{0,20}')[0];
      numLength = parseInt('1' + newArr) * 100;
    }
    if (numLength === 0) {
      numLength = 10000000000;
    }
    return numLength;
  } else {
    // 没有{}的
    if (StrValue.indexOf('.') !== -1 && StrValue.indexOf('e') === -1) {
      StrValue = StrValue.toString().split('.')[1];
      let pat = '[0]{0,20}';
      let zeroNum: any = StrValue.match(pat);
      StrValue = '1' + zeroNum[0];
    } else if (StrValue.indexOf('e') !== -1) {
      // 科学计数法
      let NewNum = parseFloat(StrValue);
      StrValue = scientificToNumber(NewNum);
      StrValue = StrValue.toString().split('.')[1];
      let pat = '[0]{0,20}';
      let zeroNum: any = StrValue.match(pat);
      if (zeroNum[0].length <= 10) {
        StrValue = '1' + zeroNum[0];
      } else if (zeroNum[0].length == 15) {
        StrValue = '1' + zeroNum[0] + '0';
        return parseInt(StrValue);
      } else {
        // 最多支持16位小数
        return 10000000000000000;
      }
    } else {
      StrValue = '1';
    }
    return parseInt(StrValue) * 10000;
  }
};

// k线图计算当前时间
export const computedTime = (value: string) => {
  // 需要返回的时间戳
  let FinishTime = null;
  // 当前时间
  let current = new Date().getTime();
  // 当前时间的整分时间
  let mm = dayjs(current).format('YYYY-MM-DD HH:mm');
  // 当前时间的整时时间
  let hh = dayjs(current).format('YYYY-MM-DD HH');
  if (value == '1') {
    // 上一分钟--ok
    FinishTime = dayjs(mm).subtract(1, 'minute').valueOf();
  } else if (value === '5') {
    // 上五分钟
    let current = new Date().getTime();
    let Time = parseInt(dayjs(current).format('mm'));
    if (Time % 5 == 0) {
      FinishTime = dayjs(mm).subtract(5, 'minute').valueOf();
    } else {
      FinishTime = dayjs(mm)
        .subtract(Time % 5, 'minute')
        .valueOf();
    }
  } else if (value == '15') {
    // 15分钟的
    let current = new Date().getTime();
    let Time = parseInt(dayjs(current).format('mm'));
    if (Time % 15 == 0) {
      FinishTime = dayjs(mm).subtract(15, 'minute').valueOf();
    } else {
      FinishTime = dayjs(mm)
        .subtract(Time % 15, 'minute')
        .valueOf();
    }
  } else if (value == '60') {
    // 一小时的
    FinishTime = dayjs(hh).valueOf();
  } else if (value == '240') {
    // 当前的整点时间
    let curH = dayjs(current).format('HH');
    // 应该减去的时间
    let num = parseInt(curH) % 4;
    FinishTime = dayjs(hh).subtract(num, 'hour').valueOf(); //ok
  } else if (value == '1D') {
    // 一天的
    let DD = dayjs(current).format('YYYY-MM-DD');
    FinishTime = dayjs(DD).valueOf(); // ok
  }
  return FinishTime;
};

// 右侧详情图标排序，有链接的放前面
export const sortImg = (list: any) => {
  let temp = [];
  for (let i = 0; i < list.length; i++) {
    // 如果没有链接，放最后
    if (!list[i]['url']) {
      temp.push(list[i]);
    } else {
      temp.unshift(list[i]);
    }
  }
  return temp;
};

// 过滤两者之间的值--比较number大小
export const filtercriteria = (filter, list) => {
  // 解构
  const { min, max, filtervalue } = filter;
  let newList: any = [];
  for (let i = 0; i < list.length; i++) {
    if (list[i][filtervalue] >= min && list[i][filtervalue] <= max) {
      newList.push(list[i]);
    }
  }
  return newList;
};

/**
 * @param key 比较的键
 * @param value 比较的值
 * @param list 过滤的数组
 */
export const filterIncludeValue = (
  key: string,
  value: string | number,
  list: any
) => {
  let filterList = list.filter((item: any) => item[key] === value);
  return filterList;
};

/**
 * 合并去重
 * @param list :数据源
 * @param newList :新进来的数据
 */
export const filterRepeatTimestamp = (list: any, newList: any) => {
  // 需要插入的数据
  let NewData: any = [];
  for (let i = 0; i < newList.length; i++) {
    let index = list.findIndex((item: any) => item.ts === newList[i].ts);
    if (index == -1) {
      // 没找到重复的
      NewData.push(newList[i]);
    }
  }
  return NewData;
};
