// 起始长度
let start = 1;
// 每页长度
let pagelength = 15;
//page
let page = 1;
// 起始时间
let startDate = null;
let endDate = null;
//展开的 数据  id
let sel_id = new Array();
let datatable = null;
let sx_time = null;
let last_time = new Date().getTime();
curr = new Date().getTime(),
    out = 6 * 1000; //设置超时时间：6s
// 是否正在刷新
let is_sx = false;

$(function () {
    let udplog_data = Cookies.get('udplog_data') || null;
    udplog_data = udplog_data != null ? JSON.parse(udplog_data) : [];
    $('#CONTENT_DECRYPT').val(udplog_data['CONTENT_DECRYPT']);
    $('#DESTINATION_PORT').val(udplog_data['DESTINATION_PORT']);
    $('#DESTINATION').val(udplog_data['DESTINATION']);
    $('#SOURCE_PORT').val(udplog_data['SOURCE_PORT']);
    $('#SOURCE_IP').val(udplog_data['SOURCE_IP']);
    $('#DIRECTION').val(udplog_data['DIRECTION']);
    $('#DATA_VALID').val(udplog_data['DATA_VALID']);
    pagelength = udplog_data['pagelength'] || pagelength;
    $('#pagelength').val(pagelength);
    startDate = udplog_data.startDate || moment().startOf("days").format('YYYY-MM-DD HH:mm:ss');
    endDate = udplog_data.endDate || moment().format('YYYY-MM-DD HH:mm:ss');
    // 带有时间选择的日期范围选择器
    $('#reservationtime').daterangepicker({
        startDate: startDate || "2022-3-25 01:01:01",
        endDate: endDate || new Date(),
        timePicker: true,
        maxDate: new Date(),
        minDate: "2022-3-25 01:01:01",
        timePicker24Hour: true,
        timePickerSeconds: true,
        locale: {
            cancelLabel: 'Clear',
            format: 'YYYY-MM-DD HH:mm:ss'
        }
    }).on('apply.daterangepicker', function (ev, picker) {
        startDate = picker.startDate.format('YYYY-MM-DD HH:mm:ss');
        endDate = picker.endDate.format('YYYY-MM-DD HH:mm:ss');
    }).on('cancel.daterangepicker', function (ev, picker) {
        $(this).val('');
        startDate = null;
        endDate = null;
    });
    loc();
    table_init();
    // 用户操作后停止自动刷新  未使用
    $(document).mouseover(function (e) {
        last_time = new Date().getTime(); //更新操作时间
    });
    set_Timeout();
});



//头部点击隐藏
function titlehiede(that) {
    $($(that).siblings()).toggle();
    loc();
}

// 计算距离
/// 初始的 底部距离 
let footloc = 0;
function loc() {
    if (footloc == 0) {
        footloc = $('.main-footer').offset().top;
        $('.main-footer').hide();
    }
    let STR = "calc(100vh - " + $('.table-responsive').offset().top + "px)";
    $('.table-responsive').css("height", STR)
}

// 选择长度
function lengthCHANGE(that) {
    pagelength = $(that).val();
    table_init();
}

// 定时检测刷新  勾选了就自动刷新

function set_Timeout() {
    sx_time = setInterval(function () {
        curr = new Date().getTime(); //更新当前时间
        if (
            //curr - last_time > out  //判断是否超时
            // $("#remember").prop("checked") 是否勾选
            //&& !is_sx &&

            $("#remember").prop("checked")) {
            if (startDate == null) {
                startDate = moment().startOf("days").format('YYYY-MM-DD HH:mm:ss');
            }
            endDate = moment().format('YYYY-MM-DD HH:mm:ss');
            $('#reservationtime').val(startDate + "-" + endDate)
            is_sx = true;
            table_init(function () {
                is_sx = false;
            });
        }
    }, 1000);
}
// table数据初始化刷新

function table_init(success = null) {

    let data = {
        DESTINATION_PORT: $('#DESTINATION_PORT').val(),
        CONTENT_DECRYPT: $('#CONTENT_DECRYPT').val(),
        DESTINATION: $('#DESTINATION').val(),
        SOURCE_PORT: $('#SOURCE_PORT').val(),
        SOURCE_IP: $('#SOURCE_IP').val(),
        DIRECTION: $('#DIRECTION').val(),
        DATA_VALID: $('#DATA_VALID').val(),
        startDate,
        endDate
    };
    if (datatable != null) {
        datatable.destroy();
        //$('#dataTable').empty();
    }
    $.fn.dataTable.ext.errMode = 'none';//屏蔽掉报错弹窗

    datatable = $('#dataTable').on('error.dt', function (e, settings, techNote, message) {
        console.log(e, settings, techNote)
        console.log('An error has been reported by DataTables: ', message);
        location.reload();
    }).DataTable({
        "ordering": false,
        "paging": true,
        "serverSide": true,
        "ajax": function (datas, callback, settings) {
            data.start = datas.start;
            data.length = datas.length;
            data.draw = datas.draw
            //is_sx 自动刷新的 话 取消弹窗
            MyPost("/Server/GetUDPLog", { data, isSwal: !is_sx }, res => { callback(res) });
        },
        "columns": [{
            'sTitle': '',/*.substring(6)*/
            'render': function (data, type, row) {
                return `
                         <td  class=" text-gray info-box-content" style="padding: 0; margin: 0; line-height: 1; overflow: hidden;display:block;width:100%;">
                         <div style='color: #D3D3D3;' class="row  " `+ (sel_id.indexOf(row["UDP_ID"]) != -1 ? "ID = '" + row["UDP_ID"] + "'" : "") + ` >
                         <div class="col-6">
                         `+ row["UDP_ID"] + `
                         <span style="background-color:`+ (row["DIRECTION"] == "TX" ? '#FFB6C1' : '#B0E0E6') + ` !important;  padding-left:5px;padding-right:5px;margin-left:5px;" class=' ` + (row["DIRECTION"] == "TX" ? 'bg-danger' : 'bg-success') + ` '>
                         `+ row["DIRECTION"] + `</span>
                         <span style='color:gray;'> `  +
                    //无效数据不判断指令
                    (row["DATA_VALID"] != "1" ? "" : (
                        (row["CONTENT_DECRYPT"].trim().substring(48, 50) == "01" ? "搜索主机" :
                            (row["CONTENT_DECRYPT"].trim().substring(48, 50) == "02" ? "设置密钥" :
                                (row["CONTENT_DECRYPT"].trim().substring(48, 50) == "03" ? "心跳包" :
                                    (row["CONTENT_DECRYPT"].trim().substring(48, 50) == "04" ? "状态上报" :
                                        (row["CONTENT_DECRYPT"].trim().substring(48, 50) == "05" ? "下发参数" :
                                            (row["CONTENT_DECRYPT"].trim().substring(48, 50) == "06" ? "启动测试" :
                                                (row["CONTENT_DECRYPT"].trim().substring(48, 50) == "07" ? "RCU发送测试" : "其他")))))))
                        + (row["DIRECTION"] != "TX" ? "" : "ACK"))) +
                    `</span>
                         </div>
                         <div class="col-6  ">src:
                         `+ row["SOURCE_IP"] + `:
                         `+ row["SOURCE_PORT"] + `
                         </div>
                         <div class="col-6  ">
                         `+ row["DATETIME"].substring(2).replace("T", " ") + `
                         </div>
                         <div class="col-6  ">dst:
                         `+ row["DESTINATION"] + `:
                         `+ row["DESTINATION_PORT"] + `
                         </div>
                        <div STYLE="`+ (row["DATA_VALID"] == "0" ? "" : "color: #D3D3D3;") + `" class="col-12 ` + (row["DATA_VALID"] == "0" ? '' : 'text-success') + `">
                         
                         <text style="color:`+ (row["DATA_VALID"] == "1" ? '#D3D3D3 !important' : ' ') + `">` + row["CONTENT_DECRYPT"].trim().substring(0, 18) + `</text>
                         <text style="color:`+ (row["DATA_VALID"] == "1" ? '#000 !important' : ' ') + `">` + row["CONTENT_DECRYPT"].trim().substring(18, 24) + `</text>
                         <text style="color:`+ (row["DATA_VALID"] == "1" ? '#DC143C !important' : ' ') + `">` + row["CONTENT_DECRYPT"].trim().substring(24, 27) + `</text>
                        <text style="color:`+ (row["DATA_VALID"] == "1" ? '#D3D3D3 !important' : ' ') + `">` + row["CONTENT_DECRYPT"].trim().substring(27, 30) + `</text>
                        <text>`+ row["CONTENT_DECRYPT"].trim().substring(30, 48) + `</text>

                        <text style="`+ (row["DATA_VALID"] == "1" ? 'color:#9932CC !important;FONT-WEIGHT: BOLD;' : ' ') + `">` + row["CONTENT_DECRYPT"].trim().substring(48, 54) + `</text>
                        <text>`+ row["CONTENT_DECRYPT"].trim().substring(54) + `</text>
                        </div>
                         </div>
                         </td>`
            }
        }],
        "fnCreatedRow": function (nRow, aData, iDataIndex) {
            $(nRow).addClass('bg-white').addClass('shadow');

            $('thead').hide();
            $(nRow).click(
                function () {
                    ShowLog(nRow, aData);
                }
            )
        },
        "searching": false,
        "autoWidth": false,
        "bDeferRender ": true,
        'iDisplayLength': pagelength,
        "bLengthChange": false,
        "initComplete": function (oSettings, json) {
            Cookies.set('udplog_data', data, { expires: 7, path: window.location.pathname });
            for (let i = 0; i < sel_id.length; i++) {
                $($("#" + sel_id[i]).closest('tr')).click();
            }
            if (success != null) {
                success();
            }
        },
        'aLengthMenu': [50, 15, 25, 35,], //设置每页显示记录的下拉菜单
        "language":
        {
            "sProcessing": "处理中...",
            "sLengthMenu": "显示 _MENU_ 项结果",
            "sZeroRecords": "没有匹配结果",
            "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
            "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
            "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
            "sInfoPostFix": "",
            "sSearch": "搜索:",
            "sUrl": "",
            "sEmptyTable": "表中数据为空",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页"
            },
            "oAria": {
                "sSortAscending": ": 以升序排列此列",
                "sSortDescending": ": 以降序排列此列"
            }
        }
    });
}

// 搜索按钮
function search_result() {
    table_init();
}

// 显示详细数据
function ShowLog(that, data) {
    let STR =
        `
        <div onclick="javascript:event.stopPropagation();event.preventDefault();"    class="text-info card-body  shadow-sm" style="padding:0.5rem;  background-color: rgb(255, 250, 240);">
        <div class="row">
        <div class="col-md-4 col-6">
        UDP_ID : <span class='text-gray'>`+ data.UDP_ID + `</span></div>
        <div class="col-md-4 col-6">
        MAC : <span class='text-gray'>`+ data.MAC + `</span></div>
        <div class="col-md-4 col-6">
        MSG_ID : <span class='text-gray'>`+ data.MSG_ID + `</span></div>
        <div class="col-md-4 col-6">
        长度 : <span class='text-gray'>`+ data.LENGTH + `</span></div>
        <div class="col-md-4 col-6">
        TCP_ID : <span class='text-gray'>`+ data.TCP_ID + `</span></div>
        <div class="col-md-4 col-6">
        处理结果 : <span class='text-gray'>`+ (data.RESULT == 0 ? "失败" : "成功") + `</span></div>
        <div class="col-md-4 col-6">
        重发次数 : <span class='text-gray'>`+ data.RETRY_COUNT + `</span></div>
        <div class="col-md-4 col-6">
        是否有效 : <span class='text-gray'>`+ (data.DATA_VALID == 0 ? "无效" : "有效") + `</span></div>
        <div class="col-md-4 col-6">
        接收间隔 : <span class='text-gray'>`+ data.RCV_TIMEOUT + `ms</span></div>
        <div class="col-md-4 col-6">
        通讯命令 : <span class='text-gray'>`+ data.UDP_CMD + `</span></div>
        <div class="col-md-4 col-6">
        发送间隔 : <span class='text-gray'>`+ data.SED_TIMEOUT + `ms</span></div>
        <div class="col-md-4 col-6">
        处理耗时 : <span class='text-gray'>`+ data.PROCESSING_TIMESPENT + `ms</span></div>
        <div class="col-md-4 col-6">
        端口通讯时差 : <span class='text-gray'>`+ data.Prot_TimeOut + `ms</span></div>
        <div class="col-md-12 col-12 ">
        备注 : <span class='text-gray'>`+ data.REMARK + `</span></div>
        `;
    // 自动刷新后 如果 已经展开显示  那么就  不会收起来
    if (($(that).find(".card-body").length != 0)) {// 判断是否之前有展开过 有的话就不会执行添加 
        $($(that).find(".card-body")).toggle();// 显示  或者 隐藏 
        // 如果隐藏 就执行移除记录
        if ($($(that).find(".card-body")).attr("style").indexOf('display: none;') >= 0) {

            sel_id = sel_id.filter((id) => {
                return id != data.UDP_ID;
            })

        } else {

            if (sel_id.indexOf(data.UDP_ID) < 0) {
                sel_id.push(data.UDP_ID);
            }
        }
    } else {
        // 判断是否之前有添加过 有的话就不会记录
        if (sel_id.indexOf(data.UDP_ID) < 0) {
            sel_id.push(data.UDP_ID);
        }
        $(that).find("td").append(STR);
    }
}
