import { inherits } from 'ol'
import VectorLayer from 'ol/layer/Vector'
import VectorSource from 'ol/source/Vector'
import Style from 'ol/style/Style'
import Text from 'ol/style/Text'
import Fill from 'ol/style/Fill'
import Icon from 'ol/style/Icon'
import Circle from 'ol/style/Circle'
import Point from 'ol/geom/Point'
import Feature from 'ol/Feature'
import { fromExtent } from 'ol/geom/Polygon'
import { transform } from 'ol/proj'
import FontSymbol from '../style/FontSymbol'
import Stroke from 'ol/style/Stroke'
export default function ClusterLayer(options) {
    var self = this
    self.styleFunc = function(feat) {
        var attribute = feat.get("attribute")
        var count = attribute.cluster.length
        if (count < 1) {
            let symbol = attribute.data.symbol
            let { icon, radius = 5, color = '#007979', fillColor = '#007979', StrokeColor = '#fff', rotation = 0.0 } = symbol.image
            let sty = new Style({
                image: new FontSymbol({
                    glyph: icon,
                    radius,
                    color,
                    fill: new Fill({
                        color: fillColor
                    }),
                    stroke: new Stroke({
                        color: StrokeColor,
                        width: 1
                    })
                })
            })
            if (rotation) {
                sty.getImage().setRotation(rotation)
            }
            return sty
                // return new Style({
                //     image: new Icon( /** @type {olx.style.IconOptions} */ ({
                //         anchor: [0.5, 60],
                //         anchorOrigin: 'top-right',
                //         anchorXUnits: 'fraction',
                //         anchorYUnits: 'pixels',
                //         offsetOrigin: 'top-right',
                //         offset: [0, 1], //偏移量设置
                //         scale: 0.7, //图标缩放比例
                //         opacity: 0.75, //透明度
                //         src: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADQAAAAfCAYAAACoE+4eAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyFpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDE0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INRzMgfgIA3SYDAv4BcSWQHyOUp/czZegSx46CcSNeORrqOEZehcK7UB8GIv4XiDuGYql3F8gjgXiD0hib4E4Doj/D0UPgcBDIM5A4oMy7jNaWshChxJoJRDbQQuCjbS2DCDAAKRJJxspr2RvAAAAAElFTkSuQmCC'
                //     }))
                // })

        } else {
            var _smallCorlor
            var _bigCorlor
            if (count < 100) {
                if (count > 50) {
                    _smallCorlor = "#f0cd41"
                    _bigCorlor = "#f5de8b"
                } else {
                    _smallCorlor = "#94d769"
                    _bigCorlor = "#cde7b1"
                }
            } else {
                _smallCorlor = '#f1964d'
                _bigCorlor = "#f9bda2"
            }
            count++
            count = count.toString()
                // var smallRadius = count.length * 10
                // smallRadius = smallRadius < 10 ? 12 : smallRadius
                // var bigRadius = smallRadius + 5
            return [
                // new Style({
                //     image: new Circle({
                //         radius: bigRadius,
                //         fill: new Fill({
                //             color: _bigCorlor
                //         })
                //     })
                // }),
                new Style({
                    // image: new Circle({
                    //     radius: smallRadius,
                    //     fill: new Fill({
                    //         color: _smallCorlor
                    //     })
                    // }),
                    image: new Icon({
                        src: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADQAAAAfCAYAAACoE+4eAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyFpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDE0IDc5LjE1MTQ4MSwgMjAxMy8wMy8xMy0xMjowOToxNSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZ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Text({
                            text: count,
                            fill: new Fill({
                                color: '#fff'
                            }),
                            font: 'Arial,Helvetica,SimSun,sans-serif',
                            offsetY: -1
                                // stroke: textStroke
                        })
                        // text: new Text({
                        //     text: count,
                        //     fill: new Fill({
                        //         color: '#620022'
                        //     }),
                        //     textAlign: "center",
                        //     textBaseline: "middle"
                        // })
                })
            ]
        }
    }
    var defaults = {
            map: null,
            maxZoom: 12,
            distance: 256,
            data: [],
            style: self.styleFunc
        }
        //将default和options合并
    self.options = {
        map: options.map,
        maxZoom: (options.maxZoom ? options.maxZoom : defaults.maxZoom),
        distance: (options.distance > 0 ? options.distance : defaults.distance),
        data: options.data,
        style: (options.style != null ? options.style : defaults.style)
    }

    self.proj = self.options.map.getView().getProjection()

    self.vectorSource = new VectorSource({
        features: []
    })
    self.vectorLayer = new VectorLayer({
        source: self.vectorSource,
        style: self.options.style
    })
    self.clusterData = []
        //判断该点是否聚合
    self._clusterTest = function(data, dataCluster) {
            var _flag = false
                //将地理坐标转换成屏幕坐标，进行距离判断
            let _point = data.geom.points.split(',')
            let _clusterPoints = dataCluster.geom.points.split(',')
            var _dataCoord = self._getCoordinate(parseFloat(_point[0]), parseFloat(_point[1]))
            var _cdataCoord = self._getCoordinate(parseFloat(_clusterPoints[0]), parseFloat(_clusterPoints[1]))
            var _dataScrCoord = self.options.map.getPixelFromCoordinate(_dataCoord)
            var _cdataScrCoord = self.options.map.getPixelFromCoordinate(_cdataCoord)
                //  计算两点之间的屏幕距离------
            var _distance = Math.sqrt(
                    Math.pow((_dataScrCoord[0] - _cdataScrCoord[0]), 2) +
                    Math.pow((_dataScrCoord[1] - _cdataScrCoord[1]), 2)
                )
                // 判断两点之间的距离是否比设定的小---
            _flag = _distance <= self.options.distance
                //如果超过最大的缩放级别，数据全部展示
            var _zoom = self.options.map.getView().getZoom()
                // 获取地图设定的最大级别
            var _maxZoom = self.options.maxZoom
                // 如果地图的当前级别比此最大级别大，则不需要聚合-----
            if (_zoom > _maxZoom) _flag = false
            return _flag
        }
        //坐标转换
    self._getCoordinate = function(lon, lat) {
            return transform([parseFloat(lon), parseFloat(lat)],
                "EPSG:4326",
                self.proj
            )
        }
        //添加数据到聚合图
    self._add2CluserData = function(index, data) {
        self.clusterData[index].cluster.push(data)
    }
    self._clusterCreate = function(data) {
            self.clusterData.push({
                data: data,
                cluster: []
            })
        }
        //展示数据
    self._showCluster = function() {
        self.vectorSource.clear()
        var _features = []
        for (var i = 0, len = self.clusterData.length; i < len; i++) {
            let _cdata = self.clusterData[i]
            let _points = _cdata.data.geom.points.split(',')
            let _coord = self._getCoordinate(_points[0], _points[1])
            let _feature = new Feature({
                geometry: new Point(_coord),
                attribute: _cdata
            })
            _features.push(_feature)
        }
        self.vectorSource.addFeatures(_features)
    }
    self._clusterFeatures = function() {
        self.clusterData = []
            //可视域处理
        var _viewExtent = self.options.map.getView().calculateExtent()
            //声明一个矩形，范围就是屏幕的四至
        var _viewGeom = new fromExtent(_viewExtent)
        for (var i = 0, ilen = self.options.data.length; i < ilen; i++) {
            let _data = self.options.data[i]
            let _points = _data.geom.points.split(',')
            let _coord = self._getCoordinate(parseFloat(_points[0]), parseFloat(_points[1]))
            if (_viewGeom.intersectsCoordinate(_coord)) {
                //当前点是否聚合，默认是false
                var _clustered = false
                for (var j = 0, jlen = self.clusterData.length; j < jlen; j++) {
                    var _cdata = self.clusterData[j]
                    if (self._clusterTest(_data, _cdata.data)) {
                        self._add2CluserData(j, _data)
                        _clustered = true
                        break
                    }
                }
                if (!_clustered) {
                    self._clusterCreate(_data)
                }
            }
        }
        self.vectorSource.clear()
        self._showCluster()
    }
    self.init = function() {
        self.options.map.once('postrender', function() {
            self._clusterFeatures()
        })
        self.options.map.on("moveend", function() {
            self._clusterFeatures()
        })
    }
    self.init()
    return self.vectorLayer
}

inherits(ClusterLayer, VectorLayer)