var cmenu;
var selectedRowID = null;
var selectedGroup = undefined;
//var refreshTimer = null;
var page = 1, rows = 500;

function createContextMenu() {
    cmenu = $('<div/>').menu().appendTo('body');
    cmenu.menu('appendItem', {
        text: lang.RoomStatusSetting,
        onclick: function () {
            $("#dialog").window({
                title: lang.RoomStatusSetting,
                href: "/RoomStatus/RoomStatus/",
                queryParams: { HostID: selectedRowID },
                resizable: false,
                maximized: false,
                width: 550,
                height: 250
            }).window('center').window("open");
        }
    });
    cmenu.menu('appendItem', {
        text: lang.DeviceInfo,
        onclick: function () {
            $("#dialog").window({
                title: lang.DeviceInfo,
                href: '/RoomStatus/DeviceStatus/',
                queryParams: { HostID: selectedRowID },
                resizable: false,
                maximized: false,
                width: 800,
                height: 400
            })
			.window('center').window("open");
        }
    });
}

function showContextMenu(hostID, event) {
    //window.event.preventDefault();
    if (!cmenu) {
        createContextMenu();
    }
    selectedRowID = hostID;
    cmenu.menu('show', { left: window.event.clientX, top: window.event.clientY });
}

function showRoomDetail(hostID) {
    if (hostID > 0) {
        $("#dialog")
			.window({
			    title: lang.GuestRoomDetailed,
			    href: "/RoomStatus/RoomDetail/",
			    queryParams: { HostID: hostID },
			    resizable: true,
			    maximized: false,
			    draggable: true,
			    width: 800,
			    height: 430
			}).window('center').window('open');
    } else {
        $.tools.alert(lang.PleaseSelectTheData);
    }
}

avalon.libraries.ms.$init = function (vm) {
    for (var i in vm) {
        if (vm.hasOwnProperty(i) && typeof vm[i] === "function") {
            vm[i] = vm[i].bind(vm)
        }
    }
}

function lineWidth(floor) {
    if (vm.switchLine) {
        return 'auto';
    } else {
        return floor.FloorRooms.length * 104;
    }
}
function cbtGroupOnSelect(row) {
    if (row.id != 0) {
        selectedGroup = row.id;
        loadRooms({ group: row.id });
    }
}
function cbxServiceFormatter(row) {
    var styles = 'background:' + row.Color + ';';
    if (row.Code == '') {
        styles += 'color:#000;'
    }
    return '<div style="' + styles + '" class="combobox-service-item">' + row.Name + '</div>';
}
function cbxServiceOnSelect(row) {
    var styles = row.Code == '' ? { background: '#FFF', color: '#000'} : { background: row.Color, color: '#FFF' };
    $(this).combobox('textbox').css(styles);
    vm.queryType = 0;
    vm.queryService = row;
}
function cbxRoomStatusFormatter(row) {
    var styles = 'background:' + row.Color + ';';
    if (row.ID == 0) {
        styles += 'color:#000;'
    }
    return "<div style='" + styles + "' class='combobox-service-item'>" + row.Name + "</div>";
}
function cbxRoomStatusOnSelect(row) {
    var styles = row.ID == 0 ? { background: "#FFF", color: "#000"} : { background: row.Color, color: "#FFF" };
    $(this).combobox("textbox").css(styles);
    vm.queryType = 1;
    vm.queryRoomStatus = row;
}
function cbxAirFormatter(row) {
    var styles = "background:" + row.Color + ";";
    if (row.ID == -1) {
        styles += "color:#000;"
    }
    return "<div style='" + styles + "' class='combobox-service-item'>" + row.Name + "</div>";
}
function cbxAirOnSelect(row) {
    var styles = row.ID == -1 ? { background: "#FFF", color: "#000"} : { background: row.Color, color: "#FFF" };
    $(this).combobox("textbox").css(styles);
    vm.queryType = 2;
    vm.queryValve = row;
}
//空调模式
function airMode(mode) {
    switch (mode) {
        case 1:
            return lang.Refrigeration;
        case 2:
            return lang.Heating;
        case 3:
            return lang.BlowingIn;
        default:
            return '';
    }
}
//空调风速
function fanSpeed(speed) {
    switch (speed) {
        case 1:
            return lang.low;
        case 2:
            return lang.Middle;
        case 3:
            return lang.HighSpeed;
        default:
            return '';
    }
}
function serviceActive(service) {
    return vm.queryService.Code === service.Code && service.Status == 1;
}
function roomBackground(host) {
    var color = '#FFFFFF';
    if (host.HostStatus) {
        switch (vm.queryType) {
            case 0://服务
                for (var i in host.Services) {
                    if (host.Services[i].Code == vm.queryService.Code && host.Services[i].Status == 1) {
                        color = host.Services[i].Color;
                        break;
                    }
                }
                break;
            case 1://房态
                if (vm.queryRoomStatus.ID != 0) {
                    if (vm.queryRoomStatus.ID == host.RoomStatusID) {
                        color = vm.queryRoomStatus.Color;
                    } else if (vm.queryRoomStatus.ID == 32 && host.IsConnectingRoom) {
                        color = vm.queryRoomStatus.Color;
                    }
                }
                break;
        }
    } else {
        color = '#C9CBCA';
    }
    return color;
}

var vm = avalon.define({
    $id: 'rooms',
    queryType: 0,
    queryService: { Code: "", Name: "", Color: "" },
    queryRoomStatus: { ID: 0, Name: "", Color: "" },
    queryValve: { ID: 0, Name: "", Color: "" },
    switchLine: true,
    floors: []
});

function loadRooms(opts, callback) {
    var options = opts || {};
    !options.timeRefresh && $.tools.ajaxLoading(lang.LoadingData);
    $.ajax({
        url: "/RoomStatus/LoadRooms/",
        type: "POST",
        cache: false,
        data: { page: page, rows: rows, groupId: options.group, isAirDetect: $("#chkAirDetect").is(':checked') },
        success: function (r) {
            if (r.IsSuccess) {
                var tdCount = Math.floor(document.documentElement.clientWidth / 124);
                $('#rooms').html("");
                var strHtml = "<tbody>";
                for (var i = 0; i < r.Data.length; i++) {
                    for (var j = 0; j < r.Data[i].FloorRooms.length; j++) {
                        if (j == 0) {
                            strHtml += "<tr>";
                        } else if ($("#chkSwitchLine").is(':checked') && (j + 1) % tdCount == 1) {
                            strHtml += "</tr><tr>";
                        }
                        var strRoomTemp = "<font style='color:green'>"; //室内温度：大于28°显示红色，小于22°显示蓝色，默认显示绿色
                        if (r.Data[i].FloorRooms[j].RoomTemp > 28) {
                            strRoomTemp = "<font style='color:red'>";
                        } else if (r.Data[i].FloorRooms[j].RoomTemp < 22) {
                            strRoomTemp = "<font style='color:blue'>";
                        }
                        strHtml += "<td><ul><li oncontextmenu='showContextMenu(" + r.Data[i].FloorRooms[j].ID + ",null);return false;'";
                        strHtml += " ondblclick='showRoomDetail(" + r.Data[i].FloorRooms[j].ID + ")'";
                        strHtml += " style='background:" + roomBackground(r.Data[i].FloorRooms[j]) + ";'>";

                        strHtml += "<dl><dt>" + r.Data[i].FloorRooms[j].RoomNumber;
                        var CarbonVIP_Status = r.Data[i].FloorRooms[j].CarbonVIP;
                        if (CarbonVIP_Status == "open") {
                            strHtml += "<img src='../../Images/ECO/eco_g.png' width='16' height='16' style='margin-right:5px;'/>"+r.Data[i].FloorRooms[j].RoomNumber+"</dt>";
                        }
                        else if (CarbonVIP_Status == "close") {
                            strHtml += "<img src='../../Images/ECO/eco_p.png' width='16' height='16' style='margin-right:5px;'/>"+r.Data[i].FloorRooms[j].RoomNumber+"</dt>";
                        }
                        else if (CarbonVIP_Status == "exists_nostatus") {
                            strHtml += "<img src='../../Images/ECO/eco_p.png' width='16' height='16' style='margin-right:5px;'/>"+r.Data[i].FloorRooms[j].RoomNumber+"</dt>";
                        }
                        else {
                        }
                        
                        //strHtml += "<dl><dt>";
                        if ($("#chkAirDetect").is(':checked') && r.Data[i].FloorRooms[j].AirDetects.length > 0) {//显示空气质量检测
                            for (var k = 0; k < r.Data[i].FloorRooms[j].AirDetects.length; k++) {
                                strHtml += "<dd>" + r.Data[i].FloorRooms[j].AirDetects[k].Name + ":" + r.Data[i].FloorRooms[j].AirDetects[k].Value + "</dd>";
                            }
                            strHtml += "</dl>";
                        }
                        else {
                            //strHtml += "<dd>" + r.Data[i].FloorRooms[j].Power + "</dd>";
                            strHtml += "<dd>" + r.Data[i].FloorRooms[j].RoomStatus + "&nbsp;"+r.Data[i].FloorRooms[j].Power+"</dd>";
                            strHtml += "<dd>" + lang.Identity + ":" + r.Data[i].FloorRooms[j].Identity + "&nbsp" + r.Data[i].FloorRooms[j].PowerSupplyName + "</dd>";
                            strHtml += "<dd>" + r.Data[i].FloorRooms[j].AirStatusName + "&nbsp;" + strRoomTemp + r.Data[i].FloorRooms[j].RoomTemp + "℃</font>&nbsp;" + r.Data[i].FloorRooms[j].SettingTemp + "℃" + "</dd>";
                            strHtml += "<dd>" + r.Data[i].FloorRooms[j].ValveName + "&nbsp;" + airMode(r.Data[i].FloorRooms[j].Mode) + "&nbsp;" + fanSpeed(r.Data[i].FloorRooms[j].FanSpeed) + "</dd>";
                            if (r.Data[i].FloorRooms[j].Peripheral != "") {
                                strHtml += "<dd>" + r.Data[i].FloorRooms[j].Peripheral + "</dd>";
                            }
                            strHtml += "<dd>" + lang.CurrentService + ":" + r.Data[i].FloorRooms[j].Services.length + "</dd></dl>";
                            strHtml += "<div class='service-list' style='display:" + (r.Data[i].FloorRooms[j].HostStatus ? "block" : "none") + "'>";
                            for (var k = 0; k < r.Data[i].FloorRooms[j].Services.length; k++) {
                                strHtml += "<span style='background:" + r.Data[i].FloorRooms[j].Services[k].Color + ";'>" + r.Data[i].FloorRooms[j].Services[k].Name + "</span>";
                            }
                            strHtml += "</div>";
                        }
                        strHtml += "</li></ul></td>";
                    }
                    strHtml += "</tr>";
                }
                strHtml += "</tbody>";
                $('#rooms').html(strHtml);
                tdCount = null;
                strHtml = null;
            }
            !options.timeRefresh && $.tools.ajaxLoadEnd();
            callback && callback();
        },
        error: function () {
            !options.timeRefresh && $.tools.ajaxLoadEnd();
            callback && callback();
        }
    });
}

var timeoutID1 = null;
function startTimeRefresh() {
    window.clearTimeout(timeoutID1);
    timeoutID1 = null;
    loadRooms({ timeRefresh: true, group: selectedGroup }, function () {
        timeoutID1 = setTimeout("startTimeRefresh()", 8000);
    });
}

function refresh() {
    $('#cbtGroup').combotree('reset');
    $('#cbxService').combobox('select', '');
    $('#cbxRoomStatus').combobox('select', 0);
    loadRooms();
}

$(function () {
    startTimeRefresh();
});
