import ArcGISMapImageLayer from './arcgis-layer/ArcGISMapImageLayer';
import ArcGISTileLayer from './arcgis-layer/ArcGISTileLayer';
import ArcGISVectorTileLayer from './arcgis-layer/ArcGISVectorTileLayer';

import Cesium3DTilesCacheLayer from './common-layer/Cesium3DTilesCacheLayer';
import EchartsLayer from './common-layer/EchartsLayer';

import IGSFeatureLayer from './igs-layer/IGSFeatureLayer';
import IGSImageryLayer from './igs-layer/IGSImageryLayer';
import IGSImageryTileLayer from './igs-layer/IGSImageryTileLayer';
import IGSMapImageLayer from './igs-layer/IGSMapImageLayer';
import IGSTileLayer from './igs-layer/IGSTileLayer';
import IGSVectorTileLayer from './igs-layer/IGSVectorTileLayer';
import ImageryLayer from './igs-layer/ImageryLayer';
import ImageryTileLayer from './igs-layer/ImageryTileLayer';

// import OGCLayer from './ogc-layer/OGCLayer';
import wfsLayer from './ogc-layer/wfsLayer';
import wmsLayer from './ogc-layer/wmsLayer';
import wmtsLayer from './ogc-layer/wmtsLayer';

/**
 * 图层实例管理数组
 * 用于存储所有通过 createLayer 创建的图层实例
 * @type {Array<Object>}
 */
const dataLayers = [];
const dataLayerIds = [];

/**
 * 创建图层实例的工厂方法
 * @param {Object} options - 图层配置选项
 * @param {String} options.type - 图层类型标识
 * @param {Object} options.map - 地图对象（mapboxgl.Map 实例）
 * @param {String} options.url - 服务地址
 * @param {String} [options.id] - 图层ID（可选）
 * @param {Number} [options.opacity=1] - 透明度 (0-1)
 * @param {Boolean} [options.visible=true] - 是否可见
 * @param {Object} [options.spatialReference] - 坐标系
 * @returns {Object} 图层实例（具体类型取决于 options.type）
 *
 * @example
 * // 创建 IGS 地图图片图层
 * const layer = createLayer({
 *     type: 'igs-map-image',
 *     map: mapboxMap,
 *     url: 'http://xxx/igs/rest/services/Map/图层/MapServer'
 * });
 * layer.loadLayer();
 */
export function createLayer(options) {
    const { type, ...layerOptions } = options;

    let layerInstance = null;

    switch (type) {
        // ArcGIS 图层
        case 'arcgis-map-image':
            layerInstance = new ArcGISMapImageLayer(layerOptions);
            break;
        case 'arcgis-tile':
            layerInstance = new ArcGISTileLayer(layerOptions);
            break;
        case 'arcgis-vector-tile':
            layerInstance = new ArcGISVectorTileLayer(layerOptions);
            break;

        // Common 图层
        case 'cesium-3dtiles-cache':
            layerInstance = new Cesium3DTilesCacheLayer(layerOptions);
            break;
        case 'echarts':
            layerInstance = new EchartsLayer(layerOptions);
            break;

        // IGS 图层
        case 'igs-feature':
            layerInstance = new IGSFeatureLayer(layerOptions);
            break;
        case 'igs-imagery':
            layerInstance = new IGSImageryLayer(layerOptions);
            break;
        case 'igs-imagery-tile':
            layerInstance = new IGSImageryTileLayer(layerOptions);
            break;
        case 'igs-map-image':
            layerInstance = new IGSMapImageLayer(layerOptions);
            break;
        case 'igs-tile':
            layerInstance = new IGSTileLayer(layerOptions);
            break;
        case 'igs-vector-tile':
            layerInstance = new IGSVectorTileLayer(layerOptions);
            break;

        // OGC 图层
        // case 'ogc':
        //     layerInstance = new OGCLayer(layerOptions);
        //     break;
        case 'wfs':
            layerInstance = new wfsLayer(layerOptions);
            break;
        case 'wms':
            layerInstance = new wmsLayer(layerOptions);
            break;
        case 'wmts':
            layerInstance = new wmtsLayer(layerOptions);
            break;

        default:
            console.warn(`未知的图层类型: ${type}`);
            return null;
    }

    // 将创建的图层实例添加到管理数组中
    if (layerInstance) {
        dataLayers.push(layerInstance);
        dataLayerIds.push(layerInstance._layerId);
    }

    return layerInstance;
}

/**
 * 获取所有图层实例
 * @param {Object} [filter] - 过滤条件（可选）
 * @param {String} [filter.type] - 按图层类型过滤
 * @param {String} [filter.layerId] - 按图层ID过滤
 * @param {Object} [filter.map] - 按地图对象过滤
 * @returns {Array<Object>} 图层实例数组
 *
 * @example
 * // 获取所有图层
 * const allLayers = getDataLayers();
 *
 * // 按类型过滤
 * const igsLayers = getDataLayers({ type: 'igs-map-image' });
 *
 * // 按图层ID过滤
 * const specificLayer = getDataLayers({ layerId: 'my_layer_id' });
 */
export function getDataLayers(filter = null) {
    if (!filter) {
        return [...dataLayers]; // 返回副本，防止外部修改
    }

    return dataLayers.filter(layer => {
        let match = true;

        // 按类型过滤
        if (filter.type && layer._type !== filter.type) {
            match = false;
        }

        // 按图层ID过滤
        if (filter.layerId && layer._layerId !== filter.layerId) {
            match = false;
        }

        // 按地图对象过滤
        if (filter.map && layer._map !== filter.map) {
            match = false;
        }

        return match;
    });
}

/**
 * 移除指定的图层实例（从管理数组中移除）
 * @param {Object} layerInstance - 要移除的图层实例
 * @returns {Boolean} 是否成功移除
 */
export function removeLayerFromManager(layerInstance) {
    const layerId = layerInstance._layerId || layerInstance.id;
    const index = dataLayerIds.indexOf(layerId);

    if (index > -1) {
        // 同步删除两个数组中的对应项
        dataLayerIds.splice(index, 1);
        dataLayers.splice(index, 1);
        console.log('图层已移除，当前图层数量:', dataLayers.length);
        return true;
    }

    console.warn('未找到要移除的图层:', layerId);
    return false;
}

/**
 * 清空所有图层实例（从管理数组中移除）
 * @param {Object} [map] - 如果提供地图对象，只清空该地图的图层
 */
export function clearLayers(map = null) {
    if (map) {
        // 只移除指定地图的图层
        for (let i = dataLayers.length - 1; i >= 0; i--) {
            if (dataLayers[i]._map === map) {
                dataLayers.splice(i, 1);
            }
        }
    } else {
        // 清空所有图层
        dataLayers.length = 0;
    }
}
