{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="{% static '/lib/layui/css/layui.css' %}">
    <link rel="stylesheet" href="{% static '/lib/font/fontIcon/iconfont.css' %}">
    <link rel="stylesheet" href="{% static '/lib/css/reset.css' %}">
    <style>
        /* 面包屑导航 */

        .breadcrumbs {
            /* line-height: 38px; */
            padding: 12px 0 12px 30px;
            border-bottom: 1px solid #dbdbdb;
        }

        .layui-breadcrumb>* {
            font-size: 16px;
        }

        /* 内容 */

        .tableDiv {
            display: table;
            width: 100%;
        }

        .tableDiv>div {
            display: table-cell;
        }

        .equipListDiv {
            width: 233px;
            /* height: 751px; */
            position: absolute;
        }

        .searchInp {
            text-align: center;
            margin: 10px 0;
            position: relative;
            height: 40px;
        }

        .searchInp>input {
            line-height: 30px;
            font-size: 14px;
            border: 1px solid #d9d9d9;
            width: 93%;
            padding-left: 5px;
            position: absolute;
            left: 10px;
        }

        .searchInp>button {
            position: absolute;
            top: 1px;
            right: 0;
            line-height: 31px;
            background: #bbb;
            color: #fff;
        }

        .searchInp>button:hover {
            background: #8B9AA3;
        }

        .searchInp>button span {
            padding: 0 10px;
        }

        .equipListUl>li {
            padding-left: 30px;
            color: #333;
            font-size: 14px;
            line-height: 30px;
            cursor: pointer;
            position: relative;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .equipListUl>li:before {
            position: absolute;
            content: '';
            width: 7px;
            height: 7px;
            background: #1e9fff;
            border-radius: 50%;
            margin-top: -3.5px;
            top: 50%;
            left: 15px;
        }

        .equipListUl>li.active:before {
            background: #3ab851
        }

        .equipListUl>li.active {
            background: #eee;
        }

        .equipListUl>li i {
            font-size: 12px;
            margin-right: 10px;
            color: #41baff;
        }

        .page {
            text-align: center;
            padding: 10px 0;
        }

        .page span {
            padding: 0 5px;
            vertical-align: middle;
        }

        .page span i {
            font-size: 28px;
            cursor: pointer;
            vertical-align: middle;
        }

        .page span i:hover {
            color: #1E9FFF;
        }

        /* 主体 */

        .clearfix::after {
            content: '';
            display: block;
            height: 0;
            clear: both;
        }

        .clearfix {
            zoom: 1;
        }

        .fl {
            float: left;
        }

        .fr {
            float: right;
        }

        .rightDiv {
            min-height: 730px;
            margin-left: 240px;
            border-left: 1px solid #dbdbdb;
            padding: 20px;
        }

        .widget-title {
            position: relative;
            padding-left: 10px;
            font-size: 16px;
            padding: 5px 0 5px 10px;
        }

        .widget-title::after {
            position: absolute;
            content: '';
            left: 0;
            top: 9px;
            height: 15px;
            border-left: 5px solid #23a3ee;
            padding-left: 10px;
            font-size: 16px;
            padding: 5px 0 5px 10px;
        }

        .widget-title h2 {
            font-weight: 700;
            line-height: 33px;
        }

        .widget-title h2 span {
            font-size: 13px;
            font-weight: 100;
            margin-left: 20px;
            color: #333;
        }

        .newStatusBox>div {
            width: 20%;
            margin: 15px 0;
        }

        .dev .devLeft {
            width: 30%;
            text-align: right;
        }


        .dev .devRight {
            padding-left: 15px;
            line-height: 33px;
            font-size: 14px;
            width: 60%;
        }

        .dev .devRight .val {
            font-size: 20px;
        }

        .dev .devRight .wayName {
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
        }

        /* 统计图 */

        .analysisChart {
            padding: 20px 0;
        }

        .echart {
            height: 400px;
        }

        /* 搜索时间段 */

        .layui-form-label {
            font-size: 16px;
            padding: 5px 15px;
        }

        .layui-input {
            font-size: 14px;
            color: #333;
            background-color: #FFF;
            font-weight: 100;
            width: 188px;
            line-height: 30px;
            height: 30px;
            vertical-align: middle;
        }

        .layui-form-label {
            width: 115px;
        }
    </style>
</head>

<body>
    <div class="content">
        <!-- 导航 -->
        <div class="breadcrumbs">
            <span class="layui-breadcrumb">
                <a href="info_pub" target="BoardRight">首页</a>
                <a>
                    <cite>趋势分析</cite>
                </a>
            </span>
        </div>
        <!-- 内容 -->
        <div>
            <div class="">
                <div class="equipListDiv">
                    <div class="searchInp">
                        <input type="text" id="searchImei" autocomplete="off" placeholder="请输入设备ID搜索">
                        <button id="searchBtn">
                            <span class="iconfont"><i class="layui-icon layui-icon-search"></i></span>
                        </button>
                    </div>
                    <ul class="equipListUl">
                    </ul>
                    <div class="page">
                        <span onclick="gotofirstpage()">
                            <i class="iconfont">&#xe661;</i>
                        </span>
                        <span onclick="changePage('jian')">
                            <i class="iconfont">&#xe728;</i>
                        </span>
                        <span>1</span>
                        <span>/</span>
                        <span id="totelpage">3</span>
                        <span onclick="changePage('add')">
                            <i class="iconfont">&#xe601;</i>
                        </span>
                    </div>
                </div>
                <div class="rightDiv">
                    <div>
                        <!-- 实时状态 -->
                        <div class="widget-title">
                            <button type="button" class="layui-btn  layui-btn-normal layui-btn-sm fr" onclick="newDataRefresh()">刷新</button>
                            <h2>实时状态
                                <span id="Uptime">数据更新时间:2019-07-17 09:31:56</span>
                            </h2>
                        </div>
                        <div class="newStatusBox clearfix" id="newStatusBox">
                            <!-- <div class="dev clearfix fl">
                                <div class="fl devLeft">
                                    <img src="{% static 'imgs/dev/icon_103.png'%}" alt="">
                                </div>
                                <div class="fl devRight">
                                    <p class="val">0.0 m/s</p>
                                    <p class="wayName">通道1-风速风速风速风速风速风速</p>
                                </div>
                            </div> -->

                        </div>
                        <!-- 数据存储 -->
                        <div>
                            <div class="widget-title">
                                <!-- <button type="button" class="layui-btn  layui-btn-normal layui-btn-sm fr" onclick="newDataRefresh()">刷新</button> -->
                                <h2>存储设置
                                    <!-- <span id="Uptime">数据更新时间:2019-07-17 09:31:56</span> -->
                                </h2>
                            </div>
                            <div>
                                <form class="layui-form" action="">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">数据上传间隔：</label>
                                        <div class="layui-input-inline">
                                            <select name="upDataTime" lay-verify="required" id="upDataTime" lay-filter="upDataTime">
                                                <option value="10">10分钟</option>
                                                <option value="20">20分钟</option>
                                                <option value="30">30分钟</option>
                                                <option value="40">40分钟</option>
                                                <option value="50">50分钟</option>
                                                <option value="60">60分钟</option>
                                            </select>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                        <!-- 统计分析 -->
                        <div class="widget-title">
                            <div class="fr">
                                <div class="layui-inline">
                                    <label class="layui-form-label">时间段：</label>
                                    <div class="layui-input-inline">
                                        <input type="text" class="layui-input" autocomplete="off" id="timeSearch" lay-key="1">
                                        <input type="hidden" id="begin" value="">
                                        <input type="hidden" id="end" value="">
                                    </div>
                                </div>
                                <button type="button" class="layui-btn  layui-btn-normal layui-btn-sm" onclick="sub_filter()">搜索</button>
                            </div>
                            <h2>统计分析</h2>
                        </div>
                        <div class="analysisChart">
                            <div id="line-chart" class="echart"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <input type="hidden" id="qxzPhotoId">


    <script src="{% static '/lib/js/jquery-2.1.4.min.js'%}"></script>
    <script src="{% static '/lib/layui/layui.js'%}"></script>
    <script src="http://echarts.baidu.com/build/dist/echarts-all.js"></script>
    <script src="{% static '/js/backstageNet/common.js'%}"></script>
    <script src="{% static '/lib/js/qxz_dict.js'%}"></script>
    <script>
        var currpage = 1;
        var layer, element, form;
        layui.use(['element', 'layer', 'form'], function () {
            element = layui.element;
            layer = layui.layer;
            form = layui.form;
            getEquipList(1, '');
            // loadProject('123456')
            // 搜索
            $('#searchBtn').on('click', function () {
                getEquipList(1, $('#searchImei').val())
            });
            $('#searchImei').on('keyup', function (event) {
                if (event.keyCode == 13) {
                    getEquipList(1, $('#searchImei').val())
                }
            })
            var oldVal = $('#upDataTime').val();
            form.on('select(upDataTime)', function (data) {
                var id = $(".equipListUl li.active").attr('id');
                layer.confirm('是否调整设备：' + id + ' 数据上传时间', { icon: 3, title: '数据上传时间' }, function (index) {
                    $.ajax({
                        url: 'qxz_mqtt',
                        type: 'post',
                        data: {
                            'req': 'interval',
                            'time': data.value,
                        },
                        beforeSend: function () {
                            loadFlage = layer.load();
                        },
                        complete: function () {
                            setTimeout(function () {
                                layer.close(loadFlage);
                            }, 2000)
                        },
                        success: function (data) {
                            if (data == 0) {

                            } else {
                                $('#upDataTime').val(oldVal);
                            }
                            layui.use(['form'], function () {
                                form.render('select'); //刷新select选择框渲染
                            })
                            setTimeout(function () {
                                loadProject($('#qxzPhotoId').val())
                            }, 2000)
                        },
                        error: function (type) {
                            $('#upDataTime').val(oldVal);
                            layui.use(['form'], function () {
                                form.render('select'); //刷新select选择框渲染
                            })
                        }
                    })
                    layer.close(index);
                });


                console.log(data.elem); //得到select原始DOM对象
                console.log(data.value); //得到被选中的值
                console.log(data.othis); //得到美化后的DOM对象
            });

            // 数据上传间隔
            form.on('select(formDemo)', function (data) {
                console.log(data);
                return false;
            });
        })
        // 首页
        function gotofirstpage() {
            currpage = 1;
            $('#currentpage').html(1);
            getEquipList(1, $('#searchImei').val())
        }
        function changePage(symbol) {
            var totelpage = Number($('#totelpage').html());
            if (symbol == 'add') {
                if (currpage < totelpage) {
                    currpage++;
                    $('#currentpage').html(currpage);
                    $('addPage').attr('disable', 'false')
                } else {
                    $('addPage').attr('disable', 'true')
                    return false;
                }
            } else {
                if (currpage > 1) {
                    currpage--;
                    $('#currentpage').html(currpage);
                    $('jianPage').attr('disable', 'false')
                } else {
                    $('jianPage').attr('disable', 'true')
                    return false;
                }
            }
            $(".equipListUl").on('click', 'li', function () { })
            getEquipList(currpage, $('#searchImei').val())

        }
        // 加载数据列表
        function getEquipList(page, filter) {
            $.ajax({
                url: 'qxz_page',
                type: 'get',
                dataType: 'json',
                data: {
                    page: page,
                    f_id: filter
                },
                beforeSend: function (XMLHttpRequest) {
                    loadingFlag = layer.load();
                },
                success: function (data) {
                    layer.close(loadingFlag);
                    if (data.nums) {
                        // console.log(data.ids)
                        var html = '';
                        var msg = data.ids
                        var pagecount = Math.ceil(data.nums / 10);
                        // console.log(pagecount)
                        for (var i = 0; i < msg.length; i++) {
                            if (msg[i].equip_name) {
                                var equip_name = '设备：' + msg[i].equip_name;
                            } else {
                                var equip_name = '设备：' + msg[i].equip_id;
                            }
                            // var equip_name = msg[i].equip_name?'---设备名：'+msg[i].equip_name:'';
                            html += '<li title="设备' + msg[i].equip_id + '"id="' + msg[i].equip_id + '">' + equip_name + '</li>';
                            // html += '<a href="javascript:;" title="设备' + msg[i].equip_id + '" class="text-overflow" id="' + msg[i].equip_id + '" data-pid="322">' + equip_name + '</a>'
                        }
                        $('.equipListUl').html(html);
                        $('.page').show();
                        $('#totelpage').html(pagecount)
                        // 菜单栏
                        $(".equipListUl li:eq(0)").addClass('active');
                        loadProject(msg[0].equip_id);
                        $('#qxzPhotoId').val(msg[0].equip_id)
                    } else {
                        $('.page').hide();
                        var html = '<a href="javascript:;" class="text-overflow nulldata" data-pid="322">暂未设备</a>'
                        $('#firstpane .menu_body').html(html);
                    }
                },
                error: function (type) {
                    layer.close(loadingFlag);
                    // console.log(type)
                }
            })
        }
        $(".equipListUl").on('click', 'li', function () {
            $(".equipListUl li").removeClass("active");
            $(this).addClass("active");
            var facId = $(this).attr("id");
            if (facId && facId != null && facId != "") {
                $('#timeSearch').val('');
                $('#begin').val('');
                $('#end').val('');
                loadProject(facId);
                $('#qxzPhotoId').val(facId);
            }
        });
        //实时状态数据请求 
        function loadProject(facId) {
            loadCharts(facId)
            // $.ajax({
            //     url: 'qxz_status',
            //     type: 'post',
            //     dataType: 'json',
            //     data: {
            //         e_id: facId,
            //     },
            //     beforeSend: function (XMLHttpRequest) {
            //         loadingFlag = layer.load();
            //     },
            //     success: function (data) {
            //         // console.log(data)
            //         layer.close(loadingFlag);
            //         if (data.length) {
            //             // 实时状态
            //             var newData = data[0];
            //             newStatus('newStatusBox', newData, facId)
            //             $('#upDataTime').val(data[0].interval)
            //             layui.use(['form'], function () {
            //                 form.render('select'); //刷新select选择框渲染
            //             })
            //         } else {
            //             $('#newStatusnewStatusBox').html('<h3 style="text-align:center">空</h3>');
            //             $('#Uptime').html('')
            //             scrollBar()
            //         }


            //     },
            //     error: function (type) {
            //         layer.close(loadingFlag);
            //         // console.log(type)
            //     }
            // })

            $.ajax({
                url: 'qxz_status2',
                type: 'post',
                dataType: 'json',
                data: {
                    e_id: facId,
                },
                beforeSend: function (XMLHttpRequest) {
                    loadingFlag = layer.load();
                },
                success: function (data) {
                    layer.close(loadingFlag);
                    $('#upDataTime').val(data.interval)
                    $('#Uptime').html('数据更新时间:' + data.upl_time)
                    layui.use(['form'], function () {
                        form.render('select'); //刷新select选择框渲染
                    })
                    newStatus2(data, facId)
                },
                error: function (type) {
                    layer.close(loadingFlag);
                    // console.log(type)
                }
            })
        }
        // stauts2实时状态填充
        function newStatus2(data, facId) {
            var datlen = Object.keys(data.dat).length;;
            var json = data.dat;
            var html = '';
            $(document.getElementById('newStatusBox')).html('');
            for (var i = 1; i <= datlen; i++) {
                if (json['e' + i] != '') {
                    var curVal = json['e' + i].split('#');
                    var icon = curVal[1];
                    var el = 'e' + i;
                    var val = curVal[0];
                    html += '<div class="dev clearfix fl"><div class="fl devLeft">' +
                        '<img src="../static/imgs/dev/icon_' + icon + '.png" alt="">' +
                        '</div><div class="fl devRight"><p class="val">' + val + qxz_dict[icon][2] + '</p>' +
                        '<p class="wayName">通道' + i + '-' + qxz_dict[icon][1] + '</p></div></div>';
                }
                if (i == datlen) {
                    $('#newStatusBox').html(html);
                    scrollBar()
                }
            }
        }

        // 实时状态填充
        function newStatus(statusBox, dat, facId) {
            var html = '';
            $(document.getElementById(newStatusBox)).html('');
            var count = Object.keys(dat).length;  //json子长度
            // console.log(count);
            var i = 0;
            for (var item in dat) {
                i++;
                if (dat[item] && item != 'upl_time' && dat[item] && item != 'interval') {
                    var curVal = dat[item].split('#');
                    var icon = curVal[1];
                    var el = curVal[2];
                    var val = curVal[0];
                    html += '<div class="dev clearfix fl"><div class="fl devLeft">' +
                        '<img src="../static/imgs/dev/icon_' + icon + '.png" alt="">' +
                        '</div><div class="fl devRight"><p class="val">' + val + qxz_dict[icon][2] + '</p>' +
                        '<p class="wayName">通道' + item.substr(1) + '-' + qxz_dict[icon][1] + '</p></div></div>';
                }
                if (i == count) {
                    // console.log(html)
                    // $(document.getElementById(newStatusBox)).html(html);
                    $('#newStatusBox').html(html);
                    $('#Uptime').html('数据更新时间:' + dat.upl_time)
                    scrollBar()
                }
            }

        }

        layui.use('laydate', function () {
            var laydate = layui.laydate;

            //执行一个laydate实例
            laydate.render({
                elem: '#timeSearch' //指定元素
                , range: true //或 range: '~' 来自定义分割字符
                , done: function (value, date) {
                    var dateArray = value.split(' - ')
                    $('#begin').val(dateArray[0])
                    $('#end').val(dateArray[1])
                }
            });
        });

        // 1基于准备好的dom，初始化echarts实例
        var lineChart = echarts.init(document.getElementById('line-chart'));

        // 指定图表的配置项和数据
        var option = {
            title: {
                text: '元素分析',
                textStyle: {
                    color: '#029eef'
                }
            },
            tooltip: {
                trigger: 'axis',
            },
            legend: {
                data: ['风速', '湿度', '光照', '雨量']
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            toolbox: {
                feature: {
                    // saveAsImage: {}
                }
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: []
            },
            yAxis: {
                type: 'value',
                data: []
            },
            dataZoom: {
                show: true,
                // start: 70
            },
            series: [
            ]
        };

        // 折线图搜索
        function sub_filter() {
            var currId = $(".equipListUl .active").attr("id");
            loadCharts(currId)
            // console.log(currId)
        }

        //统计图
        function loadCharts(facId) {
            $.ajax({
                url: 'qxzchart',
                type: 'post',
                dataType: 'json',
                data: {
                    id: facId,
                    begin: $('#begin').val(),
                    end: $('#end').val(),
                },
                beforeSend: function () {
                    loadFlage = layer.load();
                },
                complete: function () {
                    layer.close(loadFlage);
                },
                success: function (data) {
                    echartFun(data.dat, facId)
                },
                error: function (type) {
                }
            })
        }

        // 折线图处理
        function echartFun(dat, facId) {
            $('#line-chart').prev().html('').css('z-index', 0);
            option.series = [];
            option.xAxis.data = [];
            if (dat.length) {
                var upTime = []; //
                var kindCount = dat[0].e_len;
                var seriesDat = [];
                var legend = []; //几条折线
                for (var i = 0; i < dat.length; i++) {
                    upTime.unshift(dat[i].upl_time);
                    for (var j = 0; j < dat[i].unit.length; j++) {
                        if (i == 0) {
                            var elementName = dat[0].unit[j][1];
                            legend.push(dat[0].unit[j][3] + elementName);
                        }
                        if (seriesDat[j]) {
                            seriesDat[j].unshift(parseFloat(dat[i].unit[j][0]));
                        } else {
                            var arr = [];
                            arr.unshift(parseFloat(dat[i].unit[j][0]));
                            seriesDat[j] = arr;
                        }
                    }
                    if (i == dat.length - 1) {
                        // console.log(seriesDat)
                        var legendData = { data: legend }
                        option.legend = legendData;

                        for (var count = 0; count < kindCount; count++) {
                            var data = {
                                name: legend[count],
                                type: 'line',
                                data: seriesDat[count]
                            }
                            option.series.push(data);
                        }
                        option.xAxis.data = upTime;
                        setTimeout(function () {
                            var lineChart = echarts.init(document.getElementById('line-chart'));
                            lineChart.setOption(option, true);
                        })
                    }

                }
            } else {
                option.series = [{
                    name: '',
                    type: 'line',
                    stack: '总量',
                    // itemStyle: {normal: {areaStyle: {type: 'default'}}},
                    data: []
                }];
                option.xAxis.data = [];
                var lineChart = echarts.init(document.getElementById('line-chart'));
                lineChart.setOption(option, true);
            }
        }

        // 获取最新数据
        function newDataRefresh() {
            $.ajax({
                url: 'qxz_mqtt',
                type: 'post',
                data: {
                    'req': 'read',
                    'imei': $('#qxzPhotoId').val(),
                },
                beforeSend: function () {
                    loadFlage = layer.load();
                },
                complete: function () {
                    setTimeout(function () {
                        layer.close(loadFlage);
                    }, 2000)
                },
                success: function (data) {
                    setTimeout(function () {
                        loadProject($('#qxzPhotoId').val())
                    }, 2000)
                }
            })
        }

    </script>
</body>

</html>