using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Common;
using Domain;
using Service;

namespace WebSite.Controllers
{
    public class RoomTypeSceneController : BaseController
    {
        private const int AUTHORITY_RoomTypeScene = 32;
        private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(RoomTypeSceneController));
        public IRoomTypeSceneManager RoomTypeSceneManager { get; set; }
        public IRoomTypeSceneModalManager RoomTypeSceneModalManager { get; set; }
        public IRoomTypeManager RoomTypeManager { get; set; }
        public IRoomTypeModalManager RoomTypeModalManager { get; set; }
        public IHostSceneManager HostSceneManager { get; set; }
        public IHostTimingControlManager HostTimingControlManager { get; set; }

        #region Actions

        [Authorize]
        public ActionResult Index()
        {
            return View("SimonIndex");
        }

        [Authorize]
        public ActionResult Edit(int id, int roomTypeID)
        {
            if (id != 0)
            {
                return View(RoomTypeSceneManager.Get(id));
            }
            RoomType roomType = RoomTypeManager.Get(roomTypeID);
            return View("~/Views/RoomTypeScene/Edit.ascx", new RoomTypeScene { ID = 0, RoomType = roomType });
        }

        [Authorize]
        public ActionResult LoadAll(int? roomTypeID, int? hostID)
        {
            IList<RoomTypeScene> list = new List<RoomTypeScene>();
            if (roomTypeID.HasValue && roomTypeID > 0)
            {
                list = RoomTypeSceneManager.LoadAll().Where(r => r.RoomType.ID == roomTypeID).ToList();
                if (hostID.HasValue && hostID > 0)
                {
                    var hostSceneList = HostSceneManager.LoadByHostID((int)hostID);
                    foreach (RoomTypeScene r in list)
                    {
                        int status = 2;
                        foreach (HostScene h in hostSceneList)
                        {
                            if (r.ID == h.Scene.ID)
                            {
                                status = h.Status;
                                break;
                            }
                        }
                        r.Name = ReturnNameByLanguage(r.Name, r.EnglishName, r.TWName) + "(" + (status == 1 ? HttpContext.InnerLanguage("On") : HttpContext.InnerLanguage("Off")) + ")";
                    }
                    return Json(list.Select(r => new { r.ID, r.Name }));
                }
                else
                {
                    return Json(list.Select(r => new { r.ID, Name = ReturnNameByLanguage(r.Name, r.EnglishName, r.TWName) }));
                }
            }
            return Json(list);
        }

        [Authorize]
        public ActionResult LoadAllByPage(int page, int rows, string order, string sort, int roomTypeID)
        {
            long total = 0;
            var list = RoomTypeSceneManager.LoadAllByPage(out total, page, rows, order, sort, CurrentHotelID, roomTypeID).ToList();
            var result = list.Select(r => new
            {
                r.ID,
                RoomTypeID = r.RoomType.ID,
                RoomTypeName = r.RoomType.Name,
                r.GroupAddress,
                r.EnglishName,
                Type = EnumDescription.GetDescription(r.Type),
                r.Name,
                r.TWName,
                r.ActiveIndicator,
                r.TakeInverse,
                r.Sort,
                r.AliasName
            });
            return Json(new { total = total, rows = result });
        }

        [Authorize]
        public ActionResult LoadRoomTypeSceneModals(int? roomTypeSceneID)//新增场景网格数据显示
        {
            try
            {
                IList<RoomTypeSceneModal> list = new List<RoomTypeSceneModal>();
                var scene = RoomTypeSceneManager.Get(roomTypeSceneID);
                if (scene != null)
                {
                    list = RoomTypeSceneModalManager.LoadAll(scene);
                }
                //查询数据库
                var result = list.Select(s =>
                    {
                        return new
                        {
                            s.Modal.ID,
                            s.Modal.ModalAddress,
                            Name = ReturnNameByLanguage(s.Modal.Name, s.Modal.EnglishName, s.Modal.TWName),
                            Type = s.Modal.Type.ToString(),
                            TypeName = HttpContext.InnerLanguage(s.Modal.Type.ToString()),
                            s.Status,
                            s.Brightness,
                            s.CurrentTemp,
                            s.Mode,
                            s.FanSpeed,
                            s.Valve
                        };
                    })
                    .OrderBy(o => o.ID)
                    .OrderByDescending(o => o.Status)
                    .ToList();

                return Json(new { total = result.Count(), rows = result });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("LoadDataFailedBecause") + ex.Message });
            }
        }

        /// <summary>
        /// 加载设备回路
        /// </summary>
        /// <param name="roomTypeId"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadDevices(int roomTypeId)
        {
            IList<RoomTypeModal> list = new List<RoomTypeModal>();
            var roomType = RoomTypeManager.Load(roomTypeId);
            if (roomType != null)
            {
                list = RoomTypeModalManager.LoadAll(roomType, 0).Where(r => r.ActiveIndicator).ToList();
            }
            var result = list.Select(r => new
            {
                r.ID,
                r.ModalAddress,
                r.Name,
                Type = r.Type.ToString(),
                TypeName = HttpContext.InnerLanguage(r.Type.ToString())
            });
            return Json(new { total = list.Count(), rows = result });
        }
        //保存场景
        [Authorize]
        public ActionResult Save(string jsonData)
        {
            try
            {
                IDictionary<string, object> json = Newtonsoft.Json.JsonConvert.DeserializeObject<IDictionary<string, object>>(jsonData);
                int roomTypeSceneID = 0;
                if (json.ContainsKey("ID"))
                {
                    roomTypeSceneID = Convert.ToInt32(json["ID"]);
                }
                RoomType roomType = null;
                if (json.ContainsKey("RoomTypeID"))
                {
                    roomType = RoomTypeManager.Get(Convert.ToInt32(json["RoomTypeID"]));
                }
                SceneType type = SceneType.Custom;
                if (json.ContainsKey("Type"))
                {
                    type = (SceneType)Convert.ToInt32(json["Type"]);
                }
                string name = "";
                if (json.ContainsKey("Name"))
                {
                    name = json["Name"].ToString();
                }
                string aliasName = "";
                if (json.ContainsKey("AliasName"))
                {
                    aliasName = json["AliasName"].ToString();
                }
                string englishName = "";
                if (json.ContainsKey("EnglishName"))
                {
                    englishName = json["EnglishName"].ToString();
                }
                string twName = "";
                if (json.ContainsKey("TWName"))
                {
                    twName = json["TWName"].ToString();
                }
                string groupAddress = "";
                if (json.ContainsKey("GroupAddress"))
                {
                    groupAddress = json["GroupAddress"].ToString();
                }
                int sort = 1;
                if (json.ContainsKey("Sort"))
                {
                    sort = Convert.ToInt16(json["Sort"].ToString());
                }
                RoomTypeScene existRoomTypeScene = RoomTypeSceneManager.Get(roomType, name);
                RoomTypeScene roomTypeScene = null;
                if (roomTypeSceneID == 0)
                {
                    //新增
                    if (existRoomTypeScene != null)
                    {
                        return Json(new { IsSuccess = false, Message = String.Format("【{0}】【{1}】" + HttpContext.InnerLanguage("PatternAlreadyExists"), roomType.Name, name) });
                    }
                    roomTypeScene = new RoomTypeScene();
                    roomTypeScene.ID = roomTypeSceneID;
                    roomTypeScene.RoomType = roomType;
                    roomTypeScene.Name = name;
                    roomTypeScene.EnglishName = englishName;
                    roomTypeScene.TWName = twName;
                    roomTypeScene.Type = type;
                    roomTypeScene.GroupAddress = groupAddress;
                    roomTypeScene.HotelID = CurrentHotelID;
                    roomTypeScene.Sort = sort;
                    roomTypeScene.AliasName = aliasName;

                    RoomTypeSceneManager.Save(roomTypeScene);

                    string logDetail = HttpContext.InnerLanguage("SceneType" + roomTypeScene.Type.ToString()) + "【" + (Language == Language.CN ? roomTypeScene.Name : roomTypeScene.EnglishName) + "】";
                    SaveSystemLog(AUTHORITY_RoomTypeScene, HttpContext.InnerLanguage("New"), logDetail);
                }
                else
                {
                    //更新
                    if (existRoomTypeScene != null && existRoomTypeScene.ID != roomTypeSceneID)
                    {
                        return Json(new { IsSuccess = false, Message = String.Format("【{0}】【{1}】" + HttpContext.InnerLanguage("PatternAlreadyExists"), roomType.Name, name) });
                    }
                    else
                    {
                        roomTypeScene = existRoomTypeScene;
                    }
                    roomTypeScene = RoomTypeSceneManager.Get(roomTypeSceneID);
                    roomTypeScene.RoomType = roomType;
                    roomTypeScene.Type = type;
                    roomTypeScene.Name = name;
                    roomTypeScene.EnglishName = englishName;
                    roomTypeScene.TWName = twName;
                    roomTypeScene.GroupAddress = groupAddress;
                    roomTypeScene.HotelID = CurrentHotelID;
                    roomTypeScene.Sort = sort;
                    roomTypeScene.AliasName = aliasName;

                    RoomTypeSceneManager.Update(roomTypeScene);

                    foreach (var modal in RoomTypeSceneModalManager.LoadAll(roomTypeScene))
                    {
                        RoomTypeSceneModalManager.Delete(modal.ID);
                    }

                    string logDetail = HttpContext.InnerLanguage("SceneType" + roomTypeScene.Type.ToString()) + "【" + (Language == Language.CN ? roomTypeScene.Name : roomTypeScene.EnglishName) + "】";

                    SaveSystemLog(AUTHORITY_RoomTypeScene, HttpContext.InnerLanguage("Edit"), logDetail);
                }
                if (type == SceneType.Custom && json.ContainsKey("Modals"))
                {
                    foreach (var modal in DeserializeRoomTypeSceneModal(roomTypeScene, json["Modals"].ToString()))
                    {
                        RoomTypeSceneModalManager.Save(modal);
                    }
                }
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
            }
            catch (Exception ex)
            {
                logger.Error("保存场景失败：" + ex);
                SaveSystemLog(AUTHORITY_RoomTypeScene, HttpContext.InnerLanguage("NewOrEdit"), ex.Message, false);
                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 SaveTakeInverseChange(int id, bool activeIndicator)
        {
            try
            {
                var modal = RoomTypeSceneManager.Get(id);
                if (modal == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidMenu"));
                }
                modal.TakeInverse = activeIndicator;
                RoomTypeSceneManager.Update(modal);

                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 });
            }
        }
        //删除场景
        [Authorize]
        public ActionResult Delete(IList<int> idList)
        {
            try
            {
                IList<string> sceneList = new List<string>();
                foreach (int id in idList)
                {
                    var scene = RoomTypeSceneManager.Get(id);
                    if (scene != null)
                    {
                        sceneList.Add(HttpContext.InnerLanguage("SceneType" + scene.Type.ToString()) + "【" + (Language == Language.CN ? scene.Name : scene.EnglishName) + "】");

                        HostSceneManager.DeteleByRoomTypeScene(id);//删除主机执行场景记录
                        var roomTypeSceneModalList = RoomTypeSceneModalManager.LoadAll(scene);
                        foreach (var modal in roomTypeSceneModalList)
                        {
                            RoomTypeSceneModalManager.Delete(modal.ID);//删除场景关联回路
                        }
                        var hostTimingList = HostTimingControlManager.LoadAll().Where(r => r.RoomTypeSceneID == id).ToList();
                        foreach (var timing in hostTimingList)
                        {
                            HostTimingControlManager.Delete(timing.ID);//删除场景关联定时任务
                        }

                        RoomTypeSceneManager.Delete(id);//场景主表
                    }
                }
                SaveSystemLog(AUTHORITY_RoomTypeScene, HttpContext.InnerLanguage("Delete"), String.Join(",", sceneList.ToArray()));
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("DeleteSuccess") });
            }
            catch (Exception ex)
            {
                logger.Error("删除场景失败：" + ex);
                SaveSystemLog(AUTHORITY_RoomTypeScene, HttpContext.InnerLanguage("Delete"), ex.Message, false);
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("DeleteFailedBecause") + ex.Message });
            }
        }

        #endregion
        #region Private Methods
        /// <summary>
        /// 将json格式的数据反序列化为RoomTypeSceneModal
        /// </summary>
        /// <param name="roomTypeSceneID"></param>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        private IList<RoomTypeSceneModal> DeserializeRoomTypeSceneModal(RoomTypeScene scene, string jsonData)
        {
            IList<RoomTypeSceneModal> roomTypeSceneModals = new List<RoomTypeSceneModal>();
            IList<IDictionary<string, object>> modals = Newtonsoft.Json.JsonConvert.DeserializeObject<IList<IDictionary<string, object>>>(jsonData);
            foreach (IDictionary<string, object> modal in modals)
            {
                roomTypeSceneModals.Add(new RoomTypeSceneModal
                {
                    Scene = scene,
                    Modal = RoomTypeModalManager.Get(Convert.ToInt32(modal["ID"])),
                    Status = Convert.ToInt32(modal["Status"]),
                    Brightness = Convert.ToInt32(modal["Brightness"]),
                    CurrentTemp = Convert.ToInt32(modal["CurrentTemp"]),
                    Mode = Convert.ToInt32(modal["Mode"]),
                    FanSpeed = Convert.ToInt32(modal["FanSpeed"]),
                    Valve = Convert.ToInt32(modal["Valve"])
                });
            }
            return roomTypeSceneModals;
        }

        #endregion
    }
}
