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

namespace WebSite.Controllers
{
    public class AlarmSettingController : BaseController
    {
		private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(AlarmSettingController));

        private const int AUTHORITY_AlarmSetting = 21;

		public IAlarmSettingManager AlarmSettingManager { get; set; }

		#region Action

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

		[Authorize]
		public ActionResult Edit()
		{
            return View(AlarmSettingManager.LoadAll().Where(r => r.HotelID == CurrentHotelID));
		}

		[Authorize]
		public ActionResult LoadAll() 
		{
            var settings = AlarmSettingManager.LoadAll().Where(r => r.HotelID == CurrentHotelID);

			var result = new Dictionary<string, object>();

			foreach(var s in settings) 
			{
				result.Add(s.Code, s);
			}

			return Json(new { IsSuccess = true, Data = result }, JsonRequestBehavior.AllowGet);
		}

        [Authorize]
        public ActionResult LoadAll2()
        {
            List<AlarmSetting> list = AlarmSettingManager.LoadAll().Where(r => r.HotelID == CurrentHotelID).OrderBy(r => r.Sort).ToList();

            if (list.Count == 0)
            {
                return Json(new { IsSuccess = false, Data = "当前酒店没有报警信息数据。" }, JsonRequestBehavior.AllowGet);
            }

            IEnumerable<IGrouping<char, AlarmSetting>> list2 = list.GroupBy(r => r.Type);

            IDictionary<string, IList<object>> list3 = new Dictionary<string, IList<object>>();

            foreach (var item in list2)
            {
                var type = item.Key.ToString();
                list3[type] = new List<object>();
                foreach (var setting in item)
                {

                    list3[type].Add(new
                    {
                        setting.Type,
                        setting.Code,
                        Name = ((Boolean)Session["isCN"]) ? setting.Name : setting.EName,
                        Value = int.Parse(setting.Value),
                        setting.Color,
                        setting.Sort,
                        setting.Beep
                    });
                }
            }

            return Json(new { IsSuccess = true, Data = list3 }, JsonRequestBehavior.AllowGet);
        }

		/// <summary>
		/// 加载服务和异常设置
		/// </summary>
		/// <returns></returns>
		public ActionResult LoadServicesAndAbnormities()
		{
			var list = new List<AlarmSetting>();

            list.AddRange(AlarmSettingManager.LoadAll('B').Where(r => r.HotelID == CurrentHotelID));

            list.AddRange(AlarmSettingManager.LoadAll('C').Where(r => r.HotelID == CurrentHotelID));

            var result = list.Select(r => new { r.Code, Name = r.Name != null ? r.Name:r.EName});// ((Boolean)Session["isCN"]) ? r.Name : r.EName });

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

        /// <summary>
        /// 获取当前服务信息
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadCurrentMsg()
        {
            var settings = AlarmSettingManager.LoadAll().Where(r => r.HotelID == CurrentHotelID && r.Type == 'B' && r.Value == "1").OrderBy(r => r.Sort);

            return Json(new { IsSuccess = true, Data = settings }, JsonRequestBehavior.AllowGet);
        }

		[Authorize]
		public ActionResult Save(string jsonData)
		{
			try
			{
				IList<AlarmSetting> settings = Newtonsoft.Json.JsonConvert.DeserializeObject<IList<AlarmSetting>>(jsonData);

				if (settings != null)
				{
					foreach (var setting in settings)
					{
                        var entity = AlarmSettingManager.Get(CurrentHotelID, setting.Type, setting.Code);

						entity.Value = setting.Value;
						entity.Beep = setting.Beep;

						AlarmSettingManager.Update(entity);

					}
				}

                SaveSystemLog(AUTHORITY_AlarmSetting, HttpContext.InnerLanguage("EditAlarmSetting"), "");

				return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
			}
			catch (Exception ex)
			{
				if (logger.IsErrorEnabled)
				{
                    logger.Error(HttpContext.InnerLanguage("FailedToSaveTheAlarmSettings"), ex);
				}

                SaveSystemLog(AUTHORITY_AlarmSetting, HttpContext.InnerLanguage("EditAlarmSetting"), "", false);

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

		#endregion
	}
}
