<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Template</title>
    <link rel="stylesheet" href="./js/layui/css/layui.css">
    <link rel="stylesheet" href="./js/layui/css/modules/index.css">
    <style>
        .all {
            padding-top: 10px;
            padding-left: 30px;
            padding-right: 30px;

        }

        .c {
            float: left;
            background-color: #fff;
            padding: 10px;
        }

        .c1 {
            margin: 10px;
            float: left;
        }

        .t1 {
            /* width: 18%; */
            /* margin-right: 10px; */
            -webkit-box-sizing:border-box; 
            -moz-box-sizing:border-box; 
            -ms-box-sizing:border-box; 
            box-sizing:border-box 
        }

        .row {
            height: 50px;
        }
        .row2 {
            height: 130px;
        }

        .t2 {
            width: 10%;
        }

        .view {

            /* width: 79%; */
        }

        #timeType {
            float: left;
            width: 10%;
        }

        #time1 {
            float: left;
            width: 10%;
        }

        .btn {
            float: left;
            width: 10%;
        }

        .label {
            height: 50px;
            line-height: 32px;
        }
        #column{
            width: 100%;
        }
    </style>
</head>

<body>
    <div class="banner">
        <!-- <img src="../static/js/layui/css/modules/layer/default/nokiaLogo.png" alt="" width="150px" height="50px"> -->
        <div class="logo"></div>
        <div class="name">KPI-Analyser</div>
        <div class="userinfo">
            <!-- <i class="layui-icon layui-icon-username"></i>  -->
            <span>你好，</span>
            <span id="userName"></span>
            <span class="logOut" onclick="logOutFun()">退出登录</span>
        </div>
    </div>
<div class="all layui-row">
    <div class=" t1 layui-col-md2 " >
        <div class="c" style="width:90%;height: 85vh;overflow: auto;">
            <div class="grid-demo grid-demo-bg1">
                <button type="button" class="layui-btn layui-btn-sm" onclick="addTemplate()">添加指标模板</button>
                <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="deleteTemplate()">删除指标模板</button>
                <div id="allArea"></div>
                <div id="indicatorTemplate"></div>
                <div id="add-template" style="display: none;">
                    <form class="layui-form" action="">
                        <div class="layui-form-item" style="margin-top: 20px">
                            <label class="layui-form-label">模板名称</label>
                            <div class="layui-input-block" style="width: 400px">
                                <input id="templateName" type="text" name="templateName" required lay-verify="required"
                                       placeholder="请输入模板名称" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </form>
                    <div id="allIndicator"></div>
                </div>
            </div>
        </div>
    </div>
    <!-- <div class="c t2">
        <form class="layui-form" action="">
            <div class="column" id="searchType">
                <input type="radio" name="where" value="eci" title="按eci查询" lay-filter="where" checked>
                <input type="radio" name="where" value="all" title="全网选择" lay-filter="where">
            </div>
            <textarea id="condition" cols="14" rows="19"
                      style="border-width:1px;border-style: solid;border-color: #eee;"></textarea>
        </form>
    </div> -->
    <div class="c view layui-col-md10">
        <div class="grid-demo">
            <div class="row layui-form row2">
                <div style="width:100%;float: left;">
                    <div class="c1 label"> 粒度:</div>
        
                    <div class="timeTypeDiv c1" style="width: 10%;">
                        <select name="timeType" id="timeType">
                            <option value="QUATER">15分钟</option>
                            <option value="HOUR">小时</option>
                            <option value="DAY">天</option>
                            <!--<option value="week">星期</option>-->
                            <!--<option value="month">月</option>-->
                        </select>
                    </div>
        
                    <div class="c1 label" style="margin-left: 120px;">时间:</div>
                    <input type="text" class="layui-input c1" style="width: 300px;" id="time1">
                    <button class="layui-btn btn c1" style="margin-left: 20px;" onclick="search()">查询</button>
    <!--                <button class="layui-btn btn c1" style="margin-left: 20px;" onclick="conditionSearch()">条件查询</button>-->
                </div>
            </br>
                <div style="width:100%;float: left;">
                    <div class="column" id="searchType" style="width:auto;float: left;">
                        <input type="radio" name="where" value="AREA" title="按地市查询" lay-filter="where" checked>
                        <input type="radio" name="where" value="ECI" title="按eci查询" lay-filter="where" >
                    </div>
                    <div style="width:70%;float: left;">
                        <input id="condition" class="layui-input" placeholder="如多个eci查询请用英文逗号隔开"
                                    style="border-width:1px;border-style: solid;border-color: #eee;"></input>
                    </div>
                </div>
            </div>
            <div>
                <table id="demo" lay-filter="test" style="width: 200px;"></table>
            </div>
        </div>
    </div>
</div>
<script src="./js/jquery-3.5.1.min.js"></script>
<script src="./js/layui/layui.js"></script>
<script>
        var dataA;
        var layer;
        var tree;
        var table;
        layui.use(['layer', 'tree', 'form', 'laydate', 'table'], function () {
            tree = layui.tree;
            layer = layui.layer;
            table = layui.table;
            var form = layui.form, laydate = layui.laydate;
            // layer.msg('Hello Zhou')
            table.render({
                elem: '#demo',
                height: 480,
                // url: 'https://www.layui.com/demo/table/user/' , //数据接口
                page: true, //开启分页
                toolbar: true,
                defaultToolbar: [{
                    title: '导出' //标题
                    ,
                    layEvent: 'export' //事件名，用于 toolbar 事件中使用
                    ,
                    icon: 'layui-icon-export' //图标类名
                }],
                limit: 50,
                limits: [50, 200, 500],
                cols: [],
                data: []
            });
            //工具条事件
            table.on('toolbar(test)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                var data = obj.data; //获得当前行数据
                var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
                if (layEvent === 'export') {
                    // layer.alert('Hi，头部工具栏扩展的右侧图标。');
                    var tableData = table.cache['demo']
                    obj.config.title = "地市指标"
                    table.exportFile(obj.config.id, dataA, 'csv')
                }
            });
            laydate.render({
                elem: '#time1',
                type: 'datetime',
                range: true,
            });
            initTreeCity(tree)
            initTreeIndicator(tree)
            initTreeIndicatorTemplate(tree)
            // console.log(window.localStorage.getItem('userName'))
            $("#userName").text(window.localStorage.getItem('userName'))
        })

        var treeCity;
        function initTreeCity(tree) {
            $.ajax({
                type: "POST",
                // url: '/api/json/citys.json',
                url: '/api/initTreeCitys',
                success: function (r) {
                    if (r?.success) {
                        treeCity = tree.render({
                            elem: '#allArea',
                            showCheckbox: true,
                            accordion: true,
                            id: 'Id1',
                            data: r?.data
                        });
                        return
                    }
                    alert(r?.message ?? '发生错误了');
                }
            });
        }

        var treeIn;
        // 渲染指标模板
        function initTreeIndicatorTemplate(tree) {
            $.ajax({
                type: "POST",
                url: '/api/initTreeIndicatorTemplate',
                success: function (r) {
                    if (r?.success) {
                        treeIn = tree.render({
                            elem: '#indicatorTemplate',
                            showCheckbox: true,
                            accordion: true,
                            id: 'Id3',
                            data: r?.data
                        });
                        return
                    }
                    alert(r?.message ?? '发生错误了');
                }
            });
        }

        function initTreeIndicator(tree) {
            $.ajax({
                type: "POST",
                url: '/api/initTreeIndicator',
                success: function (r) {
                    if (r?.success) {
                        treeIn = tree.render({
                            elem: '#allIndicator',
                            showCheckbox: true,
                            accordion: true,
                            id: 'Id2',
                            data: r?.data
                        });
                        return
                    }
                    alert(r?.message ?? '发生错误了');
                }
            });
        }

        function renderTable(condition, searchType, table, citys, quxians, indicators, timeType, startTime, endTime) {
            var tishi = layer.load(1, {
                shadeClose: false,
                title: '加载中..',
                shade: [0.5,'#000'] //0.1透明度的白色背景
            });
            // setTimeout(()=>{
            //     layer.close(tishi);
            // },5000)
            const dataJson = JSON.stringify({
                "condition": condition,
                "searchType": searchType,
                "citys": [...citys],
                "quxians": [...quxians],
                "indicators": [...indicators],
                "timeType": timeType,
                "startTime": startTime,
                "endTime": endTime
            })
            $.ajax({
                type: "POST",
                contentType: "application/json;charset=UTF-8",
                url: '/api/renderTable',
                data: dataJson,
                success: function (r) {
                    layer.close(tishi);
                    if (r?.success) {
                        dataA = r?.data?.datas
                        table.render({
                            elem: '#demo',
                            height: 480,
                            // url: 'https://www.layui.com/demo/table/user/' , //数据接口
                            page: true, //开启分页
                            toolbar: true,
                            defaultToolbar: [{
                                title: '提示' //标题
                                ,
                                layEvent: 'export' //事件名，用于 toolbar 事件中使用
                                ,
                                icon: 'layui-icon-export' //图标类名
                            }],
                            limit: 50,
                            limits: [50, 200, 500],
                            cols: [
                                r?.data?.cols ?? []
                            ],
                            data: r?.data?.datas ?? []
                        });
                        return
                    }
                    alert(r?.message ?? '发生错误了');
                },
                error: function(err){
                    layer.close(tishi);
                }
            });
        }

        function search() {
            if ($('#time1').val() === 0) {
                alert('填选择时间')
                return;
            }
            if (tree.getChecked('Id3').length === 0) {
                alert('请选择指标')
                return;
            }
            let condition = $('#condition').val();
            let searchType = $('#searchType').find('input:checked').val()
            if (searchType === 'ECI' && $('#condition').val().length === 0) {
                alert('请填写eci')
                return;
            }
            if (searchType === 'AREA' && tree.getChecked('Id1').length === 0) {
                alert('请选择地市')
                return;
            }
            let checkData1 = tree?.getChecked('Id1')?.[0]?.children;
            let quxians = new Set()
            let citys = new Set()
            if (checkData1) {
                checkData1.forEach(eee => {
                    citys.add(eee.title)
                    eee.children.forEach(ee => {
                        quxians.add(ee.title)
                    })
                });
            }
            let checkData2 = tree.getChecked('Id3')[0].children;
            const indicators = new Set();
            checkData2.forEach(eee => {
                eee.children.forEach(ee => {
                    indicators.add(ee.id)
                })
            });
            indicators.add('eci')
            let timeType = $('#timeType').val()
            let sdate = $('#time1').val()
            const [startTime, endTime] = sdate.split(' - ')
            renderTable(condition, searchType, table, citys, quxians, indicators, timeType, startTime, endTime)
            return false;
        }

        // 添加指标模板
        function addTemplate() {
            layer.open({
                type: 1,
                title:"添加指标模板",
                content: $("#add-template"),
                area: ['600px', '600px'],
                btn: ['确定'],
                shadeClose: true,
                yes: function(index, layero){
                    const templateName = $('#templateName').val()
                    if (!templateName || templateName.length <= 0) {
                        alert('请输入模板名称！')
                        return
                    }
                    const checkedData = tree?.getChecked('Id2')?.[0]?.children
                    if (!checkedData || checkedData.length <= 0) {
                        alert('请选择指标！')
                        return
                    }
                    const indicators = new Set()
                    checkedData.forEach(eee => {
                        eee.children.forEach(ee => {
                            indicators.add(ee.id)
                        })
                    });
                    const dataJson = JSON.stringify({
                        "templateName": templateName,
                        "indicators": [...indicators],
                    })
                    $.ajax({
                        type: "POST",
                        contentType: "application/json;charset=UTF-8",
                        url: '/api/addTemplate',
                        data: dataJson,
                        success: function (r) {
                            if (r?.success) {
                                initTreeIndicatorTemplate(tree)
                                layer.msg('添加成功')
                                layer.close(index)
                                return
                            }
                            alert(r?.message ?? '发生错误了');
                        }
                    });
                },
            });
        }

        // 删除指标模板
        function deleteTemplate() {
            const checkedData = tree?.getChecked('Id3')?.[0]?.children
            if (!checkedData || checkedData.length <= 0) {
                alert('请选择要删除的指标模板！')
                return
            }
            const ids = new Set()
            checkedData.forEach(t => {
                ids.add(t.id)
            });
            const dataJson = JSON.stringify({
                "ids": [...ids],
            })
            layer.confirm('确认删除？', {icon: 3, title:'删除模板'}, function(index){
                $.ajax({
                    type: "POST",
                    contentType: "application/json;charset=UTF-8",
                    url: '/api/deleteTemplate',
                    // async: false,
                    data: dataJson,
                    success: function (r) {
                        if (r?.success) {
                            initTreeIndicatorTemplate(tree)
                            layer.msg('删除成功')
                            layer.close(index)
                            return
                        }
                        alert(r?.message ?? '发生错误了')
                    }
                });
            });
        }

        // 获取登录用户信息

        // 退出登录
        function logOutFun() {
            console.log('tuichu')
            $.ajax({
                type: "POST",
                // url: '/api/json/citys.json',
                url: '/api/logout',
                success: function (r) {
                    console.log('r: ', r);
                    if (r?.success) {
                        layer.msg('退出登录成功');
                        setTimeout(() => window.location.href = '/login', 1000)
                    }else{
                        alert('退出登录失败');
                    }
                }
            });
        }

        // 
        $(document).ready(function(){
            setTimeout(()=>{
              $(".layui-tree-txt").mouseenter(function(){
                    // console.log('this',this)
                    $(this).attr("title",$(this).text());
                    // console.log('this.text(): ', $(this).text());
                });
            },1000)
        });
    </script>
</body>

</html>