using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using Common;
using Domain;
using Service;

namespace WebSite.Controllers
{
    public class RoomTypeController : BaseController
    {
        #region Properties

        private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(RoomTypeController));
        private const int AUTHORITY_RoomType = 20;
        public IRoomTypeManager RoomTypeManager { get; set; }
        public IRoomTypeModalManager RoomTypeModalManager { get; set; }
        public IRoomModalManager RoomModalManager { get; set; }
        public IModalTypeManager ModalTypeManager { get; set; }
        public IRoomTypeAirManager RoomTypeAirManager { get; set; }
        public IHostManager HostManager { get; set; }
        public IHostModalManager HostModalManager { get; set; }
        public IHostAirManager HostAirManager { get; set; }
        public IRoomTypeWXMenusManager RoomTypeWXMenusManager { get; set; }
        public IRoomTypeSceneManager RoomTypeSceneManager { get; set; }
        public IHostFaultsManager HostFaultsManager { get; set; }
        public ISysOauth2Manager SysOauth2Manager { get; set; }
        public IRoomTypeProgramFilesManager RoomTypeProgramFilesManager { get; set; }
        public ISysHotelManager SysHotelManager { get; set; }

        #endregion

        #region Action

        [Authorize]
        public ActionResult Index()
        {
            return View("SimonIndex");
        }
        /// <summary>
        /// 获取当前酒店房型
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="order"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadAllByPage(int page, int rows, string order, string sort)
        {
            long total = 0;

            var list = this.RoomTypeManager.LoadAllByPage(out total, page, rows, order, sort, CurrentHotelID);

            var result = list.Select(r => new
            {
                r.ID,
                r.Code,
                r.HostName,
                r.Name,
                r.Default
                //ControlType = r.ControlType == ControlType.Two ? HttpContext.InnerLanguage("TwoControl") : HttpContext.InnerLanguage("FourControl")
            });
            return Json(new { total = total, rows = result });
        }
        /// <summary>
        /// 编辑房型
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult Edit(int? id)
        {
            if (id.HasValue && id != 0)
            {
                return View(RoomTypeManager.Get(id));
            }
            List<RoomType> list = RoomTypeManager.LoadAll().Where(r => r.HotelID == CurrentHotelID).ToList();
            string newCode = (Convert.ToInt32(list[list.Count - 1].Code) + 1).ToString();
            return View(new RoomType { ID = 0, Code = newCode, HostName = "", Name = "", ControlType = ControlType.Two, Default = false });
        }
        /// <summary>
        /// 根据酒店ID获取对应房型
        /// </summary>
        /// <param name="hotelID"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadRoomType(int? hotelID)
        {
            if (!hotelID.HasValue || hotelID == 0)
            {
                hotelID = CurrentHotelID;
            }
            var entities = RoomTypeManager.LoadAll().Where(r => r.HotelID == Convert.ToInt16(hotelID) && !r.IsDeleted);
            IList<object> types = new List<object>();
            foreach (RoomType type in entities)
            {
                types.Add(new { ID = type.ID, Code = type.Code, Name = type.Code + "-" + type.Name });
            }
            return Json(types, JsonRequestBehavior.AllowGet);
        }

        [Authorize]
        public ActionResult ImportConfigFile(int id)
        {
            return View(RoomTypeManager.Get(id));
        }

        #region RoomTypeModal
        //打开回路管理界面
        [Authorize]
        public ActionResult RoomTypeModal(int roomTypeID)
        {
            RoomType roomType = RoomTypeManager.Get(roomTypeID);
            return View(roomType);
        }
        //宝易上传的回路
        [Authorize]
        public ActionResult RoomTypeModalBY(int id)
        {
            return View(id);
        }
        //自定义回路
        [Authorize]
        public ActionResult RoomTypeModalZDY(int id)
        {
            return View(id);
        }
        /// <summary>
        /// 根据回路类型获取默认回路第一条回路地址的前6位
        /// </summary>
        /// <param name="deviceType"></param>
        /// <returns></returns>
        public ActionResult LoadDefaultRoomModal(DeviceType deviceType)
        {
            RoomModal rm = RoomModalManager.LoadAll().Where(r => r.Type == deviceType).FirstOrDefault();//获取有默认回路第一条
            if (rm == null)
            {
                return Json(new { IsSuccess = true, ModalAddress = "" });
            }
            else
            {
                return Json(new { IsSuccess = true, ModalAddress = rm.ModalAddress.Substring(0, 6) });
            }
        }
        /// <summary>
        /// 分页方式加载回路
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="order"></param>
        /// <param name="sort"></param>
        /// <param name="roomTypeID"></param>
        /// <returns></returns>
        public ActionResult LoadRoomTypeModalsWithPage(int? page, int? rows, string order, string sort, int roomTypeID, DeviceType deviceType)
        {
            var roomType = RoomTypeManager.Get(roomTypeID);
            var roomTypeModals = RoomTypeModalManager.LoadAll(roomType, 0).OrderBy(r => r.ModalAddress).ToList();//, deviceType);//获取该房型所有回路
            var roomModals = RoomModalManager.LoadAll().OrderBy(r => r.ModalAddress).ToList();//.Where(r => r.Type == deviceType).ToList();//获取所有默认回路
            foreach (RoomModal rm in roomModals)
            {
                if (roomTypeModals.Where(r => r.ModalAddress == rm.ModalAddress).ToList().Count == 0)//不存在，则新增新的默认回路
                {
                    roomTypeModals.Add(new RoomTypeModal()
                    {
                        ID = 0,
                        RoomType = roomType,
                        ModalAddress = rm.ModalAddress,
                        Outlet = rm.Outlet,
                        Name = rm.Name,
                        EnglishName = "",
                        TWName = "",
                        AliasName = "",
                        Power = rm.Power,
                        LowPower = 0,
                        Default = true,
                        Type = rm.Type,
                        Subtype = null,
                        Sort = rm.Sort,
                        ActiveIndicator = false,
                        OfflineDisplay = false,
                        LowPowerDisplay = false,
                        Beep = false,
                        Abnormal = false,
                        Color = rm.Color,
                        TCLDeviceName = "",
                        MultipleTCLName = "",
                        MultipleGroupID = 0
                    });
                }
            }
            var result = roomTypeModals//.AsQueryable().OrderBy(sort + " " + order).Skip((page - 1) * rows).Take(rows)
                .Select(r => new
                {
                    r.ID,
                    RoomTypeID = r.RoomType.ID,
                    r.ModalAddress,
                    r.Outlet,
                    r.Name,
                    r.EnglishName,
                    r.TWName,
                    r.AliasName,
                    r.Power,
                    r.LowPower,
                    r.Default,
                    r.Type,
                    TypeName = HttpContext.InnerLanguage(r.Type.ToString()),
                    //Subtype = r.Subtype.HasValue ? HttpContext.InnerLanguage(r.Subtype.ToString()) : "",
                    r.Sort,
                    r.ActiveIndicator,
                    r.OfflineDisplay,
                    r.LowPowerDisplay,
                    r.Beep,
                    r.Abnormal,
                    r.Color,
                    r.TCLDeviceName,
                    r.MultipleTCLName,
                    r.MultipleGroupID
                });
            return Json(new { total = result.Count(), rows = result });
        }
        /// <summary>
        /// 装载宝易上传的回路
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="order"></param>
        /// <param name="sort"></param>
        /// <param name="roomTypeID"></param>
        /// <param name="deviceType"></param>
        /// <returns></returns>
        public ActionResult LoadRoomTypeModalsBY(int? page, int? rows, string order, string sort, int roomTypeID, DeviceType deviceType)
        {
            var roomType = RoomTypeManager.Get(roomTypeID);
            var roomTypeModals = RoomTypeModalManager.LoadAll(roomType, 1).OrderBy(r => r.ModalAddress).ToList();//, deviceType);//获取该房型所有回路
            var result = roomTypeModals//.AsQueryable().OrderBy(sort + " " + order).Skip((page - 1) * rows).Take(rows)
                .Select(r => new
                {
                    r.ID,
                    RoomTypeID = r.RoomType.ID,
                    r.Type,
                    TypeName = HttpContext.InnerLanguage(r.Type.ToString()),
                    r.ModalAddress,
                    Circuit = r.ModalAddress.Substring(r.ModalAddress.Length - 3),
                    r.Outlet,
                    r.Name,
                    r.EnglishName,
                    r.TWName,
                    r.AliasName,
                    r.ActiveIndicator,
                    r.WXActiveIndicator,
                    r.Beep,
                    r.Power,
                    r.Sort,
                    r.OfflineDisplay,
                    r.LowPowerDisplay,
                    r.Abnormal,
                    r.Color,
                    r.SourceType
                });
            return Json(new { total = result.Count(), rows = result });
        }
        //编辑回路
        [Authorize]
        public ActionResult RoomTypeModalEdit(int id, int roomTypeId, DeviceType deviceType, string modalAddress = "", string outlet = "", string name = "", string color = "", string aliasName = "", string multipleTCLName = "", int multipleGroupID = 0)
        {
            RoomTypeModal roomTypeModal = null;
            if (id != 0)
            {
                roomTypeModal = RoomTypeModalManager.Get(id);
                if (string.IsNullOrEmpty(roomTypeModal.MultipleTCLName))
                {
                    roomTypeModal.MultipleTCLName = "";
                }

                if (string.IsNullOrEmpty(roomTypeModal.TCLDeviceName))
                {
                    roomTypeModal.TCLDeviceName = "";
                }
            }
            else
            {
                roomTypeModal = new RoomTypeModal
                {
                    ID = 0,
                    RoomType = new RoomType { ID = roomTypeId },
                    ModalAddress = modalAddress,
                    Outlet = outlet,
                    Name = name,
                    EnglishName = "",
                    TWName = "",
                    AliasName = "",
                    Power = 0,
                    LowPower = 0,
                    Type = deviceType,
                    Default = string.IsNullOrEmpty(modalAddress) ? false : true,
                    Sort = 1,
                    Color = color,
                    SourceType = 0,
                    TCLDeviceName = "",
                    MultipleGroupID = 0,
                    MultipleTCLName = ""
                };
            }
            return View(roomTypeModal);
        }

        public ActionResult LoadRoomTypeModals(string roomNumber, DeviceType? deviceType)
        {
            IList<RoomTypeModal> result = new List<RoomTypeModal>();
            try
            {
                var host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
                if (host != null)
                {
                    if (deviceType.HasValue)
                    {
                        result = RoomTypeModalManager.LoadAll(host.RoomType, deviceType.Value, 0).Where(r => r.ActiveIndicator).ToList();
                    }
                    else
                    {
                        result = RoomTypeModalManager.LoadAll(host.RoomType, 0).Where(r => r.ActiveIndicator).ToList();
                    }
                }
                return Json(new
                {
                    total = result.Count,
                    rows = result.Select(r => new
                    {
                        r.ID,
                        r.ModalAddress,
                        r.Outlet,
                        r.Name,
                        RoomType = r.RoomType.Name
                    })
                });
            }
            catch (Exception ex)
            {
                if (logger.IsErrorEnabled)
                {
                    logger.Error("加载回路失败，原因：", ex);
                }
                return Json(new { total = result.Count, rows = result });
            }
        }
        /// <summary>
        /// 保存回路
        /// </summary>
        /// <param name="id"></param>
        /// <param name="roomTypeID"></param>
        /// <param name="modalAddress"></param>
        /// <param name="outlet"></param>
        /// <param name="name"></param>
        /// <param name="power"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult SaveRoomTypeModal(int id, int roomTypeID, string modalAddress, string outlet, string name, string englishName, int power, string twName, string aliasName, DeviceType type, int sort, string color, string MultipleGroupID, string MultipleTCLName, string TCLDeviceName)//int lowPower, DeviceSubtype? subtype, int sort)
        {
            try
            {
                var roomTypeModal = new RoomTypeModal();
                if (id == 0)
                {
                    var roomType = RoomTypeManager.Get(roomTypeID);
                    if (roomType == null)
                    {
                        throw new ApplicationException(HttpContext.InnerLanguage("InvalidRoomType"));
                    }
                    var modall = RoomTypeModalManager.LoadAll().Where(r => r.RoomType.ID == roomTypeID && r.ModalAddress == modalAddress).ToList();
                    if (modall != null && modall.Count > 0)
                    {
                        return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("LoopAddressExists") });
                    }
                    roomTypeModal.RoomType = roomType;
                    roomTypeModal.ModalAddress = modalAddress;
                    roomTypeModal.Outlet = outlet;
                    roomTypeModal.Name = name;
                    roomTypeModal.EnglishName = englishName;
                    roomTypeModal.TWName = twName;
                    roomTypeModal.AliasName = aliasName;
                    roomTypeModal.Power = power;
                    roomTypeModal.Default = false;
                    roomTypeModal.Type = type;
                    roomTypeModal.Subtype = null;
                    roomTypeModal.Sort = sort;
                    roomTypeModal.Color = color;
                    roomTypeModal.ActiveIndicator = true;//新增时默认显示
                    roomTypeModal.WXActiveIndicator = true;//只要显示，微信默认允许控制
                    roomTypeModal.SourceType = 0;
                    roomTypeModal.MultipleTCLName = MultipleTCLName;
                    roomTypeModal.TCLDeviceName = TCLDeviceName;
                    int a = 0;
                    int.TryParse(MultipleGroupID, out a);
                    roomTypeModal.MultipleGroupID = a;
                    RoomTypeModalManager.Save(roomTypeModal);//新增房型下单个回路
                    string logDetail = "【" + (Language == Language.CN ? roomTypeModal.Name : roomTypeModal.EnglishName) + "】";
                    SaveSystemLog(AUTHORITY_RoomType, HttpContext.InnerLanguage("NewRoomTypeModal"), logDetail);
                }
                else
                {
                    roomTypeModal = RoomTypeModalManager.Get(id);
                    if (roomTypeModal == null)
                    {
                        throw new ApplicationException(HttpContext.InnerLanguage("InvalidCircuit"));
                    }
                    //非默认的回路才可以修改回路地址
                    if (!roomTypeModal.Default)
                    {
                        roomTypeModal.ModalAddress = modalAddress;
                    }
                    roomTypeModal.Outlet = outlet;
                    roomTypeModal.Name = name;
                    roomTypeModal.EnglishName = englishName;
                    roomTypeModal.TWName = twName;
                    roomTypeModal.AliasName = aliasName;
                    roomTypeModal.Power = power;
                    roomTypeModal.Type = type;
                    roomTypeModal.Subtype = null;
                    roomTypeModal.Sort = sort;

                    roomTypeModal.MultipleTCLName = MultipleTCLName;
                    roomTypeModal.TCLDeviceName = TCLDeviceName;
                    int a = 0;
                    int.TryParse(MultipleGroupID, out a);
                    roomTypeModal.MultipleGroupID = a;
                    RoomTypeModalManager.Update(roomTypeModal);//更新房型下回路
                    string logDetail = "【" + (Language == Language.CN ? roomTypeModal.Name : roomTypeModal.EnglishName) + "】";
                    SaveSystemLog(AUTHORITY_RoomType, HttpContext.InnerLanguage("EditRoomTypeModal"), logDetail);
                }
                System.Threading.Tasks.Task.Factory.StartNew<bool>(() => UpdateHostModals(roomTypeModal));//更新主机回路
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
            }
            catch (Exception ex)
            {
                SaveSystemLog(AUTHORITY_RoomType, HttpContext.InnerLanguage("NewOrEditRoomTypeModal"), ex.Message, false);
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("SaveFailedBecause") + ex.Message });
            }
        }
        /// <summary>
        /// 更新主机回路
        /// </summary>
        /// <param name="roomTypeModal"></param>
        /// <returns></returns>
        private bool UpdateHostModals(RoomTypeModal roomTypeModal)
        {
            List<Host> hosts = HostManager.LoadAll().Where(t => t.RoomType.ID == roomTypeModal.RoomType.ID).ToList();
            foreach (Host host in hosts)//该房型下所有主机关联回路
            {
                var hostModal = HostModalManager.GetByModalAddress(host.ID, roomTypeModal.ModalAddress);
                if (null == hostModal)
                {
                    HostModalManager.Save(new HostModal { HostID = host.ID, Modal = roomTypeModal, Status = 2, Time = 0, UpdateTime = DateTime.Now });
                }
            }
            return true;
        }
        /// <summary>
        /// 删除回路
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult RemoveRoomModal(int[] ids)
        {
            try
            {
                IList<string> modalList = new List<string>();
                foreach (var id in ids)
                {
                    var modal = RoomTypeModalManager.Get(id);
                    if (modal != null)
                    {
                        List<Host> hosts = HostManager.LoadAll().Where(t => t.RoomType == modal.RoomType).ToList();
                        foreach (Host host in hosts)
                        {
                            HostModalManager.DeteleByRoomTypeModal(host.ID, modal.ID);//先删除主机关联回路
                        }
                        RoomTypeModalManager.Delete(modal);//再删除房型关联回路
                        modalList.Add(Language == Language.CN ? modal.Name : modal.EnglishName);
                    }
                }
                SaveSystemLog(AUTHORITY_RoomType, HttpContext.InnerLanguage("DeleteRoomTypeModal"), "【" + String.Join(",", modalList.ToArray()) + "】");
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("DeleteSuccess") });
            }
            catch (Exception ex)
            {
                SaveSystemLog(AUTHORITY_RoomType, HttpContext.InnerLanguage("DeleteRoomTypeModal"), ex.Message, false);
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("DeleteFailedBecause") + ex.Message });
            }
        }
        /// <summary>
        /// 加载设备类型
        /// </summary>
        /// <returns></returns>
        public ActionResult LoadDeviceTypes()
        {
            var list = new List<object>();
            list.Add(new { Value = "", Name = HttpContext.InnerLanguage("CheckAll") });
            string[] names = Enum.GetNames(typeof(DeviceType));
            foreach (var name in names)
            {
                list.Add(new { Value = name, Name = HttpContext.InnerLanguage(name) });
            }
            return Json(list);
        }
        /// <summary>
        /// 保存设备控制是否显示标记
        /// </summary>
        /// <returns></returns>
        public ActionResult SaveDeviceDisplayChange(int id, bool activeIndicator)
        {
            try
            {
                var modal = RoomTypeModalManager.Get(id);
                if (modal == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidLoop"));
                }
                if (modal.SourceType == 0 && !activeIndicator && !modal.OfflineDisplay && !modal.LowPowerDisplay)//不显示、离线和低电不提示，则直接删除
                {
                    RoomTypeModalManager.Delete(id);
                }
                else
                {
                    modal.ActiveIndicator = activeIndicator;
                    modal.WXActiveIndicator = activeIndicator;//只要显示，微信默认允许控制
                    RoomTypeModalManager.Update(modal);
                }
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("SaveFailedBecause") + ex.Message });
            }
        }
        /// <summary>
        /// 保存离线是否显示
        /// </summary>
        /// <param name="id"></param>
        /// <param name="activeIndicator"></param>
        /// <returns></returns>
        public ActionResult SaveOfflineDisplayChange(int id, bool activeIndicator)
        {
            try
            {
                var modal = RoomTypeModalManager.Get(id);
                if (modal == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidMenu"));
                }
                modal.OfflineDisplay = activeIndicator;
                RoomTypeModalManager.Update(modal);
                if (!activeIndicator)
                {
                    HostFaultsManager.DeleteByAddress(modal.ModalAddress, modal.RoomType.ID);
                }

                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("SaveFailedBecause") + ex.Message });
            }
        }
        /// <summary>
        /// 保存低电是否显示
        /// </summary>
        /// <param name="id"></param>
        /// <param name="activeIndicator"></param>
        /// <returns></returns>
        public ActionResult SaveLowPowerDisplayChange(int id, bool activeIndicator)
        {
            try
            {
                var modal = RoomTypeModalManager.Get(id);
                if (modal == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidMenu"));
                }
                modal.LowPowerDisplay = activeIndicator;
                RoomTypeModalManager.Update(modal);
                if (!activeIndicator)
                {
                    HostFaultsManager.DeleteByAddress(modal.ModalAddress, modal.RoomType.ID);
                }

                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("SaveFailedBecause") + ex.Message });
            }
        }
        /// <summary>
        /// 保存是否报警显示
        /// </summary>
        /// <param name="id"></param>
        /// <param name="activeIndicator"></param>
        /// <returns></returns>
        public ActionResult SaveBeepDisplayChange(int id, bool activeIndicator)
        {
            try
            {
                var modal = RoomTypeModalManager.Get(id);
                if (modal == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidMenu"));
                }
                modal.Beep = activeIndicator;
                RoomTypeModalManager.Update(modal);

                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("SaveFailedBecause") + ex.Message });
            }
        }
        /// <summary>
        /// 保存是否异常判断
        /// </summary>
        /// <param name="id"></param>
        /// <param name="activeIndicator"></param>
        /// <returns></returns>
        public ActionResult SaveAbnormalChange(int id, bool activeIndicator)
        {
            try
            {
                var modal = RoomTypeModalManager.Get(id);
                if (modal == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidMenu"));
                }
                modal.Abnormal = activeIndicator;
                RoomTypeModalManager.Update(modal);

                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("SaveFailedBecause") + ex.Message });
            }
        }

        #endregion

        #region WX
        //打开场景界面
        [Authorize]
        public ActionResult RoomTypeScene(int roomTypeID)
        {
            return View(roomTypeID);
        }
        //打开微信界面
        [Authorize]
        public ActionResult RoomTypeWeiXin(int roomTypeID)
        {
            RoomType roomType = RoomTypeManager.Get(roomTypeID);
            return View(roomType);
        }
        /// <summary>
        /// 获取指定房型微信菜单
        /// </summary>
        /// <param name="roomTypeID"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadRoomTypeWXMenus(int? roomTypeID)
        {
            var list = RoomTypeWXMenusManager.LoadAll(Convert.ToInt16(roomTypeID)).OrderBy(r => r.Sort);
            var result = list.Select(r => new
            {
                ID = r.ID,
                Name = r.Name,
                EName = r.EName,
                TWName = r.TWName,
                Sort = r.Sort,
                ActiveIndicator = r.ActiveIndicator,
                TakePower = r.TakePower
            });

            return Json(result, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 保存微信菜单是否显示标记
        /// </summary>
        /// <param name="id"></param>
        /// <param name="activeIndicator"></param>
        /// <returns></returns>
        public ActionResult SaveRoomTypeWXMenus(int id, bool activeIndicator)
        {
            try
            {
                var menu = RoomTypeWXMenusManager.Get(id);
                if (menu == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidMenu"));
                }
                menu.ActiveIndicator = activeIndicator;
                RoomTypeWXMenusManager.Update(menu);

                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("SaveFailedBecause") + ex.Message });
            }
        }
        /// <summary>
        /// 保存取电标记
        /// </summary>
        /// <param name="id"></param>
        /// <param name="takePower"></param>
        /// <returns></returns>
        public ActionResult SaveRoomTypeWXMenusTakePower(int id, bool takePower)
        {
            try
            {
                var menu = RoomTypeWXMenusManager.Get(id);
                if (menu == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidMenu"));
                }
                menu.TakePower = takePower;
                RoomTypeWXMenusManager.Update(menu);

                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("SaveFailedBecause") + ex.Message });
            }
        }
        /// <summary>
        /// 获取房型场景
        /// </summary>
        /// <param name="roomTypeID"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadRoomTypeWXScene(int? roomTypeID)
        {
            var list = RoomTypeSceneManager.LoadAll().Where(r => r.RoomType.ID == Convert.ToInt16(roomTypeID)).ToList();
            var result = list.Select(r => new
            {
                ID = r.ID,
                Name = r.Name,
                EnglishName = r.EnglishName,
                TWName = r.TWName,
                Sort = r.Sort,
                ActiveIndicator = r.ActiveIndicator
            });

            return Json(result, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 保存房型场景
        /// </summary>
        /// <param name="id"></param>
        /// <param name="activeIndicator"></param>
        /// <returns></returns>
        public ActionResult SaveRoomTypeWXScene(int id, bool activeIndicator)
        {
            try
            {
                var menu = RoomTypeSceneManager.Get(id);
                if (menu == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidScene"));
                }
                menu.ActiveIndicator = activeIndicator;
                RoomTypeSceneManager.Update(menu);

                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("SaveFailedBecause") + ex.Message });
            }
        }
        /// <summary>
        /// 获取房型设备
        /// </summary>
        /// <param name="roomTypeID"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadRoomTypeWXDevice(int? roomTypeID, DeviceType deviceType)
        {
            var roomType = RoomTypeManager.Get(roomTypeID);
            //var list = RoomTypeModalManager.LoadAll(roomType, deviceType).Where(r => r.RoomType.ID == Convert.ToInt16(roomTypeID) && r.ActiveIndicator).ToList();
            var list = RoomTypeModalManager.LoadAll(roomTypeID).Where(r => r.ActiveIndicator).OrderBy(r => r.Type).ToList();
            var result = list.Select(r => new
            {
                ID = r.ID,
                ModalAddress = r.ModalAddress,
                Type = r.Type,
                TypeName = HttpContext.InnerLanguage(r.Type.ToString()),
                Name = r.Name,
                EnglishName = r.EnglishName,
                TWName = r.TWName,
                Sort = r.Sort,
                WXActiveIndicator = r.WXActiveIndicator
            });

            return Json(result, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 保存房型设备
        /// </summary>
        /// <param name="id"></param>
        /// <param name="activeIndicator"></param>
        /// <returns></returns>
        public ActionResult SaveRoomTypeWXDevice(int id, bool activeIndicator)
        {
            try
            {
                var roomType = RoomTypeModalManager.Get(id);
                if (roomType == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidLoop"));
                }
                roomType.WXActiveIndicator = activeIndicator;
                RoomTypeModalManager.Update(roomType);
                //通知该房型下所有智能语音更新技能
                var hosts = HostManager.LoadAll().Where(r => r.RoomType != null && r.RoomType.ID == roomType.RoomType.ID).ToList();
                string hotelCode = hosts.Count > 0 ? hosts[0].SysHotel.Code : "";
                string accessToken = SysOauth2Manager.GetXiaoDuToken();
                if (!string.IsNullOrEmpty(accessToken))//小度
                {
                    foreach (var host in hosts)
                    {
                        if (!string.IsNullOrEmpty(host.XiaoDuCUID))
                        {
                            System.Threading.Tasks.Task.Factory.StartNew(() =>
                            {
                                foreach (string cuid in host.XiaoDuCUID.Split(','))//多个小度英文逗号隔开
                                {
                                    XiaoDuOperation.PostWebRequestToXiaoDu(accessToken, cuid, new XiaoDuParamJson() { method = "deviceSync", isNoBlocked = 1 }, host.SysHotel.Code, host.RoomNumber);//更新技能
                                }
                            });
                        }
                    }
                }
                if (!string.IsNullOrEmpty(hotelCode))
                {
                    var sysOauth2 = SysOauth2Manager.LoadAll().Where(r => r.RedirectUri == "https://cgw.duiopen.com/account-link/v1/skill/2020120900000014" && r.Code.StartsWith(hotelCode)).OrderByDescending(r => r.ID).FirstOrDefault();
                    if (sysOauth2 != null && !string.IsNullOrEmpty(sysOauth2.AccessToken))//Dui电视
                    {
                        foreach (var host in hosts)
                        {
                            System.Threading.Tasks.Task.Factory.StartNew(() =>
                            {
                                DuiOperation.UploadDeviceFun(host.SysHotel.Name, host.RoomNumber, sysOauth2.AccessToken);
                            });
                        }
                    }
                }
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("SaveFailedBecause") + ex.Message });
            }
        }


        #endregion

        #region RoomTypeAir

        [Authorize]
        public ActionResult RoomTypeAir(int id)
        {
            return View(id);
        }

        [Authorize]
        public ActionResult RoomTypeAirEdit(int roomTypeId, int? id)
        {
            var roomTypeAir = new RoomTypeAir
            {
                ID = 0,
                RoomType = new RoomType { ID = roomTypeId },
                CustomerName = "",
                EnglishName = "",
                Sort = 1
            };

            if (id.HasValue && id.Value != 0)
            {
                roomTypeAir = RoomTypeAirManager.Get(id);
            }

            return View(roomTypeAir);
        }

        /// <summary>
        /// 加载 ModalType
        /// </summary>
        /// <returns></returns>
        public ActionResult LoadModalTypes()
        {
            var list = ModalTypeManager.LoadAll();
            return Json(list);
        }
        /// <summary>
        /// 加载空调
        /// </summary>
        /// <param name="roomTypeID"></param>
        /// <returns></returns>
        public ActionResult LoadRoomTypeAirs(int roomTypeID)
        {
            RoomType roomType = RoomTypeManager.Get(roomTypeID);

            var list = RoomTypeAirManager.LoadAll(roomType);

            var result = list.Select(r => new { r.ID, RoomTypeID = r.RoomType.ID, r.ModalTypeName, r.CustomerName, r.EnglishName, r.Sort }).OrderBy(r => r.Sort);

            return Json(new { total = result.Count(), rows = result });
        }

        /// <summary>
        /// 保存空调
        /// </summary>
        /// <param name="id"></param>
        /// <param name="roomTypeID"></param>
        /// <param name="modalTypeId"></param>
        /// <param name="customName"></param>
        /// <returns></returns>
        public ActionResult SaveRoomTypeAir(int id, int roomTypeID, int modalTypeId, string customName, string englishName, int sort)
        {
            try
            {
                var roomType = RoomTypeManager.Get(roomTypeID);
                if (roomType == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidRoomType"));
                }

                var modalType = ModalTypeManager.Get(modalTypeId);
                if (modalType == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidConfigurationName"));
                }

                var existRoomTypeAir = RoomTypeAirManager.Load(roomType, modalType);

                if (id == 0)
                {
                    if (existRoomTypeAir != null)
                    {
                        throw new ApplicationException("【" + existRoomTypeAir.ModalTypeName + "】" + HttpContext.InnerLanguage("AlreadyExist"));
                    }

                    var roomTypeAir = new RoomTypeAir();
                    roomTypeAir.RoomType = roomType;
                    roomTypeAir.ModalType = modalType;
                    roomTypeAir.ModalTypeName = modalType.Name;
                    roomTypeAir.CustomerName = customName;
                    roomTypeAir.EnglishName = englishName;
                    roomTypeAir.Sort = sort;

                    RoomTypeAirManager.Save(roomTypeAir);

                    string logDetail = "【" + (Language == Language.CN ? roomTypeAir.CustomerName : roomTypeAir.EnglishName) + "】";

                    SaveSystemLog(AUTHORITY_RoomType, HttpContext.InnerLanguage("NewRoomTypeAir"), logDetail);

                    IList<Host> List = HostManager.LoadAll().Where(r => r.RoomType.ID == roomType.ID).ToList();

                    foreach (Host host in List)
                    {
                        HostAir hostAir = new HostAir();
                        hostAir.HostID = host.ID;
                        hostAir.Modal = roomTypeAir;

                        HostAirManager.Save(hostAir);
                    }

                }
                else
                {
                    if (existRoomTypeAir != null && existRoomTypeAir.ID != id)
                    {
                        throw new ApplicationException("【" + existRoomTypeAir.ModalTypeName + "】" + HttpContext.InnerLanguage("AlreadyExist"));
                    }

                    var roomTypeAir = RoomTypeAirManager.Get(id);
                    if (roomTypeAir == null)
                    {
                        throw new ApplicationException(HttpContext.InnerLanguage("InvalidAirConditioning"));
                    }

                    roomTypeAir.ModalType = modalType;
                    roomTypeAir.ModalTypeName = modalType.Name;
                    roomTypeAir.CustomerName = customName;
                    roomTypeAir.EnglishName = englishName;
                    roomTypeAir.Sort = sort;

                    RoomTypeAirManager.Update(roomTypeAir);

                    string logDetail = "【" + (Language == Language.CN ? roomTypeAir.CustomerName : roomTypeAir.EnglishName) + "】";

                    SaveSystemLog(AUTHORITY_RoomType, HttpContext.InnerLanguage("EditRoomTypeAir"), logDetail);
                }

                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
            }
            catch (Exception ex)
            {
                SaveSystemLog(AUTHORITY_RoomType, HttpContext.InnerLanguage("NewOrEditRoomTypeAir"), ex.Message, false);

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

        /// <summary>
        /// 删除空调
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult RemoveRoomTypeAir(int[] ids)
        {
            try
            {
                IList<string> airList = new List<string>();

                if (ids != null)
                {
                    foreach (var id in ids)
                    {
                        var air = RoomTypeAirManager.Get(id);
                        if (air != null)
                        {
                            RoomTypeAirManager.Delete(air.ID);

                            IList<Host> List = HostManager.LoadAll().Where(r => r.RoomType.ID == air.RoomType.ID).ToList();

                            foreach (Host host in List)
                            {
                                HostAirManager.Delete(host.ID, air.ID);
                            }

                            airList.Add(Language == Language.CN ? air.CustomerName : air.EnglishName);
                        }
                    }
                }

                SaveSystemLog(AUTHORITY_RoomType, HttpContext.InnerLanguage("DeleteRoomTypeAir"), "【" + String.Join(",", airList.ToArray()) + "】");

                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("DeleteSuccess") });
            }
            catch (Exception ex)
            {
                SaveSystemLog(AUTHORITY_RoomType, HttpContext.InnerLanguage("DeleteRoomTypeAir"), ex.Message, false);

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

        #endregion

        /// <summary>
        /// 装在房型给下拉框
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadDataForRoomTypeCombobox()
        {
            var list = RoomTypeManager.LoadAll().Where(r => r.HotelID == CurrentHotelID);
            var result = list.Select(r => new { r.ID, r.Name }).ToList<object>();
            result.Insert(0, new { ID = 0, Name = HttpContext.InnerLanguage("CheckAll") });
            return Json(result);
        }
        /// <summary>
        /// 保存房型
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult Save(string jsonData)
        {
            RoomType entity = Newtonsoft.Json.JsonConvert.DeserializeObject<RoomType>(jsonData);
            RoomType existRoomType = RoomTypeManager.GetByCode(entity.Code, CurrentHotelID);
            if (existRoomType != null)
            {
                if (entity.ID == 0 || entity.ID != existRoomType.ID)
                {
                    return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("RoomTypeNumber") + "【" + entity.Code + "】" + HttpContext.InnerLanguage("AlreadyExist") });
                }
            }
            if (entity.ID == 0)
            {
                entity.HotelID = CurrentHotelID;
                RoomTypeManager.Save(entity);
                SaveSystemLog(AUTHORITY_RoomType, HttpContext.InnerLanguage("New"), entity.Name);
            }
            else
            {
                RoomType roomType = RoomTypeManager.Get(entity.ID);
                roomType.Code = entity.Code;
                roomType.Name = entity.Name;
                roomType.HostName = entity.HostName;
                roomType.HotelID = CurrentHotelID;
                RoomTypeManager.Update(roomType);
                SaveSystemLog(AUTHORITY_RoomType, HttpContext.InnerLanguage("Edit"), entity.Name);
            }
            return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
        }
        /// <summary>
        /// 复制房型
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult Copy(int id)
        {
            try
            {
                RoomTypeManager.Copy(id);
                SaveSystemLog(AUTHORITY_RoomType, HttpContext.InnerLanguage("Copy"), "复制房型ID：" + id);
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("OperationSuccess") });
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("TheOperationFailedTheFailureReasons") + ex.Message });
            }
        }
        /// <summary>
        /// 删除房型
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult Delete(int id)
        {
            try
            {
                if (RoomTypeManager.Get(id).Default == true)
                {
                    return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("DeleteFailedBecause") + HttpContext.InnerLanguage("DefaultRoomTypeNotDelete") });
                }
                if (RoomTypeProgramFilesManager.LoadAll().Where(r => r.RoomType != null && r.RoomType.ID == id).ToList().Count > 0)
                {
                    return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("DeleteFailedBecause") + "存在程序文件，不可删除！" });
                }
                if (HostManager.LoadAll().Where(r => r.RoomType != null && r.RoomType.ID == id && !r.IsDeleted).ToList().Count > 0)
                {
                    return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("DeleteFailedBecause") + HttpContext.InnerLanguage("PresenceHost") });
                }
                RoomTypeManager.Delete(id);
                SaveSystemLog(AUTHORITY_RoomType, HttpContext.InnerLanguage("Delete"), "id:" + id);
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("DeletedSuccess") });
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("DeleteFailedBecause") + ex.Message });
            }
        }
        /// <summary>
        /// 获取房型下的程序文件
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="order"></param>
        /// <param name="sort"></param>
        /// <param name="roomTypeID"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadRoomTypeProgramFiles(int page, int rows, string order, string sort, int roomTypeID)
        {
            long total = 0;
            var list = RoomTypeProgramFilesManager.LoadAllByPage(out total, page, rows, order, sort, roomTypeID);
            List<object> result = new List<object>();
            foreach (RoomTypeProgramFiles rtpf in list)
            {
                result.Add(new
                {
                    ID = rtpf.ID,
                    FileName = rtpf.FileName,
                    FileType = rtpf.FileType,
                    Size = rtpf.Size,
                    UploadTime = rtpf.UploadTime,
                    Account = rtpf.Account,
                    Href = rtpf.Href
                });
            }
            return Json(new { total = total, rows = result });
        }
        /// <summary>
        /// 上传程序文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult UploadProgramFile(HttpPostedFileBase file, int fileType, int roomTypeID)
        {
            try
            {
                if (file == null || file.ContentLength <= 0)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("PleaseSelectTheProgramFile"));
                }
                var roomType = RoomTypeManager.Get(roomTypeID);
                if (roomType == null)
                {
                    throw new ApplicationException("房型不能为空");
                }
                var sysHotel = SysHotelManager.Get(roomType.HotelID);
                RoomTypeProgramFiles entity = new RoomTypeProgramFiles
                {
                    ID = 0,
                    RoomType = roomType,
                    FileType = fileType,
                    FileName = file.FileName,
                    Md5 = Tools.ComputeFileHash(file.InputStream),
                    Size = file.ContentLength,
                    Href = "Uploads/" + sysHotel.Code + "/" + roomType.Code + "/" + file.FileName,
                    UploadTime = DateTime.Now,
                    Account = this.User.Identity.Name
                };

                string filePath = Server.MapPath("~/Uploads/" + sysHotel.Code + "/" + roomType.Code + "/");
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                filePath += file.FileName;
                if (System.IO.File.Exists(filePath))
                {
                    throw new ApplicationException("该程序文件已上传，请重新选择！");
                }
                RoomTypeProgramFilesManager.Save(entity);
                file.SaveAs(filePath);
                SaveSystemLog(AUTHORITY_RoomType, HttpContext.InnerLanguage("ProgramFile"), "【" + entity.FileName + "】");
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("UploadSuccessful") });
            }
            catch (Exception ex)
            {
                SaveSystemLog(AUTHORITY_RoomType, HttpContext.InnerLanguage("ProgramFile"), ex.Message, false);
                return Json(new { IsSuccess = false, Message = HttpUtility.HtmlEncode(ex.Message) });
            }
        }
        /// <summary>
        /// 删除程序文件
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult DeleteProgramFile(IList<int> idList)
        {
            try
            {
                IList<string> updateList = new List<string>();
                foreach (int id in idList)
                {
                    RoomTypeProgramFiles rtpf = RoomTypeProgramFilesManager.Get(id);
                    if (rtpf != null)
                    {
                        string file = Server.MapPath("~/" + rtpf.Href);
                        if (System.IO.File.Exists(file))
                        {
                            System.IO.File.Delete(file);
                        }
                        updateList.Add(rtpf.FileName);
                    }
                }
                RoomTypeProgramFilesManager.Delete(idList.Cast<object>().ToList());
                SaveSystemLog(AUTHORITY_RoomType, HttpContext.InnerLanguage("DeleteProgramFile"), "【" + String.Join(",", updateList.ToArray()) + "】");
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("DeleteSuccess") });
            }
            catch (Exception ex)
            {
                SaveSystemLog(AUTHORITY_RoomType, HttpContext.InnerLanguage("DeleteProgramFile"), ex.Message, false);
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("DeleteFailedBecause") + ex.Message });
            }
        }
        #endregion
    }
}
