import { Fill, Stroke, Style, Text, Icon, Circle } from 'ol/style'
import { Vector as VectorLayer } from 'ol/layer'
import { Vector as VectorSource } from 'ol/source'
import Feature from 'ol/Feature'
import LineString from 'ol/geom/LineString'
import Point from 'ol/geom/Point'
import turf_along from '@turf/along'
import turf_linestring from 'turf-linestring'
import turf_length from '@turf/length'

function _getStyle(type, url) {
    let sytle = null
    if (type === 'node') {
        sytle = new Style({
            image: new Circle({
                radius: 0.1,
                stroke: new Stroke({
                    color: "#FF5809",
                    width: 2
                }),
                fill: new Fill({
                    color: "#FF5809"
                })
            }),
            text: new Text({
                font: "normal 1px 黑体",
                text: "",
                fill: new Fill({
                    color: 'rgba(255,255,255,1)'
                })
            })
            // image: new Circle({
            //     radius: 5,
            //     stroke: new Stroke({
            //         color: "#0000CD",
            //         width: 2
            //     }),
            //     fill: new Fill({
            //         color: "#0000CD"
            //     })
            // }),
            // text: new Text({
            //     font: "normal 12px 黑体",
            //     text: "",
            //     fill: new Fill({
            //         color: 'rgba(255,255,255,1)'
            //     })
            // })
        })
    }
    if (type === 'start') {
        let src = url || 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABMAAAAfCAYAAAAFkva3AAACd0lEQVR42qWU3UuTYRjG34iiw+gk6CAp2XRqsyazWRuz8c656UF/QV8URhQSNaMP5kzRudQ5Zy3zD+i0gygiZ44oogjDJJBqjMTS1Gxzm1s17+4rYmBzbXt38OPhue/r+jEG7yMQURoWZ2QHY2XGmBkm8ff0Y479er01F3N3eBPTzsQs7gQ1eJPUOETUOMzwiTvm2COH/LqyekdoK+Mz98ep4Q4XhzODPXKcH2W2rZGZupY2MiP17hWycDBXkOfec2ZzSlbXuWg39UXJPER5gx76BJmxY347EzPx/1HHy3xBD314BLF97qLYs0zG26uSQZ89VsHQ9mVUHFgh0ZuUDPrwCIfsM3OGmz/I4P0lGfTZMyvU2qaTtbd+UqHAI+ivBZf1gwnSs10q6LMnLOiuBsZ1rgjpeCCZ/gix542gvfLerXXM00FPXDJaxwKxxyMcuDSlqbEFSeNZkQz68Pz5Ampa3o3t75yl6oFY3qCHfupz0lgnS5i42hUmtTuaM8ijh35KBqovTLSp7Z+oqj+aM8ijl/YEqc+Pb2ECqq6vtM8VyQpyyKOXJgNVza8Pqy5PkbJvOSvIIZ/xpQWqcy9HKvnnV/SGM4I953zI/1e29+wLJZMs7w1RJrBHLqsMVJ55drfCFiBFz/c0MMceuZxkytNPy5hV+Y0l+hfMsc9ZBvY0+e+VtgZJ5vyWAnfMsc9LVn7qiahofkXFzsUUuGOet6zspG8D87G44zPt7l4gnLhjnrcMKE48tsmsb6mIXwWcfG/FXJKs9PijUnmTn3byE4UTd8kyUHLs4Yei69OEE/eCZPKjDwZ3tUwSzoJlsiP3RSbEGLNlfwPf80fNP6DL+QAAAABJRU5ErkJggg=='
        sytle = new Style({
            image: new Icon({
                anchor: [0.5, 1],
              src
            })
        })
    }
    if (type === 'end') {
        let src = url || 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABMAAAAfCAYAAAAFkva3AAACd0lEQVR42qWU3UuTYRjG34iiw+gk6CAp2XRqsyazWRuz8c656UF/QV8URhQSNaMP5kzRudQ5Zy3zD+i0gygiZ44oogjDJJBqjMTS1Gxzm1s17+4rYmBzbXt38OPhue/r+jEG7yMQURoWZ2QHY2XGmBkm8ff0Y479er01F3N3eBPTzsQs7gQ1eJPUOETUOMzwiTvm2COH/LqyekdoK+Mz98ep4Q4XhzODPXKcH2W2rZGZupY2MiP17hWycDBXkOfec2ZzSlbXuWg39UXJPER5gx76BJmxY347EzPx/1HHy3xBD314BLF97qLYs0zG26uSQZ89VsHQ9mVUHFgh0ZuUDPrwCIfsM3OGmz/I4P0lGfTZMyvU2qaTtbd+UqHAI+ivBZf1gwnSs10q6LMnLOiuBsZ1rgjpeCCZ/gix542gvfLerXXM00FPXDJaxwKxxyMcuDSlqbEFSeNZkQz68Pz5Ampa3o3t75yl6oFY3qCHfupz0lgnS5i42hUmtTuaM8ijh35KBqovTLSp7Z+oqj+aM8ijl/YEqc+Pb2ECqq6vtM8VyQpyyKOXJgNVza8Pqy5PkbJvOSvIIZ/xpQWqcy9HKvnnV/SGM4I953zI/1e29+wLJZMs7w1RJrBHLqsMVJ55drfCFiBFz/c0MMceuZxkytNPy5hV+Y0l+hfMsc9ZBvY0+e+VtgZJ5vyWAnfMsc9LVn7qiahofkXFzsUUuGOet6zspG8D87G44zPt7l4gnLhjnrcMKE48tsmsb6mIXwWcfG/FXJKs9PijUnmTn3byE4UTd8kyUHLs4Yei69OEE/eCZPKjDwZ3tUwSzoJlsiP3RSbEGLNlfwPf80fNP6DL+QAAAABJRU5ErkJggg=='
        sytle = new Style({
            image: new Icon({
                anchor: [0.5, 1],
                src
            })
        })
    }
    return sytle
}
/**
 * 轨迹对象类---------
 * @param {*} map 地图对象
 * @param {*} coods 轨迹坐标串 格式 [[经度，纬度],[经度，纬度]] [{pos: [经度，纬度], attributes: {}}]
 * @param {*} opts { isMoving = false, intervalTime = 1500, lineWidth = 7, lineColor = '#FFA042', url, content = '车牌：陕A-0p1v6' }
 */
export function HistoryTrack(map, coods, opts = {}) {
    this.lines_arr = coods
    this.map = map
    let { lineWidth = 3, isRotate = true, startPic, scale = 0.5, endPic, velocity = 100, lineColor = '#FFA042', url, content = '车牌：陕A-0p1v6', isCenter = false } = opts
    if (!url) {
        url = 'data:image/png;base64, '
    }
    this.conf = {
        // 历史轨迹
        history: {
            isRotate,
            // 运动标识
            move_key: false,
            velocity: velocity,
            // 轨迹时间
            time: 1000,
            isCenter,
            start: startPic,
            end: endPic,
            mediumSvg:'',
            // 线的样式
            line_style: new Style({
                stroke: new Stroke({
                    width: lineWidth,
                    color: lineColor,
                })
            }),
            // 点的样式
            p_style: new Style({
                // 设置一个标识
                image: new Icon({
                    src: url,
                    // 这个是相当于是进行切图了
                    // size: [50,50],
                    // 注意这个，竟然是比例 左上[0,0]  左下[0,1]  右下[1，1]
                    anchor: [0.5, 0.5],
                    // 这个直接就可以控制大小了
                    scale: scale,
                    // 开启转向
                    rotateWithView: true,
                    // rotation: 0,
                }),
                text: new Text({
                    // 对其方式
                    textAlign: 'center',
                    // 基准线
                    textBaseline: 'middle',
                    offsetY: 0,
                    offsetX: 62,
                    // 文字样式
                    font: 'normal 16px 黑体',
                    // 文本内容
                    text: "陕AS158Z",
                    // 文本填充样式
                    fill: new Fill({
                        color: 'rgba(255,255,255,1)'
                    }),
                    padding: [5, 5, 5, 5],
                    backgroundFill: new Fill({
                        color: 'rgba(0,0,255,0.6)'
                    })
                })
            })
        }
    }
    this.all_obj = {
        history: {
            // 历史图层------
            layer: null,
            // 图层数据源变量--------
            data_c: null,
            // marker
            p_data: null,
            line_layer: null, // 胡红勋新添加-----轨迹线的相关图层------------2019-4-8
            line_str: null,
            line_length: null
        }
    }
}
HistoryTrack.prototype.init = function() {
        this._history()
    }
    // 轨迹暂停的方法------
HistoryTrack.prototype.pause = function() {
        this.conf.history.move_key = false
    }
    // 轨迹开始的方法------
HistoryTrack.prototype.start = function() {
        if (!this.conf.history.move_key) {
            this.conf.history.move_key = true
            let index = this.start_index || 1
            this._history_start(index)
        }
}
    // 设置速度
HistoryTrack.prototype.setVelocity = function(velocity) {
        if (!this.conf.history.move_key) {
            this.conf.history.velocity = velocity
            this.start_index = null
            this.all_obj.history.p_data.setGeometry(new Point(this.lines_arr[0].pos))
        }
    }
    // 重新设置轨迹以及数组------
HistoryTrack.prototype.setTrackCoods = function(coods) {
    if (!this.conf.history.move_key) {
        this.start_index = null
        this.lines_arr = coods
        this.clearTrack()
            // 点
        this._history_p()
            // 线
        this._history_line()
            // 最优一次
        this._map_fit(this.all_obj.history.data_c)
    }
}
HistoryTrack.prototype._map_fit = function(data_c) {
        // 整个容器每个元素的最小最大 集合数组
        var point_arr = []
        data_c.getFeatures().forEach((ele, index) => {
                point_arr.push(this._one(ele.getGeometry()))
            })
            // 假设第一个点为最合适的点
        var fit_point = point_arr[0]
        point_arr.forEach(function(point, index) {
                // 最小经度
                if (point[0] < fit_point[0]) {
                    fit_point[0] = point[0]
                }
                // 最小纬度
                if (point[1] < fit_point[1]) {
                    fit_point[1] = point[1]
                }
                // 最大经度
                if (point[2] > fit_point[2]) {
                    fit_point[2] = point[2]
                }
                // 最大纬度
                if (point[3] > fit_point[3]) {
                    fit_point[3] = point[3]
                }
            })
            // 没有数据
        if (data_c.getFeatures().length == 0) {
            return
        }
        // 单个DOM
        else if (data_c.getFeatures().length == 1) {
            this.map.getView().setCenter([fit_point[0], fit_point[1]])
        }
        // 多个dom
        else {
            this.map.getView().fit(fit_point, this.map.getSize())
        }
    }
    // 单个点的最小经纬度/最大经纬度
HistoryTrack.prototype._one = function(dom) {
    // 4点数组
    var one_p = null
        // 类型
    var type = dom.getType()
        // 每个类型的坐标值
    var path = dom.getCoordinates()
    if (type == 'Point') {
        one_p = [path[0], path[1], path[0], path[1]]
    }
    // 多边形
    else if (type == 'Polygon') {
        var line_path = path[0]
        one_p = [line_path[0][0], line_path[0][1], line_path[0][0], line_path[0][1]]
        line_path.forEach(function(p, index) {
            // 最小经度
            if (p[0] < one_p[0]) {
                one_p[0] = p[0]
            }
            // 最小纬度
            if (p[1] < one_p[1]) {
                one_p[1] = p[1]
            }
            // 最大经度
            if (p[0] > one_p[2]) {
                one_p[2] = p[0]
            }
            // 最大纬度
            if (p[1] > one_p[3]) {
                one_p[3] = p[1]
            }
        })
    }
    // 线
    else if (type == 'LineString') {
        one_p = [path[0][0], path[0][1], path[0][0], path[0][1]]
        path.forEach(function(p, index) {
            // 最小经度
            if (p[0] < one_p[0]) {
                one_p[0] = p[0]
            }
            // 最小纬度
            if (p[1] < one_p[1]) {
                one_p[1] = p[1]
            }
            // 最大经度
            if (p[0] > one_p[2]) {
                one_p[2] = p[0]
            }
            // 最大纬度
            if (p[1] > one_p[3]) {
                one_p[3] = p[1]
            }
        })
    }
    // 圆
    else if (type == 'Circle') {
        path = dom.getCenter()
        one_p = [path[0], path[1], path[0], path[1]]
    }
    return one_p
}
HistoryTrack.prototype._map_p_rotation = function(new_p, old_p) {
    // 90度的PI值
    var pi_90 = Math.atan2(1, 0)
        // 当前点的PI值
    var pi_ac = Math.atan2(new_p[1] - old_p[1], new_p[0] - old_p[0])
    return pi_90 - pi_ac
}
HistoryTrack.prototype._history = function() {
    // 层
    this._history_layer()
        // 点
    this._history_p()
        // 线
    this._history_line()
        // 最优一次
    this._map_fit(this.all_obj.history.data_c)
}

// 图层数据源设置------
HistoryTrack.prototype._history_layer = function() {
    const start = this.conf.history.start
    const end = this.conf.history.end
        // 轨迹线图层添加------开始------ 2019-0408
    this.all_obj.history.line_layer = new VectorLayer({
        source: new VectorSource(),
        style: function(feature) {
            let _style = null
            if (feature.get('type') === 'node') {
                _style = _getStyle(feature.get('type'))
                if (feature.get("order")) {
                    _style.getText().setText(feature.get("order"))
                }
            }
            if (feature.get('type') === 'start') {
                _style = _getStyle(feature.get('type'), start)
            }
            if (feature.get('type') === 'end') {
                _style = _getStyle(feature.get('type'), end)
            }
            return _style
        }
    })
    this.all_obj.history.line_layer.setZIndex(10)
    this.map.addLayer(this.all_obj.history.line_layer)
        // 轨迹线图层添加------结束------

    // 矢量容器层
    this.all_obj.history.layer = new VectorLayer()
        // 注入数据层--可以注入多个Feature，每个feature有自己的数据和样式
    this.all_obj.history.data_c = new VectorSource() // 引用数据源-----------
        // 
    this.all_obj.history.layer.setSource(this.all_obj.history.data_c)
    this.all_obj.history.layer.setZIndex(11)
        // 打到地图上
    this.map.addLayer(this.all_obj.history.layer)
}

HistoryTrack.prototype._history_p = function() {
    // 创建一个活动图标需要的Feature，并设置位置
    var p_data = new Feature({
        // 就一个参数啊，定义坐标
        geometry: new Point(this.lines_arr[0].pos)
    })
    p_data.setStyle(this.conf.history.p_style)
    p_data.set('drawMark', true)
        // 数据层收集marker
    this.all_obj.history.data_c.addFeature(p_data)
        // 拿到全局
    this.all_obj.history.p_data = p_data
    p_data = null
}
HistoryTrack.prototype._history_line = function() {
    let vectors = []
    let line_coods = []
        //  轨迹线的构造----开始-----
    this.lines_arr.forEach(ele => {
        line_coods.push(ele.pos)
    })
    let line_data = new Feature({
        geometry: new LineString(line_coods)
    })
    line_data.setStyle(this.conf.history.line_style)
    line_data.set('drawMark', true)
    this.all_obj.history.line_str = turf_linestring(line_data.getGeometry().getCoordinates())
    this.all_obj.history.line_length = turf_length(this.all_obj.history.line_str, { units: 'kilometers' })
    vectors.push(line_data)
        //  轨迹线的构造----结束-----
    for (var i = 0; i < this.lines_arr.length; i++) {
        if (i > 0 && i < this.lines_arr.length - 1) {
            let nodeMarker = new Feature({
                order: (i + 1).toString(),
                type: 'node',
                geometry: new Point(this.lines_arr[i].pos),
                attributes: this.lines_arr[i].attributes
            })
            vectors.push(nodeMarker)
        } else {
            if (i == 0) {
                let starMarker = new Feature({
                    type: 'start',
                    geometry: new Point(this.lines_arr[i].pos),
                    attributes: this.lines_arr[i].attributes
                })
                vectors.push(starMarker)
            } else if (i == this.lines_arr.length - 1) {
                let startMarker = new Feature({
                    type: 'end',
                    geometry: new Point(this.lines_arr[i].pos),
                    attributes: this.lines_arr[i].attributes
                })
                vectors.push(startMarker)
            }
        }
    }
    // 注入数据层
    this.all_obj.history.line_layer.getSource().addFeatures(vectors)
    line_data = null
}
HistoryTrack.prototype._history_start = function(index) {
    if (!this.conf.history.move_key) {
        this.start_index = index
        return
    }
    // 开始运动
    setTimeout(() => {
        let _distance = this.conf.history.velocity * index / 1000
        if (_distance >= this.all_obj.history.line_length) {
            // 运动完毕
            this.conf.history.move_key = false
            this.start_index = null
            return
        } else {
            var old_p = this.all_obj.history.p_data.getGeometry().getCoordinates()
            let new_p = turf_along(this.all_obj.history.line_str, _distance, { units: 'kilometers' }).geometry.coordinates
            this.all_obj.history.p_data.setGeometry(new Point(new_p))
            if (this.conf.history.isRotate) {
                this.all_obj.history.p_data
                    .getStyle()
                    .getImage()
                    .setRotation(this._map_p_rotation(new_p, old_p))
            }
            if (this.conf.isCenter) {
                this.map.getView().setCenter(new_p)
            }
            index++
            this._history_start(index)
        }
    }, this.conf.history.time)
}
HistoryTrack.prototype.clearTrack = function(index) {
    this.all_obj.history.line_layer.getSource().clear()
    this.all_obj.history.data_c.clear()
}