var tables = null,
    drawcount = 0;
var user = config.user, pwd = config.password;
var clickID = null;
var disk_status = [{
        state: "idle",
        status: $.i18n.prop("i18n-disk-status1")
    },
    {
        state: "writting",
        status: $.i18n.prop("i18n-disk-status2")
    },
    {
        state: "reading",
        status: $.i18n.prop("i18n-disk-status3")
    },
    {
        state: "diskexception",
        status: $.i18n.prop("i18n-disk-status4")
    },
    {
        state: "diskerror",
        status: $.i18n.prop("i18n-disk-status5")
    },
    {
        state: "readonly",
        status: $.i18n.prop("i18n-disk-status6")
    },
    {
        state: "readwrite",
        status: $.i18n.prop("i18n-disk-status7")
    },
    {
        state: "nodisk",
        status: $.i18n.prop("i18n-disk-status8")
    },
    {
        state: "exceptionneedformat",
        status: $.i18n.prop("i18n-disk-status9")
    },
    {
        state: "exceptionneedChangeDisk",
        status: $.i18n.prop("i18n-disk-status10")
    },
    {
        state: "formatfailedneedreboot",
        status: $.i18n.prop("i18n-disk-status11")
    }
];

var disk_format = [{
        state: "unformatted",
        status: $.i18n.prop("i18n-disk-format-status1")
    },
    {
        state: "formatting",
        status: $.i18n.prop("i18n-disk-format-status2")
    },
    {
        state: "formatted",
        status: $.i18n.prop("i18n-disk-format-status3")
    },
    {
        state: "format failure",
        status: $.i18n.prop("i18n-disk-format-status4")
    },
    {
        state: "umount failure",
        status: $.i18n.prop("i18n-disk-format-status5")
    },
    {
        state: "device is busy",
        status: $.i18n.prop("i18n-disk-format-status6")
    }
];
$(document).ready(function () {
    // if (sessionStorage.getItem("isdeviceType") == "vms") { //针对vms按照项目经理要求隐藏录像和图片两个模块
    //     $(".cardishow").hide();
    //     $(".imgishow").hide();
    // }
    initDiskPage();
    getDiskInfo();
    $("#videoSearch").click(function() {
        $('#recordTable').dataTable().fnDraw();
    });
    $("#format").click(function () { //格式化
        if ("admin" == user || "super_admin" == user) {
            $("#myModal").modal('show');
        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger")
        }

    });
    $("#imgSearch").click(function() {
        $('#snapShotTable').dataTable().fnDraw();
    });
    $('#myTab a').click(function(e) {
        e.preventDefault();
        $(this).tab('show');
        tables = null; //销毁表格实例
        if ($(this).attr("aria-controls") == "diskinfo") {
            clickID = '#diskinfo';
            getDiskInfo();
        } else if ($(this).attr("aria-controls") == "serchrecord") {
            clickID = '#recordTable';
            dataTableDraw("#recordTable");
        } else if ($(this).attr("aria-controls") == "serchimg") {
            clickID = '#serchimg';
            dataTableDraw("#snapShotTable");
        }
    });
});

function initDiskPage() {
    if (!$('.select2').hasClass('select2-offscreen')) {
        $(".select2").select2({
            minimumResultsForSearch: -1,
            width: 360
        });
    }
    config.deviceCap[0].StorageCapacity == 'false' && $('.isShowStorageCapacity').hide();
    // ==================== 第一组：录像时间选择（正常）====================
    $("#disk-start-record").datetimepicker({
        format: "yyyy-mm-dd hh:ii:ss",
        autoclose: true,
        language: 'zh-CN',
    }).on("click", function(e) {
        e.currentTarget.blur();
        // 限制录像开始时间不能晚于录像结束时间
        $("#disk-start-record").datetimepicker("setEndDate", $("#disk-end-record").val());
    });

    $("#disk-end-record").datetimepicker({
        format: "yyyy-mm-dd hh:ii:ss",
        autoclose: true,
        language: 'zh-CN',
    }).on("click", function(e) {
        e.currentTarget.blur();
        // 限制录像结束时间不能早于录像开始时间
        $("#disk-end-record").datetimepicker("setStartDate", $("#disk-start-record").val());
    });

    // 设置录像时间默认值
    var now = $.dateFormat(Date.now());
    var recordStart = now.split(" ")[0] + " 00:00:00";
    $("#disk-start-record").val(recordStart);
    $("#disk-end-record").val($.dateFormat());

    // ==================== 第二组：图片时间选择（修复版）====================
    $("#disk-start-img").datetimepicker({
        format: "yyyy-mm-dd hh:ii:ss",
        autoclose: true,
        language: 'zh-CN',
    }).on("click", function(e) {
        e.currentTarget.blur();
        // 修复：只限制自己这组的结束时间
        $("#disk-start-img").datetimepicker("setEndDate", $("#disk-end-img").val());
    });

    $("#disk-end-img").datetimepicker({
        format: "yyyy-mm-dd hh:ii:ss",
        autoclose: true,
        language: 'zh-CN',
    }).on("click", function(e) {
        e.currentTarget.blur();
        // 修复：只限制自己这组的开始时间
        $("#disk-end-img").datetimepicker("setStartDate", $("#disk-start-img").val());
    });

    // 设置图片时间默认值（可以与录像时间不同）
    $("#disk-start-img").val(recordStart);  // 同样从当天凌晨开始
    $("#disk-end-img").val($.dateFormat());  // 结束时间为当前时间
}

function dataTableDraw(tableId) {
    var aoColumns = [{
            "mDataProp": "id", //mDataProp
            "sWidth": "10%" //设置列宽
        },
        {
            "mDataProp": "FileName",
            "sWidth": "25%" //设置列宽
        },
        {
            "mDataProp": "FileSize",
            "mRender": function(data) {
                if (data < 1024) {
                    return data + 'B'; // 小于1KB显示字节
                } else if (data < 1024 * 1024) {
                    return (data / 1024).toFixed(1) + 'KB'; // 显示KB
                } else {
                    return (data / (1024 * 1024)).toFixed(1) + 'MB'; // 显示MB
                }
            }
        },
        {
            "mRender": function(data, type, full) { // 返回自定义内容
                var PathName = data.PathName;
                var FileName = data.FileName;
                var g_bIsIE = !(/(msie\s|trident.*rv:)([\w.]+)/.exec(navigator.userAgent.toLowerCase()) == null);
                if (g_bIsIE || sessionStorage.getItem("xystyle") == "p2p") {
                    return '<a style="color: #3a77fe;cursor: pointer;" onclick="downSource(\'' + PathName + '\', \'' + FileName + '\')">' + $.i18n.prop('i18n-disk-download') + '</a>';
                } else {
                    return '<a style="color: #3a77fe;cursor: pointer;" download href="' + config.baseUrl + PathName + '/' + FileName + '">' + $.i18n.prop('i18n-disk-download') + '</a>';
                }


            },
            "mDataProp": null,
        }
    ];
    if (tableId == "#recordTable") {
        aoColumns.splice(3, 0, {
            "mDataProp": "StartTime"
        });
        aoColumns.splice(4, 0, {
            "mDataProp": "StopTime"
        });
    } else {
        aoColumns.splice(3, 0, {
            "mDataProp": "SnapshotTime"
        });
    }
    tables = $(tableId).dataTable({
        "language": {
            "lengthMenu": $.i18n.prop('i18n-pageshow') + "_MENU_" + $.i18n.prop('i18n-pagesize'),
            "processing": $.i18n.prop("i18n-page-load"),
            // "info": "第 _START_ 到第 _END_ 条数据，总共有 _TOTAL_ 条记录",
            "sZeroRecords": $.i18n.prop('i18n-sZeroRecords'),
            // "infoFiltered" : "（从 _MAX_ 条数据中过滤得到）",
            "paginate": {
                "first": $.i18n.prop("i18n-sInfo9"),
                "last": $.i18n.prop("i18n-sInfo8"),
                "next": $.i18n.prop("i18n-sNext"),
                "previous": $.i18n.prop("i18n-sPrevious"),
            },
        },
        "retrieve": true, //可能是表格重复使用时受到影响 必须加上
        "processing": true,
        "paging": true,
        "bPaginate": true, //翻页功能
        // "sPaginationType": "bootstrap", //翻页风格
        "bLengthChange": true, //每页显示的记录数
        "bFilter": false, //过滤功能
        "bSort": false, //排序功能
        "bInfo": true, //页脚信息
        "bAutoWidth": false, //自动宽度
        "bServerSide": true, //启用服务器分页
        "bDestroy": false, //解决重新渲染问题
        "iDisplayLength": 10, //每页显示数量
        "aoColumns": aoColumns,
        "dom": '<t><lfip>',
        "infoCallback": function(settings, start, end, max, total, pre) { //自定义总数
            if (total > 0) {
                return $.i18n.prop("i18n-page-tip") + " " + total + " " + $.i18n.prop("i18n-page-tips");
            } else {
                return $.i18n.prop("i18n-page-tip") + " " + 0 + " " + $.i18n.prop("i18n-page-tips");
            }

        },
        // 当表格重绘就会调用这个回调
        fnDrawCallback: function(data) {

        },
        fnServerData: retrieveData
    });
}

function downSource(PathName, FileName) {
    config.isDownLoad = true;
    $.MaskUtil.mask($.i18n.prop("i18n-Downloading"));
    $.ajax({
        type: "GET",
        url: config.baseUrl + PathName + '/' + FileName,
        async: true,  // 异步下载（避免阻塞UI）
        xhrFields: {
            responseType: sessionStorage.getItem("xystyle") == "p2p" ? "text" : "blob"
        },
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");  // 禁用缓存
        },
        success: function (blob, status, xhr) {
            $.MaskUtil.unmask();
            config.isDownLoad = false;
            if (sessionStorage.getItem("xystyle") == "p2p") {//返回是base64字符串
                console.log(typeof blob); // 如果是 "object"，说明是 Blob，不是字符串
                var base64String = blob;
                if (base64String.indexOf(',') !== -1) {
                    base64String = base64String.split(',')[1];
                }
                var byteCharacters = atob(base64String);
                var byteArrays = [];
                for (var i = 0; i < byteCharacters.length; i++) {
                    byteArrays.push(byteCharacters.charCodeAt(i));
                }
                var blob = new Blob([new Uint8Array(byteArrays)], { type: "application/octet-stream" });
                var g_bIsIE = !(/(msie\s|trident.*rv:)([\w.]+)/.exec(navigator.userAgent.toLowerCase()) == null);
                if (g_bIsIE && window.navigator.msSaveOrOpenBlob) {
                    // IE 浏览器：使用 msSaveOrOpenBlob
                    window.navigator.msSaveOrOpenBlob(blob, FileName);
                } else {
                    // 非IE浏览器：使用标准 Blob URL 下载
                    var downloadUrl = URL.createObjectURL(blob);
                    // 创建隐藏的 <a> 标签触发下载
                    var a = document.createElement('a');
                    a.href = downloadUrl;
                    a.download = FileName; // 设置下载文件名
                    a.style.display = 'none';
                    document.body.appendChild(a);
                    a.click();
                    // 清理内存
                    setTimeout(function() {
                        document.body.removeChild(a);
                        URL.revokeObjectURL(downloadUrl);
                    }, 100);
                }
            } else { //网页ie
                window.navigator.msSaveOrOpenBlob(blob, FileName);
            }
        },
        error: function (xhr, status, error) {
            console.error("请求失败：" + error);
            $.MaskUtil.unmask();
            config.isDownLoad = false;
        }
    });

}
function retrieveData(sSource, aoData, fnCallback) {
    // 获取pageSize
    var pageSize = aoData[4].value;
    //获取page
    var start = aoData[3].value;
    var page = Math.ceil(start / pageSize) + 1;
    if (clickID == "#recordTable") {
        setVideoParam(pageSize, page, fnCallback);
    } else if(clickID == "#serchimg") {
        setImageParam(pageSize, page, fnCallback);
    }

}

function setVideoParam(pageSize, page, fnCallback) {
    if ($("#disk-start-record").val() == "" || $("#disk-end-record").val() == "") {
        $.optionBootoast($.i18n.prop("i18n-tip1"), "danger");
        return false;
    }
    var t = $.dateString($("#disk-start-record").val());
    var e = $.dateString($("#disk-end-record").val());
    var sTime = t.y + t.m + t.d + ' ' + t.h + t.ms + t.s;
    var eTime = e.y + e.m + e.d + ' ' + e.h + e.ms + e.s;
    var xml = "<?xml version='1.0' encoding='UTF-8' ?><RecordFileListAttribute Version='1.0'>" +
        "<begin_time>" + sTime + "</begin_time>" +
        "<end_time>" + eTime + "</end_time>" +
        "<timezone_min_between_utc>480</timezone_min_between_utc>" +
        "<RecordFileSumCount>0</RecordFileSumCount>" +
        "<RecordFileCountPerPage>" + pageSize + "</RecordFileCountPerPage>" +
        "</RecordFileListAttribute>";
    $.ajax({ //put下发参数
        type: 'PUT',
        unmask:true,
        url: config.baseUrl + "/RecordFileList/Attribute",
        dataType: 'XML',
        contentType: "application/xml",
        data: xml,
        success: function(res) {
            var pageInfo = getVideoParam(); //得到总条数 与当前页多少条
            getList(fnCallback, pageInfo, page);
        }
    });
}

function setImageParam(pageSize, page, fnCallback) {
    if ($("#disk-start-img").val() == "" || $("#disk-end-img").val() == "") {
        $.optionBootoast($.i18n.prop("i18n-tip1"), "danger");
        return false;
    }
    var t = $.dateString($("#disk-start-img").val());
    var e = $.dateString($("#disk-end-img").val());
    var sTime = t.y + t.m + t.d + ' ' + t.h + t.ms + t.s;
    var eTime = e.y + e.m + e.d + ' ' + e.h + e.ms + e.s;
    var xml = "<?xml version='1.0' encoding='UTF-8' ?><SnapshotFileListAttribute Version='1.0'>" +
        "<begin_time>" + sTime + "</begin_time>" +
        "<end_time>" + eTime + "</end_time>" +
        "<timezone_min_between_utc>480</timezone_min_between_utc>" +
        "<SnapshotFileSumCount>0</SnapshotFileSumCount>" +
        "<SnapshotFileCountPerPage>" + pageSize + "</SnapshotFileCountPerPage>" +
        "</SnapshotFileListAttribute>";
    $.ajax({
        type: "PUT",
        url: config.baseUrl + "/SnapshotFileList/Attribute",
        dataType: 'XML',
        unmask:true,
        data: xml,
        contentType: "application/xml",
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            var pageInfo = getImageParam(); //得到总条数 与当前页多少条
            getListImg(fnCallback, pageInfo, page);
        }
    });

}

function getList(fnCallback, pageInfo, page) {
    var urlTmp = config.baseUrl + "/RecordFileList/Pages/" + page;
    if( sessionStorage.getItem( "xystyle" ) == "p2p" &&
        sessionStorage.getItem( "isdeviceType" ) == "vms" &&
        config.forceEV != "true"
    )
        urlTmp += "?Pathtype=1";
    $.ajax({
        type: "GET",
        url: urlTmp,
        async: false,
        dataType: 'XML',
        // data: xml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(res) {
            //严格按照如下格式
            //只需获取然后原数返回即可，iTotalRecords字面理解意思是当前数据表中总的记录数，
            //iTotalDisplayRecords是当前页面要展示的记录数，aaData为返回列表的数据。
            var length = $(res).find('RecordFileList').find('RecordFile').length;
            var list = [];
            for (var index = 0; index < length; index++) {
                var itme = {};
                itme.id = index + 1;
                itme.FileName = $(res).find('RecordFileList').find('RecordFile').eq(index).find('FileName').text();
                itme.FileSize = $(res).find('RecordFileList').find('RecordFile').eq(index).find('FileSize').text();
                itme.StartTime = formatTime($(res).find('RecordFileList').find('RecordFile').eq(index).find('StartTime').text());
                itme.StopTime = formatTime($(res).find('RecordFileList').find('RecordFile').eq(index).find('StopTime').text());
                itme.PathName = $(res).find('RecordFileList').find('RecordFile').eq(index).find('PathName').text();
                list.push(itme);

            }
            //iTotalRecords和iTotalDisplayRecords数据别搞错了
            //iTotalRecords 当前页显示多少条，iTotalDisplayRecords为总条数
            var result = {
                "iTotalRecords": pageInfo.pageSize,
                "iTotalDisplayRecords": pageInfo.totalCount,
                "aaData": list
            };
            fnCallback(result);
        }
    });
}

function getListImg(fnCallback, pageInfo, page) {
    var urlTmp = config.baseUrl + "/SnapshotFileList/Pages/" + page;
    if( sessionStorage.getItem( "xystyle" ) == "p2p" &&
        sessionStorage.getItem( "isdeviceType") == "vms" &&
        config.forceEV != "true"
    )
        urlTmp += "?Pathtype=1";
    $.ajax({
        type: "GET",
        url: urlTmp,
        async: false,
        dataType: 'XML',
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(res) {
            var length = $(res).find('SnapshotFileList').find('SnapshotFile').length;
            var list = [];
            for (var index = 0; index < length; index++) {
                var itme = {};
                itme.id = index + 1;
                itme.FileName = $(res).find('SnapshotFileList').find('SnapshotFile').eq(index).find('FileName').text();
                itme.FileSize = $(res).find('SnapshotFileList').find('SnapshotFile').eq(index).find('FileSize').text();
                itme.SnapshotTime = formatTime($(res).find('SnapshotFileList').find('SnapshotFile').eq(index).find('SnapshotTime').text());
                itme.PathName = $(res).find('SnapshotFileList').find('SnapshotFile').eq(index).find('PathName').text();
                list.push(itme);

            }
            console.log(list,'listlistlistlistlistlistlist');

            var result = {
                "iTotalRecords": pageInfo.pageSize,
                "iTotalDisplayRecords": pageInfo.totalCount,
                "aaData": list
            };
            fnCallback(result);
        }
    });
}

function setdiskformat() {
    $.ajax({
        type: "PUT",
        url: config.baseUrl + "/Record/Format/Call",
        processData: false,
        data: "",
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xmlDoc) {
            $('#myModal').modal('hide');
            var diskStatus = $(xmlDoc).find('ResponseStatus').eq(0).find('statusCode').eq(0).text();
            if (diskStatus != 0) {
                $.optionBootoast($.i18n.prop('i18n-disk-format-status5'), "danger"); //格式化失败
            } else {
                $.optionBootoast($.i18n.prop('i18n-disk-format-status4'), "success"); //格式化成功
                getDiskInfo();
            }
        },
    });
}

function getDiskInfo(message) {
    var cyURL = config.baseUrl + "/Disk";
    $.ajax({
        url: cyURL,
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, xhr) {
            $("#TotalCapacity").val($(xmlDoc).find('TotalCapacity').text());
            $("#AvailableCapacity").val($(xmlDoc).find('AvailableCapacity').text());
            $("#DiskStorageType").val($(xmlDoc).find('DiskStorageType').text());
            var DiskAttribute = $(xmlDoc).find('DiskFormatStatus').text();
            for (var i = 0; i < disk_format.length; i++) {
                if (DiskAttribute === disk_format[i].state) {
                    $("#DiskStorageAttribute").val(disk_format[i].status);
                }
            }
            $("#PictureCapacityPercent").val($(xmlDoc).find('PictureCapacityPercent').text());
            $("#RecordCapacityPercent").val($(xmlDoc).find('RecordCapacityPercent').text());
            var DiskFormat = $(xmlDoc).find('DiskStorageAttribute').text();
            if (DiskFormat === "nodisk") {
                $("#format").css({
                    "color": "#a0a0a1",
                    "pointer-events": "none"
                });
            } else {
                $("#format").css("color", "#3a77fe");
            }
            for (var j = 0; j < disk_status.length; j++) {
                if (DiskFormat === disk_status[j].state) {
                    $("#DiskFormatStatus").val(disk_status[j].status);
                }
            }
        },
        error: function(xhr) {}
    });
}

function getVideoParam() {
    var pageInfo = {};
    $.ajax({
        type: "GET",
        url: config.baseUrl + "/RecordFileList/Attribute",
        async: false,
        processData: false,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            //总条数与页码
            pageInfo.totalCount = $(xmlDoc).find('RecordFileListAttribute').eq(0).find('RecordFileSumCount').text();
            pageInfo.pageSize = $(xmlDoc).find('RecordFileListAttribute').eq(0).find('RecordFileCountPerPage').text();
        }
    });
    return pageInfo;
}

function getImageParam() {
    var pageInfo = {};
    $.ajax({
        type: "GET",
        url: config.baseUrl + "/SnapshotFileList/Attribute",
        async: false,
        processData: false,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            pageInfo.totalCount = $(xmlDoc).find('SnapshotFileListAttribute').eq(0).find('SnapshotFileSumCount').text();
            pageInfo.pageSize = $(xmlDoc).find('SnapshotFileListAttribute').eq(0).find('SnapshotFileCountPerPage').text();
        }
    });
    return pageInfo;
}

function formatTime(time) { //	20230412 09:39:40
    var ymd = time.split(" ")[0];
    return ymd.substring(0, 4) + "-" + ymd.substring(4, 6) + "-" + ymd.substring(6, 8) + " " + time.split(" ")[1];
}
