

layui.use(['layer', 'element', 'form', 'table', 'laydate'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var element = layui.element;
    var form = layui.form;
    var laydate = layui.laydate;

    // 开门趋势
    var myCharts = echarts.init(document.getElementById('data-view'), myEchartsTheme);
    var selectDateType=0;
    var selectDateTypeTemp1=0;
    var selectDateTypeTemp2=0;
    var lineChartTabIndex=0;
    var selectDate="";
    var selectDateObj;
    var initOpenCountLineChartFn=function () {
        var yData=[];
        var xData=["01:00", "02:00", "03:00", "04:00", "05:00", "06:00", "07:00", "08:00", "09: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"];
        if(selectDateType==1){
            xData=["星期一","星期二","星期三","星期四","星期五","星期六","星期日"];
        }else if(selectDateType==2||selectDateType==5){
            xData=[];
            var dayCount;
            if(selectDateType==5){
                //获取选中时间当月天数
                dayCount=laydate.getEndDate(selectDateObj.month, selectDateObj.year);
            }else{
                //获取当月天数
                var currentDate=new Date();
                dayCount=laydate.getEndDate(currentDate.getMonth()+1, currentDate.getFullYear());
            }
            for(var i=1;i<=dayCount;i++){
                xData[i-1]=i;
            }
        }else if(selectDateType==3||selectDateType==4){
            xData=["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"];
        }
        var option = {
            title: {
                text: "开门趋势",

                textStyle: {
                    fontWeight: 'bold',
                    fontSize: 18,
                    color: '#333'
                }
            },
            grid: {
                left: '0',
                right: '0',
                bottom: '20',
                containLabel: true
            },
            tooltip: {
                trigger: "axis",
                formatter: "{b}<br>开门次数：{c}",
                backgroundColor:'rgba(255,255,255,0.8)',//通过设置rgba调节背景颜色与透明度
                color:'black',
                borderWidth:'1',
                borderColor:'#dadada',
                textStyle:{
                    color:'#575757',
                    fontSize:'12'
                },
                extraCssText:'line-height:26px;padding:10px;box-shadow:0 0 10px rgba(0,0,0,0.3)',
            },
            calculable: true,
            xAxis: [{
                type: "category",
                axisLine: {
                    lineStyle: {
                        color: '#5a5a5a'
                    }
                },
                axisPointer: {
                    snap: true,
                    lineStyle: {
                        color: '#666',
                        opacity: 0.5,
                        width: 1
                    },

                },
                data:xData,
            }],
            yAxis: [{
                type: "value",

                axisLine: {
                    show: false, //隐藏y轴
                    lineStyle: {
                        color: '#5a5a5a'
                    }
                }
            }],
            series: [{
                type: "line",
                data: yData,
                itemStyle: {normal: {color: "#3ba1ff"}},
            }]


        }
        myCharts.setOption(option);
        //加载数据
        $.ajax({
            type: "POST",
            url:  "/home/estateOpenCountLineChart",
            data:"selectDateType="+selectDateType+"&selectDate="+selectDate,
            success: function (result) {
                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=obj.hour;
                            if(selectDateType==1){
                                timeData=obj.weekday;
                            }else if(selectDateType==2||selectDateType==5){
                                timeData=obj.day;
                            }else if(selectDateType==3||selectDateType==4){
                                timeData=obj.month;
                            }
                            if(i==timeData){
                                yData[i-1]=obj.accessCount;
                                break;
                            }else{
                                yData[i-1]=0;
                            }

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

    }

    //访客折线统计图
    var myCharts3 = echarts.init(document.getElementById('xse'), myEchartsTheme);
    var initGuestAuthorizeLineChartFn=function () {
        var yData=[];
        var xData=["01:00", "02:00", "03:00", "04:00", "05:00", "06:00", "07:00", "08:00", "09: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"];
        if(selectDateType==1){
            xData=["星期一","星期二","星期三","星期四","星期五","星期六","星期日"];
        }else if(selectDateType==2||selectDateType==5){
            xData=[];
            var dayCount;
            if(selectDateType==5){
                //获取选中时间当月天数
                dayCount=laydate.getEndDate(selectDateObj.month, selectDateObj.year);
            }else{
                //获取当月天数
                var currentDate=new Date();
                dayCount=laydate.getEndDate(currentDate.getMonth()+1, currentDate.getFullYear());
            }
            for(var i=1;i<=dayCount;i++){
                xData[i-1]=i;
            }
        }else if(selectDateType==3||selectDateType==4){
            xData=["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"];
        }
        var option = {
            title: {
                text: "访客趋势",

                textStyle: {
                    fontWeight: 'bold',
                    fontSize: 18,
                    color: '#333'
                }
            },
            grid: {
                left: '0',
                right: '0',
                bottom: '20',
                containLabel: true
            },
            tooltip: {
                trigger: "axis",
                formatter: "{b}<br>访客人数：{c}",
                backgroundColor:'rgba(255,255,255,0.8)',//通过设置rgba调节背景颜色与透明度
                color:'black',
                borderWidth:'1',
                borderColor:'#dadada',
                textStyle:{
                    color:'#575757',
                    fontSize:'12'
                },
                extraCssText:'line-height:26px;padding:10px;box-shadow:0 0 10px rgba(0,0,0,0.3)',
            },
            calculable: true,
            xAxis: [{
                type: "category",
                axisLine: {
                    lineStyle: {
                        color: '#5a5a5a'
                    }
                },
                axisPointer: {
                    snap: true,
                    lineStyle: {
                        color: '#666',
                        opacity: 0.5,
                        width: 1
                    },

                },
                data: xData,
            }],
            yAxis: [{
                type: "value",

                axisLine: {
                    show: false, //隐藏y轴
                    lineStyle: {
                        color: '#5a5a5a'
                    }
                }
            }],
            series: [{
                type: "line",
                data: yData,
                itemStyle: {normal: {color: "#3ba1ff"}},
            }]
        }
        myCharts3.setOption(option);
        //加载数据
        $.ajax({
            type: "POST",
            url:  "/home/estateGuestCountLineChart",
            data:"selectDateType="+selectDateType+"&selectDate="+selectDate,
            success: function (result) {
                if(result.code="200"&&result.data) {
                    var data=result.data;
                    for(var i=1;i<xData.length+1;i++){
                        for(var z in data){
                            var obj=data[z];
                            var timeData=obj.hour;
                            if(selectDateType==1){
                                timeData=obj.weekday;
                            }else if(selectDateType==2||selectDateType==5){
                                timeData=obj.day;
                            }else if(selectDateType==3||selectDateType==4){
                                timeData=obj.month;
                            }
                            if(i==timeData){
                                yData[i-1]=obj.guestCount;
                                break;
                            }else{
                                yData[i-1]=0;
                            }
                        }
                    }
                    myCharts3.setOption({
                        series: [{
                            type: "line",
                            data: yData,
                            itemStyle: {normal: {color: "#3ba1ff"}},
                        }]
                    });
                }
            }
        });

    }

    // 开门次数，访客人数统计时间条件
    laydate.render({
        elem: '#year'
        ,type: 'year'
        ,format: 'yyyy'
        ,max: 0
        ,done: function(value){
            selectDate=value;
            //选年
            selectDateType=4;
            if(lineChartTabIndex == 0) {
                initOpenCountLineChartFn();
            } else {
                initGuestAuthorizeLineChartFn();
            }
            $("#month_div").remove();
            $("#day_div").remove();
            $("#year_div").after("<div id=\"month_div\" class=\"layui-inline\" style='width: 250px;'>\n" +
                "                            <label class=\"layui-form-label line40\"style='width: auto;'>月份</label>\n" +
                "                            <div class=\"layui-input-inline\">\n" +
                "                                <input type=\"text\" class=\"layui-input\" id=\"month\" placeholder=\"请选择查询月份\">\n" +
                "                            </div>\n" +
                "                        </div>");
            var min = value+"-01-01";
            var max = 0;
            var now = new Date();
            var init = value+"-01";
            if(value != now.getFullYear()){
                max = value+"-12-31";
            }
            laydate.render({
                elem: '#month'
                ,type: 'month'
                ,format: 'yyyy-MM'
                ,value:init
                ,min:min
                ,max:max
                ,done: function(value,date){
                    //选月
                    selectDateType=5;
                    selectDate=value;
                    selectDateObj=date;
                    if(lineChartTabIndex == 0) {
                        initOpenCountLineChartFn();
                    } else {
                        initGuestAuthorizeLineChartFn();
                    }
                    $("#day_div").remove();
                    $("#month_div").after("<div id=\"day_div\" class=\"layui-inline\"style='width: 250px;'>\n" +
                        "                            <label class=\"layui-form-label line40\"style='width: auto;'>日份</label>\n" +
                        "                            <div class=\"layui-input-inline\">\n" +
                        "                                <input type=\"text\" class=\"layui-input\" id=\"day\" placeholder=\"请选择查询日期\">\n" +
                        "                            </div>\n" +
                        "                        </div>");
                    var min = value+"-01";
                    var max = 0;
                    var now = getFormatDate();
                    var init = value+"-01";
                    if (date.date >= 0 && date.date <= 9) {
                        date.date = "0" + date.date;
                    }
                    if((value + "-"+date.date) != now){
                        max = value + "-" +laydate.getEndDate(date.month, date.date);
                    }
                    laydate.render({
                        elem: '#day'
                        ,type: 'date'
                        ,format: 'yyyy-MM-dd'
                        ,value:init
                        ,min:min
                        ,max:max
                        ,done: function(value){
                            //选日
                            selectDateType=6;
                            selectDate=value;
                            if(lineChartTabIndex == 0) {
                                initOpenCountLineChartFn();
                            } else {
                                initGuestAuthorizeLineChartFn();
                            }
                        }
                    });
                    $("#day").val("");
                }
            });
            $("#month").val("");
        }
    });

    function getFormatDate(type) {
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        if(type == 2){
            return year +"-"+ month;
        }
        if(type == 3){
            return year;
        }
        return year +"-"+ month +"-"+ strDate;
    };


    //开门方式
    var myCharts2 = echarts.init(document.getElementById('open-way'), myEchartsTheme);
    var initOpenWayFn=function () {
        var data2 = data2=[{
            value: 0,
            name: '人脸识别'
        }, {
            value: 0,
            name: '密码开门'
        }, {
            value: 0,
            name: '刷卡开门'
        }, {
            value: 0,
            name: '远程开门'
        }];
        var option2 = {
            tooltip: {
                trigger: 'item',
                formatter: "{a} <br/>{b} : {c} ({d}%)",
                backgroundColor:'rgba(255,255,255,0.8)',//通过设置rgba调节背景颜色与透明度
                color:'black',
                borderWidth:'1',
                borderColor:'#dadada',
                textStyle:{
                    color:'#575757',
                    fontSize:'12'
                },
                extraCssText:'line-height:26px;padding:10px;box-shadow:0 0 10px rgba(0,0,0,0.3)',
            },
            legend: { //设置legend
                x: '52%',
                y: '25%',
                orient: 'vertical',
                data: ['人脸识别', '密码开门', '刷卡开门','远程开门'],
                icon: "circle",   //  这个字段控制形状  类型包括 circle，rect ，roundRect，triangle，diamond，pin，arrow，none
                itemWidth: 10,  // 设置形状宽度
                itemHeight: 10, // 设置形状高度
                formatter: function (name) {
                        return name + '{c||} ' + ' {a|' + '0% }   {b|0}';
                },
                textStyle: {
                    fontSize: 14,
                    color: '#5a5a5a',
                    rich: {
                        a: {
                            fontSize: 14,
                            verticalAlign: 'middle',
                            align: 'center',

                        },
                        b: {
                            fontSize: 14,
                            align: 'center',
                            lineHeight: 25
                        },
                        c: {
                            color: '#5a5a5a',
                            align: 'center',
                            padding: [0, 10, 0, 10],
                            lineHeight: 20,

                        }
                    }
                }
            },
            calculable: true,
            series: [
                {
                    name: '',
                    type: 'pie',
                    clockWise: true,
                    hoverAnimation: false,
                    radius: [100, 100],
                    center: ['28%', '50%'], //设置饼图位置
                    label: {
                        normal: {
                            position: 'center'
                        }
                    },
                    data: [
                        {
                            tooltip: {
                                show: false
                            },
                            value: 1,
                            label: {
                                normal: {
                                    formatter: '总数',
                                    textStyle: {
                                        color: '#5a5a5a',
                                        fontSize: 14
                                    }
                                }
                            }
                        }, {
                            tooltip: {
                                show: false
                            },
                            label: {
                                normal: {
                                    formatter: '\n0',
                                    textStyle: {
                                        color: '#5a5a5a',
                                        fontSize: 20
                                    }
                                }
                            }
                        }]
                },
                {
                    name: '开门方式',
                    type: 'pie',
                    radius: ['50%', '65%'],  //设置饼图大小
                    center: ['28%', '50%'], //设置饼图位置
                    itemStyle: {
                        normal: {
                            borderWidth: 6,
                            borderColor: '#ffffff',
                            color: function (params) {
                                //自定义颜色
                                var colorList = [
                                    '#3aa0ff', '#f2637b', '#fad337', '#4dcb73', '#36cbcb'
                                ];
                                return colorList[params.dataIndex]
                            },
                            label: {
                                show: false
                            },
                            labelLine: {
                                show: false
                            }
                        },
                        emphasis: {
                            label: {
                                show: false,
                                position: 'center',
                                textStyle: {
                                    fontSize: '18',
                                    fontWeight: 'bold'
                                }
                            }
                        }
                    },
                    data: data2,
                }
            ],
        };
        myCharts2.setOption(option2);
        //动态数据加载
        $.ajax({
            type: "POST",
            url:  "/home/openWay",
            success: function (result) {
                var data=result.data;
                if(result.code=="200"&&data) {
                    var faceOpenCount=Number(result.data.faceOpenCount);
                    var passWordOpenCount=Number(result.data.passWordOpenCount);
                    var cardOpenCount=Number(result.data.cardOpenCount);
                    var telnetOpenCount=Number(result.data.telnetOpenCount);
                    var total=faceOpenCount+passWordOpenCount+cardOpenCount+telnetOpenCount;
                    var data_open=[{
                        value: faceOpenCount,
                        name: '人脸识别'
                    }, {
                        value: passWordOpenCount,
                        name: '密码开门'
                    }, {
                        value: cardOpenCount,
                        name: '刷卡开门'
                    }, {
                        value: telnetOpenCount,
                        name: '远程开门'
                    }];
                    if(total>0){
                         option2 = {
                            legend: { //设置legend
                                data: data_open,
                                formatter: function (name) {
                                    var total = 0;
                                    var target;
                                    for (var i = 0, l = data_open.length; i < l; i++) {
                                        total +=Number(data_open[i].value);
                                        if (data_open[i].name == name) {
                                            target = Number(data_open[i].value);
                                        }
                                    }
                                    if(total>0){
                                        var arr = [
                                            '{a|' + ((target / total) * 100).toFixed(2) + '%}',
                                            '{b|' + name + '  ' + target + '}',
                                        ]
                                        return name + '{c||} ' + ' {a|' + ((target / total) * 100).toFixed(2) + '% }   {b|' + target + '}';
                                    }else{
                                        var arr = [
                                            '{a|' + '0%}',
                                            '{b|' + name + '  ' + target + '}',
                                        ]
                                        return name + '{c||} ' + ' {a|' + '0% }   {b|' + target + '}';
                                    }

                                }
                            },
                            series: [
                                {
                                    data: [{
                                        tooltip: {
                                            show: false
                                        },

                                        value: 1,
                                        label: {
                                            normal: {
                                                formatter: '总数',
                                                textStyle: {
                                                    color: '#5a5a5a',
                                                    fontSize: 14
                                                }
                                            }
                                        }
                                    }, {
                                        tooltip: {
                                            show: false
                                        },
                                        label: {
                                            normal: {
                                                formatter: '\n'+total,
                                                textStyle: {
                                                    color: '#5a5a5a',
                                                    fontSize: 20
                                                }
                                            }
                                        }
                                    }]
                                },
                                {
                                    data: data_open
                                }
                            ],
                        };
                        myCharts2.setOption(option2);
                    }
                }
            }
        });

    }

    // 窗口大小改变事件
    window.onresize = function () {
        myCharts.resize();
        myCharts2.resize();
        myCharts3.resize();
    };

    //小区
    var initResidentialFn = function() {
        $.ajax({
            type: "GET",
            url:  "/home/getResidentialAccount",
            cache: false,
            success: function (res) {
                if(res.code=="200" && res.data) {
                    $("#residential_account").html(res.data.totalCount);
                    $("#residential_month_account").html(res.data.monthCount);
                }
            }
        });
    };
    //单元
    var initUnitFn = function() {
        $.ajax({
            type: "GET",
            url:  "/home/getUnitAccount",
            cache: false,
            success: function (res) {
                if(res.code=="200" && res.data) {
                    $("#unit_account").html(res.data.totalCount);
                    $("#unit_month_account").html(res.data.monthCount);
                }
            }
        });
    };
    //住户
    var initUserFn = function() {
        $.ajax({
            type: "GET",
            url:  "/home/getUserAccount",
            cache: false,
            success: function (res) {
                if(res.code=="200" && res.data) {
                    $("#user_account").html(res.data.totalCount);
                    $("#user_month_account").html(res.data.monthCount);
                }
            }
        });
    };
    //访客
    var initGuestFn = function() {
        $.ajax({
            type: "POST",
            url:  "/home/getGuestCount",
            cache: false,
            success: function (res) {
                if(res.code=="200"&&res.data) {
                    $("#guest_count").html(res.data.guestCount);
                    $("#current_month_guest_count").html(res.data.currentMonthGuestCount);
                }
            }
        });
    };

    //设备
    var initDeviceFn = function() {
        $.ajax({
            type: "GET",
            url:  "/home/getDeviceCoverAccount",
            cache: false,
            success: function (res) {
                if(res.code=="200" && res.data) {
                    $("#device_account").html(res.data.totalCount);
                    $("#device_month_account").html(res.data.monthCount);
                }
            }
        });
    };

    //开门
    var initAccessRecordsFn = function() {
        $.ajax({
            type: "POST",
            url:  "/home/getAccessRecordsCount",
            cache: false,
            success: function (res) {
                if(res.code=="200" && res.data) {
                    $("#access_records_count").html(res.data.accessRecordsCount);
                    $("#current_month_access_records_count").html(res.data.currentMonthAccessRecordsCount);
                }
            }
        });
    };

    //数据概览
   var initDataOverviewFn=function () {
        //小区
        initResidentialFn();
        //单元
        initUnitFn();
        //住户
        initUserFn();
        //访客
        initGuestFn();
        //设备
        initDeviceFn();
        //开门
        initAccessRecordsFn();
    };

    //工作动态
    var initWorkStateFn = function() {
        $.ajax({
            type: "POST",
            url:  "/home/workState",
            success: function (result) {
                var data=result.data;
                if(result.code=="200"&&data) {
                   $("#work-state-content-id").html("");
                   for(var i in data){
                       var ddHtml="<dd><div class=\"layui-status-img1\"><img src=\""+data[i].userPortraitUri+"\" alt=\"\"></div><div>"+
                           "<p>"+data[i].operatorAccountName+
                           "在【"+data[i].menu+"】 "+data[i].message+"</p>"+
                       "<span>"+data[i].beforeDateMsg+"</span>"+
                       "</div>"+
                       "</dd>";
                       $("#work-state-content-id").append(ddHtml);
                   }
                }
            }
        });
    };

    var initApplyUserCountFn= function() {
        $.ajax({
            type: "POST",
            url:  "/home/getApplyUserCount",
            success: function (result) {
                if(result) {
                    $("#uncheck-apply-user-count-id").text(result);
                }
            }
        });
    }
    //统计图tab页面点击事件
    element.on('tab(select-data-tab)', function(data){
        lineChartTabIndex=data.index;
        $('.layui-btn-sm').removeClass("layui-this");
        if(lineChartTabIndex==1){
            $('.layui-btn-sm[data-type='+selectDateTypeTemp2+']').addClass("layui-this");
        }else{
            $('.layui-btn-sm[data-type='+selectDateTypeTemp1+']').addClass("layui-this");
        }

       if(data.index==1){
           myCharts3.resize();
       }
    });
    //查询日期选择
    $(document).on("click",".layui-btn-sm",function () {
        $('.layui-btn-sm').removeClass("layui-this");
        $(this).addClass("layui-this");
        var dataType=$(this).attr("data-type");
        selectDateType=dataType;
        if(lineChartTabIndex==1){
            selectDateTypeTemp2=dataType;
            initGuestAuthorizeLineChartFn();
        }else{
            selectDateTypeTemp1=dataType;
            initOpenCountLineChartFn();
        }

    });

    //初始化
    (function(){
        // 开门趋势
        initOpenCountLineChartFn();
        //访客趋势
        initGuestAuthorizeLineChartFn();
        initDataOverviewFn();
        //开门方式
        initOpenWayFn();
        //工作动态
        initWorkStateFn();
        //审核认证的用户
        initApplyUserCountFn();
    })();

});

