/**
 * @description
 * @author       朱琦
 * @date         2021/11/9 16:28
 */
 import { isVue2, isVue3, markRaw } from 'vue-demi'
import MapSdkT from '../lib/sdk/map-sdk/map-sdk-t'
import MapSdkF from "../lib/sdk/map-sdk/map-sdk-f"
import LazyMapLoader from './load-map/lazy-map';

import { defaultMapUIConfig } from './config/map-default-config'

import { setThemeConfig, setIconConfig } from "./theme";
import { addBusinessSdk } from './sdk/business-sdk'
import config from '../lib/config/index.js'

const { DEFAULT_MAP_ID } = config

let lazyAMapApiLoaderInstance = null; //地图加载实例
let mapUIApiLoaderInstance = []

let Vue = null

const allMapSdk = {}
/**
 * 初始化Map
 * @param config 初始化配置
 * @param mapUIConfig MapUI配置
 */
export const initAMap = (vue, config = {}, mapUIConfig = {}) => {
    Vue = vue

    if (isVue2) {
        // Vue 2 only
        Vue.prototype.$mapSdk = markRaw(getMvMapSdk)

    } else if (isVue3) {
        // Vue 3 only
        Vue.config.globalProperties.$mapSdk = markRaw(getMvMapSdk)
    }

    if (lazyAMapApiLoaderInstance) {
        return
    }

    // 设置MapUI配置
    Object.assign(defaultMapUIConfig, mapUIConfig);

    lazyAMapApiLoaderInstance = new LazyMapLoader(config);

    lazyAMapApiLoaderInstance.mapLoad().then(() => {
        createMapUIApiLoaderInstance(defaultMapUIConfig)
    })
};

/**
 * 根据地图id获取sdk
 * @param {String} id 地图id
 * @returns sdk
 */
const getMvMapSdk = (id) => {
    if (!id) {
        id = DEFAULT_MAP_ID
    }
    return allMapSdk[id]
}

/**
 * 加载Map主题配置
 * @param config
 */
export const loadMapThemeConfig = (config) => {
    setThemeConfig(config)
}

/**
 * 配置地图图标
 * @param config
 */
export const mergeMapIconConfig = (config = []) => {
    if (config.length > 0) {
        setIconConfig(config)
    }
}
/**
 * 加载业务sdk配置
 * @param {Array} config 业务sdk配置
 */
export const loadBusinessSdk = (config = []) => {
    config.forEach(sdkConfig => {
        addBusinessSdk(sdkConfig.sdkName, sdkConfig.sdkClass)
    })
}

export const initMapSdk = ({ map, mapId, mapConfig }, pointClick) => {
    let mapSdk = window.AMap.version == '2.0' ? new MapSdkT(map, mapId, mapConfig, pointClick) : new MapSdkF(map, mapId, mapConfig, pointClick)

    allMapSdk[mapId] = mapSdk

    return mapSdk
}

/**
 * 创建AMapUI实例
 */
const createMapUIApiLoaderInstance = (mapUIConfig) => {
    if (mapUIConfig) {
        Object.keys(mapUIConfig).forEach(key => {
            AMapUI.load(mapUIConfig[key], function(Simplifier) {
                mapUIApiLoaderInstance[key] = Simplifier;
            })
        })
    }
}


export {
    lazyAMapApiLoaderInstance,
    mapUIApiLoaderInstance
};