/*
 * @Author: 吴永生#A02208 yongsheng.wu@wholion.com
 * @Date: 2022-06-07 18:37:53
 * @LastEditors: 吴永生#A02208 yongsheng.wu@wholion.com
 * @LastEditTime: 2022-06-15 17:49:27
 * @FilePath: /bkunyun/src/utils/util.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { v4 as uuidv4 } from "uuid";

export const isProjectOwner = (name: string) => {
  let localName = "";
  try {
    localName = JSON.parse(localStorage.getItem("userInfo") || "{}")?.name;
  } catch {
    console.error("获取localStorage出错");
  }
  return localName === name;
};

/**
 * 生成32位的随机id
 * @returns 返回32位的uuid
 */
export const uuid = () => {
  const reg = /-/g;
  const pwd = uuidv4().replace(reg, "");
  return pwd;
};

/** 格式化时间 xx小时xx分钟xx秒
 * params: item: 毫秒的时间戳
 */
export const formatTime = (time: number) => {
  const newTime = Math.floor(time / 1000);
  const hours = Math.floor(newTime / 3600);
  const minutes = Math.floor((newTime % 3600) / 60);
  const seconds = newTime % 60;

  const hoursString = hours ? `${hours}小时` : "";
  const minutesString = minutes ? `${minutes}分钟` : "";
  const secondsString = seconds ? `${seconds}秒` : "";

  return `${hoursString}${minutesString}${secondsString}`;
};

// 获取用户信息
export const getUserInfo = () => {
  let val: any;
  try {
    val = JSON.parse(localStorage.getItem("userInfo") || "{}");
  } catch {
    console.error("获取用户信息 出错");
  }
  return val;
};

// 获取token信息
export const getTokenInfo = () => {
  let val: any;
  try {
    val = JSON.parse(localStorage.getItem("token_key") || "{}");
  } catch {
    console.error("获取token信息 出错");
  }
  return val;
};

const IsNumberLetterChineseReg = new RegExp("^[A-Za-z0-9\u4e00-\u9fa5]+$");

export const checkIsNumberLetterChinese = (string: string) => {
  return IsNumberLetterChineseReg.test(string);
};

export const getMbfromB = (b: number) => {
  return Math.floor(b / 1048576);
};

// 内存单位转换
export const storageUnitFromB = (b: number) => {
  if (b <= 0) {
    return "0B";
  } else if (b < 1024) {
    return `${b}B`;
  } else if (b < 1024 * 1024) {
    return `${(b / 1024).toFixed(2)}KB`;
  } else if (b < 1024 * 1024 * 1024) {
    return `${(b / (1024 * 1024)).toFixed(2)}MB`;
  } else if (b < 1024 * 1024 * 1024 * 1024) {
    return `${(b / (1024 * 1024 * 1024)).toFixed(2)}G`;
  } else {
    return `${(b / (1024 * 1024 * 1024 * 1024)).toFixed(2)}t`;
  }
};

// 从本地缓存拿token
export const getToken = (): string => {
  return JSON.parse(localStorage.getItem('token_key') || "{}")?.access_token || ''
}

// 请求地址拼接 没值的不拼接 需要转义的通过encodeURIComponent转义
export const getUrlThroughParams = (params: any, encodeArr: Array<string> = [], initUrl= ''):string => { // params 是要穿的参数 是个对象 encodeArr 需要通过encodeURIComponent转换的字段数组
  let url = initUrl
  Object.keys(params).forEach((item: string, index) => {
    if (params[item] || params[item] === 0) {
      let value = params[item]
      if (encodeArr.some(encodeItem => encodeItem = item)) {
        value = encodeURIComponent(params[item])
      }
      url += `${index === 0 ? '' : '&'}${item}=${value}`
    }
  })
  return url
}


// 判断上拉滚动是否需要加载   scrollLoaderThreshold 加载阈值  如0.25表示 离底部四分之一高度（包裹盒子的高）触发加载
export const getScrollLoader = (e: any, scrollLoaderThreshold: number = 0.25) => {
  const clientHeight = e.target.clientHeight; // 滚动的外层盒子高度
  const scrollHeight = e.target.scrollHeight; // 列表总高度
  const scrollTop = e.target.scrollTop; // 滚动的高度
  if (scrollTop + clientHeight * (1+scrollLoaderThreshold)> scrollHeight) {
    return true
  } else {
    return false
  }
}