import store from 'store'
import { getQuery } from "./queryString";
import { storeData } from "../store";

/** 获取浏览器信息 */
export const browser = () => {
	const u = navigator.userAgent;
	const isAndroid = /(?:Android)/.test(u);
  	const isFireFox = /(?:Firefox)/.test(u);
	function isIpadFun() {
	const ua = window.navigator.userAgent;
	let IsIPad = false;
	if (/ipad/i.test(ua)) {
		IsIPad = true;
	}
	// iPad from IOS13
	const macApp = ua.match(/Macintosh/i) != null;
	if (macApp) {
		// need to distinguish between Macbook and iPad
		const canvas = document.createElement('canvas');
		if (canvas != null) {
		const context: any =
			canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
		if (context) {
			const info = context.getExtension('WEBGL_debug_renderer_info');
			if (info) {
			const renderer = context.getParameter(info.UNMASKED_RENDERER_WEBGL);
			if (renderer.indexOf('Apple') != -1) IsIPad = true;
			}
		}
		}
	}
	return IsIPad;
	}	
	return {
		trident: u.indexOf("Trident") > -1, //IE内核
		presto: u.indexOf("Presto") > -1, //opera内核
		webKit: u.indexOf("AppleWebKit") > -1, //苹果、谷歌内核
		gecko: u.indexOf("Gecko") > -1 && u.indexOf("KHTML") == -1, //火狐内核
		mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
		ios: !!u.match(/Mac OS X/) || /(iPhone|iPad|iPod|iOS)/i.test(u), //ios终端
		android: u.indexOf("Android") > -1 || u.indexOf("Adr") > -1, //判断是否是 android终端
		iPhone: u.indexOf("ORCHESTRAAPPI") > -1, //是否为iPhone或者QQHD浏览器
		isApp:
			u.includes("DAYAAPPA") ||
			u.includes("DAYAAPPI") ||
			u.includes("COLEXIUAPPA") ||
			u.includes("COLEXIUAPPI") ||
			u.includes("ORCHESTRAAPPI") ||
			u.includes("ORCHESTRAAPPA"),
		isTeacher: u.indexOf("ORCHESTRATEACHER") > -1 || u.includes("COLEXIUTEACHER"),
		isStudent: u.indexOf("ORCHESTRASTUDENT") > -1 || u.includes("COLEXIUSTUDENT"),
		isSchool: u.indexOf("ORCHESTRASCHOOL") > -1,
		iPad: u.indexOf("iPad") > -1, //是否iPad
		isTablet:
		/(?:iPad|PlayBook)/.test(u) ||
		(isAndroid && !/(?:Mobile)/.test(u)) ||
		(isFireFox && /(?:Tablet)/.test(u)) ||
		isIpadFun(),
		webApp: u.indexOf("Safari") == -1, //是否web应该程序，没有头部与底部
		weixin: u.indexOf("MicroMessenger") > -1, //是否微信 （2015-01-22新增）
		alipay: u.indexOf("AlipayClient") > -1, //是否支付宝
		huawei: !!u.match(/huawei/i) || !!u.match(/honor/i),
		xiaomi: !!u.match(/mi\s/i) || !!u.match(/redmi/i) || !!u.match(/mix/i),
	};
};
/** uuid */
export const getRandomKey = () => {
	const key = "" + Date.now() + Math.floor(Math.random() * 1000000);
	return key;
};

export const AuthorizationKey = "AUTHORIZATION";
/** 设置token */
export const setToken = (value: any) => {
	sessionStorage.setItem(AuthorizationKey, value);
};
/** 获取token */
export const getToken = () => {
	return sessionStorage.getItem(AuthorizationKey) || "";
};

/** 设置全局通信 */
export const setGlobalData = (_key: string, _value: any) => {
	if (!_key || !_value) return;
	const GYM = (window as any).GYM || {};
	GYM[_key] = _value;
	(window as any).GYM = GYM;
};

const BEHAVIORIDKEY = "BEHAVIORID";
/** 设置 behaviorId */
export const setBehaviorId = (value: any) => {
	localStorage.setItem(BEHAVIORIDKEY, value);
};
/** 获取 behaviorId */
export const getBehaviorId = () => {
	return localStorage.getItem(BEHAVIORIDKEY);
};

const campIdKey = "CAMPID";
/** 设置 训练营ID */
export const setCampId = (value: any) => {
	sessionStorage.setItem(campIdKey, value);
};
/** 获取 训练营ID */
export const getCampId = () => {
	return sessionStorage.getItem(campIdKey) || '';
};

// 秒转分
export const getSecondRPM = (second: number, type?: string) => {
	if (isNaN(second)) return "00:00";
	let h = Math.floor((second / 60 / 60) % 24);
	let m = Math.floor((second / 60) % 60);
	let s = Math.floor(second % 60);
	if (type === "cn") {
		return `${h > 0 ? h.toString().padStart(2, "0") + "时" : ""}${m.toString().padStart(2, "0")}分${s.toString().padStart(2, "0")}秒`;
	} else {
		return `${h > 0 ? h.toString().padStart(2, "0") + ":" : ""}${m.toString().padStart(2, "0")}:${s.toString().padStart(2, "0")}`;
	}
};
const SPEEDKEY = 'speeds'
/** 设置曲谱速度 */
export const setStorageSpeed = (id: any, speed: number) => {
	const speeds = store.get(SPEEDKEY) || {}
	speeds[id] = speed
	store.set(SPEEDKEY, speeds)
}
/** 获取曲谱速度 */
export const getStorageSpeed = (id: any) => {
	const speeds = store.get(SPEEDKEY) || {}
	console.log('初始速度', speeds)
	return speeds[id] || 0
}

/** 管乐迷区分业务接口  */
export const getRequestHostname = () => {
	const query: any = getQuery();
	let blankOld = ['mteadev.dayaedu.com', 'mteatest.dayaedu.com', 'mteaonline.dayaedu.com']
	let blank = ["dev.gym.lexiaoya.cn/accompany-teacher/", "test.gym.lexiaoya.cn/accompany-teacher/", "gym.lexiaoya.cn/accompany-teacher/"];
	let webBlankOld = ["mandev.dayaedu.com", "mantest.dayaedu.com", "manonline.dayaedu.com", "test.dayaedu.com", "online.dayaedu.com"];
	let webBlank = ["dev.gym.lexiaoya.cn/accompany-web/", "test.gym.lexiaoya.cn/accompany-web/", "gym.lexiaoya.cn/accompany-web/"];
	const host = location.hostname + location.pathname
	if (blank.includes(host) || blankOld.includes(location.hostname) || query.systemType === "teacher" || storeData.isTeacher) {
		return "/api-teacher";
	} else if (webBlank.includes(host) || webBlankOld.includes(location.hostname) || query.systemType === "web") {
		return "/api-web";
	}
	return "/api-student";
};

/** debounce */
export const debounce = (fn: Function, ms = 0) => {
	let timeoutId: number | undefined;
	return function(...args: any[]) {
	  clearTimeout(timeoutId)
	  // @ts-ignore
	  timeoutId = setTimeout(() => fn.apply(this, args), ms);
	}
}