import { tingwuWindow } from '../utils/getEnv';
import { v4 as uuidv4 } from 'uuid';
// import packageConfig from '../../package.json';

export const isMac = (() => {
  if (tingwuWindow.navigator.userAgent) {
    return /(macintosh|mac os x)/i.test(tingwuWindow.navigator.userAgent);
  }
  return false;
})();
export const isWindows = (() => {
  return /(win32|win64|windows|wince)/i.test(tingwuWindow.navigator.userAgent);
})();
export const isAliyunDriveApp = (() => {
  return /(aDrive|adrive)/i.test(tingwuWindow.navigator.userAgent);
})();

const hoderZero = (num: number): string => {
  return num < 10 ? `0${num}` : `${num}`;
};

/** 格式化时间 */
export const formatTime = (timeStamp: number, format = 'H:i:s') => {
  const date = new Date(timeStamp);

  const Y = hoderZero(date.getFullYear());
  const M = hoderZero(date.getMonth() + 1);
  const D = hoderZero(date.getDate());

  const H = hoderZero(date.getHours());
  const i = hoderZero(date.getMinutes());
  const s = hoderZero(date.getSeconds());

  return format
    .replace(/Y/g, Y)
    .replace(/M/g, M)
    .replace(/D/g, D)
    .replace(/H/g, H)
    .replace(/i/g, i)
    .replace(/s/g, s);
};

export const toHHMMSS = (ms: number, isShort = false) => {
  const sec_num = ms / 1000;

  let hours: number | string = Math.floor(sec_num / 3600);
  let minutes: number | string = Math.floor((sec_num - hours * 3600) / 60);
  let seconds: number | string = Math.floor(
    sec_num - hours * 3600 - minutes * 60,
  );

  if (hours < 10) {
    hours = `0${hours}`;
  }
  if (minutes < 10) {
    minutes = `0${minutes}`;
  }
  if (seconds < 10) {
    seconds = `0${seconds}`;
  }

  if (isShort && ms < 60 * 60 * 1000) {
    hours = '';
  }

  return [hours, minutes, seconds].filter((t) => !!t).join(':');
};

export const formatSizeUnits = (bytes: number) => {
  let result = '';
  if (bytes >= 1073741824) {
    result = `${(bytes / 1073741824).toFixed(1)} G`;
  } else if (bytes >= 1048576) {
    result = `${(bytes / 1048576).toFixed(1)} M`;
  } else if (bytes >= 1) {
    result = `${(bytes / 1024).toFixed(1)} K`;
  } else {
    result = '0 ';
  }
  return result;
};

/** 获取 uuid */
export const uuid = (): string => {
  return uuidv4().substr(0, 8);
};

/** 延时 */
export const delay = (time: number): Promise<void> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, time);
  });
};

/** 运行环境 */
export enum Env {
  Browser,
  Electron,
}

/** 获取当前运行环境 */
export const getEnv = (): Env => {
  if ('require' in tingwuWindow) {
    return Env.Electron;
  }

  return Env.Browser;
};

// const { runMode } = settings;

// export const getVersion = () => {
//   return `v${packageConfig.version}`;
// };

export const sleep = async (time: number) => {
  return new Promise((resolve) => {
    setTimeout(resolve, time);
  });
};

export const applyMixins = (derivedCtor: any, baseCtors: any[]) => {
  baseCtors.forEach((baseCtor) => {
    Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
      Object.defineProperty(
        derivedCtor.prototype,
        name,
        Object.getOwnPropertyDescriptor(
          baseCtor.prototype,
          name,
        ) as PropertyDescriptor,
      );
    });
  });
};

export const getSplitPercent = (range: [number, number], splitNum: number) => {
  if (range?.length !== 2) return 0;
  if (range[1] <= splitNum) return 100;
  if (range[0] >= splitNum) return 0;
  const percent = (
    ((splitNum - range[0]) / (range[1] - range[0])) *
    100
  ).toFixed(2);

  return percent;
};

export const getPercent = (curt: number, total: number) => {
  if (!curt || curt === 0) return 0;
  return Math.fround((curt / total) * 100);
};

export const getSplitColor = (
  range: [number, number],
  splitNum: number,
  colorList: [string, string],
) => {
  if (range?.length !== 2 || colorList?.length !== 2) return;
  if (range[1] <= splitNum) return colorList[0];
  if (range[0] >= splitNum) return colorList[1];
  const percent = (
    ((splitNum - range[0]) / (range[1] - range[0])) *
    100
  ).toFixed(2);

  return `linear-gradient(
    to right,
    ${colorList[0]} 0, ${colorList[0]} ${percent}%,
    ${colorList[1]} ${percent}%, ${colorList[1]} 100%
  )`;
};

export const getBgColor = (index: any) => {
  const colors = [
    '#F7868B',
    '#F58234',
    '#E7AF00',
    '#5F9E75',
    '#24AAE0',
    '#6F91B9',
    '#607BD8',
    '#7E70DF',
    '#CB419F',
  ];
  let _index = index;
  while (_index >= colors.length) {
    _index -= colors.length;
  }
  return colors[_index];
};

export const formatHMSHover = (s: number) => {
  let str = '';
  let sec = Math.floor((s * 10000) % (60 * 10000)) / 10000;
  sec = parseFloat(sec.toFixed(2));
  const leave = sec > 9 ? sec : `0${sec}`;
  // 根据传进来的时间 的长短 进行判定， 显示几段
  if (s > 3600) {
    str = `${judeNum(s / 3600)}:${judeNum((s % 3600) / 60)}:${leave}`;
  } else if (s >= 60) {
    str = `${judeNum(s / 60)}:${leave}`;
  } else {
    str = `00:${leave}`;
  }
  function judeNum(second: any) {
    const num = Math.floor(second);
    return num < 10 ? `0${num}` : num;
  }
  return str;
};

/**
 * @desc 函数防抖
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param immediate true 表立即执行，false 表非立即执行
 */
export function debounce(
  func: any,
  wait: number | undefined,
  immediate: boolean,
) {
  let timeout: string | number | NodeJS.Timeout | null | undefined;

  return function (this: any) {
    const context = this;
    const args = arguments;

    if (timeout) clearTimeout(timeout);
    if (immediate) {
      const callNow = !timeout;
      timeout = setTimeout(() => {
        timeout = null;
      }, wait);
      if (callNow) func.apply(context, args);
    } else {
      timeout = setTimeout(() => {
        func.apply(context, args);
      }, wait);
    }
  };
}

// 获取字符串长度
export function getTitleLength(str: string) {
  if (!str) return 0;
  const cArr = str.match(/[^\x00-\xff]/gi);
  const titleLength = str.length + (cArr == null ? 0 : cArr.length);
  return titleLength;
}

// 获取单双字节
export function getByteNums(str: string) {
  let single = 0;
  let double = 0;
  for (let i = 0; i < str.length; i++) {
    const c = str.charCodeAt(i);
    if (c > 255) {
      single += 1;
    } else {
      double += 1;
    }
  }
  return { single, double };
}

// 手机号3-4-4格式
export const formatPhoneNum = (phoneNum: string) => {
  let value = '';
  let str = phoneNum.toString().replace(/ /g, '');
  const len = str.length;
  switch (true) {
    case len > 11:
      str = `${str.substr(0, 3)} ${str.substr(3, 4)} ${str.substr(7, 4)}`;
      value = str;
      break;
    case len > 7:
      str = `${str.substr(0, 3)} ${str.substr(3, 4)} ${str.substr(7)}`;
      value = str;
      break;
    case len > 3:
      str = `${str.substr(0, 3)} ${str.substr(3)}`;
      value = str;
      break;
    default:
      value = str;
  }
  return value;
};
