/**
 * 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;
    //      }
    // });
    getByAjax("../business/queryfyry/13", data => {
     loadtabledata(data);
    });

    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;
// });



//底部悬浮框显隐
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'));
	//      });
}


//根据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: '编号',
            formatter: function(value,row,index){
                return index+1;
            }
        },{
            field: 'hh',
            title: '户号'
        }, {
            field: 'name',
            title: '名称'
        }, {
            field: 'zjhm',
            title: '证件号码'
        }, {
            field: 'lxdh',
            title: '联系方式'
        }, {
            field: 'lnsj',
            title: '隔离时间'
        },  {
            field: 'Button',
            title: '操作',
            events: {
                
                //照片上传
                'click #fileid': function (e, valule, item, index) {
                    $("#file-Portrait1").fileinput("clear");
                    photoFile_vue.item = item;
                    photosFile(item);
                }
            },
            formatter: function () {
                return [
                    "<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 photosFile(item){
    photoFile_vue.photosj=[];
    $("#photosid").modal("show");
    if(item.sfzdgl){ 
    let photos=item.sfzdgl.split(",");
    for(let i=0;i<photos.length;i++){
        if(photos[i]!=""){
        photoFile_vue.photosj.push(
            {src:'/app_photos/0/'+photos[i],zjhm:item.zjhm,lnsj:item.lnsj} 
        );
        }
    }
}

    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/deletefy",{name:item.src.replace('/app_photos/0/',''),zjhm:item.zjhm,lnsj:item.lnsj},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:'0',path:item.src},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);
        $("#file-Portrait1").fileinput("clear");
        var obj_res=data.response.success[0];
        //更新图片
        postByAjax("../edit/updatefy",{name:obj_res.name,zjhm:photoFile_vue.item.zjhm,lnsj: photoFile_vue.item.lnsj },result=>{
            photoFile_vue.photosj.push({src:'/app_photos/0/'+obj_res.name,zjhm:photoFile_vue.item.zjhm,lnsj:photoFile_vue.item.lnsj });
        });
    }).on('fileerror', function(event, data, msg) {  //一个文件上传失败
        console.log('文件上传失败！'+data.id);
    });

}


