
layui.use(['layer', 'jquery','element','laydate','form'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    //0今日 1本周 2本月 3全年
    var selectDateType=0;
    // 开门数据
    var myCharts1 = echarts.init(document.getElementById('estate-open'), myEchartsTheme);
    var xData= ["1:00", "2:00", "3:00", "4:00", "5:00", "6:00", "7:00", "8:00", "9:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00", "24:00"];
    var option1 = {
        tooltip: {
            trigger: 'axis',

        },
        legend: {
            top: '0%',
            data: ['开门数据'],
            textStyle: {
                color: '#fff',
                fontSize: '14',
                fontWeight: 'bold',
            }
        },
        grid: {
            left: '10',
            top: '30',
            right: '20',
            bottom: '0',
            containLabel: true
        },

        xAxis: [{
            type: 'category',
            boundaryGap: false,
            axisLabel: {
                textStyle: {
                    color: '#fff',//坐标值得具体的颜色
                },

            },
            axisLine: {
                lineStyle: {
                    color: 'rgba(255,255,255,.2)'
                }

            },

            data:xData

        }, {

            axisPointer: { show: false },
            axisLine: { show: false },
            position: 'bottom',
            offset: 20,
        }],

        yAxis: [{
            type: 'value',
            axisTick: { show: false },
            splitArea: { show: false },
            axisLine: {
                lineStyle: {
                    color: 'rgba(255,255,255,.1)'
                }
            },
            axisLabel: {
                textStyle: {
                    color: "#fff",
                    fontSize: 12,
                },
            },

            splitLine: {
                lineStyle: {
                    color: 'rgba(255,255,255,.1)'
                }
            }
        }],
        series: [
            {
                name: '开门数据',
                type: 'line',

                symbol: 'circle',
                symbolSize: 5,
                showSymbol: false,
                lineStyle: {

                    normal: {
                        color: '#a6c4ff',
                        width: 2
                    }
                },
                areaStyle: {
                    normal: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                            offset: 0,
                            color: 'rgba(1, 132, 213, 0.4)'
                        }, {
                            offset: 0.8,
                            color: 'rgba(1, 132, 213, 0.1)'
                        }], false),
                        shadowColor: 'rgba(0, 0, 0, 0.1)',
                    }
                },
                itemStyle: {
                    normal: {
                        color: '#a6c4ff',
                        borderColor: 'rgba(221, 220, 107, .1)',
                        borderWidth: 12
                    }
                },
                data: []

            },


        ]

    };

    myCharts1.setOption(option1);
    // 窗口大小改变事件
    window.addEventListener("resize", function () {
        myCharts1.resize();
    });
    function input(date){
        var div=$("<li class='content'>"
            +'<div class="detail-item align-center-vertical" style="flex:1.5;">'+date.val1+'</div>'
            +'<div class="detail-item align-center-vertical">'+date.val2+'</div>'
            +'<div class="detail-item align-center-vertical" style="flex:2;">'+date.val3+'</div>'
            +'<div class="detail-item align-center-vertical">'+date.val4+'</div>'
            +"</li>");
        $(".d_show").prepend(div.slideUp(2000));
    }

    //全屏模式
    $(".screen-btn").click(function(){
        var parentDocument=window.parent.document;
        $(parentDocument).find("iframe").attr("allowFullScreen",true);
        //全屏
        var docElm = document.documentElement;
        if($(this).find('i').hasClass('reduce')){
            $(this).find('i').removeClass('reduce').attr('title','全屏');

            if (window.ActiveXObject)
            {
                iefull();
            }else{
                exitScreen();
            }

        }else{
            $(this).find('i').addClass('reduce').attr('title','退出全屏');
            if (window.ActiveXObject)
            {
                iefull();
            }else{
                fullScreen();
            }
        }
    });

    //全屏
    function fullScreen(){
        var el = document.documentElement;
        var rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullscreen;
        if(typeof rfs != "undefined" && rfs) {
            rfs.call(el);
        };
        return;
    }
    //退出全屏
    function exitScreen(){
        if (document.exitFullscreen) {
            document.exitFullscreen();
        }
        else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        }
        else if (document.webkitCancelFullScreen) {
            document.webkitCancelFullScreen();
        }
        else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
        if(typeof cfs != "undefined" && cfs) {
            cfs.call(el);
        }
    }
    //ie低版本的全屏，退出全屏都这个方法
    function iefull(){
        if(typeof window.ActiveXObject != "undefined") {
            //这的方法 模拟f11键，使浏览器全屏
            var wscript = new ActiveXObject("WScript.Shell");
            if(wscript != null) {
                wscript.SendKeys("{F11}");
            }
        }
    }

    //物业数量统计
    function estateDataCockpitCount(){
        $.ajax({
            url     :   '/statistics/data/cockpit/estateDataCockpitCount',
            type:'POST',
            success :   function(result){
                if(result.code=="200"&&result.data){
                    $("#residential-count").text(result.data.residentialCount);
                    $("#unit-count").text(result.data.unitCount);
                    $("#user-count").text(result.data.userCount);
                    $("#uncheck-apply-user-count").text(result.data.uncheckApplyUserCount);
                    $("#guest-count").text(result.data.guestCount);
                    $("#server-user-count").text(result.data.serverUserCount);
                    $("#device-count").text(result.data.deviceCount);
                }
            }
        });
    }

    //开门方式次数
    function estateOpenWay(){
        $.ajax({
            url     :   '/statistics/data/cockpit/estateOpenWay',
            type:'POST',
            data:"selectDateType="+selectDateType,
            success :   function(result){
                var openDoorCount=0,passWordOpenCount=0,telnetOpenCount=0,faceOpenCount=0,cardOpenCount=0;
                if(result.code=="200"&&result.data){
                    openDoorCount=result.data.openDoorCount;
                    passWordOpenCount=result.data.passWordOpenCount;
                    telnetOpenCount=result.data.telnetOpenCount;
                    faceOpenCount=result.data.faceOpenCount;
                    cardOpenCount=result.data.cardOpenCount;
                }
                $("#open-door-count").text(openDoorCount);
                $("#pass-word-open-count").text(passWordOpenCount);
                $("#telnet-open-count").text(telnetOpenCount);
                $("#face-open-count").text(faceOpenCount);
                $("#card-open-count").text(cardOpenCount);
            }
        });
    }

    //开门数据统计图
    function estateOpenLineChart(){
        var groupType=0;
        if(selectDateType==1){
            //周分组
            groupType=2;
        }else if(selectDateType==2){
            //日分组
            groupType=1;
        }else if(selectDateType==3){
            //月分组
            groupType=3;
        }
        $.ajax({
            url     :   '/statistics/data/cockpit/estateOpenCountLineChart',
            type:'POST',
            data:"groupType="+groupType,
            success :   function(result){
                //填充
                var yData=[];
                xData.forEach(function(a){
                    yData.push(0);
                });
                var data=result.data;
                if(result.code="200"&&data) {
                    for(var i=1;i<xData.length+1;i++){
                        for(var z in data){
                            var obj=data[z];
                            var timeData;
                            if(selectDateType==1){
                                timeData=obj.weekday;
                            }else if(selectDateType==2){
                                timeData=obj.day;
                            }else if(selectDateType==3){
                                timeData=obj.month;
                            }else{
                                timeData=obj.hour;
                            }
                            if(i==timeData){
                                yData[i-1]=obj.accessCount;
                                break;
                            }else{
                                yData[i-1]=0;
                            }
                        }
                    }
                }
                myCharts1.setOption({
                    xAxis: [{
                        type: 'category',
                        boundaryGap: false,
                        axisLabel: {
                            textStyle: {
                                color: '#fff',//坐标值得具体的颜色
                            },

                        },
                        axisLine: {
                            lineStyle: {
                                color: 'rgba(255,255,255,.2)'
                            }

                        },

                        data:xData

                    }],
                    series: [{
                        type: "line",
                        data: yData,
                        itemStyle: {normal: {color: "#3ba1ff"}},
                    }]
                });
            }
        });
    }

    //设备开门次数
    function estateDeviceCount(){
        $.ajax({
            url     :   '/statistics/data/cockpit/getDeviceOpenCountList',
            type:'POST',
            data:"selectDateType="+selectDateType,
            success :   function(result){
                var $deviceOpenCountList=$("#device-open-count-list");
                $deviceOpenCountList.html("");
                var data=result.data;
                if(result.code=="200"&&data&&data.length>0){
                    for(i in data){
                        var deviceName=data[i].deviceName;
                        var installPath=data[i].installPath;
                        var openCount=data[i].openCount;
                        var  liHmtl="<li class=\"content\">" +
                            "<div class=\"detail-item align-center-vertical\">"+deviceName+"</div>" +
                            "<div class=\"detail-item align-center-vertical\">"+installPath+"</div>" +
                            "<div class=\"detail-item align-center-vertical\">"+openCount+"</div>" +
                            "</li>"
                        $deviceOpenCountList.append(liHmtl);
                    }
                }
            }
        });
    }

    //选中 今日 本周 本月 全年
    $(document).on("click",".con-estate-center .left",function () {
        $(".con-estate-center .active").removeClass("active");
        $(this).addClass("active");
        var dataType=$(this).find("p").attr("data-type");
        selectDateType=dataType;
        //开门方式次数
        estateOpenWay();
        //开门数据统计图
        if(selectDateType==1){
            xData=["星期一","星期二","星期三","星期四","星期五","星期六","星期日"];
        }else if(selectDateType==2){
            xData=[];
            //获取当月天数
            var currentDate=new Date();
            var dayCount=layui.laydate.getEndDate(currentDate.getMonth()+1, currentDate.getFullYear());
            for(var i=1;i<=dayCount;i++){
                xData[i-1]=i;
            }
        }else if(selectDateType==3){
            xData=["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"];
        }else{
            xData= ["1:00", "2:00", "3:00", "4:00", "5:00", "6:00", "7:00", "8:00", "9:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00", "24:00"];
        }
        //开门数据统计图
        estateOpenLineChart();
        //设备开门次数
        estateDeviceCount();
    });

    //出入记录初始化
    var accessRecordData=[];
    function accessRecordsInit(){
        setInterval(function(){
            var height= $('.con-estate-right').height();
            var titleHeight=$('.con-estate-right .estate-title').height();
            var contentTitleHeight=$('.con-estate-right .estate-content-title').height();
            if(accessRecordData.length>0){
                var i=accessRecordData.length-1;
                //高度偏差问题 -5
                if($(".d_show").height()<height-(titleHeight+contentTitleHeight)-5){
                    input(accessRecordData[i])
                    accessRecordData.splice(i,1)
                    i--;
                }else{
                    $(".d_show").children("li:last-child").slideUp(500,function () {
                        $(".d_show").children("li:last-child").remove();
                        input(accessRecordData[i]);
                        accessRecordData.splice(i,1);
                        i--;
                    });
                }
            }
        },2000);
    }
    var beginDate="";
    //出入记录数据加载
    var timer = null;
    var accessRecordsDataLoad=function(){
            var residentialId=$('#residential_id').val();
            $.ajax({
                url     :   '/statistics/data/cockpit/getNewAccessRecordsList',
                type:'POST',
                data:"beginDate="+beginDate+"&residentialId="+residentialId,
                success :   function(result){
                    var data=result.data;
                    if(result.code=="200"&&data&&data.length>0){
                        for(var i=0;i<data.length;i++){
                            var accessRecord=data[i];
                            var accessDate=accessRecord.accessDate;
                            var residentialName="";
                            if(accessRecord.residentialName){
                                residentialName=accessRecord.residentialName;
                            }
                            var unitName="";
                            if(accessRecord.unitName){
                                unitName=accessRecord.unitName;
                            }
                            var installPath="";
                            if(accessRecord.installPath){
                                installPath=accessRecord.installPath;
                            }
                            var isAdmin=accessRecord.isAdmin;
                            var accessUserType=accessRecord.accessUserType;
                            var accessUserTypeName="";
                            if(isAdmin==1){
                                if(accessUserType==0){
                                    accessUserTypeName="保安";
                                }else if(accessUserType==1){
                                    accessUserTypeName="快递";
                                }else if(accessUserType==2){
                                    accessUserTypeName="外卖";
                                }else if(accessUserType==3){
                                    accessUserTypeName="清洁";
                                }else if(accessUserType==4){
                                    accessUserTypeName="其他";
                                }
                            }else if(isAdmin==2){
                                if(accessUserType==0){
                                    accessUserTypeName="业主";
                                }else if(accessUserType==1){
                                    accessUserTypeName="成员";
                                }else if(accessUserType==2){
                                    accessUserTypeName="租户";
                                }
                            }else if(isAdmin==3){
                                if(accessUserType==0){
                                    accessUserTypeName="朋友";
                                }else if(accessUserType==1){
                                    accessUserTypeName="外卖";
                                }else if(accessUserType==2){
                                    accessUserTypeName="快递";
                                }else if(accessUserType==3){
                                    accessUserTypeName="其他";
                                }
                            }
                            var resData={'val1':accessDate,'val2':residentialName,'val3':unitName+installPath,'val4':accessUserTypeName};
                            accessRecordData.push(resData);
                            if(i==0){
                                beginDate=accessDate;
                            }
                        }
                    }
                    timer = setTimeout(accessRecordsDataLoad,2000)
                }
            });
    }

    //window 监听页面离开
    window.onbeforeunload = function(e){
        clearInterval(timer);
    }

    /**F
     * 初始化所属小区下拉框（列表）
     */
    var initResidentialFn = function(){
        $.ajax({
            url     :   '/estate/agency/findResidentialListByCondition',
            type    :   'GET',
            success :   function (result) {
                var node = $('#residential_id');
                //  清空元素
                result.list.forEach(function(item){
                        node.append('<option value="' + item.id + '" >' + item.name + '</option>');
                });
                //重新渲染
                layui.form.render('select');
            }
        });
    };

    //定时更新数据
    function intervalRefreshData(){
        setInterval(function(){
            //刷新今日数据
            if(selectDateType==0){
                //开门数据统计图
                estateOpenLineChart();
                //开门方式次数
                estateOpenWay();
                //设备开门次数
                estateDeviceCount();
            }
        },10000);
    }

    $('#residential_id').change(function(){
        $("#width_tmp_option").html($('#residential_id option:selected').text());
        $(this).width($("#width_tmp_select").width());
    });


    //初始化
    (function(){
        //  加载所属小区
        initResidentialFn();
        //物业数量统计
        estateDataCockpitCount();
        //开门方式次数
        estateOpenWay();
        //开门数据统计图
        estateOpenLineChart();
        //设备开门次数
        estateDeviceCount();
        //出入记录
        accessRecordsInit();
        //出入记录数据定时载入
        accessRecordsDataLoad();
        //定时更新数据
        intervalRefreshData();
    })();
});
