// 微站上的百度地图

// NOTE!!! 这里的 ./ 一定不要忽略;否则被外部模块加载时,路径解析错误
define(['../testDrive', './baiduMapApi'],
    function(module){
        return module.directive('icBaiduMapTrack', function(baiduMapApi){
            // 绘制路径
            function drawPaths(map, paths,flag){
                var points = [];
                var pointsColor= [];
                var lon = 0,lat=0;
                if(paths.length>0){
                    angular.forEach(paths,function(paths){
                        var i=0;
                        //初始化车辆上一个点经纬度
                        var lonLast = paths.points[0].lon2;
                        var latLast = paths.points[0].lat2;
                        angular.forEach(paths.points,function(locus){
                            if(i==0 || i == paths.points.length - 1){
                                var icon = "";
                                var new_point = new BMap.Point(locus.lon2,locus.lat2);
                                if(i==0){
                                    icon = new BMap.Icon("/fleet/styles/images/mapIcon/start.png", new BMap.Size(25,25));
                                    var marker = new BMap.Marker(new_point,{icon:icon});  // 创建标注
                                }
                                else if(flag){
                                    icon = new BMap.Icon("/fleet/styles/images/mapIcon/end.png", new BMap.Size(25,25));
                                    var marker = new BMap.Marker(new_point,{icon:icon});  // 创建标注
                                }
                                map.addOverlay(marker);
                            }
                            if(i % 2 == 0 || i == paths.points.length - 1){
                                var Position ={};  //color
                                var twoPosition = []; //color

                               var lastPosition=new BMap.Point(lonLast,latLast); //上一个的位置的经纬度
                                twoPosition.push(lastPosition);
                               var currentPosition=new BMap.Point(locus.lon2,locus.lat2); //本次的经纬度
                                twoPosition.push(currentPosition);

                                Position.position = twoPosition;  //相邻的两个点
                                Position.speed = locus.speed;  //后一个点的速度

                                lonLast = locus.lon2;  //保存本次循环的经纬度
                                latLast = locus.lat2;

                                points.push(currentPosition);  //原始
                                pointsColor.push(Position);  //color
                            }
                            lon += parseInt(locus.lon2);
                            lat += parseInt(locus.lat2);
                            i++;
                        });
                    });
                }
                if(paths.speedColor){
                    for(var i=0;i<pointsColor.length;i++){
                        if( pointsColor[i].speed > 120){
                            var strokeColor = "#0F253F";
                        }else if( pointsColor[i].speed < 120 && pointsColor[i].speed >=90){
                            var strokeColor = "#52DC52";
                        }else if( pointsColor[i].speed < 90 && pointsColor[i].speed >= 45){
                            var strokeColor = "#5E93CE";
                        }else if( pointsColor[i].speed < 45 && pointsColor[i].speed >= 15){
                            var strokeColor = "#E46D0A";
                        }else{
                            var strokeColor = "#A40408";
                        }
                        var curve = new BMap.Polyline(pointsColor[i].position, {strokeColor:strokeColor, strokeWeight:5, strokeOpacity:1}); //创建弧线对象 颜色，宽度，透明度
                        map.addOverlay(curve); //添加到地图中
                    }
                }else{
                    var curve = new BMap.Polyline(points, {strokeColor:"blue", strokeWeight:3, strokeOpacity:0.5}); //创建弧线对象 颜色，宽度，透明度
                    map.addOverlay(curve); //添加到地图中
                }

                map.setCenter(new BMap.Point(lon/points.length,lat/points.length));
                map.setViewport(points);
                //var top_left_control = new BMap.ScaleControl({anchor: BMAP_ANCHOR_TOP_LEFT});// 左上角，添加比例尺
                //var top_left_navigation = new BMap.NavigationControl();  //左上角，添加默认缩放平移控件
                var top_right_navigation = new BMap.NavigationControl({anchor: BMAP_ANCHOR_TOP_RIGHT, type: BMAP_NAVIGATION_CONTROL_ZOOM}); //右上角，仅包含平移和缩放按钮
                /*缩放控件type有四种类型:
                 BMAP_NAVIGATION_CONTROL_SMALL：仅包含平移和缩放按钮；BMAP_NAVIGATION_CONTROL_PAN:仅包含平移按钮；BMAP_NAVIGATION_CONTROL_ZOOM：仅包含缩放按钮*/
                //map.addControl(top_left_control);
                //map.addControl(top_left_navigation);
                map.addControl(top_right_navigation);

                //map.setViewport(view);
                //curve.enableEditing(); //开启编辑功能
                // BMapLib -> baiduCurveLineApi
                // var curve = new baiduCurveLineApi.CurveLine(points, {strokeColor:"blue", strokeWeight:3, strokeOpacity:0.5}); //创建弧线对象
                // console.log(baiduCurveLineApi);
            }
            //添加起点，终止图标
            function drawIco(map, paths){
                if(paths.length>0){
                    var pointEnd = paths[0].points;   //取最后一个points
                    var pointStart = paths[paths.length-1].points;    //取第一个points
                    //终止标注的经纬度
                    var lngEnd = parseFloat(pointEnd[0].lon2);
                    var latEnd = parseFloat(pointEnd[0].lat2);
                    //起点标注的经纬度
                    var lngStart =parseFloat(pointStart[pointStart.length-1].lon2);
                    var latStart =parseFloat(pointStart[pointStart.length-1].lat2);
                    ////创建起点，终止标注
                    var ptStart = new BMap.Point(lngStart, latStart+0.004);
                    var ptEnd = new BMap.Point(lngEnd, latEnd+0.004);
                    var myIconStart = new BMap.Icon("./images/start.png", new BMap.Size(30,30));
                    var myIconEnd = new BMap.Icon("./images/end.png",new BMap.Size(30,30));
                    var markerStart = new BMap.Marker(ptStart,{icon:myIconStart});  // 创建起点标注
                    var markerEnd = new BMap.Marker(ptEnd,{icon:myIconEnd});  // 创建终止标注
                    map.addOverlay(markerStart);              // 将起点标注添加到地图中
                    map.addOverlay(markerEnd);              // 将终止标注添加到地图中
                }
            }
            function drewMap(map,icPaths){
                var lng= 0,lat=0;
                var len = 0;
                if(icPaths.length>0)
                {
                    angular.forEach(icPaths,function(points){
                      angular.forEach(points.points,function(locus){
                        lng += parseFloat(locus.lon2);
                        lat += parseFloat(locus.lat2);
                      });
                        len +=points.points.length;
                    });
                    map.centerAndZoom(new BMap.Point(lng/len, lat/len),13);
                    map.enableScrollWheelZoom();
                }
            }
            
            // BD-09坐标系转换
            function fixBD09(paths, fixLonKM, fixLatKM, cb){
                // 1KM大约是9/1000度
                var lonFix = Number(fixLonKM) * 9 / 1000;
                var latFix = Number(fixLatKM) * 9 / 1000;
                
                var ptFix = null; // 当前修正点
                var ptsNeedFix = []; // 需要修正的点集合
                var ptsNeedFixGroup = []; // 百度修正服务,每次只能接受100个点
                
                if(paths){
                    // 计算需要多少个修正点,存放在ptsNeedFix中
                    for(var i=0;i<paths.length;i++){
                        var path = paths[i];
                        if(path.points){
                            for(var j=0;j<path.points.length;j++){
                                var pt = path.points[j];
                                // 去除前置的东经E,北纬N;如果以后需要处理西半球或南半球的坐标,这里需要添加符号
                                pt.lon2 = pt.lon.substr(1);
                                pt.lat2 = pt.lat.substr(1);
                                if(i===0 && j===0){ // 第一个点必修正
                                    ptFix = pt;
                                    ptsNeedFix.push({i:i,j:j, lon: pt.lon2, lat:pt.lat2});
                                    ptsNeedFixGroup.push({pts: ptsNeedFix, done: false});
                                }
                                else{ // 如果和ptFix的偏移量超出lonFix或latFix,则增加一个修正点
                                    if(pt.lon2 - ptFix.lon2 > lonFix || pt.lat2 - ptFix.lat2 > latFix){
                                        ptFix = pt;
                                        ptsNeedFix.push({i:i,j:j, lon: pt.lon2, lat:pt.lat2});
                                        // 分组,每100个分一组
                                        if(ptsNeedFix.length === 1){
                                            ptsNeedFixGroup.push({pts: ptsNeedFix, done: false});
                                        }
                                        else if(ptsNeedFix.length === 100){
                                            ptsNeedFix = [];
                                        }
                                    }
                                }                                
                            }
                        }
                    }
                    
                    // 发往百度服务器计算修正值
                    for(var g=0;g<ptsNeedFixGroup.length;g++){
                        (function(i){
                            baiduMapApi.geoConv(ptsNeedFixGroup[i].pts, function(data){
                                var fixGroup = ptsNeedFixGroup[i];
                                if(data.status == 0 && data.result && data.result.length === fixGroup.pts.length){
                                    for(var k=0;k<data.result.length;k++){
                                        fixGroup.pts[k].deltaLon = data.result[k].x - fixGroup.pts[k].lon;
                                        fixGroup.pts[k].deltaLat = data.result[k].y - fixGroup.pts[k].lat;
                                    }
                                }
                                fixGroup.done = true;

                                // 全部DELTA值计算完成
                                for(var j=0;j<ptsNeedFixGroup.length;j++) {
                                    if (ptsNeedFixGroup[j].done === false) return;
                                }
                                
                                // 拼接全部GROUP统一处理
                                var m,n;
                                var ptsFixAll = [];
                                for(m=0;m<ptsNeedFixGroup.length;m++){
                                    for(n=0;n<ptsNeedFixGroup[m].pts.length;n++){
                                        ptsFixAll.push(ptsNeedFixGroup[m].pts[n]);
                                    }
                                }
                                
                                var fixedCurrent = null, fixedNext = null, idxFixedNext = 1;
                                if(ptsFixAll.length > 0) fixedCurrent = ptsFixAll[0];
                                if(ptsFixAll.length > idxFixedNext) fixedNext = ptsFixAll[idxFixedNext];
                                console.log("共计修正点数:" + ptsFixAll.length);
                                
                                if(fixedCurrent) { // 至少有一个修正点
                                    for (m = 0; m < paths.length; m++) {
                                        var path = paths[m];
                                        for (n = 0; n < path.points.length; n++) {
                                            var pt = path.points[n];
                                            // console.log(pt.lon + ":" + pt.lat);
                                            if (fixedNext === null || m < fixedNext.i || ( m === fixedNext.i && n < fixedNext.j )) {
                                                // 使用fixedCurrent进行修正
                                                pt.lon2 = Number(pt.lon2) + fixedCurrent.deltaLon;
                                                pt.lat2 = Number(pt.lat2) + fixedCurrent.deltaLat;
                                            }
                                            else{
                                                // 使用下一个修正点
                                                fixedCurrent = fixedNext;
                                                pt.lon2 = Number(pt.lon2) + fixedCurrent.deltaLon;
                                                pt.lat2 = Number(pt.lat2) + fixedCurrent.deltaLat;
                                                // 修正点后移一个
                                                idxFixedNext++;
                                                // console.log("fix point next" + JSON.stringify(fixedCurrent));
                                                if(idxFixedNext < ptsFixAll.length){
                                                    fixedNext = ptsFixAll[idxFixedNext];
                                                }
                                                else{
                                                    fixedNext = null; // 已到最后一个修正点
                                                }
                                            }
                                            // console.log(pt.lon + ":" + pt.lat + "->" + fixedCurrent.deltaLon + ":" + fixedCurrent.deltaLat);
                                        }
                                    }
                                }
                                // 发起回调
                                if(typeof cb === 'function') cb(paths);
                            })
                        })(g);
                    }
                }
            }

            // Link icBaiduMap
            function link(scope, element, attrs){
                var map = null;
                // 我们使用异步方式加载百度地图API,很可能此时还没有完成加载过程
                // 因此,当百度地图异步加载完成后,需要通过回调完成初始化
                baiduMapApi.initBaiduMap(function(){
                    console.log("initBaiduMap");
                    var id = attrs['id'];
                    if(!id){ // 如果没有id,那么随机分配一个
                        id = "maplocus_" + Math.random().toString().substr(2, 8);
                        element.attr('id', id);
                        attrs['id'] = id;
                    }
                    map = new BMap.Map(id);
                    map.centerAndZoom(new BMap.Point(106.28501, 35.561577), 4); // 天安门
                    //map.enableScrollWheelZoom();
                    // 如果在地图初始完成之前,icPaths数据已经准备好,那么立即绘制一次
                    if(scope.icPaths){
                        drewMap(map, scope.icPaths);
                        drawPaths(map, scope.icPaths);
                    }
                });

                // 监视icPaths
                scope.$watch('icPaths', function(value) {
                    // 地图初始后,每次icPaths更新,都需要重新绘制路径
                    console.log(value);
                    //if(map){
                    //    if(value && value[0] && value[0].fixed){
                    //        drewMap(map, value);
                    //        drawPaths(map, value,value.flag);
                    //        //drawIco(map, value);
                    //    }
                    //    else {
                            fixBD09(value, 20, 20, function (valueFixed) {
                                if (valueFixed && valueFixed.length > 0)
                                    valueFixed[0].fixed = true; // 已经修正过了的标志位

                                drewMap(map, valueFixed);
                                drawPaths(map, valueFixed,value.flag);
                                //drawIco(map, valueFixed);
                            });
                        //}
                    //}
                });
            }
            return {
                restrict:'A',
                scope: {
                    icBaiduMapTrack: '=', // 地图的初始位置
                    icPaths: '='// 地图上的路径数据
                },
                link: link
            };
        });
});