

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 initAdWatchLineChartsOption = function(){
        var option = {
            title: {
                text: "观看次数趋势",
                x: "left",
                textStyle: {
                    fontWeight: 'bold',
                    fontSize: 18,
                    color: '#333'
                }
            },

            grid: {
                left: '0',
                right: '20',
                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: ["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"],
            }],
            yAxis: [{
                type: "value",
                splitArea: {show: false},
                axisLine: {
                    show: false, //隐藏y轴
                    lineStyle: {
                        color: '#5a5a5a'
                    }
                },
                splitLine: {
                    show: true,
                    lineStyle: {
                        type: 'dashed'
                    }
                }
            }],
            series: [{
                type: "line",
                data: [],
                itemStyle: {normal: {color: "#3ba1ff"},},

            }]
        }
        myCharts.setOption(option);
    }

    //观看次数趋势数据
    var initAdWatchLineCharts = function (date,flag) {
        var data = {
            selectStatus : flag == null ? 0 : flag,
            selectCon : date == null ? getFormatDate() : date
        };
        $.ajax({
            type: "POST",
            url:  "/home/getAdWatchCountList",
            data:data,
            success: function (res) {
                var list = res.data;
                if(res.code=="200"&&list) {
                    var y_data_array = [];
                    var x_data_array = [];
                    if(flag == 0){//按天，小时为横坐标
                        x_data_array = ["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"];
                    }else if(flag == 2){//按月，天数为横坐标
                        x_data_array = [];
                        //获取当月天数
                        var dateArray=date.split("-");
                        var dayCount=laydate.getEndDate(dateArray[1],dateArray[0]);
                        for(var i=1;i<=dayCount;i++){
                            x_data_array[i-1]=i;
                        }
                    }else if(flag == 3){//按年，月数为横坐标
                        x_data_array =["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"];
                    }else{//按周，天数为横坐标
                        x_data_array =["星期1","星期2","星期3","星期4","星期5","星期6","星期7"];
                    }
                    for(var i in x_data_array){
                        var index=Number(i)+1;
                        for(var x in list){
                            var map=list[x];
                           if(index==map.indexDate){
                               y_data_array[i]=map.indexCount;
                               break;
                           }else{
                               y_data_array[i]=0;
                           }
                        }
                    }

                    //重新加载统计图形
                    myCharts.setOption({
                        xAxis: {
                            data:x_data_array
                        },
                        series: [{
                            type: "line",
                            data: y_data_array,
                            barMaxWidth: 20,
                            itemStyle: { normal: { color: "#3ba1ff" } },

                        }]
                    });
                }
            }
        });

    };


    // 观看次数统计时间条件
    laydate.render({
        elem: '#year'
        ,type: 'year'
        ,format: 'yyyy'
        ,max: 0
        ,done: function(value){
            initAdWatchLineCharts(value,3);
            $("#month_div").remove();
            $("#day_div").remove();
            $("#year_div").after("<div id=\"month_div\" class=\"layui-inline\">\n" +
                "                            <label class=\"layui-form-label line40\">月份</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){
                    initAdWatchLineCharts(value,2);
                    $("#day_div").remove();
                    $("#month_div").after("<div id=\"day_div\" class=\"layui-inline\">\n" +
                        "                            <label class=\"layui-form-label line40\">日份</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){
                            //选日
                            initAdWatchLineCharts(value,0);
                        }
                    });
                    $("#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;
    };

    //时间条件事件
    $('.layui-btn-sm').click(function () {
        $('.layui-btn-sm').removeClass("layui-this");
        $(this).addClass("layui-this");
        var dataType = $(this).attr("data-type");
        if(dataType == 0){
            initAdWatchLineCharts(getFormatDate(),0);
        }else if(dataType == 2){
            initAdWatchLineCharts(getFormatDate(2),2);
        }else if(dataType == 3){
            initAdWatchLineCharts(getFormatDate(3),3);
        }else{
            initAdWatchLineCharts(getFormatDate(),1);
        }
    });

    //观看排行
    var myChart1 = echarts.init(document.getElementById('main'));
    var initAdWatchRankFn = function() {
        var category = [];
        var barData = [];
        $.ajax({
            type: "POST",
            url:  "/home/adWatchRankForAdType",
            success: function (result) {
                var data=result.data;
                if(result.code=="200"&&data) {
                    for(var i in data){
                        var num=Number(i)+1;
                        var adWatchRankMap=data[i];
                        category[i]=adWatchRankMap.adTypeName;
                        barData[i]=adWatchRankMap.adWatchCount;
                    }
                }
            }
        });
        var option1 = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                },
                    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)',

            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '5%',
                top:'2%',
                containLabel: true
            },

            xAxis: {
                type: 'value',
                axisLine: {
                    show: false
                },
                axisTick: {
                    show: false
                },
                splitLine: {
                    show: true,
                    lineStyle: {
                        width: 1,
                        type: 'dashed'
                    }
                },

            },
            yAxis: {
                type: 'category',
                data: category,
                splitLine: {show: false},
                axisLine: {
                    show: true, //隐藏y轴
                    lineStyle: {
                        color: '#999',
                        width: 1,
                    }
                },
                axisTick: {
                    show: false
                },
                offset: 10,
                nameTextStyle: {
                    fontSize: 15
                }
            },
            series: [
                {
                    name: '数量',
                    type: 'bar',
                    data: barData,
                    barWidth: 14,
                    barGap: 10,
                    smooth: true,
                    label: {
                        normal: {
                            show: true,
                            position: 'right', //数值的位置
                            offset: [5, -2],
                            textStyle: {
                                color: '#3ba1ff',
                                fontSize: 13
                            }
                        }
                    },
                    itemStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 1, 0,
                                [
                                    {offset: 0, color: '#3977E6'},
                                    {offset: 1, color: '#37BBF8'}

                                ]
                            )
                        }
                    }
                }
            ]
        };
        myChart1.setOption(option1);
    }
    //观看类别占比
    var myChart2 = echarts.init(document.getElementById('ad-scale'), myEchartsTheme);
    var initAdWatchProportionFn = function() {
        var data2 =[{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:data2,
                icon: "circle",   //  这个字段控制形状  类型包括 circle，rect ，roundRect，triangle，diamond，pin，arrow，none
                itemWidth: 10,  // 设置形状宽度
                itemHeight: 10, // 设置形状高度
                formatter: function (name) {
                    var total = 0;
                    var target;
                    for (var i = 0, l = data2.length; i < l; i++) {
                        total += Number(data2[i].value);
                        if (data2[i].name == name) {
                            target = Number(data2[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 + '}';
                    }
                },
                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: [{
                        value: 1,
                        tooltip: {
                            show: false
                        },
                        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', '#4dcb73'
                                ];
                                return colorList[params.dataIndex]
                            },
                            label: {
                                show: false
                            },
                            labelLine: {
                                show: false
                            }
                        },
                        emphasis: {
                            label: {
                                show: false,
                                position: 'center',
                                textStyle: {
                                    fontSize: '18',
                                    fontWeight: 'bold'
                                }
                            }
                        }
                    },
                    data: data2
                }
            ],

        };
        myChart2.setOption(option2);
        //动态加载观看次数数据
        $.ajax({
            type: "POST",
            url:  "/home/adWatchProportionForAdType",
            success: function (result) {
                var data=result.data;
                if(result.code=="200"&&data) {
                    var adWatchCountTotal=0;
                    var adWatchCountList=data.adWatchCountList;
                    if(adWatchCountList){
                        for(var i in adWatchCountList){
                            var adWatchRankMap=adWatchCountList[i];
                            data2[i]={value: adWatchRankMap.adWatchCount, name: adWatchRankMap.adTypeName};
                            adWatchCountTotal+= adWatchRankMap.adWatchCount;
                        }
                    }
                    if(adWatchCountTotal>0){
                        var option2 = {
                            legend: { //设置legend
                                data: data2,
                                formatter: function (name) {
                                    var total = 0;
                                    var target;
                                    for (var i = 0, l = data2.length; i < l; i++) {
                                        total += Number(data2[i].value);
                                        if (data2[i].name == name) {
                                            target = Number(data2[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 + '}';
                                    }
                                }
                            },
                            calculable: true,
                            series: [
                                {
                                    name: '',
                                    type: 'pie',
                                    clockWise: true,
                                    hoverAnimation: false,
                                    radius: [100, 100],
                                    center: ['28%', '50%'], //设置饼图位置
                                    label: {
                                        normal: {
                                            position: 'center'
                                        }
                                    },
                                    data: [{
                                        value: 1,
                                        tooltip: {
                                            show: false
                                        },
                                        label: {
                                            normal: {
                                                formatter: '总数',
                                                textStyle: {
                                                    color: '#5a5a5a',
                                                    fontSize: 14
                                                }
                                            }
                                        }
                                    }, {
                                        tooltip: {
                                            show: false
                                        },
                                        label: {
                                            normal: {
                                                formatter: '\n'+adWatchCountTotal,
                                                textStyle: {
                                                    color: '#5a5a5a',
                                                    fontSize: 20
                                                }
                                            }
                                        }
                                    }]
                                },
                                {
                                    data: data2
                                }
                            ]

                        };
                        myChart2.setOption(option2);
                    }

                }
            }
        });
    }

    // 窗口大小改变事件
    window.addEventListener("resize", function () {
        myCharts.resize();
        myChart1.resize();
        myChart2.resize();
    });
    
    // 时间范围
    laydate.render({
        elem: '#edtDate',
        type: 'date',
        range: true,
        theme: 'molv'
    });

    var initSubordinateFn = function() {
        $.ajax({
            type: "GET",
            url:  "/home/getSubordinateAccount",
            success: function (res) {
                if(res.code=="200"&&res.data) {//
                    $("#subordinate_account").html(res.data);
                }else{
                    $("#subordinate_account").html(0);
                }
            }
        });
    };

    var initDeviceFn = function() {
        $.ajax({
            type: "GET",
            url:  "/home/getDeviceCoverAccount",
            success: function (res) {
                if(res.code=="200" && res.data) {
                    $("#cover_provice").html(res.data.provinceCount);
                    $("#cover_city").html(res.data.cityCount);
                    $("#device_account").html(res.data.totalCount);
                }else {
                    $("#cover_provice").html(0);
                    $("#cover_city").html(0);
                    $("#device_account").html(0);
                }
            }
        });
    };

    //数据概览
    var initDataCountFn = function() {
        $.ajax({
            type: "POST",
            url:  "/home/getAdHomeDataCount",
            success: function (res) {
                if(res.code=="200" && res.data) {
                    $("#ad-type-count").html(res.data.adTypeCount);
                    $("#current-month-ad-type-count").html(res.data.currentMonthAdTypeCount);
                    $("#ad-push-count").html(res.data.adPushCount);
                    $("#current-month-ad-push-count").html(res.data.currentMonthAdPushCount);
                    $("#ad-watch-count").html(res.data.adWatchCount);
                    $("#current-month-ad-watch-count").html(res.data.currentMonthAdWatchCount);
                }
            }
        });
    }

    //省份排名
    var initProvinceRankFn = function() {
        $.ajax({
            type: "POST",
            url:  "/home/adWatchRankForArea",
            success: function (result) {
                var data=result.data;
                if(result.code=="500"&&data) {
                    $("#ad-watch-rank-id").html("");
                    for(var i in data){
                        var num=Number(i)+1;
                        var adWatchRankMap=data[i];
                        var trHtml="<tr>" +
                            "<td><span class=\"layui-badge layui-bg-cyan\">"+num+"</span></td>" +
                            "<td>"+adWatchRankMap.area+"</td>" +
                            "<td>"+adWatchRankMap.adWatchCount+"</td>" +
                            "</tr>";
                        $("#ad-watch-rank-id").append(trHtml);
                    }
                }
            }
        });
    };

    //  初始化
    (function () {
        initSubordinateFn();
        initDeviceFn();
        //数据概览
        initDataCountFn();
        //观看次数
        initAdWatchLineChartsOption();
        initAdWatchLineCharts(getFormatDate(),0);
        //省份排名
        initProvinceRankFn();
        //观看排行
        initAdWatchRankFn();
        //观看类别占比
        initAdWatchProportionFn();
    })();
});

