import {isObject} from "@/utils/is";

/** px 转 vw, 375 是设置的屏幕宽度 */
export const px2vw = (px: number): string => {
  return `${window.screen.width / 750 * px / window.screen.width * 100}vw`
}


/**
 * 判断是否 url
 * */
export function isUrl(url: string) {
  return /^(http|https):\/\//g.test(url);
}


export function deepMerge<T = any>(src: any = {}, target: any = {}): T {
  let key: string;
  for (key in target) {
    src[key] = isObject(src[key]) ? deepMerge(src[key], target[key]) : (src[key] = target[key]);
  }
  return src;
}

// ¥6,285
export function toIntMark(value) {
  try {
    if (value.toString().includes('%')) {
      return value
    }
    const newVal = parseFloat(value).toFixed(0)
    if (newVal == 'NaN') {
      return value
    }
    return '¥' + newVal.replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, '$1,')
  } catch (e) {
    return value
  }
}

// 6,285
export function toInt(value) {
  try {
    if (value.toString().includes('%')) {
      return value
    }
    const newVal = parseFloat(value).toFixed(0)
    if (newVal == 'NaN') {
      return value
    }
    return newVal.replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, '$1,')
  } catch (e) {
    return value
  }
}

// ¥6k
export function toThousand(value) {
  try {
    if (!value) {
      return 0
    }
    if (value.toString().includes('%')) {
      return value
    }
    const newVal = parseFloat(value / 1000 + '').toFixed(0)
    if (newVal == 'NaN') {
      return value
    }
    return '¥' + newVal.replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, '$1,') + 'k'
  } catch (e) {
    return value
  }
}

// ¥6,285.00
export function toRoundMark(value: number | string) {
  value = value || 0
  const options = {
    style: 'currency',
    currency: 'CNY',
  };
  return value.toLocaleString('zh-CN', options)
}

// 6285.00
export function toRound(value) {
  try {
    if (value.toString().includes('%')) {
      return value
    }
    const newVal = parseFloat(value).toFixed(2)
    if (newVal == 'NaN') {
      return value
    }
    return newVal
  } catch (e) {
    return value
  }
}

export const regFenToYuan = (fen) => {
  let num;
  num=fen*0.01;
  num+='';
  const reg = num.indexOf('.') > -1 ? /(\d{1,3})(?=(?:\d{3})+\.)/g : /(\d{1,3})(?=(?:\d{3})+$)/g;
  num=num.replace(reg,'$1');
  num = toDecimal2(num)
  return num
}

export const toDecimal2 = (x) => {
  let f = parseFloat(x);
  if (isNaN(f)) {
    return false;
  }
  f = Math.round(x * 100) / 100;
  let s = f.toString();
  let rs = s.indexOf('.');
  if (rs < 0) {
    rs = s.length;
    s += '.';
  }
  while (s.length <= rs + 2) {
    s += '0';
  }
  return s;
}

/**
 *
 * @param customStyle
 * @param target
 */
export function addStyle(customStyle, target = 'object') {
  // 字符串转字符串，对象转对象情形，直接返回
  if (empty(customStyle) || typeof(customStyle) === 'object' && target === 'object' || target === 'string' &&
    typeof(customStyle) === 'string') {
    return customStyle
  }
  // 字符串转对象
  if (target === 'object') {
    // 去除字符串样式中的两端空格(中间的空格不能去掉，比如padding: 20px 0如果去掉了就错了)，空格是无用的
    customStyle = customStyle.clearSpaces('both')
    // 根据";"将字符串转为数组形式
    const styleArray = customStyle.split(';')
    const style = {}
    // 历遍数组，拼接成对象
    for (let i = 0; i < styleArray.length; i++) {
      // 'font-size:20px;color:red;'，如此最后字符串有";"的话，会导致styleArray最后一个元素为空字符串，这里需要过滤
      if (styleArray[i]) {
        const item = styleArray[i].split(':')
        style[item[0].clearSpaces('both')] = item[1].clearSpaces('both')
      }
    }
    return style
  }
  // 这里为对象转字符串形式
  let string = ''
  for (const i in customStyle) {
    // 驼峰转为中划线的形式，否则css内联样式，无法识别驼峰样式属性名
    const key = i.replace(/([A-Z])/g, '-$1').toLowerCase()
    string += `${key}:${customStyle[i]};`
  }
  // 去除两端空格
  return string.clearSpaces('both')
}

/**
 * 判断是否为空
 */
export function empty(value) {
  switch (typeof value) {
    case 'undefined':
      return true
    case 'string':
      if (value.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, '').length === 0) return true
      break
    case 'boolean':
      if (!value) return true
      break
    case 'number':
      if (value === 0 || isNaN(value)) return true
      break
    case 'object':
      if (value === null || value.length === 0) return true
      // for (const i in value) {
      //   return false
      // }
      return true
  }
  return false
}


/**
 * 获取本地图片
 * @param name // 文件名 如 doc.png
 * @returns {*|string}
 */
export function getAssetsImages(name) {
  return new URL(`/src/assets/images/${name}`, import.meta.url).href;
}


/**
 * 加法 （处理精度问题）
 * @param num1
 * @param num2
 * @returns {string}
 */
export function numAdd(num1, num2) {
  let baseNum, baseNum1, baseNum2, precision // 精度
  try {
    baseNum1 = num1.toString().split('.')[1].length
  } catch (e) {
    baseNum1 = 0
  }

  try {
    baseNum2 = num2.toString().split('.')[1].length
  } catch (e) {
    baseNum2 = 0
  }
  baseNum = Math.pow(10, Math.max(baseNum1, baseNum2))
  precision = (baseNum1 >= baseNum2) ? baseNum1 : baseNum2
  return ((num1 * baseNum + num2 * baseNum) / baseNum).toFixed(precision)
}

/**
 * 减法 （处理精度问题）
 * @param num1
 * @param num2
 * @returns {string}
 */
export function numSub(num1, num2) {
  let baseNum, baseNum1, baseNum2, precision // 精度
  try {
    baseNum1 = num1.toString().split('.')[1].length
  } catch (e) {
    baseNum1 = 0
  }
  try {
    baseNum2 = num2.toString().split('.')[1].length
  } catch (e) {
    baseNum2 = 0
  }
  baseNum = Math.pow(10, Math.max(baseNum1, baseNum2))
  precision = (baseNum1 >= baseNum2) ? baseNum1 : baseNum2
  return ((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(precision)
}

/**
 * 打电话
 * @param phoneNumber
 */
export const callPhone = (phoneNumber) => {
  if (phoneNumber) {
    window.location.href = "tel://" + phoneNumber;
  }
}

export function debounce(func: Function, time: number, immediate = false) {
  let timer: number | null = null;
  return (...args: any) => {
    if (timer) clearInterval(timer)
    if (immediate) {
      if (!timer) func.apply(this, args);
      timer = window.setTimeout(() => {
        timer = null
      }, time)
    } else {
      timer = window.setTimeout(() => {
        func.apply(this, args)
      }, time)
    }
  }
}