
//V2.7.1 更改了CAD高亮HighlightSiteModelLayer，修改了带孔洞CAD的高亮效果
/*3、区域模型高亮显示(改成了矢量地图，图层为room，share,balcony,重点是选中矢量面的高度设置，一定要吻合地面*/
var HighlightSiteModelLayer=function (main_view,main_scene,map_view,map_scene){
    var geo_area = new IV.THREE.PlaneGeometry( 0.01, 0.01, 32 ); //随便创建个高亮用的网格，不创建会警告
    var mat_area = new IV.THREE.MeshBasicMaterial({ color: 0xffff00,transparent: true,opacity:0.3 });
    //mat_area.depthTest=false;
    var mat_room = new IV.THREE.MeshLambertMaterial({ color: 0xffff00,transparent: true,opacity:1 });
    var camera = main_view.getCamera();
    mat_area.side= IV.THREE.DoubleSide;
    //mat_area.depthTest=false;
    mat_room.side= IV.THREE.DoubleSide;
    mat_room.renderOrder = 2;
    mat_area.renderOrder = 3;
    //mat_room.depthTest=false;
    mat_room.transparent=false;
    mat_room.colorWrite = false;
    var high_light_geometry;
    var locked=false;
    var mesh_area = new IV.THREE.Mesh(geo_area,mat_area);
    map_scene.add(mesh_area);
    var geo_area_main = new IV.THREE.PlaneGeometry( 0.01, 0.01, 32 ); //随便创建个高亮用的网格，不创建会警告
    var mesh_area_main=new IV.THREE.Mesh(geo_area_main,mat_area);
    var attributes=[{name:"room",color:	0xffff00},{name:"share",color:	0x0000ff},{name:"balcony",color:0xff00ff},{name:"park",color:0x808000}];
    mesh_area_main.position.set( 0, 0, -4 );
    main_view.overlayScene.add(mesh_area_main);
   // console.log(mesh_area_main);
    var rooms,floor,squareShape,preSelectedId=-1;
    var wall_group = new IV.THREE.Group();
    main_view.overlayScene.add(wall_group);

    var vectorMapRepository =window.IV.injector.get("VectorMapRepository");
    var vectorMapService =window.IV.injector.get("VectorMapService");
    var geo_service = IV.injector.get('GeoTransformationService');
    //console.log(vectorMapService);
/* 以后通过射线获取本层的实际高度，这样高亮的网格能够画再地面上
    setTimeout(function(){
            var raycastService =window.IV.injector.get("RaycastService");
            console.log("settimeour");
            var camera = IV.getMainView().getCamera();
            var source_position = new IV.THREE.Vector3(camera.position.x, camera.position.y, camera.position.z);
            var ray_position = new IV.THREE.Vector3(camera.position.x, camera.position.y, camera.position.z-0.1);
            var dataset=IV.getMainView().currentImage.dataset;
            console.log(camera.position);
            console.log("iv",IV.getMainView().currentImage.location); //dataset

            var reponse = raycastService.serverSidePickPromise(source_position, ray_position, dataset);
            reponse.then(function (response) { console.log(response);}).catch(function(error){
                console.log(error);
            });

        }, 5000);
* */
 //   console.log(floor=map_view.FloorChangerService.currentFloors[0]);
       //目前每层只支持单个dxf文件来高亮显示
        var that = this;
        vectorMapRepository.initialized.then(function () {
            floor=map_view.FloorChangerService.currentFloors[0];
            var vectorFiles=vectorMapRepository.data;
            //console.log( that);

            var vectorFiles_currentFloor = [];
            for (var i = 0; i < vectorFiles.length; i++) {
                var vector_zMin=vectorFiles[i].zMin,vector_zMax=vectorFiles[i].zMax;
                var vectorLayers=vectorFiles[i].vectorLayers;

                if(vector_zMin<floor.zMin&&vector_zMax>floor.zMin&&isHightLightVectorLayer(vectorLayers)) { //先判断矢量文件是不是属于这个楼层，再判断是不是有控制高亮的矢量文件
                    //rooms=vectorLayers;
                    vectorFiles_currentFloor.push(vectorFiles[i]);
                    //console.log(rooms);
                    //draw_walls(rooms,floor);
                    //break;
                }
            }

            //create_menu(vectorFiles_currentFloor,that);
            var current_vectorFileID =0; //默认为读取的第一个文件矢量文件
            switchMap(vectorFiles_currentFloor,current_vectorFileID)
            create_menu(vectorFiles_currentFloor,that);
        });
    function switchMap(vectorFiles_currentFloor,current_vectorFileID) {
        var  vectorFile =null;
        if(vectorFiles_currentFloor.length>0) {
            vectorFile = vectorFiles_currentFloor[current_vectorFileID];
            setChooseCADVisbileOnly(vectorFiles_currentFloor,current_vectorFileID); //仅对属于当前楼层的CAD文件操作，设置选中CAD可见，其他不可见
            // 画墙壁，起遮挡效果;
            rooms=vectorFile.vectorLayers;
            draw_walls(rooms,floor);
        }
     }
     function  setChooseCADVisbileOnly(vectorFiles_currentFloor,current_vectorFileID) {
         for (var i = 0; i < vectorFiles_currentFloor.length; i++) {
             var vectorLayers = vectorFiles_currentFloor[i].vectorLayers;
             if(i === current_vectorFileID ){
                 for (var j = 0; j < vectorLayers.length; j++) {
                     vectorLayers[j].visible = true;
                 }
             }else {
                 for (var j = 0; j < vectorLayers.length; j++) {
                     vectorLayers[j].visible = false;
                 }
             }
         }
         vectorMapService.visibilityUpdateEvent.emit()
     }
    function create_menu(vectorFiles_currentFloor,that){
        var sub_menu_items = [];
        for (var i = 0; i < vectorFiles_currentFloor.length; i++) {
            var file_name = vectorFiles_currentFloor[i].name; //用文件名称来作为地图名称
            var map_name = file_name.substring(0,file_name.indexOf('.'));//去掉文件名称后缀
            var menu_item = {
                name:map_name,
                icon:"add",
                vid:i,
                callback: function (e) {
                    IV.custom.select_map_id= e;
                    switchMap(vectorFiles_currentFloor,sub_menu_items[e].vid)

                    //console.log(sub_menu_items[e].vid)
                }
            };
            sub_menu_items.push(menu_item)
        }
        // add lock highlight


        that.onContextMenu = function(e) //点击测量图标执行删除功能
        {
            var menu_items=[{
                name: "地图模式",
                icon: "fa fa-list-ul",
                items:sub_menu_items
            }];
            if(rooms&&rooms.length>0) {
               // console.log(rooms.length)
                if (!locked) {
                    var menu_item = {
                        name: "区域锁定",
                        icon: "fa-lock",
                        vid:null,
                        callback: function () {
                            locked = true;
                        }
                    };
                    menu_items.push(menu_item)
                } else {
                    var menu_item = {
                        name: "区域解锁",
                        icon: "fa-unlock",
                        vid:null,
                        callback: function () {
                            locked = false;
                        }
                    };
                    menu_items.push(menu_item)
                }
            }
            return menu_items;
        }
    }

    IV.api.view.floorChangerService.onFloorChange.connect(floorChanged);
    function floorChanged(e) {
        ///目前每层最多只支持单个dxf文件
        var hasHightLightVector=false;
        locked=false;
        mesh_area.visible = false;
        mesh_area_main.visible = false;
        preSelectedId=-1;
        rooms=undefined;
        floor=map_view.FloorChangerService.currentFloors[0];
        var vectorFiles=vectorMapRepository.data;
        var vectorFiles_currentFloor = []
        for (var i = 0; i < vectorFiles.length; i++) {
            var vector_zMin=vectorFiles[i].zMin,vector_zMax=vectorFiles[i].zMax;
            var vectorLayers=vectorFiles[i].vectorLayers;
            if(vector_zMin<floor.zMin&&vector_zMax>floor.zMin&&isHightLightVectorLayer(vectorLayers)) { //先判断矢量文件是不是属于这个楼层，再判断是不是有控制高亮的矢量文件
                vectorFiles_currentFloor.push(vectorFiles[i]);
                hasHightLightVector=true;
            }
        }
        var current_vectorFileID =0; //默认为读取的第一个文件矢量文件
        switchMap(vectorFiles_currentFloor,current_vectorFileID)
        create_menu(vectorFiles_currentFloor,that);
        // for (var i = 0; i < vectorFiles.length; i++) {
        //     var vector_zMin=vectorFiles[i].zMin,vector_zMax=vectorFiles[i].zMax;
        //     var vectorLayers=vectorFiles[i].vectorLayers;
        //     console.log(vectorLayers);
        //     if(vector_zMin<floor.zMin&&vector_zMax>floor.zMin&&isHightLightVectorLayer(vectorLayers)) { //先判断矢量文件是不是属于这个楼层，再判断是不是有控制高亮的矢量文件
        //         rooms=vectorLayers;
        //         floor=map_view.FloorChangerService.currentFloors[0];
        //         draw_walls(rooms,floor);
        //         hasHightLightVector=true;
        //         break;
        //     }
        // }

        if(!hasHightLightVector){
            while (wall_group.children.length)
            {
                wall_group.remove(wall_group.children[0]);
            }
        }

        main_view.invalidateScene();
        map_view.invalidateScene();
    }
    //只要层级名称出现room,share,balcony等就说明是高亮层了
    function isHightLightVectorLayer(vectorLayers){
        //console.log(vectorLayers);
        for (var j = 0; j < vectorLayers.length; j++) {
            for (var a = 0; a < attributes.length; a++) {
                if (attributes[a].name === vectorLayers[j].name) {
                    return true;
                }
            }
        }
        return false;
    }
    function draw_walls(rooms,floor){
        if(floor&&rooms&&rooms.length>0){ //画sitmodel 多边形
            var zMin=floor.zMin,zMax=floor.zMax;
            var height = (zMax- zMin).toFixed(2);
            var extrudeSettings = {
                depth: height,
                steps: 1,
                bevelEnabled: false,
            };

            for (var i = 0; i < rooms.length; i++) { //这里rooms其实就是层级
                var layer=rooms[i];
                if(layer.name==="room") { //车位等不是房间，不用有遮挡效果
                     var entities=layer.vectorEntities;
                     for (var j = 0; j < entities.length; j++) {
                         var entity_coord = new Array();
                         var coordinates = entities[j].vectorEntity.coordinates;
                         for (var z = 0; z < coordinates.length; z++) {
                             var local_coordinate = geo_service.vectorToLocal(new IV.THREE.Vector3(coordinates[z].x, coordinates[z].y, 0));
                             //geo_service.vectorToLocal
                             entity_coord.push(local_coordinate);
                         }
                         var entiryShape = new IV.THREE.Shape();
                         entiryShape.moveTo(entity_coord[0].x, entity_coord[0].y);
                         for (var a = 1; a < entity_coord.length; a++) {
                             entiryShape.lineTo(entity_coord[a].x, entity_coord[a].y);
                         }
                         entiryShape.moveTo(entity_coord[0].x, entity_coord[0].y);
                         var geo_room = new IV.THREE.ExtrudeBufferGeometry(entiryShape, extrudeSettings);
                         var mesh_room = new IV.THREE.Mesh(geo_room, mat_room);
                         mesh_room.material.needsUpdate = true;
                         mesh_room.visible = true;
                         mesh_room.position.set(0, 0, zMin);
                         wall_group.add(mesh_room);
                     }

                   // console.log("rooms",rooms[i]);
                    /*
                    var varray = rooms[i].polygon.boundary;
                    var roomShape = new IV.THREE.Shape();
                    roomShape.moveTo(varray[0].x, varray[0].y);
                    for (var j = 1; j < varray.length; j++) {
                        roomShape.lineTo(varray[j].x, varray[j].y);
                    }
                    roomShape.lineTo(varray[0].x, varray[0].y);
                    var geo_room = new IV.THREE.ExtrudeBufferGeometry(roomShape, extrudeSettings);
                    var mesh_room = new IV.THREE.Mesh(geo_room, mat_room);
                    mesh_room.material.needsUpdate = true;
                    mesh_room.visible = true;
                    mesh_room.position.set(0, 0, zMin);
                    main_scene.add(mesh_room);
                    */
                }
            }
            //console.log(rooms);
        }
    }
    this.onContextMenu=function(){
        if(rooms&&rooms.length>0) {
            if (!locked) {
                return {
                    name: "区域锁定",
                    icon: "fa-lock",
                    callback: function () {
                        locked = true;
                    }
                };
            } else {
                return {
                    name: "区域解锁",
                    icon: "fa-unlock",
                    callback: function () {
                        locked = false;
                    }
                };
            }
        }
    };
    /*
    this.onClick=function(){
        for (var i = 0; i < rooms.length; i++) {
            if(preSelectedId==Number(rooms[i].id)){
                SiteModelService.selectModel(rooms[i],false); //显示选中房间
            }
        }
    }
    */
    var geo_map = new IV.THREE.BufferGeometry();
    //var MAX_POINTS = 500;
    //var positions_map = new Float32Array( MAX_POINTS * 3 ); // 3 vertices per point
    //geo_map.addAttribute( 'position', new IV.THREE.BufferAttribute( positions_map, 3 ) );
    var highligh_mesh_map = new IV.THREE.Mesh( geo_map,  mat_area );
    //highligh_mesh_map.frustumCulled = false;
    map_scene.add( highligh_mesh_map);
    var vertex2DArray = [];
    var face2DArray = [];

    var geo_main = new IV.THREE.BufferGeometry();
   // var positions_main = new Float32Array( MAX_POINTS * 3 ); // 3 vertices per point
    //geo_main.addAttribute( 'position', new IV.THREE.BufferAttribute( positions_main, 3 ) );
    var highligh_mesh_main = new IV.THREE.Mesh( geo_main,  mat_area );
    highligh_mesh_main.frustumCulled = false;
    main_view.overlayScene.add( highligh_mesh_main);

    function inside_least_area(point, rooms) { //判断当前鼠标点point，是不是在多边形顶点构成的数组中
        var included_entirs = [];
        for (var i = 0; i < rooms.length; i++) { //这里rooms其实就是层级
            var layer = rooms[i];
            var entities = layer.vectorEntities;
            for (var j = 0; j < entities.length; j++) {
                var entity_coord = new Array();
                var coordinates = entities[j].vectorEntity.coordinates;
                for (var z = 0; z < coordinates.length; z++) {
                    var local_coordinate = geo_service.vectorToLocal(new IV.THREE.Vector3(coordinates[z].x, coordinates[z].y, 0));
                    entity_coord.push(local_coordinate);
                }
                if (inside(point, entity_coord) && entity_coord.length >= 3) {
                    var entity_info ={};
                    entity_info.id = entities[j].id;
                    entity_info.name = layer.name;
                    entity_info.array = entity_coord;
                    included_entirs.push(entity_info)
                }
            }

        }
        return find_holes(included_entirs,rooms)
    }
    function find_center_point(array){
        var x=0,y=0,z=0;
        var l = array.length;
        for (var i = 0; i < l; i++) {
            x = x + array[i].x;
            y = y + array[i].y;
            z = z + array[i].z;
        }
        return new IV.THREE.Vector3(x/l, y/l, z/l)
    }
    function find_holes(included_entirs,rooms) {
        var holes = []
        if(included_entirs.length===1) {
            //var center_point = find_center_point(included_entirs[0].array)
            var poly= included_entirs[0].array;
            var poly_area = calcPolygonArea(poly);
            for (var i = 0; i < rooms.length; i++) { //这里rooms其实就是层级
                var layer = rooms[i];
                var entities = layer.vectorEntities;
                for (var j = 0; j < entities.length; j++) {
                    var entity_coord = new Array();
                    var coordinates = entities[j].vectorEntity.coordinates;
                    for (var z = 0; z < coordinates.length; z++) {
                        var local_coordinate = geo_service.vectorToLocal(new IV.THREE.Vector3(coordinates[z].x, coordinates[z].y, 0));
                        //geo_service.vectorToLocal
                        entity_coord.push(local_coordinate);
                    }
                    var center_point = find_center_point(entity_coord);
                    var entity_area = calcPolygonArea(entity_coord);
                    //一个多边形内又孔洞的认定条件：1/内部有重叠多边形，中心点来判断，2/重叠多边形的面积要小于当前多边形
                    if (inside(center_point, poly) && poly_area>entity_area) {
                        var entity_info = {};
                        entity_info.id = entities[j].id;
                        entity_info.name = layer.name;
                        entity_info.array = entity_coord;
                        holes.push(entity_info)
                    }
                }
            }
            included_entirs[0].holes = holes;
            return included_entirs[0]
        }else{
            var min_area = 100000000;
            var min_index = -1;

            for (var i = 0; i < included_entirs.length; i++) {
                var current_area = calcPolygonArea(included_entirs[i].array);
                if(min_area > current_area ) {
                    min_area = current_area;
                    min_index = i;
                }
            }
            if (min_index !== -1 &&included_entirs[min_index].name !=="room") { //图层名称不是"room"的选择最小面积
                return included_entirs[min_index]
            }else {
                var entity_info = {};
                entity_info.id = -1;
                entity_info.name = "";
                entity_info.array = [];
                entity_info.holes = []
                return entity_info //当处于多重多边形时，就是不需要高亮
            }
        }
    }
    function calcPolygonArea(vertices) {
        var total = 0;
        for (var i = 0, l = vertices.length; i < l; i++) {

            var addX = vertices[i].x;
            var addY = vertices[i == vertices.length - 1 ? 0 : i + 1].y;
            var subX = vertices[i == vertices.length - 1 ? 0 : i + 1].x;
            var subY = vertices[i].y;

            total += (addX * addY * 0.5);
            total -= (subX * subY * 0.5);
        }
        return Math.abs(total);
    }
    function make_shape(entity_coord){
        var shape = new IV.THREE.Shape();
        if(entity_coord.length>0)
            shape.setFromPoints(entity_coord);
        return shape
    }

    function make_holes(holes){
        var holes_format = []
        for (var i = 0; i < holes.length; i++) {
            var hs = holes[i].array;
            var hole_path = new IV.THREE.Path();
            if(hs.length>0)
                hole_path.setFromPoints(hs);
            holes_format.push(hole_path);
            }
        return holes_format
    }

    this.onMouseMove=function(e){
        if(rooms&&!locked) {
            var p = map_view.getPositionOnGroundPlane(e.x, e.y, 0);
            var cursorInRoom = false;
            var entity =  inside_least_area(p,rooms);

            var curr_id = entity.id;
            var room_name = entity.name;
            var entity_coord = entity.array;
            var entity_coord_shape = make_shape(entity_coord);



            if (entity_coord&&entity_coord.length&&entity_coord.length>0) {
                cursorInRoom = true;
                if (preSelectedId !== Number(curr_id)) {
                    preSelectedId = Number(curr_id);
                    var color=0xffa5000;
                    for(var a=0;a<attributes.length;a++){
                        if(attributes[a].name===room_name){
                            color=attributes[a].color;
                        }
                    }
                    if (room_name ==="room"){  //图层名称是"room"的加洞
                        entity_coord_shape.holes = make_holes(entity.holes);
                    }

                    high_light_geometry = new IV.THREE.ShapeBufferGeometry( entity_coord_shape );

                    mat_area.color.setHex(color);
                    highligh_mesh_map.geometry=high_light_geometry;
                    highligh_mesh_map.visible = true;

                    highligh_mesh_main.geometry=high_light_geometry;
                    highligh_mesh_main.visible = true;
                    highligh_mesh_main.position.z = floor.zMin+0.2;
                    map_view.invalidateScene();
                    main_view.invalidateScene();
                }
            }
            if(!cursorInRoom&&preSelectedId !==-1){
                highligh_mesh_map.visible = false;
                highligh_mesh_main.visible = false;
                mesh_area.visible = false;
                mesh_area_main.visible = false;
                preSelectedId=-1;
                main_view.invalidateScene();
                map_view.invalidateScene();
            }
        }
    };
    function inside(point, vs) { //判断当前鼠标点point，是不是在多边形顶点构成的数组中
        var x = point.x, y = point.y;
        var inside = false;
        for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
            var xi = vs[i].x, yi = vs[i].y;
            var xj = vs[j].x, yj = vs[j].y;
            var intersect = ((yi > y) != (yj > y))
                && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
            if (intersect) inside = !inside;
        }
        return inside;
    };
};

/* 查各种地理坐标的功能*/
var LookupGeoLocation= function (main_view,main_scene,map_view)
{
    if(!IV.custom) //自定义功能集合
        IV.custom={};

    var geo_service = IV.injector.get('GeoTransformationService');
    var configService =window.IV.injector.get("ConfigService");
    var userService=IV.injector.get("UserService");
   // var geo_config={};
    var menuItems = IV.getMenuItems();
    var selected_proj4=null;
    var newItem = {
        title: "坐标查询",
        icon: {
            className: "fa fa-thumb-tack"
        },
        isVisible: function()
        {
            return true;
        },
        isPreviewIconVisible: function()
        {
            return true;
        },
        order: 40,
        template:findUrl()+"template_menu/PickCoordSys.html"
    };

    newItem.onExit=function(){
        selected_proj4=null;
        cursTxt.style.visibility = "hidden";
    };
    menuItems.push(newItem);
    var custom_config={};
    var proj4_setting=null;
    var getCustomConfig=configService.configArray.find(function(t){return t.name==='core.map.measures_save'});
    //configService.saveConfig('core.map.measures_save', "");
    if (getCustomConfig.value!=null&&getCustomConfig.value !== ""){
        custom_config=JSON.parse(getCustomConfig.value);
        if(custom_config.proj4_setting!=null&&custom_config.proj4_setting.length>0){
            proj4_setting=custom_config.proj4_setting;
        }else{
            default_proj4();
        }
    }else{
        default_proj4();
    }

    function default_proj4(){
        proj4_setting=[{
                geo_name: '本地坐标',
                geo_proj4: 'local'
            }, {
                geo_name: 'Wgs84坐标',
                geo_proj4: 'world'
            }, {
                geo_name: 'EPSG 4549:CGCS2000 / 3-degree Gauss-Kruger CM 120E',
                geo_proj4: '+proj=tmerc +lat_0=0 +lon_0=120 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs'
            }];
    }
    IV.custom.init_coord=function(){

        var select_coordinate=document.getElementById("select_coordinate");
        var str = '<option value='+null+'>'+"无"+'</option>';
        for (var j = 0; j < proj4_setting.length; j++) {
            str +='<option value='+JSON.stringify(proj4_setting[j].geo_proj4)+'>'+proj4_setting[j].geo_name+'</option>';
            if(proj4_setting.geo_proj4!=="local"&&proj4_setting.geo_proj4!=="world") {
                proj4.defs(proj4_setting.geo_name, proj4_setting.geo_proj4);
            }
        }
        select_coordinate.innerHTML = str;
        if(!userService.isAdmin()) {
            var coord_div=document.getElementById("coord_editor");
            document.getElementById("editor_coord_froms").removeChild(coord_div);
        }
    };
    IV.custom.pick_coord=function(e){
        selected_proj4=e.options[e.selectedIndex];
        cursTxt.style.visibility = "hidden";
       // console.log(selected_proj4);
    };

    var MapCursor= function (){
        this.onMouseMove=function(e){
            if(selected_proj4&&selected_proj4.value!=="null"&&IV.getCurrentCursorPosition()&&IV.getCurrentCursorPosition().location) {
                var p = map_view.getPositionOnGroundPlane(e.x, e.y, 0);
                var offset = $("#insetPanel").position();
                var e_offset={x:e.x+offset.left,y:e.y+offset.top};
                handleCursorCoords(p,e_offset);
            }
        };
        this.onContextMenu = function(e)
        {
            if(selected_proj4&&selected_proj4.value!=="null"){
                var menu_items = [{
                    name: "复制坐标",
                    icon: "copy",
                    callback: function () {
                        setClipboardText(cursor_coordinates_forCopy);
                    }
                }];

                return menu_items;
            }
        };
    }
    var getMapCursor = new MapCursor();
    map_view.addToScene(getMapCursor);

    var cursor_coordinates;
    var cursor_coordinates_forCopy;
    var cursTxt = document.getElementById("curscroll");
    this.onMouseMove=function(e){
       // console.log(IV.getCurrentCursorPosition());
        if(selected_proj4&&selected_proj4.value!=="null"&&IV.getCurrentCursorPosition()&&IV.getCurrentCursorPosition().location) {
            var p=IV.getCurrentCursorPosition().location;
            handleCursorCoords(p,e);
        }
    };
    function handleCursorCoords(p,e){
        var global = geo_service.vectorToGlobal(new IV.THREE.Vector3(p.x, p.y, p.z));
        if(selected_proj4.value==="local"){
            cursor_coordinates = " x: " + p.x.toFixed(2) + "<br/> y: " + p.y.toFixed(2) + "<br/> z: " + p.z.toFixed(2);
            cursor_coordinates_forCopy=" { x: " + p.x.toFixed(2) + " , y: " + p.y.toFixed(2) + " , z: " + p.z.toFixed(2)+" }";
            cursTxt.innerHTML = cursor_coordinates;
            cursTxt.style.left = (e.x + 10)+"px";
        }else if(selected_proj4.value==="world"){
            cursor_coordinates = " 经度(lon): " + global.x.toFixed(11) + "<br/> 纬度(lat): " + global.y.toFixed(11) + "<br/> 高度(h): " + global.z.toFixed(2);
            cursor_coordinates_forCopy=" { lon: " + global.x.toFixed(11) + " , lat: " + global.y.toFixed(11) + " , h: " + global.z.toFixed(2)+" }";
            cursTxt.innerHTML = cursor_coordinates;
            cursTxt.style.left = (e.x + 20)+"px";
        }else{
            var custom=proj4(selected_proj4.value).forward([global.x,global.y]);
            cursor_coordinates = " X: " + custom[0].toFixed(11) + "<br/>Y: " + custom[1].toFixed(11);
            cursor_coordinates_forCopy=" { x: " + custom[0].toFixed(11) + " , y: " + custom[1].toFixed(11) +" }";
            cursTxt.innerHTML = cursor_coordinates;
            cursTxt.style.left = (e.x + 10)+"px";
        }
        cursTxt.style.top = (e.y + 15)+"px";
        cursTxt.style.backgroundColor="white";
        cursTxt.style.visibility = "visible";
    }
    this.onContextMenu = function(e)
    {
        if(selected_proj4&&selected_proj4.value!=="null"){
            var menu_items = [{
                name: "复制坐标",
                icon: "copy",
                callback: function () {
                    setClipboardText(cursor_coordinates_forCopy);
                }
            }];

            return menu_items;
        }
    };
    function setClipboardText(text){
        var id = "custom-clipboard-textarea-hidden-id";
        var existsTextarea = document.getElementById(id);
        if(!existsTextarea){
            var textarea = document.createElement("textarea");
            textarea.id = id;
            textarea.style.position = 'fixed';
            textarea.style.top = 0;
            textarea.style.left = 0;
            textarea.style.width = '1px';
            textarea.style.height = '1px';
            textarea.style.padding = 0;
            textarea.style.border = 'none';
            textarea.style.outline = 'none';
            textarea.style.boxShadow = 'none';
            textarea.style.background = 'transparent';
            document.querySelector("body").appendChild(textarea);
            existsTextarea = document.getElementById(id);
        }
        existsTextarea.value = text;
        existsTextarea.select();
        try {
            document.execCommand('copy');
        } catch (err) {
            console.log('Unable to copy.');
        }
    }
    IV.custom.save_coord_action=function(e){
        if(userService.isAdmin()) {
            var coord_name = document.getElementById("coord_name");
            var coord_proj4 = document.getElementById("coord_proj4");
            if (coord_name && coord_proj4) {
                if (!coord_name.value) {
                    alert("坐标系名称不能为空！");
                    return;
                }
                if (!coord_proj4.value) {
                    alert("Proj4不能为空！");
                    return;
                }
                var geo_coord = {
                    geo_name: coord_name.value,
                    geo_proj4: coord_proj4.value
                };
                try {
                    proj4.defs(geo_coord.geo_name, geo_coord.geo_proj4);
                }
                catch (err) {
                    alert("proj4输入错误，无法解析！") // 可执行
                    return;
                }

                proj4_setting.push(geo_coord);
                coord_name.value="";
                coord_proj4.value="";
                custom_config.proj4_setting=proj4_setting;
                configService.saveConfig('core.map.measures_save', JSON.stringify(custom_config));
                IV.custom.init_coord();
            }
        }else{
            alert("只有管理员权限才可以保存！");//要换成自定义对话框
        }
    };
    IV.custom.del_coord_action=function(e){
        if(userService.isAdmin()) {

            for (var i = 0; i < proj4_setting.length; i++) {
                var item =proj4_setting[i];
                if (item.geo_proj4 === selected_proj4.value&&item.geo_name===selected_proj4.innerText) {
                    proj4_setting.splice(i, 1);
                    break;
                    // console.log("111111");
                }
            }
            custom_config.proj4_setting=proj4_setting;
            configService.saveConfig('core.map.measures_save', JSON.stringify(custom_config));
            IV.custom.init_coord();
        }else{
            alert("只有管理员权限才可以删除！");//要换成自定义对话框
        }
    };
};

var Load3DModel= function (main_view,main_scene,map_view)
{
    if(!IV.custom) //自定义功能集合
        IV.custom={};

    var geo_service = IV.injector.get('GeoTransformationService');
    var uploadService=IV.injector.get("UploadService");
    var configService =window.IV.injector.get("ConfigService");
    var userService=IV.injector.get("UserService");
    var sitmodelRepo = IV.api.SiteModelApiService.repository;
    var menuItems = IV.getMenuItems();

    var newItem = {
        title: "加载3D模型",
        icon: {
            className: "fa fa-thumb-tack"
        },
        isVisible: function()
        {
            return true;
        },
        isPreviewIconVisible: function()
        {
            return true;
        },
        order: 40,
        template:findUrl()+"template_menu/LoadModels.html"
    };


    menuItems.push(newItem);
    var custom_config={};
    var getCustomConfig=configService.configArray.find(function(t){return t.name==='core.map.measures_save'});
    //configService.saveConfig('core.map.measures_save', "");
    if (getCustomConfig.value!=null&&getCustomConfig.value !== ""){
        custom_config=JSON.parse(getCustomConfig.value);
        // do
    }else{
       //do
    }
    IV.custom.refModellDownload=function(e) {
        sitmodelRepo.findAll().then(function (buildings) {
            var exporter = new IV.THREE.OBJExporter();
            for (var i = 0; i < buildings.length; i++) {
                var building = buildings[i];
                var building_polygon = building.polygon.boundary;
                var floors =  building.children;
                //console.log(building);
                for (var j = 0; j < floors.length; j++) {
                    var floor =  floors[j];
                    var singleGeometry = new IV.THREE.Geometry();
                    makeRoomsShape(singleGeometry,floor.children,floor.height);
                    var floor_polygon;
                    if(floor.polygon == null) {
                        floor_polygon = building_polygon
                    }else{
                        floor_polygon = floor.polygon.boundary;
                    }
                    var mesh = makeShape(floor_polygon,floor.height);
                    mesh.updateMatrix();
                    singleGeometry.merge(mesh.geometry, mesh.matrix);
                    var mat = new IV.THREE.MeshLambertMaterial({ color: 0xffff00,transparent: true,opacity:1 });
                    var fmesh = new IV.THREE.Mesh(singleGeometry,mat);

                    var floor_obj_name = "floor_"+floor.name+".obj";
                    var result  = exporter.parse(fmesh);

                    download(floor_obj_name, result);
                }
            }
        });
        function makeRoomsShape(singleGeometry,children,height){
            for (var i = 0; i < children.length; i++) {
                var childs = children[i];
                if(childs&&childs.children) {
                    //console.log(childs.children);
                    for (var j = 0; j < childs.children.length; j++) {
                        var boundary = childs.children[j].polygon.boundary;
                        var mesh = makeShape(boundary,height);
                        mesh.updateMatrix();
                        singleGeometry.merge(mesh.geometry, mesh.matrix);

                    }
                }
            }

        }
        function makeShape(boundary,height){
            var varray = boundary;
            var shape = new IV.THREE.Shape();
            shape.moveTo(varray[0].x, varray[0].y);
            for (var j = 1; j < varray.length; j++) {
                shape.lineTo(varray[j].x, varray[j].y);
            }
            shape.lineTo(varray[0].x, varray[0].y);
            var extrudeSettings = {
                depth: height,
                steps: 1,
                bevelEnabled: false,
            };

            var geo=new IV.THREE.ShapeGeometry( shape);
            // var mat = new IV.THREE.MeshLambertMaterial({ color: 0xffff00,transparent: true,opacity:1 });
            // var fmesh = new IV.THREE.Mesh(geo,mat);
            //console.log(geo)
            var fmesh = new IV.THREE.Mesh(geo);
            return fmesh;
        }
        function download(filename, text) {
            var pom = document.createElement('a');
            pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
            pom.setAttribute('download', filename);
            if (document.createEvent) {
                var event = document.createEvent('MouseEvents');
                event.initEvent('click', true, true);
                pom.dispatchEvent(event);
               // console.log("12312313")
            }
            else {
                pom.click();
            }
        }
    };
};

/*查找本站域名，一个通用的方法*/
function findUrl(){
    var pathArray = window.location.pathname.split( '/' );
    var newPath;
    for(var i=0;i<pathArray.length-1;i++){
        if(newPath)
            newPath+=pathArray[i]+"/";
        else
            newPath=pathArray[i]+"/";
    }
    return window.location.protocol + "//" + window.location.host  +newPath;
}

/*所有自定义功能设置*/
var Setting=function(){

    var custom_config={};
    var configService =IV.injector.get("ConfigService");
    var userService=IV.injector.get("UserService");
    var general_setting=null;
    var main_view = IV.getMainView();
    var main_scene = main_view.scene;
    var map_view = IV.getMapView();
    var map_scene = map_view.scene;
    var camera = main_view.getCamera();
    var getSettingConfig=configService.configArray.find(function(t){return t.name==='menu.settings.visible'});

    if(JSON.parse(getSettingConfig.value)&&userService.isAdmin()){

        if(!IV.custom) //自定义功能集合
            IV.custom={};
        var menuItems = IV.getMenuItems();
        var newItem = {
            title: "特色功能",
            icon: {
                className: "fa fa-cogs"
            },
            isVisible: function()
            {
                return true;
            },
            isPreviewIconVisible: function()
            {
                return true;
            },
            order: 100,
            template:findUrl()+"template_menu/Setting.html"
        };
        menuItems.push(newItem);
    }
    setting_init();

    function setting_init(){ //这个方法只执行一次
        var getCustomConfig=configService.configArray.find(function(t){return t.name==='core.map.measures_save'});

        //configService.saveConfig('core.map.measures_save', "");
        //console.log(getCustomConfig);
        if (getCustomConfig.value!=null&&getCustomConfig.value !== ""){
            custom_config=JSON.parse(getCustomConfig.value);
            if(custom_config.general_setting!=null){
                general_setting=custom_config.general_setting;
            }else{
                default_setting();
            }
        }else{
            default_setting();
        }

        load_menu();

    }

    IV.custom.settingOnload=function(){ //这个方法每次打开侧边菜单栏执行

        document.getElementById("setting_sitemodel").checked=general_setting.subArea;
        document.getElementById("setting_coord").checked=general_setting.cursorPosition;
        document.getElementById("setting_map_switch").checked=general_setting.switchMap;
        document.getElementById("setting_3dmodel").checked = general_setting.loadl3DModels;
    };
    function default_setting(){
        general_setting={
                subArea: false,
                cursorPosition: false,
                switchMap: false,
                loadl3DModels:false
        };
    }
    function load_menu(){
        if(general_setting.cursorPosition){
            var lookupGeoLocation = new LookupGeoLocation(main_view,main_scene,map_view, map_scene);
            main_view.addToScene(lookupGeoLocation);
        }
        if(general_setting.loadl3DModels){
            var load3DModel = new Load3DModel(main_view,main_scene,map_view, map_scene);
            main_view.addToScene(load3DModel);

        }
        // if(general_setting.switchMap){
        //     var cadMapChnager = new CADMapChanger(map_view, map_scene);
        //     map_view.addToScene(cadMapChnager);
        // }
        //
        if(general_setting.subArea){
             var highlightSiteModelLayer = new HighlightSiteModelLayer(main_view,main_scene,map_view, map_scene);
              map_view.addToScene(highlightSiteModelLayer);
        }

    }
    IV.custom.settingSave=function(e){
        general_setting.subArea=document.getElementById("setting_sitemodel").checked;
        general_setting.cursorPosition=document.getElementById("setting_coord").checked;
        general_setting.switchMap=document.getElementById("setting_map_switch").checked;
        general_setting.loadl3DModels=document.getElementById("setting_3dmodel").checked;
        custom_config.general_setting=general_setting;
           // console.log(custom_config);
        if(userService.isAdmin()) {
            configService.saveConfig('core.map.measures_save', JSON.stringify(custom_config));
            alert("请注意刷新网页后才能生效！");//要换成自定义对话框
        }else{
                alert("只有管理员权限才可以保存！");//要换成自定义对话框
        }

    };

};



