using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Linq.Dynamic;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using Domain;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Service;
using Common;
using System.Web.Routing;
using RCUHost;
using System.Threading;
using System.Threading.Tasks;
using System.Text;
using System.Web;
using CommonEntity;
using WebSite.Models;
using RCUHost.Protocols;
using RCUHost.Implement;
using RestSharp;
using System.Net;
namespace WebSite.Controllers
{
    public class HostController : BaseController
    {
        private const int AUTHORITY_Host = 30;
        private const int AUTHORITY_Secret = 34;
        /// <summary>
        /// 数据升级权限ID
        /// </summary>
        private const int AUTHORITY_DataUpgrade = 1003;
        private const int AUTHORITY_CHostUpgrade = 1006;//C主机升级权限
        private const int AUTHORITY_HostAuthority = 1007;//主机授权权限
        private const int AUTHORITY_MACAuthority = 1008;//MAC查询授权权限

        private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(HostController));
        private static string tool_sync_url = System.Configuration.ConfigurationManager.AppSettings["tool_sync_url"];

        public IHostManager HostManager { get; set; }
        public IHostAirManager HostAirManager { get; set; }
        public IHostUpdateManager HostUpdateManager { get; set; }
        public IRoomStatusManager RoomStatusManager { get; set; }
        public IRoomTypeAirManager RoomTypeAirManager { get; set; }
        public IGroupManager GroupManager { get; set; }
        public ISysUserManager SysUserManager { get; set; }
        public IPowerSupplyControlManager PowerSupplyControlManager { get; set; }
        public ISysHotelManager SysHotelManager { get; set; }
        public IHostRCUManager HostRCUManager { get; set; }
        public IRoomTypeManager RoomTypeManager { get; set; }

        public ITFTP_SettingMananger TFTPManager { get; set; }
        //public ISmartRobotDisableTimeMananger SmartRobotDisableTimeMananger { get; set; }

        public IHostModalManager HostModalManager { get; set; }
        #region Action

        [Authorize]
        public ActionResult Index()
        {
            ViewData["EnableDataUpgrade"] = SysUserManager.HasAuthority(User.Identity.Name, AUTHORITY_DataUpgrade);
            ViewData["AUTHORITY_CHostUpgrade"] = SysUserManager.HasAuthority(User.Identity.Name, AUTHORITY_CHostUpgrade);
            ViewData["AUTHORITY_HostAuthority"] = SysUserManager.HasAuthority(User.Identity.Name, AUTHORITY_HostAuthority);
            ViewData["AUTHORITY_MACAuthority"] = SysUserManager.HasAuthority(User.Identity.Name, AUTHORITY_MACAuthority);
            return View("SimonIndex");
        }
        [Authorize]
        public ActionResult SecretMgtIndex()
        {
            return View("SecretMgtIndex");
        }
        [Authorize]
        public ActionResult HostInfo()
        {
            return View("HostInfo");
        }

        [Authorize]
        public ActionResult Edit(int? id, string hostNumber, string ip, string mac, string version)
        {
            ViewData["Account"] = User.Identity.Name;
            if (id.HasValue)
            {
                return View(HostManager.Get(id.Value));
            }
            else
            {
                var hotel = SysHotelManager.Get(CurrentHotelID);
                return View(new Host
                {
                    ID = 0,
                    HostNumber = hostNumber,
                    RoomNumber = hostNumber,
                    MAC = mac,
                    SysHotel = hotel,
                    Group = null,
                    RoomType = null,
                    Remark = hotel.Code,
                    IsSyncRoomNumber = false,
                    IsAutoUpdate = false,
                    ServerIP = "106.75.37.225",
                    ServerPort = 3339,
                    IPType = 1,
                    LanIP = "192.168.1.200",
                    LanPort = 3341,
                    SubnetMask = "255.255.255.0",
                    Gateway = "192.168.1.1",
                    DNS = "114.114.114.114",
                    FCS_locationUUID = ""
                });
                //var host = HostManager.GetByMAC(mac, CurrentHotelID);
                //if (host != null)
                //{
                //    return View(host);
                //}
                //else
                //{
                //    var hotel = SysHotelManager.Get(CurrentHotelID);
                //    return View(new Host
                //    {
                //        ID = 0,
                //        HostNumber = hostNumber,
                //        RoomNumber = hostNumber,
                //        MAC = mac,
                //        SysHotel = hotel,
                //        Group = null,
                //        RoomType = null,
                //        Remark = hotel.Code,
                //        IsSyncRoomNumber = false,
                //        IsAutoUpdate = false,
                //        ServerIP = "106.75.37.225",
                //        ServerPort = 3339,
                //        IPType = 1,
                //        LanIP = "192.168.1.200",
                //        LanPort = 3341,
                //        SubnetMask = "255.255.255.0",
                //        Gateway = "192.168.1.1",
                //        DNS = "114.114.114.114",
                //        FCS_locationUUID=""
                //    });
                //}
            }
        }

        [Authorize]
        public ActionResult NetworkSetting()
        {
            return View();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="order"></param>
        /// <param name="sort"></param>
        /// <param name="groupId"></param>
        /// <param name="roomNumber">房号</param>
        /// <param name="mac">mac地址</param>
        /// <param name="roomType">房型名称</param>
        /// <param name="isSyncRoomNumber">房号是否同步：0否，1是，2全部</param>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadAllByPage(int page, int rows, string order, string sort, int? groupId, string roomNumber = "", string mac = "", string roomType = "", int isSyncRoomNumber = 1)
        {
            long total = 0;
            if (groupId.HasValue)
            {
                var list = HostManager.LoadAllByPage(out total, page, rows, order, sort, groupId.GetValueOrDefault(), CurrentHotelID, roomNumber, mac, roomType, isSyncRoomNumber).ToList();

                IList<object> result = new List<object>();
                foreach (var host in list)
                {
                    int hotelid = host.SysHotel.ID;
                    int hostid = host.ID;
                    TFTP_Set ttt = TFTPManager.GetData(hotelid, hostid);
                    if (ttt != null)
                    {

                    }
                    result.Add(new
                    {
                        ID = host.ID,
                        Status = CSRedisCacheHelper.Contains(host.HostNumber, host.MAC),
                        Code = host.SysHotel.Code,
                        HostNumber = host.HostNumber,
                        RoomNumber = host.RoomNumber,
                        MAC = host.MAC,
                        GroupName = host.Group.Name,
                        RoomType = host.RoomType.Name,
                        IsSyncRoomNumber = host.IsSyncRoomNumber,
                        IsAutoUpdate = host.IsAutoUpdate,
                        Version = host.Version,
                        ConfigVersion = host.ConfigVersion,
                        RegisterDate = host.RegisterDate.ToString("yyyy-MM-dd HH:mm:ss"),
                        IP = host.IP,
                        Port = host.Port,
                        LanIP = host.IPType == 1 ? host.LanIP : "",
                        LanPort = host.IPType == 1 ? host.LanPort : 0,
                        SubnetMask = host.IPType == 1 ? host.SubnetMask : "",
                        Gateway = host.IPType == 1 ? host.Gateway : "",
                        DNS = host.IPType == 1 ? host.DNS : "",
                        Remark = host.Remark,
                        XiaoDuCUID = host.XiaoDuCUID,
                        TCLCUID = host.TCLCUID,
                        TCLSkillID = host.TCLSkillID,
                        HiWeiCUID = host.HiWeiCUID,
                        HuaWeiCUID = host.HuaWeiCUID,
                        TianMaoCUID = host.TianMaoCUID,
                        RokidWebhookUrl = host.RokidWebhookUrl,
                        DeviceName = host.DeviceName,
                        DeviceSecret = host.DeviceSecret,
                        IsPublish = host.IsPublish,
                        HostSecret = host.HostSecret,
                        ProductKey = host.ProductKey,
                        IotId = host.IotId,
                        IPType = host.IPType == 1 ? HttpContext.InnerLanguage("Auto") : HttpContext.InnerLanguage("Manual"),
                        ExpireTime = host.ExpireTime == null ? "" : Convert.ToDateTime(host.ExpireTime).ToString("yyyy-MM-dd HH:mm:ss"),
                        SetExpireTime = host.SetExpireTime == null ? "" : Convert.ToDateTime(host.SetExpireTime).ToString("yyyy-MM-dd HH:mm:ss"),
                        Season = ChangeSeason(host.Season),
                        ServerIP = host.ServerIP,
                        ServerPort = host.ServerPort,
                        Model = host.Model,
                        Launcher = host.LauncherVersion,

                        IsTrigger = ttt != null ? ttt.IsTrigger : false,
                        TargetDomain = ttt != null ? ttt.TargetDomain : "",
                        TargetPort = ttt != null ? ttt.TargetPort : 0,
                        LastTime = ttt != null ? ttt.LastTime : 0,
                        CreateTime = ttt != null ? ttt.CreateTime : "",
                    });
                }
                return Json(new { total = total, rows = result });
            }
            else
            {
                return Json(new { total = 0, rows = new List<object>() });
            }
        }

        [Authorize]
        public ActionResult LoadAllByPageForInfo(int page, int rows, string order, string sort, int? groupId, string roomNumber = "", string mac = "", string roomType = "", int isSyncRoomNumber = 1)
        {
            long total = 0;
            if (groupId.HasValue)
            {
                var list = HostManager.LoadAllByPage(out total, page, rows, order, sort, groupId.GetValueOrDefault(), CurrentHotelID, roomNumber, mac, roomType, isSyncRoomNumber).ToList();
                var lstHostRCU = HostRCUManager.LoadAll(CurrentHotelID);
                IList<object> result = new List<object>();
                int flag = 0;
                foreach (var host in list)
                {
                    result.Add(new
                    {
                        ID = host.ID,
                        Flag = flag,
                        Type = "后台预设信息",
                        HotelCode = host.SysHotel.Code,
                        RoomType = host.RoomType.Name,
                        RoomNumber = host.RoomNumber,
                        MAC = host.MAC,
                        IPType = (host.IPType == 0 ? HttpContext.InnerLanguage("Unknown") : (host.IPType == 2 ? HttpContext.InnerLanguage("Manual") : HttpContext.InnerLanguage("Auto"))),
                        LanIP = host.IPType == 2 ? host.LanIP : "",
                        Remark = host.Remark,
                        RoomStatus = host.RoomStatus.Name,
                        TypeNumber = "",
                        Version = host.Version,
                        ConfigVersion = host.ConfigVersion,
                        HotelName = host.SysHotel.Name,
                        RoomTypeRemark = "",
                        HostID = host.ID,
                        RoomTypeID = host.RoomType.ID,
                        LanPort = host.IPType == 1 ? 0 : host.LanPort,
                        Gateway = host.IPType == 1 ? "" : host.Gateway,
                        SubnetMask = host.IPType == 1 ? "" : host.SubnetMask,
                        DNS = host.IPType == 1 ? "" : host.DNS,
                        ServerIP = host.ServerIP,
                        RunTime = "",
                        Season = ChangeSeason(host.Season),
                        LockStatus = "",
                        SetExpireTime = host.SetExpireTime == null ? "" : Convert.ToDateTime(host.SetExpireTime).ToString("yyyy-MM-dd HH:mm:ss"),
                        ExpireTime = host.ExpireTime == null ? "" : Convert.ToDateTime(host.ExpireTime).ToString("yyyy-MM-dd HH:mm:ss"),
                        Core = "",
                        Model = host.Model,
                        Launcher = host.LauncherVersion,
                        UpdateTime = ""
                    });
                    if (host.Version.StartsWith("C"))
                    {
                        HostRCU hostRCU = lstHostRCU.Where(r => r.HostID == host.ID).FirstOrDefault();
                        if (hostRCU != null)
                        {
                            result.Add(new
                            {
                                ID = hostRCU.HostID,
                                Flag = flag,
                                Type = "真实主机信息",
                                HotelCode = hostRCU.HotelCode,
                                RoomType = hostRCU.RoomType,
                                RoomNumber = hostRCU.RoomNumber,
                                MAC = hostRCU.MAC,
                                IPType = (hostRCU.IPType == 0 ? HttpContext.InnerLanguage("Unknown") : (hostRCU.IPType == 2 ? HttpContext.InnerLanguage("Manual") : HttpContext.InnerLanguage("Auto"))),
                                LanIP = hostRCU.LanIP,
                                Remark = hostRCU.RoomRemark,
                                RoomStatus = hostRCU.RoomStatus,
                                TypeNumber = hostRCU.TypeNumber,
                                Version = hostRCU.Version,
                                ConfigVersion = hostRCU.ConfigVersion,
                                HotelName = hostRCU.HotelName,
                                RoomTypeRemark = hostRCU.RoomTypeRemark,
                                HostID = hostRCU.HostID,
                                RoomTypeID = hostRCU.RoomTypeID,
                                LanPort = hostRCU.LanPort,
                                Gateway = hostRCU.Gateway,
                                SubnetMask = hostRCU.SubnetMask,
                                DNS = hostRCU.DNS,
                                ServerIP = hostRCU.ServerIP,
                                RunTime = hostRCU.RunTime == null ? "" : Convert.ToDateTime(hostRCU.RunTime).ToString("yyyy-MM-dd HH:mm:ss"),
                                Season = ChangeSeason(hostRCU.Season),
                                LockStatus = hostRCU.LockStatus == 0 ? "正常" : "锁定",
                                SetExpireTime = hostRCU.SetExpireTime == null ? "" : Convert.ToDateTime(hostRCU.SetExpireTime).ToString("yyyy-MM-dd HH:mm:ss"),
                                ExpireTime = hostRCU.ExpireTime == null ? "" : Convert.ToDateTime(hostRCU.ExpireTime).ToString("yyyy-MM-dd HH:mm:ss"),
                                Core = hostRCU.Core,
                                Model = hostRCU.Model,
                                Launcher = hostRCU.LauncherVersion,
                                UpdateTime = hostRCU.UpdateTime == null ? "" : Convert.ToDateTime(hostRCU.UpdateTime).ToString("yyyy-MM-dd HH:mm:ss")
                            });
                        }
                    }
                    switch (flag)
                    {
                        case 0:
                            flag = 1;
                            break;
                        default:
                            flag = 0;
                            break;
                    }
                }
                return Json(new { total = total, rows = result });
            }
            else
            {
                return Json(new { total = 0, rows = new List<object>() });
            }
        }

        private string ChangeSeason(string season)
        {
            System.Text.StringBuilder result = new System.Text.StringBuilder();
            if (season != null)
            {
                for (int i = 0; i < season.Length; i++)
                {
                    switch (Convert.ToInt16(season.Substring(i, 1)))
                    {
                        case 1:
                            result.Append(HttpContext.InnerLanguage("Spring"));
                            break;
                        case 2:
                            result.Append(HttpContext.InnerLanguage("Summer"));
                            break;
                        case 3:
                            result.Append(HttpContext.InnerLanguage("Winter"));
                            break;
                        default:
                            result.Append(HttpContext.InnerLanguage("Autumn"));
                            break;
                    }
                }
            }
            return result.ToString();
        }
        /// <summary>
        /// 根据mac地址获取主机信息
        /// </summary>
        /// <param name="mac"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        public ActionResult LoadHostByMAC(string mac)
        {
            object data = null;

            Host host = HostManager.GetByMAC(mac, CurrentHotelID);
            if (host != null)
            {
                data = new
                {
                    host.ID,
                    host.HostNumber,
                    host.RoomNumber,
                    host.IP,
                    host.MAC,
                    GroupID = host.Group != null ? host.Group.ID.ToString() : "",
                    RoomTypeID = host.RoomType != null ? host.RoomType.ID.ToString() : "",
                    host.Version,
                    host.Remark,
                    HotelID = host.SysHotel != null ? host.SysHotel.ID.ToString() : "",
                };
            }
            return Json(new { IsSuccess = true, Data = data });
        }
        /// <summary>
        /// 根据房型ID获取对应的主机列表（针对C主机）
        /// </summary>
        /// <param name="roomTypeID"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadHostByRoomType(int roomTypeID)
        {
            //var list = HostManager.LoadAll().Where(r => r.SysHotel.ID == CurrentHotelID && !string.IsNullOrEmpty(r.MAC) && r.RoomType.ID == roomTypeID && r.Version.StartsWith("C")).ToList();
            var lists = HostManager.LoadHostByRoomType(CurrentHotelID, roomTypeID);//ID,HostNumber,RoomNumber,MAC,RoomTypeID,Model,LauncherVersion,Version,ConfigVersion,UpgradeStatus,UpgradeTime
            IList<ShengJiData> result = new List<ShengJiData>();
            foreach (var list in lists)
            {
                ShengJiData sss = new ShengJiData();
                sss.ID = ((object[])list)[0];

                object hostnumber = ((object[])list)[1];
                object mac = ((object[])list)[3];
                if (hostnumber != null && mac != null)
                {
                    sss.Status = CSRedisCacheHelper.Contains(hostnumber.ToString(), mac.ToString());
                }
                else
                {
                    sss.Status = "";
                }
                //sss.Status = CSRedisCacheHelper.Contains(((object[])list)[1].ToString(), ((object[])list)[3].ToString());
                sss.RoomNumber = ((object[])list)[2].ToString();
                sss.MAC = ((object[])list)[3];
                sss.Model = ((object[])list)[5];
                sss.Launcher = ((object[])list)[6];
                sss.Version = ((object[])list)[7];
                sss.ConfigVersion = ((object[])list)[8];
                sss.UpgradeStatus = ((object[])list)[10] == null ? "" : ((object[])list)[9];
                sss.UpgradeTime = ((object[])list)[10] == null ? "" : Convert.ToDateTime(((object[])list)[10]).ToString("yyyy-MM-dd HH:mm:ss");
                sss.ProgressBar = "";
                result.Add(sss);
                //result.Add(new ShengJiData
                //{
                //    ID = ((object[])list)[0],
                //    Status = CSRedisCacheHelper.Contains(((object[])list)[1].ToString(), ((object[])list)[3].ToString()),
                //    RoomNumber = ((object[])list)[2].ToString(),
                //    MAC = ((object[])list)[3],
                //    //RoomType = host.RoomType.Name,
                //    Model = ((object[])list)[5],
                //    Launcher = ((object[])list)[6],
                //    Version = ((object[])list)[7],
                //    ConfigVersion = ((object[])list)[8],
                //    UpgradeStatus = ((object[])list)[10] == null ? "" : ((object[])list)[9],
                //    UpgradeTime = ((object[])list)[10] == null ? "" : Convert.ToDateTime(((object[])list)[10]).ToString("yyyy-MM-dd HH:mm:ss"),
                //    ProgressBar = ""
                //});
            }

            //foreach (var item in result)
            //{
            //    var SSS= item.UpgradeStatus;
            //    if (SSS!=null)
            //    {
            //        if (SSS.ToString().Length<=5)
            //        {
            //            item.UpgradeStatus = item.UpgradeStatus.ToString() + ""; 
            //        } 
            //    }
            //}
            var QQQ = result.OrderBy(A => A.RoomNumber).ToList();
            return Json(new { total = result.Count, rows = QQQ });
        }
        /// <summary>
        /// 根据房型获取所有类型主机
        /// </summary>
        /// <param name="roomTypeID"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadAllHostByRoomType(int roomTypeID)
        {
            var lists = HostManager.LoadAllHostByRoomType(CurrentHotelID, roomTypeID);
            IList<object> result = new List<object>();
            foreach (var list in lists)
            {
                result.Add(new
                {
                    ID = ((object[])list)[0],
                    Status = CSRedisCacheHelper.Contains(((object[])list)[1].ToString(), ((object[])list)[3].ToString()),
                    RoomNumber = ((object[])list)[2],
                    MAC = ((object[])list)[3],
                    ExpireTime = ((object[])list)[5] == null ? "" : Convert.ToDateTime(((object[])list)[5]).ToString("yyyy-MM-dd HH:mm:ss"),
                    SetExpireTime = ((object[])list)[6] == null ? "" : Convert.ToDateTime(((object[])list)[6]).ToString("yyyy-MM-dd HH:mm:ss")
                });
            }
            return Json(new { total = result.Count, rows = result });
        }

        [Authorize]
        [HttpPost]
        public ActionResult Save(string jsonData)
        {
            try
            {
                Host entity = Newtonsoft.Json.JsonConvert.DeserializeObject<Host>(jsonData);
                Host existHost = null;
                if (!string.IsNullOrEmpty(entity.MAC))
                {
                    if (!Regex.IsMatch(entity.MAC, Common.ValidatePattern.MAC))
                    {
                        return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("InvalidMACAddress") });
                    }
                    existHost = HostManager.GetByMAC(entity.MAC, CurrentHotelID);//同一酒店下MAC不能重复
                    if (existHost != null && existHost.ID != entity.ID)
                    {
                        return Json(new { IsSuccess = false, Message = "MAC(" + entity.MAC + ")已存在酒店(" + entity.SysHotel.Code + ")客房(" + entity.RoomNumber + ")下，请重新输入。" });
                    }
                }
                if (!string.IsNullOrEmpty(entity.RoomNumber))
                {
                    existHost = HostManager.GetByRoomNumber(entity.RoomNumber, entity.SysHotel.ID);//同一酒店下房号不能重复
                    if (existHost != null && existHost.ID != entity.ID)
                    {
                        return Json(new { IsSuccess = false, Message = "房号(" + entity.RoomNumber + ")已存在，请重新输入。" });
                    }
                }
                /*if (!string.IsNullOrEmpty(entity.XiaoDuCUID))
                {
                    existHost = HostManager.GetByXiaoDuCUID(entity.XiaoDuCUID);
                    if (existHost != null && existHost.ID != entity.ID)
                    {
                        throw new ApplicationException(string.Format("XiaoDu CUID({0})已绑定到酒店({1})客房({2})下，请重新输入。", entity.XiaoDuCUID, existHost.SysHotel.Name, existHost.RoomNumber));
                    }
                }
                if (!string.IsNullOrEmpty(entity.TCLCUID))
                {
                    existHost = HostManager.GetByTCLCUID(entity.TCLCUID);
                    if (existHost != null && existHost.ID != entity.ID)
                    {
                        throw new ApplicationException(string.Format("TCL TV CUID({0})已绑定到酒店({1})客房({2})下，请重新输入。", entity.XiaoDuCUID, existHost.SysHotel.Name, existHost.RoomNumber));
                    }
                }
                if (!string.IsNullOrEmpty(entity.HuaWeiCUID))
                {
                    existHost = HostManager.GetByHuaWeiCUID(entity.HuaWeiCUID);
                    if (existHost != null && existHost.ID != entity.ID)
                    {
                        throw new ApplicationException(string.Format("HuaWei TV CUID({0})已绑定到酒店({1})客房({2})下，请重新输入。", entity.HuaWeiCUID, existHost.SysHotel.Name, existHost.RoomNumber));
                    }
                }*/

                Host host_take = null;
                string Key = CacheKey.HostInfo_Key_HostNumber + "_" + entity.HostNumber;
                object obj = MemoryCacheHelper.Get(Key);
                if (obj != null)
                {
                    host_take = obj as Host;
                    host_take.RoomNumber = entity.RoomNumber;

                    //"SysHotel":{"ID":"1"},"Group":{"ID":"1811"},"RoomType":{"ID":"1"}}
                    if (entity.SysHotel != null && existHost != null)
                    {
                        host_take.SysHotel = existHost.SysHotel;
                    }
                    if (entity.RoomType != null && existHost != null)
                    {
                        host_take.RoomType = existHost.RoomType;
                    }
                    if (entity.Group != null && existHost != null)
                    {
                        host_take.Group = existHost.Group;
                    }
                    host_take.IPType = entity.IPType;
                }

                string action = entity.ID == 0 ? HttpContext.InnerLanguage("New") : HttpContext.InnerLanguage("Edit");
                HostManager.Save(entity);
                SaveSystemLog(AUTHORITY_Host, action, "【" + entity.RoomNumber + "】");
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
            }
            catch (Exception ex)
            {
                SaveSystemLog(AUTHORITY_Host, HttpContext.InnerLanguage("NewOrEdit"), ex.Message, false);
                logger.Error(ex);
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("SaveFailedBecause") + ex.Message });
            }
        }
        /// <summary>
        /// 通过excel导入主机列表
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult ImortHosts(System.Web.HttpPostedFileBase file)
        {
            try
            {
                if (file == null || file.ContentLength <= 0)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("PleaseSelectTheUpgradePackageFile"));
                }
                string ext = System.IO.Path.GetExtension(file.FileName).ToLower();
                if (ext != ".xls" && ext != ".xlsx")
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("PleaseSelectTheUpgradePackageFile"));
                }
                var tup = new Tuple<int, HttpPostedFileBase>(CurrentHotelID, file);
                System.Threading.Tasks.Task.Factory.StartNew((state) =>
                {
                    var ttt = state as Tuple<int, HttpPostedFileBase>;
                    var file_o = ttt.Item2;
                    var CurrentHotelIDAAA = ttt.Item1;
                    using (ExcelHelper excelHelper = new ExcelHelper(file_o.FileName))
                    {
                        DataTable dtNewHosts = excelHelper.ExcelToDataTable(file.InputStream, "", true);
                        foreach (DataRow dr in dtNewHosts.Rows)
                        {
                            if (!string.IsNullOrEmpty(dr["房号"].ToString()))
                            {
                                Host host = HostManager.GetByRoomNumber(dr["房号"].ToString(), CurrentHotelIDAAA);
                                if (host != null)
                                {
                                    logger.Error(string.Format("导入酒店({0})主机的房号({1})已存在", CurrentHotelIDAAA, dr["房号"].ToString()));
                                    continue;
                                }
                                Domain.Group group = GroupManager.LoadAll().Where(r => r.Name == dr["分组"].ToString() && r.HotelID == CurrentHotelIDAAA).FirstOrDefault();
                                if (group == null)
                                {
                                    logger.Error(string.Format("导入酒店({0})主机的分组({1})不存在", CurrentHotelIDAAA, dr["分组"].ToString()));
                                    continue;
                                }
                                RoomType roomType = RoomTypeManager.LoadAll().Where(r => r.Name == dr["房型"].ToString() && r.HotelID == CurrentHotelIDAAA).FirstOrDefault();
                                if (roomType == null)
                                {
                                    logger.Error(string.Format("导入酒店({0})主机的分组({1})不存在", CurrentHotelIDAAA, dr["房型"].ToString()));
                                    continue;
                                }
                                host = new Host();
                                host.ID = 0;
                                host.IPType = 1;
                                host.RoomNumber = dr["房号"].ToString();
                                host.SysHotel = SysHotelManager.Get(CurrentHotelIDAAA);
                                host.Group = group;
                                host.RoomType = roomType;
                                host.IsSyncRoomNumber = dr["房号同步"].ToString() == "是" ? true : false;
                                host.XiaoDuCUID = dr["小度CUID"].ToString();
                                host.TianMaoCUID = dr["天猫精灵CUID"].ToString();
                                host.TCLCUID = dr["TCLCUID"].ToString();
                                host.TCLSkillID = dr["TCLSkillID"].ToString();
                                host.HiWeiCUID = dr["HiWeiCUID"].ToString();
                                host.FCS_locationUUID = dr["FCS_LocationUUID"].ToString();
                                HostManager.Save(host);
                                SaveSystemLog(AUTHORITY_Host, "导入", "【" + host.RoomNumber + "】");
                            }
                        }
                    }
                }, tup, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("ImportSuccess") });
            }
            catch (Exception ex)
            {
                SaveSystemLog(AUTHORITY_Host, HttpContext.InnerLanguage("Import"), ex.Message, false);
                logger.Error(ex);
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("SaveFailedBecause") + ex.Message });
            }
        }
        ///// <summary>
        ///// 导出主机记录到excel
        ///// </summary>
        ///// <returns></returns>
        //[Authorize]
        //public ActionResult ExportExcel()
        //{
        //    //过滤当前酒店
        //    Domain.Group group = GroupManager.LoadAll().Where(r => r.HotelID == CurrentHotelID && r.Parent == null).First();
        //    //var list = HostManager.LoadAll(group).Select(r => new { r.RoomNumber, r.IP, r.MAC, r.Group, r.Remark }).ToList();
        //    var list = HostManager.LoadAll(group).ToList();//.Select(r => new { r.RoomNumber, r.IP, r.MAC, r.Group, r.Remark }).ToList();
        //    NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
        //    NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");

        //    sheet1.SetColumnWidth(0, 10 * 256);
        //    sheet1.SetColumnWidth(1, 20 * 256);
        //    sheet1.SetColumnWidth(2, 20 * 256);
        //    sheet1.SetColumnWidth(3, 20 * 256);

        //    NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
        //    //row1.CreateCell(0).SetCellValue(HttpContext.InnerLanguage("RoomNumber"));
        //    //row1.CreateCell(1).SetCellValue("MAC");
        //    //row1.CreateCell(2).SetCellValue(HttpContext.InnerLanguage("Floor"));
        //    //row1.CreateCell(3).SetCellValue(HttpContext.InnerLanguage("Remark"));
        //    //row1.CreateCell(4).SetCellValue("IP");
        //    row1.CreateCell(0).SetCellValue("房号");
        //    row1.CreateCell(1).SetCellValue("分组");
        //    row1.CreateCell(2).SetCellValue("房型");
        //    row1.CreateCell(3).SetCellValue("房号同步");
        //    row1.CreateCell(4).SetCellValue("小度CUID");
        //    row1.CreateCell(5).SetCellValue("天猫精灵CUID");
        //    row1.CreateCell(6).SetCellValue("TCL CUID");
        //    //row1.CreateCell(7).SetCellValue("MAC");
        //    //row1.CreateCell(8).SetCellValue("IP");
        //    //row1.CreateCell(9).SetCellValue("备注");
        //    for (int i = 0; i < list.Count; i++)
        //    {
        //        NPOI.SS.UserModel.IRow row = sheet1.CreateRow(i + 1);
        //        row.CreateCell(0).SetCellValue(list[i].RoomNumber);
        //        //row.CreateCell(1).SetCellValue(list[i].MAC);
        //        //row.CreateCell(2).SetCellValue(GroupManager.BuildGroupName(list[i].Group));
        //        //row.CreateCell(3).SetCellValue(list[i].Remark);
        //        //row.CreateCell(4).SetCellValue(list[i].IP);
        //        row.CreateCell(1).SetCellValue(list[i].Group.Name);
        //        row.CreateCell(2).SetCellValue(list[i].RoomType.Name);
        //        row.CreateCell(3).SetCellValue(list[i].IsSyncRoomNumber ? "是" : "否");
        //        row.CreateCell(4).SetCellValue(list[i].XiaoDuCUID);
        //        row.CreateCell(5).SetCellValue(list[i].TianMaoCUID);
        //        row.CreateCell(6).SetCellValue(list[i].TCLCUID);
        //        //row.CreateCell(7).SetCellValue(list[i].MAC);
        //        //row.CreateCell(8).SetCellValue(list[i].IP);
        //        //row.CreateCell(9).SetCellValue(list[i].Remark);
        //    }
        //    NPOIMemoryStream nopiMS = new NPOIMemoryStream();
        //    nopiMS.AllowClose = false;
        //    book.Write(nopiMS);
        //    nopiMS.Flush();
        //    nopiMS.Seek(0, SeekOrigin.Begin);
        //    nopiMS.AllowClose = true;

        //    //string fileName = string.Format("blw_host{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmss"));
        //    string fileName = string.Format("blv_hosts_{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmss"));
        //    SaveSystemLog(AUTHORITY_Host, HttpContext.InnerLanguage("ExportHostList"), "");
        //    return File(nopiMS, "application/vnd.ms-excel", fileName);

        //    //using (MemoryStream stream = new MemoryStream())
        //    //{
        //    //    book.Write(stream);
        //    //    stream.Seek(0, SeekOrigin.Begin);
        //    //    string filename = "blw_host.xls"; //Common.Tools.ToUtf8String("主机列表.xls");
        //    //    SaveSystemLog(AUTHORITY_Host, HttpContext.InnerLanguage("ExportHostList"), "");
        //    //    return File(stream, "application/vnd.ms-excel", filename);
        //    //}
        //}
        /// <summary>
        /// 导出主机记录到excel
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult ExportExcel()
        {
            //过滤当前酒店
            Domain.Group group = GroupManager.LoadAll().Where(r => r.HotelID == CurrentHotelID && r.Parent == null).First();
            var list = HostManager.LoadAll(group).ToList();//.Select(r => new { r.RoomNumber, r.IP, r.MAC, r.Group, r.Remark }).ToList();

            //var list = HostManager.LoadAll(group).Select(r => new { r.RoomNumber, r.IP, r.MAC, r.Group, r.Remark }).ToList();

            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");

            sheet1.SetColumnWidth(0, 10 * 256);
            sheet1.SetColumnWidth(1, 20 * 256);
            sheet1.SetColumnWidth(2, 20 * 256);
            sheet1.SetColumnWidth(3, 20 * 256);

            NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
            row1.CreateCell(0).SetCellValue("房号");
            row1.CreateCell(1).SetCellValue("分组");
            row1.CreateCell(2).SetCellValue("房型");
            row1.CreateCell(3).SetCellValue("房号同步");
            row1.CreateCell(4).SetCellValue("小度CUID");
            row1.CreateCell(5).SetCellValue("天猫精灵CUID");
            row1.CreateCell(6).SetCellValue("TCLCUID");
            row1.CreateCell(7).SetCellValue("TCLSkillID");
            row1.CreateCell(8).SetCellValue("HiWeiCUID");
            row1.CreateCell(9).SetCellValue("FCS_LocationUUID");
            //row1.CreateCell(7).SetCellValue("MAC");
            //row1.CreateCell(8).SetCellValue("IP");
            //row1.CreateCell(9).SetCellValue("备注");

            for (int i = 0; i < list.Count; i++)
            {
                NPOI.SS.UserModel.IRow row = sheet1.CreateRow(i + 1);
                row.CreateCell(0).SetCellValue(list[i].RoomNumber);
                row.CreateCell(1).SetCellValue(list[i].Group.Name);
                row.CreateCell(2).SetCellValue(list[i].RoomType.Name);
                row.CreateCell(3).SetCellValue(list[i].IsSyncRoomNumber ? "是" : "否");
                row.CreateCell(4).SetCellValue(list[i].XiaoDuCUID);
                row.CreateCell(5).SetCellValue(list[i].TianMaoCUID);
                row.CreateCell(6).SetCellValue(list[i].TCLCUID);
                row.CreateCell(7).SetCellValue(list[i].TCLSkillID);
                row.CreateCell(8).SetCellValue(list[i].HiWeiCUID);
                row.CreateCell(9).SetCellValue(list[i].FCS_locationUUID);
                //row.CreateCell(7).SetCellValue(list[i].MAC);
                //row.CreateCell(8).SetCellValue(list[i].IP);
                //row.CreateCell(9).SetCellValue(list[i].Remark);
            }
            NPOIMemoryStream nopiMS = new NPOIMemoryStream();
            nopiMS.AllowClose = false;
            book.Write(nopiMS);
            nopiMS.Flush();
            nopiMS.Seek(0, SeekOrigin.Begin);
            nopiMS.AllowClose = true;

            string fileName = string.Format("blv_hosts_{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmss"));
            SaveSystemLog(AUTHORITY_Host, HttpContext.InnerLanguage("ExportHostList"), "");
            return File(nopiMS, "application/vnd.ms-excel", fileName);

            //using (MemoryStream stream = new MemoryStream())
            //{
            //    book.Write(stream);
            //    stream.Seek(0, SeekOrigin.Begin);
            //    string filename = "blw_host.xls"; //Common.Tools.ToUtf8String("主机列表.xls");
            //    SaveSystemLog(AUTHORITY_Host, HttpContext.InnerLanguage("ExportHostList"), "");
            //    return File(stream, "application/vnd.ms-excel", filename);
            //}
        }
        ///// <summary>
        ///// 导出主机记录到excel
        ///// </summary>
        ///// <returns></returns>
        //[Authorize]
        //public ActionResult ExportExcel()
        //{
        //    //过滤当前酒店
        //    Domain.Group group = GroupManager.LoadAll().Where(r => r.HotelID == CurrentHotelID && r.Parent == null).First();
        //    var list = HostManager.LoadAll(group).Select(r => new { r.RoomNumber, r.IP, r.MAC, r.Group, r.Remark }).ToList();
        //    NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
        //    NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");

        //    sheet1.SetColumnWidth(0, 10 * 256);
        //    sheet1.SetColumnWidth(1, 20 * 256);
        //    sheet1.SetColumnWidth(2, 20 * 256);
        //    sheet1.SetColumnWidth(3, 20 * 256);

        //    NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
        //    row1.CreateCell(0).SetCellValue(HttpContext.InnerLanguage("RoomNumber"));
        //    row1.CreateCell(1).SetCellValue("MAC");
        //    row1.CreateCell(2).SetCellValue(HttpContext.InnerLanguage("Floor"));
        //    row1.CreateCell(3).SetCellValue(HttpContext.InnerLanguage("Remark"));

        //    //row1.CreateCell(1).SetCellValue(list[i].Group.Name);
        //    //row1.CreateCell(2).SetCellValue(list[i].RoomType.Name);
        //    //row1.CreateCell(3).SetCellValue(list[i].IsSyncRoomNumber ? "是" : "否");
        //    row1.CreateCell(4).SetCellValue("IP");

        //    for (int i = 0; i < list.Count; i++)
        //    {
        //        NPOI.SS.UserModel.IRow row = sheet1.CreateRow(i + 1);
        //        row.CreateCell(0).SetCellValue(list[i].RoomNumber);
        //        row.CreateCell(1).SetCellValue(list[i].MAC);
        //        row.CreateCell(2).SetCellValue(GroupManager.BuildGroupName(list[i].Group));
        //        row.CreateCell(3).SetCellValue(list[i].Remark);
        //        row.CreateCell(4).SetCellValue(list[i].IP);
        //    }

        //    NPOIMemoryStream nopiMS = new NPOIMemoryStream();
        //    //using (NPOIMemoryStream nopiMS = new NPOIMemoryStream())
        //    nopiMS.AllowClose = false;
        //    book.Write(nopiMS);
        //    nopiMS.Flush();
        //    nopiMS.Seek(0, SeekOrigin.Begin);
        //    nopiMS.AllowClose = true;
        //    string fileName = string.Format("blw_host{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmss"));
        //    SaveSystemLog(AUTHORITY_Host, HttpContext.InnerLanguage("ExportHostList"), "");
        //    return File(nopiMS, "application/vnd.ms-excel", fileName);

        //    //using (MemoryStream stream = new MemoryStream())
        //    //{
        //    //    book.Write(stream);
        //    //    stream.Seek(0, SeekOrigin.Begin);
        //    //    string filename = "blw_host.xls"; //Common.Tools.ToUtf8String("主机列表.xls");
        //    //    SaveSystemLog(AUTHORITY_Host, HttpContext.InnerLanguage("ExportHostList"), "");
        //    //    return File(stream, "application/vnd.ms-excel", filename);
        //    //}
        //}
        /// <summary>
        /// 修改主机网络
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        public ActionResult ChangeNetworkSetting(int[] hostIDs, string ip, string subnetmask, string gateway, int port)
        {
            string ipPattern = @"^([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])\.([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])\.([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])\.([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])$";
            try
            {
                if (!Regex.IsMatch(ip, ipPattern))
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidIPAddress"));
                }

                if (!Regex.IsMatch(subnetmask, ipPattern))
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidSubnetMask"));
                }

                if (!Regex.IsMatch(gateway, ipPattern))
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidDefaultGateway"));
                }

                if (port < 0 || port > 65535)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidCommunicationPort"));
                }

                var hostList = new List<Host>();
                foreach (int id in hostIDs)
                {
                    Host host = HostManager.Get(id);
                    if (host == null)
                    {
                        throw new ApplicationException(HttpContext.InnerLanguage("InvalidHostNumber") + "【" + id + "】。");
                    }

                    hostList.Add(host);
                }

                HostManager.ChangeNetworkSetting(hostList, ip, subnetmask, gateway, (ushort)port);

                string logDetail = "【" + ip + "，" + subnetmask + "," + gateway + "," + port + "】";

                SaveSystemLog(AUTHORITY_Host, HttpContext.InnerLanguage("EditNetworkSetting"), logDetail);

                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("ModifiedSuccess") });
            }
            catch (Exception ex)
            {
                SaveSystemLog(AUTHORITY_Host, HttpContext.InnerLanguage("EditNetworkSetting"), ex.Message, false);

                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("ModificationFailsTheFailureReasons") + ex.Message });
            }
        }

        /// <summary>
        /// 更改房态
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult ChangeRoomStatus(int id, int roomStatusID)
        {
            Host host = HostManager.Get(id);
            RoomStatus roomStatus = RoomStatusManager.Get(roomStatusID);
            if (host == null || roomStatus == null)
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("InvalidOperation") });
            }
            if (!host.Status)
            {
                string message = String.Format(HttpContext.InnerLanguage("SendFailedHostOffline"), host.RoomNumber);
                return Json(new { IsSuccess = false, Message = message });
            }

            string Key = CacheKey.SyncRoomStatus + "_" + host.HostNumber;
            RoomStatusRequest ddd = new RoomStatusRequest();
            ddd.HostNumber = host.HostNumber;
            ddd.MAC = host.MAC;
            ddd.Status = roomStatus;
            CSRedisCacheHelper.Set_Partition<RoomStatusRequest>(Key, ddd);

            string logDetail = string.Format("客房({0}房态({1})设置为：{2}", host.RoomNumber, host.RoomStatus.Name, roomStatus.Name); //"客房"host.RoomStatus.Name + "设置为：" + roomStatus.Name;
            HostManager.ChangeRoomStatus(host, roomStatus);
            SaveSystemLog(AUTHORITY_Host, HttpContext.InnerLanguage("SetRoomStatus"), logDetail);
            return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("ModifiedSuccess") });
        }
        /// <summary>
        /// 客房电源
        /// </summary>
        /// <param name="id"></param>
        /// <param name="roomStatusID"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult ChangePowerSupply(int hostID, PowerSupplyCtrl ctrl)
        {
            Host host = HostManager.Get(hostID);
            try
            {
                if (host == null)
                {
                    return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("InvalidRoom") });
                }

                if (!host.Status)
                {
                    return Json(new { IsSuccess = false, Message = String.Format(HttpContext.InnerLanguage("SendFailedHostOffline"), host.RoomNumber) });
                }

                PowerSupplyControlManager.SendCtrl(host, ctrl);

                host.PowerSupply = ctrl == PowerSupplyCtrl.Normal ? true : false;

                string k2 = CacheKey.PowerSupply + "_" + host.HostNumber;
                CSRedisCacheHelper.Forever<bool>(k2, host.PowerSupply);

                Host hostAAA = null;
                string Key = CacheKey.RoomStatus_Prefix + "_" + host.HostNumber;
                object obj = MemoryCacheHelper.Get(Key);
                if (obj != null)
                {
                    hostAAA = obj as Host;
                    hostAAA.PowerSupply = host.PowerSupply;
                }
                HostManager.Update(host);

                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("OperationSuccess") });

            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("OperationFailed") });
            }
        }

        [Authorize]
        public ActionResult Delete(IList<int> idList)
        {
            IList<string> roomNumberList = new List<string>();

            if (idList != null)
            {
                foreach (int id in idList)
                {
                    roomNumberList.Add(HostManager.GetRoomNumber(id));
                }
            }

            //需要删除相关设备
            HostManager.Delete(idList.Cast<object>().ToList());

            SaveSystemLog(AUTHORITY_Host, HttpContext.InnerLanguage("Delete"), "【" + String.Join(",", roomNumberList.ToArray()) + "】");

            return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("DeleteSuccess") });
        }

        [Authorize]
        public ActionResult HostAuthorization(int hostID)
        {
            return View(HostManager.Get(hostID));
        }
        /// <summary>
        /// 保存并下发到期时间
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult SaveHostAuthorization(IList<int> idList, string expireTime)
        {
            bool result = true;
            IList<string> roomNumberList = new List<string>();
            try
            {
                foreach (int id in idList)
                {
                    Host host = HostManager.Get(id);
                    roomNumberList.Add(host.RoomNumber);
                    if (Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC))
                    {
                        using (MemoryStream buffer = new MemoryStream())
                        {
                            using (BinaryWriter writer = new BinaryWriter(buffer))
                            {
                                writer.Write(new byte[] { 2 });
                                writer.Write(new byte[] { 32, 0, 0, 0 });//授权到期时间
                                writer.Write(BitConverter.GetBytes(TimeHelper.DateTimeToStamp(Convert.ToDateTime(expireTime))), 0, 4);
                                writer.Write(new byte[] { 40, 0, 0, 0 });//设置到期时间
                                writer.Write(BitConverter.GetBytes(TimeHelper.DateTimeToStamp(DateTime.Now)), 0, 4);

                                HostManager.PublishHostInfo(host, buffer.ToArray());//下发
                                HostManager.SyncHostInfo(host);//同步
                                SaveSystemLog(AUTHORITY_Secret, HttpContext.InnerLanguage("HostAuthorization"), "【" + host.RoomNumber + "】");
                            }
                        }
                    }
                    else
                    {
                        result = false;
                        string msg = String.Format(HttpContext.InnerLanguage("SendFailedHostOffline"), host.RoomNumber);
                        SaveSystemLog(AUTHORITY_Secret, HttpContext.InnerLanguage("HostAuthorization"), msg, false);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("主机授权失败：" + ex.ToString());
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("OperationFailed") });
            }
            if (result)
            {
                SaveSystemLog(AUTHORITY_Secret, HttpContext.InnerLanguage("HostAuthorization"), "【" + String.Join(",", roomNumberList.ToArray()) + "】");
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("OperationSuccess") });
            }
            else
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("OperationFailed") + HttpContext.InnerLanguage("HostOffine") });
            }
        }
        /// <summary>
        /// 智能语音绑定
        /// </summary>
        /// <param name="hostID"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult SmartVoiceBinding(int hostID)
        {
            return View(HostManager.Get(hostID));
        }
        /// <summary>
        /// 保存智能语音绑定信息
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public ActionResult SaveSmartVoiceBinding(string jsonData)
        {
            var entity = Newtonsoft.Json.JsonConvert.DeserializeObject<Host>(jsonData);
            Host existHost = null;
            if (!string.IsNullOrEmpty(entity.XiaoDuCUID))
            {
                string XiaoDuKongZhiKey = CacheKey.XiaoDuYuYin + "_" + entity.XiaoDuCUID;
                HttpContext.Cache.Remove(XiaoDuKongZhiKey);

                existHost = HostManager.GetByXiaoDuCUID(entity.XiaoDuCUID);
                if (existHost != null && existHost.ID != entity.ID)
                {
                    return Json(new { IsSuccess = false, Message = string.Format("小度CUID({0})已绑定到酒店({1})客房({2})下，请重新输入。", entity.XiaoDuCUID, existHost.SysHotel.Name, existHost.RoomNumber) });
                }
            }
            if (!string.IsNullOrEmpty(entity.TianMaoCUID))
            {
                existHost = HostManager.GetByTianMaoCUID(entity.TianMaoCUID);
                if (existHost != null && existHost.ID != entity.ID)
                {
                    return Json(new { IsSuccess = false, Message = string.Format("天猫精灵CUID({0})已绑定到酒店({1})客房({2})下，请重新输入。", entity.TianMaoCUID, existHost.SysHotel.Name, existHost.RoomNumber) });
                }
            }
            if (!string.IsNullOrEmpty(entity.TCLCUID))
            {
                existHost = HostManager.GetByTCLCUID(entity.TCLCUID);
                if (existHost != null && existHost.ID != entity.ID)
                {
                    return Json(new { IsSuccess = false, Message = string.Format("TCL TV CUID({0})已绑定到酒店({1})客房({2})下，请重新输入。", entity.TCLCUID, existHost.SysHotel.Name, existHost.RoomNumber) });
                }
            }
            if (!string.IsNullOrEmpty(entity.HuaWeiCUID))
            {
                existHost = HostManager.GetByHuaWeiCUID(entity.HuaWeiCUID);
                if (existHost != null && existHost.ID != entity.ID)
                {
                    return Json(new { IsSuccess = false, Message = string.Format("华为TV CUID({0})已绑定到酒店({1})客房({2})下，请重新输入。", entity.HuaWeiCUID, existHost.SysHotel.Name, existHost.RoomNumber) });
                }
            }

            if (!string.IsNullOrEmpty(entity.HiWeiCUID))
            {
                existHost = HostManager.GetByHuaWeiCUID(entity.HiWeiCUID);
                if (existHost != null && existHost.ID != entity.ID)
                {
                    return Json(new { IsSuccess = false, Message = string.Format("华为TV CUID({0})已绑定到酒店({1})客房({2})下，请重新输入。", entity.HuaWeiCUID, existHost.SysHotel.Name, existHost.RoomNumber) });
                }
            }

            Host host_take = null;
            string Key = CacheKey.HostInfo_Key_HostNumber + "_" + entity.HostNumber;
            object obj = MemoryCacheHelper.Get(Key);
            if (obj != null)
            {
                host_take = obj as Host;
                if (!string.IsNullOrEmpty(entity.XiaoDuCUID))
                {
                    host_take.XiaoDuCUID = entity.XiaoDuCUID;
                }
                if (!string.IsNullOrEmpty(entity.TianMaoCUID))
                {
                    host_take.TianMaoCUID = entity.TianMaoCUID;
                }
                if (!string.IsNullOrEmpty(entity.TCLCUID))
                {
                    host_take.TCLCUID = entity.TCLCUID;
                }
                if (!string.IsNullOrEmpty(entity.HuaWeiCUID))
                {
                    host_take.HuaWeiCUID = entity.HuaWeiCUID;
                }
                if (!string.IsNullOrEmpty(entity.HiWeiCUID))
                {
                    host_take.HiWeiCUID = entity.HiWeiCUID;
                }
                host_take.TCLSkillID = entity.TCLSkillID;
                host_take.DisableStartTime = entity.DisableStartTime;
                host_take.DisableEndTime = entity.DisableEndTime;
                host_take.IsWelcomeDisableTime = entity.IsWelcomeDisableTime;
                host_take.EBell_RSTP = entity.EBell_RSTP;
                host_take.EBell_TV_duration = entity.EBell_TV_duration;
            }

            //天猫的发现设备
            string ChaXunKey = CacheKey.TianMaoJingLingQuerryAll + "_" + CurrentHotelID + "_" + entity.RoomNumber;
            HttpContext.Cache.Remove(ChaXunKey);

            //小度发现设备
            string MyCacheKey = "小度音箱" + "Discovery_" + CurrentHotelID + "_" + entity.RoomNumber;
            HttpContext.Cache.Remove(MyCacheKey);

            HostManager.SaveSmartVoiceBinding(entity);

            if (existHost == null)
            {
                existHost = HostManager.GetByRoomNumber(entity.HostNumber, CurrentHotelID);
            }
            if (existHost != null)
            {
                //删除掉小度语间的缓存
                string hotelid = existHost.SysHotel.ID.ToString();
                string code = existHost.SysHotel.Code;
                string roomno = existHost.RoomNumber;
                string KKA = CacheKey.XiaoDuCacheUpdate + "_" + code + "_" + roomno;
                string CUIDKey = CSRedisCacheHelper.Get_Partition<string>(KKA);

                //XiaoDuYuYin_950932DC9960012309FD
                if (!string.IsNullOrEmpty(CUIDKey))
                {
                    string XiaoDuKongZhiKey = CacheKey.XiaoDuYuYin + "_" + CUIDKey;
                    HttpContext.Cache.Remove(CUIDKey);
                }

                string TianMaoKongZhiKey = CacheKey.TianMaoJingLing + "_" + hotelid + "_" + roomno;
                HttpContext.Cache.Remove(TianMaoKongZhiKey);
            }


            //string ti = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //SmartRobotDisableTime ss = new SmartRobotDisableTime();
            //ss.HostID = existHost.ID;
            //ss.HotelCode = existHost.SysHotel.Code;
            //ss.RoomNumber = existHost.RoomNumber;
            //ss.DisableSTime = entity1.WStarttime;
            //ss.DisableSTime = entity1.WEndtime;
            //ss.CreateTime = ti;
            //SmartRobotDisableTimeMananger.SaveOrUpdate(ss);

            SaveSystemLog(AUTHORITY_Host, HttpContext.InnerLanguage("Edit") + HttpContext.InnerLanguage("SmartVoiceBinding"), "【" + entity.RoomNumber + "】");
            return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
        }

        /// <summary>
        /// 设置或取消连通房
        /// </summary>
        /// <param name="hostIDs">主机ID列表</param>
        /// <param name="cancel">false/设置连通房，true/取消连通房</param>
        /// <returns></returns>
        [Authorize]
        public ActionResult ConnectRoom(IList<int> hostIDs, bool cancel = false)
        {
            try
            {
                var hosts = new List<Host>();
                foreach (int hostID in hostIDs)
                {
                    var host = HostManager.Get(hostID);
                    if (host != null)
                    {
                        hosts.Add(host);
                    }
                }
                //HostManager.ConnectRoom(hosts, cancel);
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("OperationSuccess") });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("TheOperationFailedTheFailureReasons") + ex.Message });
            }
        }
        /// <summary>
        /// 获取密钥
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult GetKey(IList<int> idList)
        {
            bool result = true;
            IList<string> roomNumberList = new List<string>();
            //根据酒店code和mac地址，调用阿里云物联网获取密钥
            try
            {
                foreach (int id in idList)
                {
                    Host host = HostManager.Get(id);
                    roomNumberList.Add(host.RoomNumber);

                    DeviceRegisterResult resultData = FreeGoOperation.DeviceRegister(host.MAC);

                    if (resultData.errcode == "0")
                    {
                        host.DeviceName = resultData.device_name;
                        host.DeviceSecret = resultData.device_secret;
                        host.IotId = resultData.iot_id;
                        host.ProductKey = resultData.product_key;
                        host.IsPublish = false;
                        HostManager.Update(host);
                    }
                    else
                    {
                        result = false;
                        string msg = string.Format("调用FreeGo接口返回错误：RoomNumber:{0},ErrorCode:{1},ErrorMessage:{2}", host.RoomNumber, resultData.errcode, resultData.msg);
                        SaveSystemLog(AUTHORITY_Secret, HttpContext.InnerLanguage("GetKey"), msg, false);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("调用阿里云接口失败：" + ex.ToString());
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("OperationFailed") });
            }
            if (result)
            {
                SaveSystemLog(AUTHORITY_Secret, HttpContext.InnerLanguage("GetKey"), "【" + String.Join(",", roomNumberList.ToArray()) + "】");
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("OperationSuccess") });
            }
            else
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("OperationFailed") });
            }
        }
        /// <summary>
        /// 下发密钥
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult PublishKey(IList<int> idList)
        {
            bool result = true;
            IList<string> roomNumberList = new List<string>();
            try
            {
                foreach (int id in idList)
                {
                    Host host = HostManager.Get(id);
                    roomNumberList.Add(host.RoomNumber);

                    if (Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC))
                    {
                        HostManager.SetDeviceSecret(host);
                        host.IsPublish = true;
                        HostManager.Update(host);
                    }
                    else
                    {
                        result = false;
                        string msg = String.Format(HttpContext.InnerLanguage("SendFailedHostOffline"), host.RoomNumber);
                        SaveSystemLog(AUTHORITY_Secret, HttpContext.InnerLanguage("PublishKey"), msg, false);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("下发密钥失败失败：" + ex.ToString());
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("OperationFailed") });
            }
            if (result)
            {
                SaveSystemLog(AUTHORITY_Secret, HttpContext.InnerLanguage("PublishKey"), "【" + String.Join(",", roomNumberList.ToArray()) + "】");
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("OperationSuccess") });
            }
            else
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("OperationFailed") + HttpContext.InnerLanguage("HostOffine") });
            }
        }
        /// <summary>
        /// 获取主机密钥
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult GetHostKey(IList<int> idList)
        {
            bool result = true;
            IList<string> roomNumberList = new List<string>();
            try
            {
                foreach (int id in idList)
                {
                    Host host = HostManager.Get(id);
                    roomNumberList.Add(host.RoomNumber);
                    if (Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC))
                    {
                        HostManager.SendForGetHostSecret(host);
                    }
                    else
                    {
                        result = false;
                        string msg = String.Format(HttpContext.InnerLanguage("SendFailedHostOffline"), host.RoomNumber);
                        SaveSystemLog(AUTHORITY_Secret, HttpContext.InnerLanguage("GetHostKey"), msg, false);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("发送获取主机密钥命令失败：" + ex.ToString());
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("OperationFailed") });
            }
            if (result)
            {
                SaveSystemLog(AUTHORITY_Secret, HttpContext.InnerLanguage("GetHostKey"), "【" + String.Join(",", roomNumberList.ToArray()) + "】");
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("OperationSuccess") });
            }
            else
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("OperationFailed") + HttpContext.InnerLanguage("HostOffine") });
            }
        }
        /// <summary>
        /// 同步信息
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult SyncInfo(IList<int> idList)
        {
            bool result = true;
            IList<string> roomNumberList = new List<string>();
            try
            {
                foreach (int id in idList)
                {
                    Host host = HostManager.Get(id);
                    roomNumberList.Add(host.RoomNumber);
                    if (Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC))
                    {
                        HostManager.SyncHostInfo(host);
                    }
                    else
                    {
                        result = false;
                        string msg = String.Format(HttpContext.InnerLanguage("SendFailedHostOffline"), host.RoomNumber);
                        SaveSystemLog(AUTHORITY_Secret, HttpContext.InnerLanguage("SyncInfo"), msg, false);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("发送同步主机信息命令失败：" + ex.ToString());
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("OperationFailed") });
            }
            if (result)
            {
                SaveSystemLog(AUTHORITY_Secret, HttpContext.InnerLanguage("SyncInfo"), "【" + String.Join(",", roomNumberList.ToArray()) + "】");
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("OperationSuccess") });
            }
            else
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("OperationFailed") + HttpContext.InnerLanguage("HostOffine") });
            }
        }
        /// <summary>
        /// 下发信息给主机
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult PublishInfo(IList<int> idList)
        {
            bool result = true;
            IList<string> roomNumberList = new List<string>();
            try
            {
                foreach (int id in idList)
                {
                    Host host = HostManager.Get(id);
                    roomNumberList.Add(host.RoomNumber);
                    if (Common.CSRedisCacheHelper.Contains(host.HostNumber, host.MAC))
                    {
                        HostManager.PublishHostInfo(host);
                        //if (string.IsNullOrEmpty(host.ServerIP) || !Regex.IsMatch(host.ServerIP, Common.ValidatePattern.IPAddress))
                        //{
                        //    return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("OperationFailed") + "服务器IP不合法" });
                        //}
                        //if (host.IPType == 2)
                        //{
                        //    if (string.IsNullOrEmpty(host.LanIP) || !Regex.IsMatch(host.LanIP, Common.ValidatePattern.IPAddress))
                        //    {
                        //        return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("OperationFailed") + "局域网IP不合法" });
                        //    }
                        //    if (string.IsNullOrEmpty(host.SubnetMask) || !Regex.IsMatch(host.SubnetMask, Common.ValidatePattern.IPAddress))
                        //    {
                        //        return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("OperationFailed") + "子网掩码不合法" });
                        //    }
                        //    if (string.IsNullOrEmpty(host.Gateway) || !Regex.IsMatch(host.Gateway, Common.ValidatePattern.IPAddress))
                        //    {
                        //        return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("OperationFailed") + "网关不合法" });
                        //    }
                        //    if (string.IsNullOrEmpty(host.DNS) || !Regex.IsMatch(host.DNS, Common.ValidatePattern.IPAddress))
                        //    {
                        //        return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("OperationFailed") + "DNS不合法" });
                        //    }
                        //}
                    }
                    else
                    {
                        result = false;
                        string msg = String.Format(HttpContext.InnerLanguage("SendFailedHostOffline"), host.RoomNumber);
                        SaveSystemLog(AUTHORITY_Secret, HttpContext.InnerLanguage("PublishInfo"), msg, false);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("下发主机房型房号命令失败：" + ex.ToString());
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("OperationFailed") });
            }
            if (result)
            {
                SaveSystemLog(AUTHORITY_Secret, HttpContext.InnerLanguage("PublishInfo"), "【" + String.Join(",", roomNumberList.ToArray()) + "】");
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("OperationSuccess") });
            }
            else
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("OperationFailed") + HttpContext.InnerLanguage("HostOffine") });
            }
        }
        /// <summary>
        /// 工具同步
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult ToolSync(string key)
        {
            if (string.IsNullOrEmpty(tool_sync_url))
            {
                return Json(new { IsSuccess = false, Message = "未配置工具同步服务器地址！" });
            }
            try
            {
                string result = HttpWebRequestHelper.PostWebRequest(tool_sync_url, "");
                Newtonsoft.Json.Linq.JObject jData = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(result);
                if (jData["Status"] != null && Convert.ToBoolean(jData["Status"]) == true)
                {
                    return Json(new { IsSuccess = true, Message = jData["messages"].ToString() });
                }
                else
                {
                    return Json(new { IsSuccess = false, Message = jData["messages"].ToString() });
                }
            }
            catch (Exception ex)
            {
                logger.Error("发送工具同步命令失败：" + ex.ToString());
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("OperationFailed") + ex.Message });
            }
        }
        /// <summary>
        /// 根据mac获取对应的主机列表
        /// </summary>
        /// <param name="roomTypeID"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadHostsByMAC(string mac)
        {
            IList<object> result = new List<object>();
            if (!string.IsNullOrEmpty(mac))
            {
                IList<Host> hosts;
                if (mac.Length == 17)
                {
                    hosts = HostManager.LoadAll().Where(r => r.MAC == mac).ToList();
                }
                else
                {
                    hosts = HostManager.LoadAll().Where(r => r.MAC.Contains(mac)).ToList();
                }
                foreach (Host host in hosts)
                {
                    result.Add(new
                    {
                        ID = host.ID,
                        HostNumber = host.HostNumber,
                        RoomNumber = host.RoomNumber,
                        MAC = host.MAC,
                        Code = host.SysHotel.Code,
                        Name = ReturnNameByLanguage(host.SysHotel.Name, host.SysHotel.EName, host.SysHotel.TWName)
                    });
                }
            }
            return Json(new { total = result.Count, rows = result });
        }

        #region 加载控件数据

        [Authorize]
        public ActionResult LoadDataForRoomNumberCombobox()
        {
            var result = new List<object>();
            var currentUser = SysUserManager.Get(User.Identity.Name);//获取当前用户
            //var sysUserHotel = SysUserHotelManager.Get(currentUser.ID, CurrentHotelID);//获取当前用户所在酒店
            var currentGroup = GroupManager.Get(currentUser.Group.ID);//获取当前用户所在酒店的楼层
            if (currentUser.HotelID != CurrentHotelID)//如果当前用户所在酒店跟当前所选酒店不一致，则获取该酒店下第一个楼层分组
            {
                currentGroup = GroupManager.LoadAll().FirstOrDefault(r => r.Parent == null && r.HotelID == CurrentHotelID);
            }
            DataTable table = HostManager.LoadRoomNumbers(currentGroup, CurrentHotelID);
            foreach (DataRow row in table.Rows)
            {
                result.Add(new { ID = row["ID"], RoomNumber = row["RoomNumber"], RoomTypeID = row["RoomTypeID"] });
            }
            result.Insert(0, new { ID = 0, RoomNumber = HttpContext.InnerLanguage("CheckAll") });
            return Json(result);
        }

        [Authorize]
        public ActionResult LoadRoomNumbersForCombobox()
        {
            var result = HostManager.LoadRoomNumbers().Select(r => new { RoomNumber = r });
            return Json(result);
        }

        #endregion


        [Authorize]
        public ActionResult Read_TFTPSet_Array()
        {

            int hotelid = CurrentHotelID;
            using (Stream stream = Request.InputStream)
            {
                stream.Position = 0;
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    string body = reader.ReadToEnd();

                    var qqq = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(body);

                    foreach (var item in qqq)
                    {
                        string hotelcode = item["hotelcode"].ToString();
                        string hostnumber = item["hostnumber"].ToString();
                        string mac = item["mac"].ToString();
                        HostManager.Send_Query_Data(new byte[] { }, hostnumber, mac);
                    }
                }
            }

            TFTP_Set TFG = TFTPManager.GetData(hotelid, 111);
            return Json(new { IsSuccess = true, Message = TFG });
        }

        [Authorize]
        public ActionResult TFTPSet_Execute()
        {
            try
            {
                int hotelid = CurrentHotelID;
                using (Stream stream = Request.InputStream)
                {
                    stream.Position = 0;


                    //AA 55 15 01 54 33 53 41 D9 10 00 FF FF FF FF //包头
                    //FF //日志开启状态
                    //FF：全开 00：全关
                    //DC FF //日志上报端口
                    //65500 18 00
                    ////日志上报时间 24 小时
                    //17 //域名字符长度
                    ////域名 BoonliveNAS.synology.me 42 6F 6F 6E 6C 69 76 65 4E 41 53 2E 73 79 6E 6F 6C 6F 67 79 2E 6D 65
                    //XX XX //CRC 根据实际计算结果为准


                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        string body = reader.ReadToEnd();

                        var item = JsonConvert.DeserializeObject<FTP_JSON>(body);

                        var lll = item.host_data;
                        foreach (var singleitem in lll)
                        {
                            List<byte> list = new List<byte>();
                            if (item.isenable)
                            {
                                list.Add(0xff);
                            }
                            else
                            {
                                list.Add(0x00);
                            }
                            byte[] p1 = BitConverter.GetBytes(item.port);
                            list.AddRange(p1);
                            byte[] p2 = BitConverter.GetBytes(item.lasttime);
                            list.AddRange(p2);

                            byte[] bbb = Encoding.ASCII.GetBytes(item.domain);
                            byte len = (byte)bbb.Length;
                            list.Add(len);
                            list.AddRange(bbb);
                            byte[] bba = list.ToArray();
                            var hostnumber = singleitem.hostnumber;
                            var mac = singleitem.mac;
                            HostManager.Send_Setting_Data(bba, hostnumber, mac);
                        }
                    }
                    return Json(new { IsSuccess = true, Message = "成功" });
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                logger.Error(ex.StackTrace);
                return Json(new { IsSuccess = false, Message = "保存失败" });
            }


        }

        [Authorize()]
        public ActionResult GetVersion(List<int> idList)
        {
            foreach (int id in idList)
            {
                Host host = HostManager.Get(id);
                HostManager.SyncHostInfo(host);
            }
            return Json(new { IsSuccess = true, Message = "成功" });
        }
        #endregion

        /// <summary>
        /// 生成主机编号
        /// </summary>
        /// <returns></returns>
        [Authorize()]
        public ActionResult GenericHOSTNUMBER()
        {
            try
            {
                //1001-默认酒店
                string[] Name = CurrentHotelName.Split('-');
                string code = Name[0];
                NewDataSQL.GenericHOSTNUMBER(CurrentHotelID.ToString(), code);
                return Json(new { IsSuccess = true, Message = "成功" });
            }
            catch (Exception)
            {
                return Json(new { IsSuccess = false, Message = "失败" });
            }
        }

        /// <summary>
        /// 发送B1
        /// </summary>
        /// <returns></returns>
        [Authorize()]
        public ActionResult Send_B1(string MAC, string HostNumber)
        {
            try
            {
                var hostList = HostManager.LoadAll(CurrentHotelID);
                //[AA 55 15 00 54 33 53 41 B1 01 00 FF FF FF FF 00 00 00 00 1F 24 ]
                var L1 = hostList.Select(A => new { HostNumber = A.HostNumber, MAC = A.MAC });
                foreach (var item in L1)
                {
                    HostModalManager.SendData(item.HostNumber, item.MAC, new byte[] { });
                }

                return Json(new { IsSuccess = true, Message = "成功" });
            }
            catch (Exception)
            {
                return Json(new { IsSuccess = false, Message = "失败" });
            }
        }

        //{
        //  "baiduReqBody": "{\"header\":{\"namespace\":\"DuerOS.ConnectedHome.Discovery\",\"name\":\"DiscoverAppliancesRequest\",
        //\"messageId\":\"6d6d6e14-8aee-473e-8c24-0d31ff9c17a2\",
        //\"payloadVersion\":\"1\"},\


        //"payload\":{\"accessToken\":\"pass\",\"openUid\":\"pass\",\"cuid\":\"pass\"}}",
        //  "deviceFactory": "携旅提供-客控逻辑标识",
        //  "forceUpdate": "1",
        //  "deleteFlag": "1",
        //  "hotelContract": "携旅提供-酒店逻辑标识",
        //  "macList": [
        //    "00:00:00:00:00:00"
        //  ]
        //}
        [Authorize()]
        public ActionResult HaiXinFoundDevice()
        {
            try
            {
                HaiXinData h = new HaiXinData();

                CommonEntity.header h1 = new CommonEntity.header();
                h1.@namespace = "DuerOS.ConnectedHome.Discovery";
                h1.name = "DiscoverAppliancesRequest";
                h1.messageId = Guid.NewGuid().ToString("N");
                h1.payloadVersion = "1";

                CommonEntity.payload p = new CommonEntity.payload()
                {
                    accessToken = "pass",
                    openUid = "pass",
                    cuid = "pass"
                };
                HaiXinHeader he = new HaiXinHeader() { header = h1, payload = p };
                string str = JsonConvert.SerializeObject(he);
                HaiXinData da = new HaiXinData();
                da.baiduReqBody = str;
                da.deviceFactory = "boonlive";
                da.forceUpdate = "1";
                da.deleteFlag = "1";


                var Q = SysHotelManager.Get(CurrentHotelID);
                da.hotelContract = Q.HeTongNumber;

                List<string> hosts = HostManager.LoadAll().Where(A => A.SysHotel.ID == CurrentHotelID).Select(A => A.XiaoDuCUID).ToList();
                da.macList = hosts;


                var client1 = new RestClient("https://device-manage.ctlife.tv/");
                var request1 = new RestRequest("api/extend/device/app/baiduSeriesFindDevice", Method.POST);
                logger.Error("发送的数据为：" + JsonConvert.SerializeObject(da));

                request1.AddJsonBody(da);

                var QQQ = client1.Execute(request1);
                string ddd = QQQ.Content;
                logger.Error("发现设备返回的是：" + ddd);
                HttpStatusCode HHH = QQQ.StatusCode;
                if (HHH == HttpStatusCode.Created || HHH == HttpStatusCode.OK)
                {
                }
                return Json(new { IsSuccess = true, Message = "设备更新成功" });

            }
            catch (Exception ex)
            {
                logger.Error("发现设备：" + ex.Message);
                return Json(new { IsSuccess = false, Message = "失败" });
            }
        }
    }


    public class host_data
    {
        public string hostnumber { get; set; }
        public string mac { get; set; }
    }
    public class FTP_JSON
    {
        public List<host_data> host_data { get; set; }
        public bool isenable { get; set; }
        public string domain { get; set; }
        public UInt16 port { get; set; }
        public UInt16 lasttime { get; set; }
    }
    public class ShengJiData
    {
        public object ID { get; set; }
        public object Status { get; set; }
        public string RoomNumber { get; set; }
        public object MAC { get; set; }
        public object Model { get; set; }
        public object Launcher { get; set; }
        public object Version { get; set; }
        public object ConfigVersion { get; set; }
        public object UpgradeStatus { get; set; }
        public object UpgradeTime { get; set; }
        public string ProgressBar { get; set; }
    }
}
