import { Circle as CircleStyle, Fill, Stroke, Style, Text, Icon } from 'ol/style'
import { Vector as VectorLayer } from 'ol/layer'
import { Vector as VectorSource } from 'ol/source'
import qs from 'qs'
import Feature from 'ol/Feature'
import { Point } from 'ol/geom'
import axios from 'axios'
import { transform } from 'ol/proj'
import { FlashMarker } from './flash.js'
import { gcj_encrypt } from '../base/poiQuery.js'
import { wgs84Toweb3857, web3857ToWgs84 } from './factory.js'
export function flashingPoints(id, map, citys) {
    let flashingObj = null
    flashingObj = new FlashMarker(id, map, citys);
    // return new FlashMarker(id, map, citys);
    return flashingObj
}
export function filterKeySearch(name, config) {
    return new Promise(function(resolve) {
        if (name == null || name == "") {
            return
        }
        var _this = this;
        var initData = {
            "posArray": [{
                "name": name,
                'pageSize': config.pageSize,
                'currentPage': config.currentPage,
                'tableName': config.tableName
            }]
        }
        axios.post(config.serurl, qs.stringify(initData), {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        }).then(res => {
            let data = res.data
            resolve(data)
        })
    })
}
export function findFreeHandRoad(dataBaseConfig) {
    return new Promise(function(resolve) {
        if (dataBaseConfig.roadId == '' && dataBaseConfig.roadName == '') {
            return
        }
        // var _this = this;
        var initData = {
            "posArray": [{
                "roadId": dataBaseConfig.roadId,
                "roadName": dataBaseConfig.roadName,
                "tableName": dataBaseConfig.tableName
            }]
        }
        axios.post(dataBaseConfig.serurl, qs.stringify(initData), {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        }).then(res => {
            let data = res.data
            resolve(data)
        })
    })
}
export function saveFreeHandRoad(roadNodeArr, roadLineArr, roadIdAndName, dataBaseConfig) {
    return new Promise(function(resolve) {
        // if (roadNodeArr.length == 0) {
        //     return
        // }
        if (roadLineArr.length == 0) {
            return
        }
        var _this = this;
        var initData = {
            "posArray": [{
                "roadNodeArr": roadNodeArr,
                "roadLineArr": roadLineArr,
                "roadIdAndName": roadIdAndName,
                "tableName": dataBaseConfig.tableName
            }]
        }
        axios.post(dataBaseConfig.serurl, qs.stringify(initData), {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        }).then(res => {
            let data = res.data
            resolve(data)
        })
    })
}

function addPoiVectors(attributes, pos, map, config) {
    var vectorSource = new VectorSource({ id: config.id })
    let iconStyle = new Style({
        image: new Icon({
            scale: config.scale,
            src: config.img
        })
    })
    let iconFeature;
    iconFeature = new Feature({
        id: config.id,
        attributes: attributes,
        geometry: new Point(pos)
    })
    vectorSource.addFeature(iconFeature)
    let vectorLayerPoi = new VectorLayer({
        id: config.id,
        source: vectorSource,
        style: iconStyle
    })
    vectorLayerPoi.setZIndex(config.zIndex)
    map.addLayer(vectorLayerPoi)
}
// function addPoiVectors(attributes, pos, map, config) {
//     var vectorSource = new VectorSource({ id: config.id })
//     let iconStyle = new Style({
//         image: new Icon({
//             scale: config.scale,
//             src: config.img
//         })
//     })
//     let iconFeature;
//     iconFeature = new Feature({
//         id: config.id,
//         attributes: attributes,
//         geometry: new Point(pos)
//     })
//     vectorSource.addFeature(iconFeature)
//     let vectorLayerPoi = new VectorLayer({
//         id: config.id,
//         source: vectorSource,
//         style: iconStyle
//     })
//     vectorLayerPoi.setZIndex(config.zIndex)
//     map.addLayer(vectorLayerPoi)
// }
export function addHugePointsGif(layerId, vectors, config, map) {
    // var coords =[]
    // var red = 0
    // for(var i = 0; i < 500; i++)
    // {
    //     var x = 118  +  4 * Math.random()
    //     var y = 28 + 5 * Math.random()
    //     coords.push([x,y])
    // }
    // var vectorLayerPoi = null ;
    var vectorSourcePoi = new VectorSource({})
    var vectorLayerPoi = new VectorLayer({
        id: layerId,
        source: vectorSourcePoi,
        // style: iconStyle,
        // updateWhileAnimating:true
    })
    vectorLayerPoi.setZIndex(config.zIndex)
    var canvas = document.createElement("canvas"); //创建一个canvas标签
    canvas.width = 150;
    canvas.height = 400;
    var image = new Image();
    var ctx = canvas.getContext("2d");
    image.src = config.img
    image.onload = function() {
        var imageWidth = image.width; //获取当前图片的尺寸
        var imageHeight = image.height;
        var personWidth = imageWidth / 54; //小人的宽高
        var personHeight = imageHeight * 2; //小人的高
        var index = 0;
        var x0 = ctx.canvas.width / 54 - personWidth / 54; //小人的起始位置
        var y0 = ctx.canvas.height / 54 - personHeight / 54;;
        ctx.drawImage(image, 0, 0, personWidth, personHeight, x0, y0, personWidth, personHeight);
        setInterval(function() {
            ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
                //context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);
                //image:规定要使用的图像、画布或视频。
                //开始剪切的 x 坐标位置。
                //开始剪切的 y 坐标位置。
                //被剪切图像的宽度。
                //被剪切图像的高度。
                //在画布上放置图像的 x 坐标位置。
                //在画布上放置图像的 y 坐标位置。
                //可选。要使用的图像的宽度。（伸展或缩小图像）
                //可选。要使用的图像的高度。（伸展或缩小图像）
            ctx.drawImage(image, index * personWidth, 0, personWidth, personHeight, x0, y0, personWidth, personHeight);
            index++;
            if (index >= 54) {
                index = 0;
            }
            vectorLayerPoi.getSource().changed()
        }, 50);
    }
    for (var i = 0; i < vectors.length; i++) {
        let coord = vectors[i];
        let circle = new Feature({
            attributes: vectors[i].attributes,
            geometry: new Point(wgs84Toweb3857([coord.X, coord.Y]))
        });
        circle.setStyle(new Style({
            image: new Icon({
                img: canvas,
                imgSize: [canvas.width, canvas.height],
                scale: config.scale
            })
        }));
        vectorLayerPoi.getSource().addFeature(circle);
    }
    map.addLayer(vectorLayerPoi);
}
export function addHugePointsGifCar(layerId, vectors, config, map, rotate) {
    // var coords =[]
    // var red = 0
    // for(var i = 0; i < 500; i++)
    // {
    //     var x = 118  +  4 * Math.random()
    //     var y = 28 + 5 * Math.random()
    //     coords.push([x,y])
    // }
    // var vectorLayerPoi = null ;
    var vectorSourcePoi = new VectorSource({})
    var vectorLayerPoi = new VectorLayer({
        id: layerId,
        source: vectorSourcePoi,
        // style: iconStyle,
        // updateWhileAnimating:true
    })
    vectorLayerPoi.setZIndex(config.zIndex)
    var canvas = document.createElement("canvas"); //创建一个canvas标签
    canvas.width = 150;
    canvas.height = 400;
    var image = new Image();
    var ctx = canvas.getContext("2d");
    image.src = config.img
    image.onload = function() {
        var imageWidth = image.width; //获取当前图片的尺寸
        var imageHeight = image.height;
        var personWidth = imageWidth / 24; //小人的宽高
        var personHeight = imageHeight * 2; //小人的高
        var index = 0;
        var x0 = ctx.canvas.width / 24 - personWidth / 12; //小人的起始位置
        var y0 = ctx.canvas.height / 24 - personHeight / 12;;
        ctx.drawImage(image, 0, 0, personWidth, personHeight, x0, y0, personWidth, personHeight);
        setInterval(function() {
            ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
                //context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);
                //image:规定要使用的图像、画布或视频。
                //开始剪切的 x 坐标位置。
                //开始剪切的 y 坐标位置。
                //被剪切图像的宽度。
                //被剪切图像的高度。
                //在画布上放置图像的 x 坐标位置。
                //在画布上放置图像的 y 坐标位置。
                //可选。要使用的图像的宽度。（伸展或缩小图像）
                //可选。要使用的图像的高度。（伸展或缩小图像）
            ctx.drawImage(image, index * personWidth, 0, personWidth, personHeight, x0, y0, personWidth, personHeight);
            index++;
            if (index >= 24) {
                index = 0;
            }
            vectorLayerPoi.getSource().changed()
        }, 50);
    }
    for (var i = 0; i < vectors.length; i++) {
        let coord = vectors[i];
        let circle = new Feature({
            attributes: vectors[i].attributes,
            geometry: new Point([coord.X, coord.Y])
        });
        circle.setStyle(new Style({
            image: new Icon({
                img: canvas,
                imgSize: [canvas.width, canvas.height],
                scale: config.scale,
                rotation: rotate,
                offset: [0, -120]
            })
        }));
        vectorLayerPoi.getSource().addFeature(circle);
    }
    map.addLayer(vectorLayerPoi);
}
export function addMultiHugePoints(layerId, vectors, config, map) {
    for (let i = 0; i < layerId.length; i++) {
        var index = i
        let targetLayer = this.findByIdToLayer(layerId[index], this.poiMap)
        if (targetLayer == undefined) { //去掉重复的渲染
            var vectorSource = new VectorSource({})
            let iconStyle = new Style({
                image: new Icon({
                    scale: config.scale,
                    src: config.img
                })
            })
            let hugePointsArr = [];
            if (vectors.length == 0) return;
            for (var i = 0; i < vectors.length; i++) {
                let iconFeature = new Feature({
                    attributes: vectors[i].attributes,
                    geometry: new Point([vectors[i].X, vectors[i].Y])
                })
                hugePointsArr.push(iconFeature)
            }
            vectorSource.addFeatures(hugePointsArr)
            let vectorLayerPoi = new VectorLayer({
                id: layerId[index],
                source: vectorSource,
                style: iconStyle,
                updateWhileAnimating: true
            })
            vectorLayerPoi.setZIndex(config.zIndex)
            map.addLayer(vectorLayerPoi)
        }
    }

}
export function addHugePoints3857(layerId, vectors, config, map) {
    var vectorSource = new VectorSource({})
    let iconStyle = new Style({
        image: new Icon({
            scale: config.scale,
            src: config.img
        })
    })
    let hugePointsArr = [];
    if (vectors.length == 0) return;
    for (var i = 0; i < vectors.length; i++) {
        // let pos3857 = new transform([vectors[i].X, vectors[i].Y], "EPSG:3857", "EPSG:4326")
        let gaode = gcj_encrypt(vectors[i].X, vectors[i].Y) //84转高德
            // let pos3857 = new transform(gaode, "EPSG:4326", "EPSG:3857")//4326转为3857
        let iconFeature = new Feature({
            attributes: vectors[i].attributes,
            geometry: new Point(gaode)
        })
        hugePointsArr.push(iconFeature)
    }
    vectorSource.addFeatures(hugePointsArr)
    let vectorLayerPoi = new VectorLayer({
        id: layerId,
        source: vectorSource,
        style: iconStyle,
        updateWhileAnimating: true
    })
    vectorLayerPoi.setZIndex(config.zIndex)
    map.addLayer(vectorLayerPoi)
}
// export function addHugePoints3857(layerId, vectors, config, map) {
//     var vectorSource = new VectorSource({})
//     let iconStyle = new Style({
//         image: new Icon({
//             scale: config.scale,
//             src: config.img
//         })
//     })
//     let hugePointsArr = [];
//     if (vectors.length == 0) return;
//     for (var i = 0; i < vectors.length; i++) {
//         let gaode = gcj_encrypt(vectors[i].X, vectors[i].Y)//84转高德
//         // let pos3857 = new transform(gaode, "EPSG:4326", "EPSG:3857")//4326转为3857
//         let iconFeature = new Feature({
//             attributes: vectors[i].attributes,
//             geometry: new Point(gaode)
//         })
//         hugePointsArr.push(iconFeature)
//     }
//     vectorSource.addFeatures(hugePointsArr)
//     let vectorLayerPoi = new VectorLayer({
//         id: layerId,
//         source: vectorSource,
//         style: iconStyle,
//         updateWhileAnimating: true
//     })
//     vectorLayerPoi.setZIndex(config.zIndex)
//     map.addLayer(vectorLayerPoi)
// }
export function addHugePoints(layerId, vectors, config, map) {
    var vectorSource = new VectorSource({})
        // let iconStyle = new Style({
        //     image: new Icon({
        //         scale: config.scale,
        //         src: config.img
        //     })
        // })
    let hugePointsArr = [];
    if (vectors.length == 0) return;
    for (var i = 0; i < vectors.length; i++) {
        let iconFeature = new Feature({
            attributes: vectors[i].attributes,
            config: config,
            geometry: new Point(wgs84Toweb3857([parseFloat(vectors[i].X), parseFloat(vectors[i].Y)]))
        })
        hugePointsArr.push(iconFeature)
    }
    vectorSource.addFeatures(hugePointsArr)
    let vectorLayerPoi = new VectorLayer({
        id: layerId,
        source: vectorSource,
        style: styleFunction, //先渲染所有的poi点完成之后再回调style函数
        updateWhileAnimating: true
    })
    vectorLayerPoi.setZIndex(config.zIndex)
    map.addLayer(vectorLayerPoi)
}

function styleFunction(feature) {
    let iconStyle = new Style({
        image: new Icon({
            scale: feature.values_.config.scale,
            src: feature.values_.config.img
        }),
        // text: new Text({//******可为poi元素上面添加字体元素*/
        //     // 对其方式
        //     textAlign: 'center',
        //     // 基准线
        //     textBaseline: 'middle',
        //     offsetY: -30,
        //     // 文字样式
        //     font: 'normal 16px 黑体',
        //     // 文本内容
        //     text: feature.values_.attributes.name,
        //     // 文本填充样式
        //     fill: new Fill({
        //         color: 'rgba(255,255,255,1)'
        //     }),
        //     padding: [5, 5, 5, 5],
        //     backgroundFill: new Fill({
        //         color: 'rgba(0,0,255,0.6)'
        //     })
        // })
    })
    return iconStyle
}
export function queryGeometryMulti(posArr, map, config) {
    return new Promise((resolve) => {
        if (config == undefined) return;
        let finalStrArr = [];
        for (var i = 0; i < posArr.length; i++) {
            let posArrStr = '';
            for (var j = 0; j < posArr[i][0].length; j++) {
                if (j == posArr[i][0].length - 1) {
                    posArrStr += "[" + posArr[i][0][j] + "]";
                } else {
                    posArrStr += "[" + posArr[i][0][j] + "],";
                }
            }
            finalStrArr.push(posArrStr)
        }
        var _this = this;
        var initData = {
            "posArray": [{
                "posArr": finalStrArr,
                "tableName": config.tableName
            }]
        }
        axios.post(config.serurl, qs.stringify(initData), {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        }).then(res => {
            let data = res.data
            resolve(data)
        })
    })
}
export function queryGeometry(posArr, map, config) {
    return new Promise((resolve) => {
        if (config == undefined) return;
        let posArrStr = '';
        for (var i = 0; i < posArr.length; i++) {
            if (i == posArr.length - 1) {
                posArrStr += "[" + posArr[i] + "]";
            } else {
                posArrStr += "[" + posArr[i] + "],";
            }
        }
        var _this = this;
        var initData = {
            "posArray": [{
                "posArr": posArrStr,
                "tableName": config.tableName
            }]
        }
        axios.post(config.serurl, qs.stringify(initData), {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        }).then(res => {
            let data = res.data
            resolve(data)
        })
    })
}
export function addressSearch(address, config) {
    var _this = this;
    return new Promise(function(resolve) {
        if (address == null || address == "") {
            return
        }
        var initData = {
            "posArray": [{
                "address": address,
                "tableName": config.tableName
            }]
        }
        axios.post(config.serurl, qs.stringify(initData), {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        }).then(res => {
            let data = res.data
            resolve(data);
        })
    })
}
export function revAddressSearch(address, config) {
    var _this = this;
    return new Promise(function(resolve) {
        if (address == null || address == "") {
            return
        }
        var initData = {
            "posArray": [{
                "addressPoints": address,
                "tableName": config.tableName
            }]
        }
        axios.post(config.serurl, qs.stringify(initData), {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        }).then(res => {
            let data = res.data
            resolve(data);
        })
    })
}