import { Platform } from './types'
import { TIME } from './constant'

/**
 * 判断元素是否在可视区域
 * @param el
 */
export function isElementVisible(el: Element): boolean {
    const viewWidth = window.innerWidth || document.documentElement.clientWidth
    const viewHeight = window.innerHeight || document.documentElement.clientHeight
    const { top, left, bottom, right, height, width } = el.getBoundingClientRect()

    // 判断标准：高度 > 屏幕高度，dom 高度出现在屏幕超过自身高度一半；反之，dom 的顶部or底部达到或超过屏幕中心位置
    if (height <= viewHeight) {
        return (
            top + height / 2 >= 0 &&
            left + width / 2 >= 0 &&
            right <= viewWidth + width / 2 &&
            bottom <= viewHeight + height / 2
        )
    } else {
        return (
            (top <= height / 2 || bottom >= height / 2) &&
            top >= 0 &&
            left >= 0 &&
            right <= viewWidth &&
            bottom <= viewHeight
        )
    }
}

/**
 * 获取默认平台
 * @returns {Platform}
 */
export function getInitPlatform(): Platform {
    return 'native'
}

export function simpleThrottle<T extends (...args: any[]) => any>(
    cb: T,
    time = 500,
): T | ((...arg: any[]) => any) {
    let preTime = Date.now()
    return (...arg: any[]): any => {
        if (Date.now() - preTime >= time) {
            cb(...arg)
        }
        preTime = Date.now()
    }
}

/**
 * 简易请求, 用于发起log接口，获取did接口
 * @param url {String}
 * @param options
 * @returns Promise
 */
export function request(
    url: string,
    options: { method: 'GET' | 'POST' },
    data: any,
    headers: Record<string, any>,
): Promise<any> {
    return new Promise((resolve, reject) => {
        fetch(url, {
            ...options,
            headers: {
                'content-type': 'application/json',
                ...headers,
            },
            credentials: 'include',
            body: data && JSON.stringify(data),
        })
            .then((res) => res.json())
            .then((res) => resolve(res))
            .catch((e) => reject(e))
    })
}

export function setCache(key: string, data: any) {
    try {
        window.localStorage.setItem(key, JSON.stringify(data))
    } catch (error) {
        //ignore
    }
}

export function getCache(key: string): any {
    const str = window.localStorage.getItem(key)
    try {
        if (str) return JSON.parse(str)
    } catch (error) {
        return str
        //ignore
    }
}

export function delCache(key: string) {
    window.localStorage.removeItem(key)
}

/**
 * 获取http协议，避免blocked
 * @param url {string}
 * @returns {string}
 */
export function getUrlWidthProto(url: string): string {
    try {
        const protos = window.location.protocol
        const newUrl = new URL(url)
        newUrl.protocol = protos
        return newUrl.href
    } catch (error) {
        // ignore
        console.log('获取http协议失败', error)
        return url
    }
}

export function getLaunchTime(key: string) {
    try {
        const str = localStorage.getItem(key)
        if (str) {
            const strData = { expires: Date.now(), ...JSON.parse(str) }
            if (Date.now() - strData.expires >= TIME.MINUTE * 1) {
                // 已过期
                const newTime = Date.now()
                strData.expires = newTime
                setCache(key, strData)
                return newTime
            }
            return strData.expires
        } else {
            setCache(key, { expires: Date.now() })
        }
    } catch (error) {
        return null
    }
}
