import md5 from "md5";
import { getGameId } from "./auth";
import { message } from "antd";


/**
 * 判断平台环境
 * @returns 
 */
export const isOs = () => {
  let userAgent = navigator.userAgent.toLowerCase();
  let os = 'windows'
  if (/iphone|ipad|ipod/.test(userAgent)) {
    // iOS设备
    console.log("iOS");
    os = 'ios'
  } else if (/android/.test(userAgent)) {
    // Android设备
    console.log("Android");
    os = 'android'
  } else if (/macintosh|mac os x/.test(userAgent)) {
    // Mac设备
    console.log("Mac");
    os = 'mac'
  } else {
    // PC设备
    console.log("PC");
    os = 'windows'
  }
  return os
}

/**
 * 签名
 * @param time 
 * @returns 
 */
export const sign = (time: number) => {
  let appKey = 'e842dd57bf9f70ebd9452cdca272cfc3'
  let str = `appKey=${appKey}&gameId=${getGameId()}&timestamp=${time}`
  let sign = md5(str).toLocaleUpperCase()
  return sign;
}


/**
 * 判断是否是手机号
 * @param mobile 
 * @returns 
 */
export const isMobile = (mobile: string) => {
  return /1[0-9]{10}/.test(mobile)
}

/**
 * 保存账号密码
 * @param username 
 * @param password 
 * @returns 
 */
export const addAccount = (username: string, password: string) => {
  let obj: any = {}
  let arr = []
  let isExist = false
  let data = localStorage.getItem('acountArrList')
  let storageArr = data ? JSON.parse(data) : []
  for (var i = 0; i < storageArr.length; i++) {
    if (storageArr[i].username == username) {
      isExist = true
      if (storageArr[i].password === password) {
        return false;
      }
    }
  }
  obj.username = username
  obj.password = password
  if (storageArr.length <= 0) {
    arr.push(obj)
    localStorage.setItem('acountArrList', JSON.stringify(arr))
  } else {
    if (isExist) { // 修改密码
      let newStorageArr = []
      for (var i = 0; i < storageArr.length; i++) {
        if (storageArr[i].username == username) {
          newStorageArr.push(obj)
        } else {
          newStorageArr.push(storageArr[i])
        }
      }
      localStorage.setItem('acountArrList', JSON.stringify(newStorageArr))
    } else {
      storageArr.push(obj)
      localStorage.setItem('acountArrList', JSON.stringify(storageArr))
    }
  }
}

/**
 * 点击复制
 *@param str 要复制的文字
 *@param cb 将message 方法传进来可避免警告
 * */
export const copy = (str: string, cb?: any) => {
  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);
  cb?.success(`复制成功：${str}`, 1) ?? message.success(`复制成功：${str}`, 1)
}

/**
 * 判断是否在微信浏览器
 * @returns 
 */
export const isWx = () => {
  return /micromessenger/i.test(navigator.userAgent)
}

/**
 * code失效删除重新进入
 */
export const getRedirectUrl = () => {
  if (window.location.search.includes('code')) {
    let urlParams: any = new URLSearchParams(window.location.search);
    urlParams.delete('code');
    urlParams = urlParams.toString().replace('&state=STATE', '')
    window.location.href = window.location.origin + '/?' + urlParams
  }
}

/**
 * 判断是横屏还是竖屏
 * @returns 
 */
export const getOrientation = () => {
  let orientationType = 'VERTICAL'
  if (window.matchMedia("(orientation: landscape)").matches) { // 横屏
    orientationType = 'LANDSCAPE'
  } else { // 竖屏
    orientationType = 'VERTICAL'
  }
  return orientationType
}

/**
 * 判断是否是必须在微信打开
 * @returns 
 */
export const isWeChat = () => {
  return isWx() || window.location.href.includes('/wechat/');
}

/**
 * 一些页面tab居中
 * @param e 
 */
export const scrollToTab = (e: React.MouseEvent<HTMLLIElement, MouseEvent>) => {
  const tab = e.currentTarget;
  const tabContainer = tab.parentElement?.parentElement; // 获取 tab 的父容器  
  if (tabContainer) {
      const tabPosition = tab.getBoundingClientRect().left + tabContainer.scrollLeft; // 计算 tab 的绝对位置  
      const containerWidth = tabContainer.clientWidth; // 获取容器的宽度  
      const scrollPosition = tabPosition - containerWidth / 2 + tab.offsetWidth / 2; // 计算滚动位置  
      tabContainer?.scrollTo({
          left: scrollPosition,
          behavior: 'smooth' // 平滑滚动  
      });
  }
};