/**
 * Created by 10086 on 2018/10/31.
 */
/**
 * 全局变量定义
 *
 */
layui.use(['form', 'element', 'layer'], function () {
    form = layui.form,
    element = layui.elementx,
    layer = layui.layer;
});
var myMap;
var flag=true;
var clickBottomCount=0;
var graphicslayer_test, graphicslayer_tj;
var  photo_typeid;
dojo.require("esri.renderers.BlendRenderer");
dojo.require("esri.toolbars.draw");
dojo.require("esri.toolbars.edit");

function init() {
    initFileInput("file-Portrait1")
    community_conf.map.forEach(function(val,inde,array){
        //发布环境
        if(val.url.indexOf("http")<0 &&  val.url.indexOf("https")<0){
            val.url="../"+val.url;
         }
    });
    createMapLoad("myMap", community_conf.extent, community_conf.map,  function(map){
        edit = new esri.toolbars.Edit(map);
        edit.on("graphic-click", editEnd);

        myMap = map;
        graphicslayer_test=new esri.layers.GraphicsLayer({
            id: "graphicslayer_test",
            className: "案件",
            visible: true
        });
        myMap.addLayer(graphicslayer_test);
        graphicslayer_test.on("click",function(o){
            graphicslayer_test_click(o);
        });
        addPoint(result=>{
            loadtabledata(result);
        });
    });
    sj();
}
dojo.ready(init);

getByAjax("../rest/areatypequery", result => {
    $.each(result, function (key, values) {
        $(".sel").append('<option value="' + values.extenddata+ '">' + values.typename + '</option>');
    });
    vue_csxg.typedata=result;
});

//场所修改弹框
var vue_csxg=new Vue({
    el:"#csbjk",
    data:{
        vtitle:"",
        item_detail:[],
        item_base:{name:"",x:0,y:0,wkt:"",id:"",typeid:"",extenddata:""},
        restful_url:"",
        restful_baseurl:"",
        guid:"",
        typedata:[],
        type:"0",
        index:0
    },
    methods:{
        save:function(){
                if(checkWKT(this.item_base.wkt)){
                    postByAjax("../edit/areabaseedit",this.item_base,result=>{
                        if(this.type=="0"){//增
                            $("#areatable").bootstrapTable('prepend', this.item_base);
                        }else{                     //改
                            $("#areatable").bootstrapTable('updateRow', {index: vue_csxg.index, row: this.item_base});
                        }
                        addPoint();
                        if(this.item_base.extenddata&&this.item_base.extenddata!="null"){
                            postByAjax("../edit/"+this.restful_url,this.item_detail,result=>{
                                alert("成功");
                                $("#csbjk").modal("hide");
                            });
                        }else{
                            alert("成功");
                            $("#csbjk").modal("hide");
                        }
                    });
                }else{
                    alert("基础空间属性数据格式无效");
                } 
        }
    },
    computed:{
        myId:function(){
            for(let i=0;i<this.item_detail.length;i++){
                if(this.item_detail[i].key=="id"&&!this.item_detail[i].data){
                    this.item_detail[i].data=this.guid;
                    return this.guid;
                }
            }
        }
    }
});

//底部悬浮框显隐
function bottomClickSpan() {
    var bottomheight = $('#BottomBar').height();
    if (clickBottomCount % 2 == 0) {
        $('#BottomBar').css('bottom', 15 - bottomheight);
        clickBottomCount++;
    } else {
        $('#BottomBar').css('bottom', 0);
        clickBottomCount++;
    }
    $(window).trigger('resize');
}
//系统时间
function sj() {
    setInterval(function () {
        var now = new Date();
        var year = now.getFullYear();
        var month = now.getMonth() + 1;
        var date = now.getDate();
        var day = now.getDay();
        var hour = now.getHours();
        var minute = now.getMinutes();
        var second = now.getSeconds();
        var newMonth = (month < 10) ? "0" + month : month;
        var newDate = (date < 10) ? "0" + date : date;
        var newHour = (hour < 10) ? "0" + hour : hour;
        var newMinute = (minute < 10) ? "0" + minute : minute;
        var newSecond = (second < 10) ? "0" + second : second;
        var weekDay = ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
        var clock = newHour + " : " + newMinute + " : " + newSecond;
        var date = year + ' ' + newMonth + ' ' + newDate + ' ' + weekDay[day];
        $('#date').text(date);
        var html = "";
        html = html + '<span style="float:left">' + newHour + '</span>';
        html = html + '<span id="online" style="width:16px; display:block; float:left">' + ': ' + '</span>';
        html = html + '<span style="float:left">' + newMinute + '</span>';
        html = html + '<span id="online2" style="width:16px; display:block; float:left">' + ': ' + '</span>';
        html = html + '<span style="float:left">' + newSecond + '</span>';
        $('#clock').html(html);
    }, 1000);
};
//bootstrap 时间控件
function bootstrap_sjkj() {
    // $('#date2').daterangepicker({
    //     applyClass:"btn btn-primary",
    //     autoUpdateInput: false,
    //     ranges: {
    //         '今天': [moment(), moment()],
    //         '昨天': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
    //         '近7天': [moment().subtract(7, 'days'), moment()],
    //         '这个月': [moment().startOf('month'), moment().endOf('month')],
    //         '上个月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
    //     },
    //     locale: {
    //         format: "YYYY/MM/DD",
    //         opens: "left",
    //         separator: " - ",
    //         applyLabel: "确认",
    //         cancelLabel: "清空",
    //         customRangeLabel: "自定义",
    //         daysOfWeek: ["日", "一", "二", "三", "四", "五", "六"],
    //         monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
    //         firstDay:1
    //     }
    //    }).on('cancel.daterangepicker', function (ev, picker) {
	//          $("#date2").val("请选择日期范围");
	//          $("#startTime").val("");
	//          $("#endTime").val("");
	//      }).on('apply.daterangepicker', function (ev, picker) {
	//          $("#startTime").val(picker.startDate.format('YYYY-MM-DD'));
	//          $("#endTime").val(picker.endDate.format('YYYY-MM-DD'));
	//          $("#date2").val(picker.startDate.format('YYYY-MM-DD') + " 至 " + picker.endDate.format('YYYY-MM-DD'));
	//      });
}


//点位上图
function addPoint(callback) {
    graphicslayer_test.clear();
    getByAjax("../rest/areabasequery/null", data => {
        for (var j = 0; j < data.length; j++) {
            let g=createGraphic(data[j]);
            if(g){
                graphicslayer_test.add(g);
            }
        }
        if(callback){
            callback(data);
        }
    });
    $("#BottomBar").slideDown(200);
}
//根据obj创建graphic
function createGraphic(obj){
    var g1=null;
    if (obj.wkt && obj.wkt) {
        var polygon = new esri.geometry.Polygon({
            rings: (Terraformer.WKT.parse(obj.wkt)).coordinates,
            spatialReference: {
                wkid: 4326
            }
        });
        var symbolx = getSymbol("#000000", "#C4C4C4", 0.2);
        g1 = new esri.Graphic(polygon, symbolx, {
            data: obj,
            symbol: symbolx
        });
    } else if (obj.x && obj.y) {
        var symbolx = new esri.symbol.PictureMarkerSymbol("../img/dwgl.png", 30, 30);
        g1 = new esri.Graphic(esri.geometry.Point(obj.x, obj.y), symbolx, {
            data: obj
        });
    }
    return g1;
}
//样式
function getSymbol(lineColor,fillColor,a){
    return new esri.symbol.SimpleFillSymbol(
        esri.symbol.SimpleFillSymbol.STYLE_SOLID,
        new esri.symbol.SimpleLineSymbol(
            esri.symbol.SimpleLineSymbol.STYLE_SOLID,
            new dojo.Color(lineColor),
            3
        ),
        new dojo.Color((a!=undefined?rgbTranform(fillColor,a):fillColor))
    );
}
//颜色转换
function rgbTranform(rgb,a) {
    if(rgb.length==7){
        return [parseInt(rgb.substr(1,2),16),parseInt(rgb.substr(3,2),16),parseInt(rgb.substr(5,2),16),a];
    }else {
        return [0,0,0,0];
    }
}
function graphicslayer_test_click(o){
    var item=o.graphic.attributes.data;
    myMap.infoWindow.setTitle(item.typename);
    myMap.infoWindow.setContent("名称:" + item.name);
    myMap.infoWindow.show(myMap.toScreen(o.mapPoint));
}


//表格渲染
function loadtabledata(resultdata) {
    $('#areatable').bootstrapTable({
        // url: '../edit/area/null', //请求后台的URL（*）
        data:resultdata,
        // method: 'get', //请求方式（*）
        sortOrder: "asc", //排序方式
        height: 255,
        exportDataType: "all", //basic', 'all', 'selected'.
        search: true,
        toolbar: true,
        cardView: false, //是否显示详细视图
        striped: true,
        columns: [{
            field: 'id',
            title: '编号'
        }, {
            field: 'name',
            title: '名称'
        }, {
            field: 'typename',
            title: '类型'
        }, {
            field: 'x',
            title: '经度'
        }, {
            field: 'y',
            title: '纬度'
        }, {
            field: 'Button',
            title: '操作',
            events: {
                'click #btstrapedit1': function (e, valule, item, index) {
                    vue_csxg.type="2";
                    vue_csxg.index=index;
                    vue_csxg.item_base = Object.assign({},item);
                    vue_csxg.vtitle = item.name;
                    vue_csxg.restful_url = "areadetailupdate/" + item.id + "/" + item.extenddata;
                    getByAjax("../rest/areadetailquery/" + item.id + "/" + item.extenddata, result => {
                        vue_csxg.item_detail = result;
                        $("#csbjk").modal("show");
                    });
                },
                //混合编辑
                'click #btstrapedit2': function (e, valule, item, index) {
                    if(item.x&&item.y&&!item.wkt){
                        vue_csxg.type="2";
                        locate(item);
                        editStart(item);     
                        vue_csxg.item_base = item;
                        vue_csxg.vtitle = item.name;
                        vue_csxg.restful_url = "areadetailupdate/" + item.id + "/" + item.extenddata;
                        getByAjax("../rest/areadetailquery/" + item.id + "/" + item.extenddata, result => {
                            vue_csxg.item_detail = result;
                        });
                    }else{
                        alert("不支持混合编辑");
                    }   
                },
                //关联监控
                'click #btstrapgl': function (e, valule, item, index) {
                    showassociatemonitor(item.id);
                },
                //删除
                'click #btstrapdelete': function (e, valule, item, index) {
                    if (confirm("确定删除吗")==true) {
                         getByAjax("../edit/areadelete/" + item.id + "/" + item.extenddata, result => {
                            $("#areatable").bootstrapTable('remove', {field: 'id', values: [item.id]});//field:根据field的值来判断要删除的行
                            addPoint();
                            myMap.infoWindow.hide();
                            alert("删除成功");
                          });
                     }
                },
                //定位
                'click #btstraplocate': function (e, valule, item, index) {
                    locate(item);
                },
                //照片上传
                'click #fileid': function (e, valule, item, index) {
                    $("#file-Portrait1").fileinput("clear");
                    photoFile_vue.item = item;
                    photosFile(item);
                }
            },
            formatter: function () {
                return [
                    "<button id='btstrapedit1' style='height:20px;padding: 0px 13px'  type='button' class='RoleOfdelete btn btn-primary  btn-sm'>简易编辑</button> &nbsp;&nbsp;",
                    "<button id='btstrapedit2' style='height:20px;padding: 0px 13px'  type='button' class='RoleOfdelete btn btn-primary  btn-sm'>混合编辑</button> &nbsp;&nbsp;",
                    "<button id='btstrapgl'  style='height:20px;padding: 0px 13px'  type='button' class='RoleOfdelete btn btn-primary  btn-sm'>关联监控</button> &nbsp;&nbsp;",
                    "<button id='btstrapdelete'  style='height:20px;padding: 0px 13px'  type='button' class='RoleOfdelete btn btn-primary  btn-sm'>删除</button> &nbsp;&nbsp;",
                    "<button id='btstraplocate'  style='height:20px;padding: 0px 13px'  type='button' class='RoleOfdelete btn btn-primary  btn-sm'>定位</button> &nbsp;&nbsp;",
                    "<button id='fileid'  style='height:20px;padding: 0px 13px'  type='button' class='RoleOfdelete btn btn-primary  btn-sm'>照片管理</button> &nbsp;&nbsp;"
                ].join("");
            }
        }],
        showExport: true,
        exportTypes: ['excel', 'xlsx'], //导出类型
        exportOptions: {
            fileName: '警情数据', //文件名称设置  
            worksheetName: '警情数据', //表格工作区名称  
            tableName: '警情数据',
            excelstyles: ['background-color', 'color', 'font-size', 'font-weight']
        }
    });
}


//新增
function addarea(){
    //新增清空属性
    vue_csxg.type="0";
    vue_csxg.item_base=Object.assign({}, vue_csxg.item_base);
    for(var item in vue_csxg.item_base){
        vue_csxg.item_base[item]="";
    }
    //获取选择的类型
    var obj = document.getElementById("areatype"); //定位id
    var index = obj.selectedIndex; // 选中索引
    var text = obj.options[index].text; // 选中文本
    var value = obj.options[index].value; // 选中值
    
    if(!value){
        alert("此类型无更多详情");
        return;
    }
    getByAjax("../rest/areadetailquery/null"+"/"+value, result => {
        vue_csxg.item_detail=result; 
        vue_csxg.vtitle=text; 
        vue_csxg.restful_url="areadetailinsert/null/"+value; 
        vue_csxg.guid=uuid();
        //i和类型id赋值
        vue_csxg.item_base.id=vue_csxg.guid;
        vue_csxg.item_base.typeid=vue_csxg.typedata[index].typeid;
        vue_csxg.item_base.extenddata=value;
        vue_csxg.item_base.typename=text;
        $("#csbjk").modal("show");
    });
}
//上传wkt文件
function getWKT(input){
    var file = input.files[0];
    var reader = new FileReader();
    reader.readAsText(file);
    reader.onload = function (e) {
         var data = e.target.result;
         if(checkWKT()){
             vue_csxg.item_base.wkt=data;
         }else{
             alert("格式无效");
            vue_csxg.item_base.wkt="";
         }
    };
}
//检查wkt格式
function checkWKT(wkt){
    let result=true;
    if(wkt){
        try {
            wkt=Terraformer.WKT.parse(wkt).coordinates;
         } catch (error) {
            result=false;
         }
    }
     return result;
}
//生成从minNum到maxNum的随机数
function randomNum(minNum, maxNum) {
    switch (arguments.length) {
        case 1:
            return parseInt(Math.random() * minNum + 1, 10);
            break;
        case 2:
            return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
            break;
        default:
            return 0;
            break;
    }
}


//编辑点位
function editStart(obj) {
    let g=getGraphic(obj);
    if(g){
        edit.activate(esri.toolbars.Edit.MOVE, g);
        myMap.infoWindow.hide();
    }
}
//编辑完成
function editEnd(evt) {
   edit.deactivate();
   vue_csxg.item_base.x=evt.info.mapPoint.x;
   vue_csxg.item_base.y=evt.info.mapPoint.y;
   $("#csbjk").modal("show");
}
//根据obj获取地图上的graphic
function getGraphic(obj){
    for(var i=0;i<graphicslayer_test.graphics.length;i++){
        if(obj.id==graphicslayer_test.graphics[i].attributes.data.id){
           return graphicslayer_test.graphics[i];
        }
    }
    return null;
}


//定位
function locate(obj){
    var point = null;
    if (obj.x && obj.y) {
        point = new esri.geometry.Point(obj.x, obj.y);
    } else if(obj.wkt){
        var polygon = new esri.geometry.Polygon({
            rings: (Terraformer.WKT.parse(obj.wkt)).coordinates,
            spatialReference: {
                wkid: 4326
            }
        });
        point = polygon.getExtent().getCenter();
    }else{
        alert("没有空间数据，无法定位");
        return;
    }
    myMap.centerAndZoom(point, 18);
    myMap.infoWindow.setTitle(obj.typename);
    myMap.infoWindow.setContent("名称:" + obj.name);
    myMap.infoWindow.show(myMap.toScreen(point));
}


//关联监控
getByAjax("../rest/querymonitor",result=>{
    vue_associatemonitor.datax_allmonitor=result;
});

var vue_associatemonitor=new Vue({
    el:"#associatemonitor",
    data:{
        datax_selectedmonitor:[],
        datax_allmonitor:[],
        areaid:""
    },
    methods:{
        associatemonitor:function(item,type){
           postByAjax("../edit/associatemonitor",{type:type,areaid:this.areaid,monitorid:item.id},result=>{
                if(type=="add"&&result==1){
                    this.datax_selectedmonitor.push(item);
                }else if(type=="delete"&&result==1){
                    this.datax_selectedmonitor.remove(item);
                }
           });
        }
    },
    computed:{
        cpd_allmonitor:function(){
             var arr=this.datax_allmonitor.diff(this.datax_selectedmonitor);
             return arr;
        }
    }
});
function showassociatemonitor(areaid){
     $("#associatemonitor").modal("show");
     vue_associatemonitor.areaid=areaid;
     getByAjax("../rest/queryassociateedmonitor/"+areaid,result=>{
        vue_associatemonitor.datax_selectedmonitor=result;
    });
}

////////////////////////////////////////////////////////////////////////////////////////////////////照片管理
//照片弹出层显示
function photosFile(item){
    $("#photosid").modal("show");
    var areaid=item.id;
    if(areaid){
        photo_typeid=item.typeid;
        getByAjax("../rest/queryphotos/"+areaid+"/"+item.typeid,result=>{
            photoFile_vue.photosj=result;
        });
    }
}

var photoFile_vue=new Vue({
    el:"#zpid",
    data:{
        photosj:[],
        item:{}
    },
    methods:{
        //照片删除
        deletePhoto:function (item) {

            var statu = confirm("确定删除该图片?");
            if(!statu){
             return false;
            }
            postByAjax("../edit/deletephoto",{id:item.id,folder:item.folder},result=>{
                for (var i = 0; i<this.photosj.length; i++){
                    if (this.photosj[i].src==item.src){
                        this.photosj.splice(i,1);
                        i--;
                    }
                }              

                postByAjaxWithoutCookie("http://61.155.110.210:7008/upload/delete",{folder:item.folder,path:item.path},result=>{
                        console.log(result);
                });

                // postByAjax("http://61.155.110.210:7008/upload/delete",{folder:item.folder,path:item.path},result=>{
                //         console.log(result);
                // });

            });
        },
        photoBig:function(item){
            if(item){
                var json = { title: "照片", data:[item] };
                    layer.photos({
                        photos: json,
                        anim: 5
                });
            } 
        }
    },
});

//初始化fileinput控件（第一次初始化）
function initFileInput(ctrlName) {    
    var control = $('#' + ctrlName); 
    console.log(ctrlName);
    control.fileinput({
        language: 'zh', //设置语言        
        uploadUrl: "http://61.155.110.210:7008/upload/add",
        allowedFileExtensions : ['jpg', 'png','gif'],//接收的文件后缀
        showUpload: false, //是否显示上传按钮
        showCaption: false,//是否显示标题
        browseClass: "btn btn-primary", //按钮样式        
        enctype:'multipart/form-data',     
        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",       
        })
    .on('filepreupload', function(event, data, previewId, index) {     //上传中
       var form = data.form, files = data.files, extra = data.extra;
        console.log('文件正在上传');
    }).on("fileuploaded", function (event, data, previewId, index) {//一个文件上传成功
        console.log('文件上传成功！'+data.id);
        var obj_res=data.response.success[0];
        postByAjax("../edit/uploadimg",{name:obj_res.originalname, id:obj_res.name,path:obj_res.name,module:photoFile_vue.item.typename,areaid:photoFile_vue.item.id},result=>{
            photoFile_vue.photosj.push({src:result,alt:obj_res.originalname,folder:photoFile_vue.item.typeid,path:obj_res.name,id:obj_res.name});
        });

    }).on('fileerror', function(event, data, msg) {  //一个文件上传失败
        console.log('文件上传失败！'+data.id);
    });

}


