
//生成hostnumber
function generichostnumber()
{
    $.tools.post({}, "/Host/GenericHOSTNUMBER/", function () {
    }, this)
}

//发送B1命令
function getrcuinfocmd()
{
    var rows = $('#dg').datagrid('getSelections');
        if (!rows || rows.length == 0) {
            $.tools.alert(lang.PleaseSelectTheData);
            return;
        }
    $.each(rows, function (i, n) {
        console.log(n);
        let H= n.HostNumber;
        let M=n.MAC;
        var param={"HostNumber":H,"MAC":M};
        $.tools.post(param, "/Host/Send_B1/", function () {
        }, this);
    });
}

function FoundDeviceList()
{
    $.tools.post({}, "/Host/HaiXinFoundDevice", function () {
    }, this);
}
//选择所属分组过滤
function groupTreeOnSelect(row) {
    var params = {
        groupId: $('#groupTree').treegrid('getSelected').ID,
        roomNumber: $('#txtRoomNumber').val(),
        mac: $('#txtMac').val(),
        roomType: $('#txtRoomType').val(),
        isSyncRoomNumber: $('#cbxIsSyncRoomNumber').combobox('getValue')
    };
    $('#dg').datagrid({ url: '/Host/LoadAllByPage/', queryParams: params ,onLoadSuccess:function(data)
    {

    }});
}
//选择所属分组过滤（主机信息使用）
function groupTreeOnSelectForInfo(row) {
    var params = {
        groupId: $('#groupTree').treegrid('getSelected').ID,
        roomNumber: $('#txtRoomNumber').val(),
        mac: $('#txtMac').val(),
        roomType: $('#txtRoomType').val(),
        isSyncRoomNumber: $('#cbxIsSyncRoomNumber').combobox('getValue')
    };
    $('#dg').datagrid({ url: '/Host/LoadAllByPageForInfo/', queryParams: params });
}
//新增主机
function add() {
    $('#dialog')
		.find('.dlg-content').panel({ href: '/Host/Edit/', queryParams: {} }).end()
		.find('.dlg-footer .dlg-btn-save').unbind('click').bind('click', save).end()
		.dialog({ title: lang.AddHost, width: 650, height: 360 })
		.dialog('open');
}
//编辑主机
function edit() {
    var row = $('#dg').datagrid('getSelected');
    if (row) {
        $('#dialog')
			.find('.dlg-content').panel({ href: '/Host/Edit/', queryParams: { ID: row.ID} }).end()
			.find('.dlg-footer .dlg-btn-save').unbind('click').bind('click', save).end()
			.dialog({ title: lang.EditHost + " (ID:" + row.ID + ")", width: 650, height: 360 })
			.dialog('open');
    } else {
        $.tools.alert(lang.PleaseSelectTheData);
    }
}
//所属酒店选择事件
function cbxHotelsOnSelect(row) {
    if (row.ID > 0) {
        $('#cbxGroup1').combotree('setValue', "");
        $("#cbxGroup1").combotree("reload", "/Group/LoadGroupTree2?hotelID=" + row.ID);
        $('#cbxRoomType1').combobox('setValue', "");
        $("#cbxRoomType1").combobox("reload", "/RoomType/LoadRoomType?hotelID=" + row.ID);
    }
}
//IP类型选择事件
function cbxIPTypeSelect(row) {
    if (row.value == "1") {
        $('#txtLanIP').attr("disabled", "disabled");
        $('#txtLanPort').attr("disabled", "disabled");
        $('#txtSubnetMask').attr("disabled", "disabled");
        $('#txtGateway').attr("disabled", "disabled");
        $('#txtDNS').attr("disabled", "disabled");
    } else {
        $('#txtLanIP').removeAttr("disabled");
        $('#txtLanPort').removeAttr("disabled");
        $('#txtSubnetMask').removeAttr("disabled");
        $('#txtGateway').removeAttr("disabled");
        $('#txtDNS').removeAttr("disabled");
    }
}
//导入主机
function importHosts() {
    $('#formImportHosts').form('submit', {
        url: '/Host/ImortHosts/',
        onSubmit: function () {
            var file = formImportHosts.file.value;
            var mime = file.toLowerCase().substr(file.lastIndexOf('.'));
            if (mime !== '.xls' && mime !== '.xlsx') {
                $.tools.alert("导入错误，导入文件必须是excel格式！");
                return false;
            }
            return true;
        },
        success: function (r) {
            r = $.parseJSON(r);
            if (r.IsSuccess) {
                $('#importHosts').window('close');
            }
            $.tools.alert(r.Message);
        }
    });
}
//保存主机
function save() {
    var form = $('#dialog').find('form');
    if (form.form('enableValidation').form('validate')) {
        var entity = form.serializeJson();
        entity.SysHotel = { ID: entity.HotelID };
        entity.Group = { ID: entity.GroupID };
        entity.RoomType = { ID: entity.RoomTypeID };
        $.tools.post({ jsonData: JSON.stringify(entity) }, '/Host/Save/', function () {
            //$('#dg').datagrid('reload');
            $('#dialog').window('close');
        }, this);
    }
}
//删除主机
function delHost() {
    var rows = $('#dg').datagrid('getSelections');
    if (!rows || rows.length == 0) {
        $.tools.alert(lang.PleaseSelectTheData);
        return;
    }
    var param;
    $.each(rows, function (i, n) {
        if (i == 0) {
            param = 'idList=' + n.ID;
        } else {
            param += '&idList=' + n.ID;
        }
    });
    $.tools.delPost(param, '/Host/Delete/', function () {
        $('#dg').datagrid('clearSelections');
        $('#dg').datagrid('reload');
    }, this);
}
//工具同步
function toolSync() {
    $.tools.post({ key: "fs%sd" }, '/Host/ToolSync/', function (r) {
    }, this);
}
//打开C主机升级界面
function updateHostC() {
    $('#updateHostC').window({ title: lang.HostUpgrade }).window('open');
}
//打开A主机升级界面
function updateHost() {
    $('#updateHost').window({ title: lang.HostUpgrade }).window('open');
}
//上传升级包
function uploadFile() {
    $('#uploadForm').form('submit', {
        url: '/HostUpdate/Upload/',
        onSubmit: function () {
            var fileType = $('#cbxFileType').combobox('getValue');
            var file = uploadForm.file.value;
            var mime = file.toLowerCase().substr(file.lastIndexOf('.'));
            if (fileType == 0 && mime !== '.bin') {
                $.tools.alert(lang.UEFFMBIF);
                return false;
            } else if (fileType == 1) {
                if (mime == '.xml' || mime == '.dat') {
                    return true;
                }
                $.tools.alert(lang.UETCFMBIF);
                return false;
            }
            return true;
        },
        success: function (r) {
            r = $.parseJSON(r);
            if (r.IsSuccess) {
                $('#uploadFile').window('close');
                $('#dgUpdateHost').datagrid('reload');
            }
            $.tools.alert(r.Message);
        }
    });
}
//下载文件
function downloadFile(val) {
    return '<a href="' + "../../" + val + '" download style="text-decoration:none;">' + lang.Download + '</a>';
}
//删除升级包
function delHostUpdate() {
    var rows = $('#dgUpdateHost').datagrid('getSelections');
    if (!rows || rows.length == 0) {
        $.tools.alert(lang.PleaseSelectTheData);
        return;
    }
    var param;
    $.each(rows, function (i, n) {
        if (i == 0) {
            param = 'idList=' + n.ID;
        } else {
            param += '&idList=' + n.ID;
        }
    });
    $.tools.delPost(param, '/HostUpdate/Delete/', function () {
        $('#dgUpdateHost').datagrid('clearSelections');
        $('#dgUpdateHost').datagrid('reload');
    }, this);
}
//房型选中事件
function treeRoomTypeonCheck(node, checked) {
    if (node.id == 0) {
        var roots = $('#treeRoomNumber').tree('getRoots'); //返回tree的所有根节点数组
        var findNode = $('#treeRoomNumber').tree('find', roots[0].id); //查找节点
        if (checked) {
            $('#treeRoomNumber').tree('check', findNode.target);
        }
        else {
            $('#treeRoomNumber').tree('uncheck', findNode.target);
        }
    }
    else {
        if (checked) {
            var nodes = $('#treeRoomNumber').tree('getChecked', 'unchecked');
            for (var i in nodes) {
                if (node.id == nodes[i].attributes.roomTypeID) {
                    $('#treeRoomNumber').tree('check', nodes[i].target);
                }
            }
        }
        else {
            var nodes = $('#treeRoomNumber').tree('getChecked');
            for (var i in nodes) {
                if (node.id == nodes[i].attributes.roomTypeID) {
                    $('#treeRoomNumber').tree('uncheck', nodes[i].target);
                }
            }
        }
    }
}
//刷新升级状态
function refreshUpdateStatus() {
    $.ajax({
        url: "/HostUpdate/UpdateHostStatus/",
        type: "POST",
        dataType: "json",
        cache: false,
        data: { hostUpdateID: hostUpdateID },
        success: function (r) {
            var nodes = $('#treeRoomNumber').tree('getChecked');
            for (var i in nodes) {
                for (var j in r.Data) {
                    if (nodes[i].attributes.isHost && nodes[i].id == r.Data[j].hostID) {
                        var status = '升级就绪';
                        switch (r.Data[j].status) {
                            case 0:
                                status = "升级就绪";
                                break;
                            case 1:
                                status = "升级成功";
                                break;
                            default:
                                status = "升级失败";
                                break;
                        }
                        var stopLen = nodes[i].text.lastIndexOf('升级');
                        if (stopLen > -1) {
                            nodes[i].text = nodes[i].text.substring(0, stopLen) + status;
                        }
                        else {
                            nodes[i].text = nodes[i].text + status;
                        }
                        $("#treeRoomNumber").tree("update", nodes[i]);
                        break;
                    }
                }
            }
        }
    });
}

var timerRefreshStatus = null;
var timerRefreshStatusC = null;
var hostUpdateID = 0;
//升级RCU主机
function update() {
    var row = $('#dgUpdateHost').datagrid('getSelected');
    if (row == null) {
        $.tools.alert(lang.PSUP);
        return;
    }
    hostUpdateID = row.ID;
    var nodes = $('#treeRoomNumber').tree('getChecked');
    if (nodes.length == 0) {
        $.tools.alert(lang.PSTHTU);
        return;
    }
    var hostIDs = [];
    for (var i in nodes) {
        if (nodes[i].attributes.isHost) {
            hostIDs.push(nodes[i].id);
        }
    }
    var param = { hostUpdateID: hostUpdateID, subGroupID: row.HotelID, hostIDs: JSON.stringify(hostIDs), isTFTP: $("input[name='rd']:checked").val() == "1" ? true : false };
    $.tools.confrimPost(lang.CTU, param, '/HostUpdate/UpdateHost/', function () {
        window.clearInterval(timerRefreshStatus);
        timerRefreshStatus = null;
        timerRefreshStatus = setInterval("refreshUpdateStatus()", 2000); //刷新升级状态
    }, this);
}
//C主机升级房型选择事件
function cbxRoomTypeOnSelect(r) {
    stopUpgradeC();
    $('#tbHosts').datagrid('clearChecked');
    $('#tbHosts').datagrid({ url: '/Host/LoadHostByRoomType/', queryParams: { roomTypeID: r.ID} });
    $('#cbxFiles').combobox('clear');
    $("#cbxFiles").combobox("loadData", {});
}
//自动刷新升级状态
function refreshUpdateStatusC() {
    $('#tbHosts').datagrid('reload');
}
//获取升级文件（C主机），并绑定到下拉框
function getUpdatedFile() {
    stopUpgradeC();
    var roomTypeID = $('#cbxRoomType').combobox('getValue');
    if (roomTypeID == "") {
        $.tools.alert(lang.PSRT);
        return;
    }
    $("#cbxRoomType").combobox('readonly', true);
    $('#btnGetFiles').linkbutton('disable');
    $.tools.post({ roomTypeID: roomTypeID }, '/HostUpdate/GetUpdatedFile/', function (r) {
        if (r.IsSuccess) {
            var data = [];
            for (var i in r.Data) {
                data.push({ "text": r.Data[i], "id": r.Data[i] });
            }
            $("#cbxFiles").combobox("loadData", data);
            if (data.length > 0) {
                $('#cbxFiles').combobox('select', data[0].id);
            }
        }
        else {
            $.tools.alert(r.Message);
        }
        $("#cbxRoomType").combobox('readonly', false);
        $('#btnGetFiles').linkbutton('enable');
    }, this);
}
//升级RCU主机（C主机）
function updateC() {
    stopUpgradeC();
    var rows = $('#tbHosts').datagrid('getSelections');
    if (!rows || rows.length == 0) {
        $.tools.alert(lang.PSTHTU);
        return;
    }
    var fileFullName = $('#cbxFiles').combobox('getValue');
    fileFullName = fileFullName.split(':')[1].split(' || ');
    var fileName = fileFullName[2];
    var extNmae = fileName.substring(fileName.length - 3).toLowerCase();
    var param;
    for (var i = 0; i < rows.length; i++) {
        if (!rows[i].Status) {
            $.tools.alert("存在不在线主机，请重新选择或刷新数据！");
            return;
        }
        switch (extNmae) {
            case "bin": //固件
                console.log(fileFullName[0]);
                if (rows[i].Model.indexOf(fileFullName[0]) == -1) {
                    $.tools.alert("MCU机型名称不匹配！");
                    return;
                }
                var fileNames = fileName.split('_');
                if (fileNames.length < 3) {
                    $.tools.alert("升级文件没有Launcher！");
                    return;
                }
                //Launcher_C1F_V04.6
                var devLauncher = rows[i].Launcher.replace(/\0.*$/g, '').trim();
                console.log(11111);
                console.log(devLauncher);
                if (devLauncher == undefined || devLauncher == null || devLauncher == "") {
                    devLauncher = "L2";
                }
                else {
                    //devLauncher = devLauncher.substring(0, 1) + devLauncher.substring(devLauncher.length - 1);
                    var NS=devLauncher.split("_");
                    var VV=NS[2];
                    var V1= VV.substring(1,VV.length);
                    var V2= parseFloat(V1);
                    var integerPart = Math.floor(V2);
                    devLauncher=devLauncher.substring(0,1)+ integerPart;
                }
                //C1F_A_L4_41_250306_NM.bin
                console.log(fileNames[2]);
                console.log(devLauncher);
                if (fileNames[2] != devLauncher) {
                    $.tools.alert("主机(" + rows[i].RoomNumber + ")Launcher不匹配！");
                    return;
                }
                break;
            case "dat": //配置
                if (rows[i].Model == undefined || rows[i].Model == null || rows[i].Model == "") {
                    $.tools.alert("主机(" + rows[i].RoomNumber + ")未设置机型，请先设置机型再升级配置！");
                    return;
                }
                if (rows[i].Model.indexOf(fileFullName[0]) == -1) {
                    $.messager.confirm(lang.Prompt, "该文件配置主机型与当前主机(" + rows[i].RoomNumber + ")机型不匹配，是否继续升级？", function (r) {
                        if (!r) {
                            return;
                        }
                    });
                }
                break;
            default:
                $.tools.alert("升级文件不合法！");
                return;
        }
        if (i == 0) {
            param = 'idList=' + rows[i].ID;
        } else {
            param += '&idList=' + rows[i].ID;
        }
    }
    fileName = fileName.replace(/\+/g, "%2B");
    fileName = fileName.replace(/\&/g, "%26");
    param += '&fileName=' + fileName;
    $.tools.confrimPost(lang.CTU, param, '/HostUpdate/UpdateHostC/', function (r) {
        timerRefreshStatusC = setInterval("refreshUpdateStatusC()", 3000); //刷新升级状态
    }, this);
}


function upgrade_mqtt_data(update_data)
{
    //{"ID":0,"HotelID":98,"HotelCode":"1085","HostID":48713,"RoomNumber":"研发测试","TargetDomain":"blv-tftp-log.blv-oa.com","TargetPort":69,"LastTime":720,"IsTrigger":false,"CreateTime":"2025-01-08 17:28:58"}
    var dg=$("#tbHosts");
    var qarray = $('#tbHosts').datagrid('getSelections');
    // 遍历选中的行并更新数据
    $.each(qarray, function(index, selectedRow){
        // 查找与选中行匹配的新数据
        console.log(selectedRow.ID);
        if(update_data.HostID==selectedRow.ID)
        {
            var rowIndex = dg.datagrid('getRowIndex', selectedRow);
            if(update_data.Upgrade_status&&update_data.Upgrade_status!="")
            {
                selectedRow.UpgradeStatus=update_data.Upgrade_status;
            }
            if(update_data.BaiFenBi&&update_data.BaiFenBi!="")
            {
                selectedRow.ProgressBar=update_data.BaiFenBi;
            }
            if(update_data.Version&&update_data.Version!="")
            {
                selectedRow.Version=update_data.Version;
            }
            if(update_data.ConfiguraVersion&&update_data.ConfiguraVersion!="")
            {
                selectedRow.ConfigVersion=update_data.ConfiguraVersion;
            }
            if(update_data.Upgrade_DateTime&&update_data.Upgrade_DateTime!="")
            {
                selectedRow.UpgradeTime=update_data.Upgrade_DateTime;
            }
            dg.datagrid('updateRow', 
            {
                index: rowIndex,
                row: selectedRow
            });
        }
    });
}

//停止刷新升级状态
function stopUpgradeC() {
    if (timerRefreshStatusC != null) {
        window.clearInterval(timerRefreshStatusC);
        timerRefreshStatusC = null;
    }
}
//下发信息（改为下发房型房号）
function publishInfo() {
    window.clearInterval(timerRefreshStatusC);
    timerRefreshStatusC = null;
    var rows = $('#tbHosts').datagrid('getSelections');
    if (!rows || rows.length == 0) {
        $.tools.alert(lang.PleaseSelectTheData);
        return;
    }
    if (!rows[0].Version.startsWith("C")) {
        $.tools.alert("该功能只支持C系列主机！");
        return;
    }
    var param;
    $.each(rows, function (i, n) {
        if (i == 0) {
            param = 'idList=' + n.ID;
        } else {
            param += '&idList=' + n.ID;
        }
    });
    $.tools.post(param, '/Host/PublishInfo/', function () {
        $('#tbHosts').datagrid('clearSelections');
    }, this);
}
//主机授权到期时间
function hostAuthorization() {
    /*var rows = $('#dg').datagrid('getSelections');
    if (!rows || rows.length == 0) {
    $.tools.alert(lang.PleaseSelectTheData);
    return;
    }
    $("#dialog2")
    .find(".dlg-content").panel({ href: "/Host/HostAuthorization/", queryParams: { hostID: rows[0].ID} }).end()
    .find(".dlg-footer .dlg-btn-save").unbind("click").bind("click", saveHostAuthorization).end()
    .dialog({ title: lang.HostAuthorization + "(ID:" + rows[0].ID + ")", width: 330, height: 150 })
    .dialog("open");*/
    $('#divHostAuthorization').window({ title: lang.HostAuthorization }).window('open');
}
//主机授权房型选择事件
function cbxRoomTypeOnSelect1(r) {
    $('#tbHostAuthorization').datagrid({ url: '/Host/LoadAllHostByRoomType/', queryParams: { roomTypeID: r.ID} });
}
//解除主机授权，当前时间增加100年
function secureClick() {
    var now = new Date("2100-12-31 00:00:00");
    //now.setFullYear(now.getFullYear() + 100);
    $('#txtExpireTime').datetimebox('setValue', now.format("yyyy-MM-dd hh:mm:ss"));
}
//保存主机到期时间
function saveHostAuthorization() {
    var rows = $('#tbHostAuthorization').datagrid('getSelections');
    if (!rows || rows.length == 0) {
        $.tools.alert(lang.PleaseSelectTheData);
        return;
    }
    var param;
    $.each(rows, function (i, n) {
        if (i == 0) {
            param = 'idList=' + n.ID;
        } else {
            param += '&idList=' + n.ID;
        }
    });
    param += '&expireTime=' + $('#txtExpireTime').datetimebox('getValue');
    $.tools.post(param, '/Host/SaveHostAuthorization/', function () {
        $('#tbHostAuthorization').datagrid('reload');
    }, this);

    /*var form = $("#dialog2").find("form");
    if (form.form("enableValidation").form("validate")) {
    var entry = form.serializeJson();
    var param = { jsonData: JSON.stringify(entry) };
    $.tools.post(param, "/Host/SaveHostAuthorization/", function () {
    $('#dg').datagrid('reload');
    $("#dialog2").window('close');
    }, this);
    }*/
}
//点击升级包记录事件
function dgUpdateHostOnSelect(index, row) {
    //$('#treeRoomNumber').tree({ url: '/HostUpdate/LoadGroupTreeWithRoom/', queryParams: { hostUpdateID: row.ID} });
}
//获取密钥
function getKey() {
    var rows = $('#dg').datagrid('getSelections');
    if (!rows || rows.length == 0) {
        $.tools.alert(lang.PleaseSelectTheData);
        return;
    }
    var param;
    $.each(rows, function (i, n) {
        if (i == 0) {
            param = 'idList=' + n.ID;
        } else {
            param += '&idList=' + n.ID;
        }
    });
    $.tools.post(param, '/Host/GetKey/', function () {
        $('#dg').datagrid('clearSelections');
        $('#dg').datagrid('reload');
    }, this);
}
//下发密钥
function publishKey() {
    var rows = $('#dg').datagrid('getSelections');
    if (!rows || rows.length == 0) {
        $.tools.alert(lang.PleaseSelectTheData);
        return;
    }
    var flag = true;
    var param;
    $.each(rows, function (i, n) {
        if (n.DeviceSecret == undefined || n.DeviceSecret == "") {
            flag = false;
            return;
        }
        if (i == 0) {
            param = 'idList=' + n.ID;
        } else {
            param += '&idList=' + n.ID;
        }
    });
    if (!flag) {
        $.tools.alert(lang.EmptySecretNotPublish);
        return;
    }
    $.tools.post(param, '/Host/PublishKey/', function () {
        $('#dg').datagrid('clearSelections');
        //$('#dg').datagrid('reload');
    }, this);
}
//获取密钥
function getHostKey() {
    var rows = $('#dg').datagrid('getSelections');
    if (!rows || rows.length == 0) {
        $.tools.alert(lang.PleaseSelectTheData);
        return;
    }
    var param;
    $.each(rows, function (i, n) {
        if (i == 0) {
            param = 'idList=' + n.ID;
        } else {
            param += '&idList=' + n.ID;
        }
    });
    $.tools.post(param, '/Host/GetHostKey/', function () {
        $('#dg').datagrid('clearSelections');
        $('#dg').datagrid('reload');
    }, this);
}
//智能语音绑定
function smartVoiceBinding() {
    var rows = $('#dg').datagrid('getSelections');
    if (!rows || rows.length == 0) {
        $.tools.alert(lang.PleaseSelectTheData);
        return;
    }
    $("#dialog")
			.find(".dlg-content").panel({ href: "/Host/SmartVoiceBinding/", queryParams: { hostID: rows[0].ID} }).end()
			.find(".dlg-footer .dlg-btn-save").unbind("click").bind("click", saveSmartVoiceBinding).end()
			.dialog({ title: lang.SmartVoiceBinding + "(ID:" + rows[0].ID + ")", width: 650, height: 390 })
			.dialog("open");
}
//保存智能语音绑定
function saveSmartVoiceBinding() {
    var form = $("#dialog").find("form");
    if (form.form("enableValidation").form("validate")) {
        var entry = form.serializeJson();
        var IsWelcomeDisableTime_id=$("#IsWelcomeDisableTime_id").prop("checked");
        entry.IsWelcomeDisableTime=IsWelcomeDisableTime_id;
        var qqq=  JSON.stringify(entry);
        var param = { jsonData: JSON.stringify(entry) };
        $.tools.post(param, "/Host/SaveSmartVoiceBinding/", function () {
            $('#dg').datagrid('reload');
            $("#dialog").window('close');
        }, this);
    }
}
//同步信息
function syncInfo() {
    var rows = $('#dg').datagrid('getSelections');
    if (!rows || rows.length == 0) {
        $.tools.alert(lang.PleaseSelectTheData);
        return;
    }
    var param = "";
    $.each(rows, function (i, n) {
        if (n.Type == "后台预设信息" && n.Version.startsWith("C")) {
            if (i == 0) {
                param = 'idList=' + n.ID;
            } else {
                param += '&idList=' + n.ID;
            }
        }
    });
    if (param == "") {
        $.tools.alert("请选择“后台预设信息”且属于C主机记录！");
        return;
    }
    $.tools.post(param, '/Host/SyncInfo/', function () {
        $('#dg').datagrid('clearSelections');
        $('#dg').datagrid('reload');
    }, this);
}
//打开酒店第三方对接信息
function dockingInfo() {
    $("#dialog")
			.find(".dlg-content").panel({ href: "/SysHotel/EditDockingInfo/", queryParams: {} }).end()
			.find(".dlg-footer .dlg-btn-save").unbind("click").bind("click", saveDockingInfo).end()
			.dialog({ title: lang.DockingInformation, width: 600, height: 380 })
			.dialog("open");
}
function deletemusic()
{
     $.ajax({
        url: '/SysHotel/DeleteBGM/',
        type: 'Post',
        //contentType: 'application/x-www-form-urlencoded',
        contentType: 'application/json',
        //data: JSON.stringify(getdata),
        data: {},
        success: function(response) {
             $("#welcomebgmid").val("");
        },
        error: function(xhr, status, error) {
            console.log(error);
        },
        beforeSend: function(xhr) {
            console.log('Sending request...');
        },
        complete: function(xhr, status) {
            console.log('Request completed.');
        }
    });
}
function uploadmusic()
{
    var filename = $("#welcomebgm").val();
    if (filename == "") {
        return;
    }
    $.ajaxFileUpload({
        url: "/SysHotel/UploadWebcomeBGM/",
        type: "POST",
        secureuri: false,
        fileElementId: "welcomebgm",
        dataType: "json",
        success: function (response) {
            console.log(response);
            var fname= response.FileName;
            $("#welcomebgmid").val(fname);
        },
        error: function (data, status, e) {
            $("#msg").html(e);
        }
    });
}

//保存酒店第三方对接信息
function saveDockingInfo() {
    var form = $("#dialog").find("form");
    if (form.form("enableValidation").form("validate")) {
        var entry = form.serializeJson();
        var param = { jsonData: JSON.stringify(entry) };
        $.tools.post(param, "/SysHotel/SaveDockingInfo/", function () {
            $("#dialog").window('close');
        }, this);
    }
}
//mac查询
function macSearch() {
    $('#macSearch').window({ title: "MAC查询" }).window('open');
}

function loadMACSearch() {
    var mac = $('#txtMACSearch').val();
    if (mac == "") {
        $.tools.alert("MAC不能为空！");
        return;
    }

    $('#tbMACSearch').datagrid({ url: '/Host/LoadHostsByMAC/', queryParams: { mac: mac} });
}


//阿宝添加的代码
function setTFTP() {
    $('#tftpsetting').window('open');
}

function mqtt_data(update_data)
{
    //{"ID":0,"HotelID":98,"HotelCode":"1085","HostID":48713,"RoomNumber":"研发测试","TargetDomain":"blv-tftp-log.blv-oa.com","TargetPort":69,"LastTime":720,"IsTrigger":false,"CreateTime":"2025-01-08 17:28:58"}
    var dg=$("#dg");
    var qarray = $('#dg').datagrid('getSelections');
    // 遍历选中的行并更新数据
    $.each(qarray, function(index, selectedRow){
        // 查找与选中行匹配的新数据
        console.log(selectedRow.ID);
        if(update_data.HostID==selectedRow.ID)
        {
            var rowIndex = dg.datagrid('getRowIndex', selectedRow);
            selectedRow.IsTrigger=update_data.IsTrigger;
            selectedRow.TargetDomain=update_data.TargetDomain;
            selectedRow.TargetPort=update_data.TargetPort;
            selectedRow.CreateTime=update_data.CreateTime;
            selectedRow.LastTime=update_data.LastTime;
            dg.datagrid('updateRow', {
                index: rowIndex,
                row: selectedRow
            });
        }
    });
}
function read_log_setting() {
    let qarray = $('#dg').datagrid('getSelections');
    let len=qarray.length;
    if(len>0)
    {
        let ResultArray=[];
        $.each(qarray,function(Index,qq)
        {
          let hotelCode= qq.Code;
          let hostno= qq.HostNumber;
          let roomno= qq.RoomNumber;
          let mac= qq.MAC;
          let abc={hotelcode: hotelCode,hostnumber:hostno,mac:mac};
          ResultArray.push(abc);
        });
        console.log(ResultArray);
        let js=JSON.stringify(ResultArray);
        $.tools.post(js, "/Host/Read_TFTPSet_Array/", function (data1) {

        }, this);
    }
    else
    {
           $.tools.alert("请至少选择一条数据"); 
    }
}

function board_log_setting() {

    var hghg=$("#CurrentHotelID").val();
    var qarray = $('#dg').datagrid('getSelections');
    let len=qarray.length;
    if(len<=0)
    {
          $.tools.alert("请至少选择一条数据"); 
          return;
    }

    let ResultArray=[];
    $.each(qarray,function(Index,qq)
    {
        var hostno= qq.HostNumber;
        var mac= qq.MAC;
        let aaa={ hostnumber: hostno,mac: mac};
        ResultArray.push(aaa);
    });
    
    let is_enable=$("#t_ftp_enable").prop("checked");
    let server_domain=$("#txt_domain").val();
    let server_port=$("#txt_server_port").val();
    let report_lasttime=$("#txt_log_report_time").val();

    let param={host_data:ResultArray,  isenable:is_enable, domain:server_domain,port:parseInt(server_port),lasttime:parseInt(report_lasttime)};

    let ddddd=JSON.stringify(param);
    $.tools.post(ddddd, "/Host/TFTPSet_Execute/", function (data) {
             $('#tftpsetting').window('close');
             $.tools.alert(data.Message);
    }, this);
}

function getVersion()
{
    let ddddd="idList=[1,2,3,4,5]";
    $.tools.post(ddddd, "/Host/GetVersion/", function (data) {
             $('#tftpsetting').window('close');
             $.tools.alert(data.Message);
    }, this);
}

$(function () {
    window.group = new Group('#groupTree');
});


/*//主机搜索模块
var hostSearcher = (function () {
var searching = false,
timer = null, //定时器，用于定时刷新搜索结果
timer1 = null, //定时器，定时停止搜索结果(1分钟),
timer1Count = 0,
startSearchUrl = '/SearchHost/StartSearch/',
stopSearchUrl = '/SearchHost/StopSearch/',
getSearchResultUrl = '/SearchHost/GetSearchResult/',
searchingUrl = '/SearchHost/Searching/',
ClearSearchResultUrl = '/SearchHost/ClearSearchResult/',
btnStopOption = { text: lang.StopSearching, iconCls: 'icon-loading' },
btnStartOption = { text: lang.SearchHost, iconCls: 'icon-search' };

function loadFilter(data) {
if (data.IsSuccess) {
return data.Data;
}
return { total: 0, rows: [] };
}
//打开搜索主机窗口
function open() {
$('#cbxGroup').combotree('reload', '/Group/LoadGroupTree2/');
$('#cbxRoomType').combobox('reload', '/RoomType/LoadRoomType/');

$('#dgSearchHost').datagrid({
toolbar: '#editHostToolbar',
url: getSearchResultUrl,
border: false,
pagination: true,
pageSize: 500,
rownumbers: true,
fit: true,
fitColumns: false,
singleSelect: false,
sortName: 'IP',
sortOrder: 'asc',
method: 'POST',
pageList: [50, 100, 200, 500],
loadFilter: loadFilter,
columns: [[
{ field: 'ck', checkbox: true, sortable: true, resizable: false },
{ field: 'HostNumber', title: lang.ID, sortable: true, resizable: false },
{ field: 'IP', title: lang.IPAddress, sortable: true, resizable: false },
{ field: 'SubnetMask', title: lang.SubnetMask, sortable: true, resizable: false },
{ field: 'Gateway', title: lang.Gateway, sortable: true, resizable: false },
{ field: 'Port', title: lang.Port, sortable: true, resizable: false },
{ field: 'MAC', title: "MAC", sortable: true, resizable: false },
{ field: 'Registered', title: lang.WhetherToRegister, sortable: true, resizable: false, formatter: function (value) { return value ? lang.Yes : lang.No; } },
{ field: 'Version', title: lang.VersionNumber, width: 100, sortable: true, resizable: false },
{ field: 'ConfigVersion', title: lang.ConfigurationVersionNumber, width: 100, sortable: true, resizable: false }
]],
onDblClickRow: function (index, row) { registerHost(row); }
});

//初始化“搜索主机”按钮状态
$.tools.post(null, searchingUrl, function (r) {
searching = r.searching;
$('#searchHost').linkbutton(searching ? btnStopOption : btnStartOption);

}, this, true);

$('#editHost').window({ onClose: function () { stopSearch(); } }).window('open');
}
//刷新查询数据
function refreshSearchResult(page, rows, sort, order) {
$.tools.post({ page: page, rows: rows, sort: sort, order: order }, getSearchResultUrl, function (r) {
if (r.IsSuccess) {
$('#dgSearchHost').datagrid('loadData', r);
}
clearTimeout(timer);
timer = null;
timer = setTimeout(function () {
refreshSearchResult(page, rows, sort, order)
}, 5000);
}, this, true);
}
//停止搜索主机
function stopSearch() {
if (searching) {
$.tools.post(null, stopSearchUrl, function (r) {
if (r.IsSuccess) {
searching = false;
clearTimeout(timer);
clearInterval(timer1);
$('#searchHost').linkbutton(btnStartOption);
}
$.tools.alert(r.Message);
}, this, true);
}
}
//开始搜索主机
function startSearch() {
if (!searching) {
$.tools.post({ registered: $('#cbxRegistered').combobox('getValue') }, startSearchUrl, function (r) {
if (r.IsSuccess) {
searching = true;
timer1Count = 120;
$('#searchHost').linkbutton({ text: lang.StopSearching + '(' + timer1Count + 's)', iconCls: 'icon-loading' });

var pager = $('#dgSearchHost').datagrid('getPager');
var page = pager.pagination('options').pageNumber;
var rows = pager.pagination('options').pageSize;
var sort = $('#dgSearchHost').datagrid('options').sortName;
var order = $('#dgSearchHost').datagrid('options').sortOrder;

refreshSearchResult(page, rows, sort, order);

timer1 = setInterval(function () {
timer1Count--;
if (timer1Count <= 0) {
stopSearch();
} else {
$('#searchHost').linkbutton({ text: lang.StopSearching + '(' + timer1Count + 's)', iconCls: 'icon-loading' });
}
}, 1000);

$('#searchHost').linkbutton(btnStopOption);
} else {
$.tools.alert(r.Message);
}
}, this, true);
}
}
//开始搜索
function start() {
if (searching) {
stopSearch();
} else {
startSearch();
}
}

function DelSearch() {
stopSearch();
$.tools.post(null, ClearSearchResultUrl, function (r) {
$('#dgSearchHost').datagrid('reload');
}, this, true);
}

return { open: open, start: start, Del: DelSearch };
})();

function networkSetting() {
var rows = $('#dg').datagrid('getChecked');
if (rows.length > 0) {
$('#dialog')
.find('.dlg-content').panel({ href: '/Host/NetworkSetting/' }).end()
.find('.dlg-footer .dlg-btn-save').unbind('click').bind('click', saveNetworkSetting).end()
.dialog({ title: lang.networkSettings, width: 300, height: 270 })
.dialog('open');
} else {
$.tools.alert(lang.PleaseSelectTheData);
}
}
//打开主机注册窗口
function registerHost(row) {
var form = $('#registerHostForm');
if (form.form('enableValidation').form('validate')) {
var rows = $('#dgSearchHost').datagrid('getChecked');
if (rows.length > 0) {
var params = form.serialize() + '&hosts=' + JSON.stringify(rows);
$.tools.post(params, '/SearchHost/RegisterHosts/', function () {
$('#dg').datagrid('reload');
}, this);

} else {
$.tools.alert(lang.PleaseSelectTheData);
}
}
}

function saveNetworkSetting() {
var form = $('#dialog').find('form');
if (form.form('enableValidation').form('validate')) {
var params = '';
var entry = form.serializeJson();
params = 'IP=' + entry.IP + '&SubnetMask=' + entry.SubnetMask + '&Gateway=' + entry.Gateway + '&Port=' + entry.Port;
var rows = $('#dg').datagrid('getChecked');
for (var i in rows) {
params += '&hostIDs=' + rows[i].ID;
}
$.tools.post(params, '/Host/ChangeNetworkSetting/', function () {
$('#dg').datagrid('reload');
$('#dialog').window('close');
}, this);
}
}
//设置连通房
function connectRoom(cancel) {
var rows = $('#dg').datagrid('getChecked');
if (rows.length == 0) {
$.tools.alert(lang.PleaseSelectTheData);
return;
}
cancel = cancel ? true : false;
var confirmMsg = lang.TCTCOTCR;
if (!cancel) {
confirmMsg = lang.CTSCR;
if (rows.length < 2) {
$.tools.alert(lang.TNOCRSNBLT);
return;
}
}
var param = '';
$.each(rows, function (i, n) {
param += (i == 0) ? 'hostIDs=' + n.ID : '&hostIDs=' + n.ID;
});
param += '&cancel=' + cancel;
$.tools.confrimPost(confirmMsg, param, '/Host/ConnectRoom/');
}

function onRowContextMenu(e, index, row) {
e.preventDefault();
if (!cmenu) {
createRowContextMenu();
}
cmenu.menu('show', { left: e.pageX, top: e.pageY });
}

var cmenu;
function createRowContextMenu() {
cmenu = $('<div/>').appendTo('body');
cmenu.menu();
cmenu.menu('appendItem', { text: lang.SettingsConnectingRoom, iconCls: 'icon-connect-room', onclick: function () { connectRoom(false); } });
cmenu.menu('appendItem', { text: lang.CancelConnectedRoom, iconCls: 'icon-cancel-connect-room', onclick: function () { connectRoom(true) } });
}
//新增主机
function add() {
$('#dialog')
.find('.dlg-content').panel({ href: '/Host/Edit/', queryParams: {} }).end()
.find('.dlg-footer .dlg-btn-save').unbind('click').bind('click', save).end()
.dialog({
title: lang.AddHost,
width: 400,
height: 410
})
.dialog('open');
}
*/



