import { newImageMarkTooltip } from '../components/ImageMarkTooltip'

// 专门用于绘制图片的api数据类
export default class ImageMarkData {
    key = null
    markerIcon = null
    api = null
    // 提示框实例，当鼠标移入或者点击图例时，需要获取到该实例
    tooltip = null
    onResponse = null
    cacheData = null
    expiresAt = null
    abortController = null
    loading = false
    /**
     * 60秒内重复点击使用缓存数据，减少服务器压力
     */
    cacheTime = 60 * 1000

    constructor({ api, tooltip, markerIcon, onResponse, key }) {
        this.api = api
        this.key = key
        this.response = onResponse
        this.markerIcon = markerIcon
        // 初始化提示框
        this.tooltip = tooltip || newImageMarkTooltip({key})
    }

    getCache = () => {
        // 检查缓存是否有效
        if (
            this.cacheData?.length &&
            this.expiresAt > Date.now()
        ) {
            return this.cacheData
        }
    }

    request = async (params) => {
        // 首先查看缓存是否可用
        const cacheData = this.getCache()
        if (cacheData) return cacheData
        this.loading = true
        const controller = this.createAbortController()
        const config = {}
        if (controller) config.signal = controller.signal
        let res = null
        try {
            res = await this.api(params, config)
        } catch (error) {
            console.error('请求失败: ', error)
        } finally {
            this.loading = false
            let data = null
            if (this.response) data = this.response(res)
            else data = this.commonOnResponse(res)

            this.cacheData = data
            this.expiresAt = Date.now() + this.cacheTime

            return data
        }
    }

    createAbortController = () => {
        if (typeof AbortController === 'undefined') {
            console.warn('当前环境不支持 AbortController')
            return null
        }
        return new AbortController()
    }

    cancelRequest = () => {
        if (this.abortController) {
            try {
                this.abortController.abort()
            } catch (error) {
                this.console.warn('取消请求失败', error)
            } finally {
                this.abortController = null
            }
        }
    }

    // 通用的响应处理
    commonOnResponse = (res) => {
        if (res?.success) {
            const dataList = res.data.map((item) => {
                item.mapData = {
                    id: this.key + '-' + item.rid,
                    layerId: this.key,
                    position: [item.jd, item.wd, 0],
                    image: this.markerIcon
                }
                return item
            })
            return dataList
        }
        return []
    }
}