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

namespace WebSite.Controllers
{
    public class MobileAppController : BaseController
    {
        private const int AUTHORITY_MobileApp = 33;

        public IAppMenuManager AppMenuManager { get; set; }

        public IAppHotelManager AppHotelManager { get; set; }

        public IAlarmSettingManager AlarmSettingManager { get; set; }

        public IRoomTypeModalManager RoomTypeModalManager { get; set; }

        public IRoomTypeSceneManager RoomTypeSceneManager { get; set; }

        public IAppRoomManager AppRoomManager { get; set; }

        public ActionResult Index()
        {
            #if SIMON
            return View("SimonIndex");
            #else
			return View();
            #endif
        }

        #region 菜单
        /// <summary>
        /// 
        /// </summary>
        /// <param name="type">0app,1微信</param>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadMenus(int type)
        {
            var list = this.AppMenuManager.LoadAll(type, CurrentHotelID);
            return Json(new { total = list.Count, rows = list });
        }

        [Authorize]
        public ActionResult LoadAppMenusByPage(int page, int rows, string order, string sort)
        {
            long total = 0;

            var list = this.AppMenuManager.LoadAllByPage(out total, page, rows, order, sort).Where(r => r.Type == 0);

            return Json(new { total = total, rows = list });
        }

        [Authorize]
        public ActionResult SaveAppMenu(int id, string name, HttpPostedFileBase icon, int sort, bool activeIndicator)
        {
            try
            {
                var menu = AppMenuManager.Get(id);
                if (menu == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidMenu"));
                }

                if (String.IsNullOrWhiteSpace(name))
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("TheMenuNameCanNotBeEmpty"));
                }

                if (icon != null)
                {
                    if (icon.ContentLength == 0)
                    {
                        throw new ApplicationException(HttpContext.InnerLanguage("InvalidMenuIcon"));
                    }

                    if (icon.ContentType != "image/png" &&
                        icon.ContentType != "image/jpeg" &&
                        icon.ContentType != "image/gif")
                    {
                        throw new ApplicationException(HttpContext.InnerLanguage("InvalidFormatMenuIconMenuIconFormatCanOnlyBe") + "png、jpg/jpeg、gif。");
                    }

                    string filePath = Server.MapPath("~/Uploads/AppIcons/");
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }
					string fileName = Path.GetFileName(icon.FileName);
					filePath += fileName;
					if (System.IO.File.Exists(filePath))
                    {
						throw new ApplicationException(HttpContext.InnerLanguage("IconFiles") + "【" + fileName + "】" + HttpContext.InnerLanguage("AlreadyExistsRenameAndThenUpload"));
                    }
                    icon.SaveAs(filePath);
					menu.Icon = "Uploads/AppIcons/" + fileName;
                }

                menu.Name = name;
                menu.Sort = sort;
                menu.ActiveIndicator = activeIndicator;

                AppMenuManager.Update(menu);

                SaveSystemLog(AUTHORITY_MobileApp, HttpContext.InnerLanguage("EditMenu"), Language == Domain.Language.CN ? menu.Name : menu.EnglishName);

                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") }, "text/html");
            }
            catch (Exception ex)
            {
                SaveSystemLog(AUTHORITY_MobileApp, HttpContext.InnerLanguage("EditMenu"), ex.Message, false);

				return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveFailedBecause") + ex.Message }, "text/html");
            }
        }
        [Authorize]
        public ActionResult SaveWXMenu(int id, bool activeIndicator)
        {
            try
            {
                var menu = AppMenuManager.Get(id);
                if (menu == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidMenu"));
                }

                menu.ActiveIndicator = activeIndicator;

                AppMenuManager.Update(menu);

                SaveSystemLog(AUTHORITY_MobileApp, HttpContext.InnerLanguage("EditMenu"), Language == Domain.Language.CN ? menu.Name : menu.Name);

                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") }, "text/html");
            }
            catch (Exception ex)
            {
                SaveSystemLog(AUTHORITY_MobileApp, HttpContext.InnerLanguage("EditMenu"), ex.Message, false);

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

        #endregion

        #region 酒店介绍

        [Authorize]
        public ActionResult LoadAppHotel()
        {
            var result = new Dictionary<string, string>();
            foreach (var item in AppHotelManager.LoadAll())
            {
                result.Add(item.Code, item.Value);
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [Authorize]
        public ActionResult SaveAppHotel(string jsonData)
        {
            try
            {
                var list = Newtonsoft.Json.JsonConvert.DeserializeObject<IDictionary<string, string>>(jsonData);

                foreach (KeyValuePair<string, string> item in list)
                {
                    var entity = AppHotelManager.Get(item.Key);
                    if (entity != null)
                    {
                        entity.Value = item.Value;
                        AppHotelManager.Update(entity);
                    }
                }

                SaveSystemLog(AUTHORITY_MobileApp, HttpContext.InnerLanguage("EditHotelIntroduce"), "");

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

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

        #endregion

        #region 服务

        [HttpPost]
        [Authorize]
        public ActionResult LoadServices()
        {
            var list = AlarmSettingManager.LoadAll('B').Where(r => r.HotelID == CurrentHotelID);

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

        [HttpPost]
        [Authorize]
        public ActionResult SaveService(char type, string code, bool appApply)
        {
            try
            {
                var serviceSetting = AlarmSettingManager.Get(CurrentHotelID, type, code);
                if (serviceSetting == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidService"));
                }

                serviceSetting.AppApply = appApply;

                AlarmSettingManager.Update(serviceSetting);
                
                string logDetail = serviceSetting.AppApply ? HttpContext.InnerLanguage("Show") : HttpContext.InnerLanguage("Hide");

                logDetail += "【" + (Language == Language.CN ? serviceSetting.Name : serviceSetting.EName) + "】";

                SaveSystemLog(AUTHORITY_MobileApp, HttpContext.InnerLanguage("EditService"), logDetail);

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

            }
            catch (Exception ex)
            {
                SaveSystemLog(AUTHORITY_MobileApp, HttpContext.InnerLanguage("EditService"), ex.Message, false);

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

        #endregion

        #region 灯光

        [Authorize]
        public ActionResult LoadLightsByPage(int page, int rows, string order, string sort, int roomTypeId)
        {
            long total = 0;

            var list = RoomTypeModalManager.LoadAllByPage(out total, page, rows, order, sort, roomTypeId);

            var result = list.Select(r => new { r.ID, r.Outlet, r.Name, Type = HttpContext.InnerLanguage(r.Type.ToString()), r.AppApply, r.EnglishName });

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

        [HttpPost]
        [Authorize]
        public ActionResult SaveLight(int id, bool appApply)
        {
            try
            {
                var light = RoomTypeModalManager.Get(id);
                if (light == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidLight"));
                }

                light.AppApply = appApply;

                RoomTypeModalManager.Update(light);
                
                string logDetail = light.AppApply ? HttpContext.InnerLanguage("Show") : HttpContext.InnerLanguage("Hide");

                logDetail += "【" + light.RoomType.Name + "】";

                logDetail += "【" + (Language == Language.CN ? light.Name : light.EnglishName) + "】";

                SaveSystemLog(AUTHORITY_MobileApp, HttpContext.InnerLanguage("EditLight"), logDetail);

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

            }
            catch (Exception ex)
            {
                SaveSystemLog(AUTHORITY_MobileApp, HttpContext.InnerLanguage("EditLight"), ex.Message, false);

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

        #endregion

        #region 场景

        [Authorize]
        public ActionResult LoadScenesByPage(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);

            var result = list.Select(r => new { r.ID, r.Name, r.AppApply, r.EnglishName, r.Icon });

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

        public ActionResult SaveScene(int id, bool appApply)
        {
            try
            {
                var scene = RoomTypeSceneManager.Get(id);
                if (scene == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidScene"));
                }

                scene.AppApply = appApply;

                RoomTypeSceneManager.Update(scene);

                string logDetail = scene.AppApply ? HttpContext.InnerLanguage("Show") : HttpContext.InnerLanguage("Hide");

                logDetail += "【" + scene.RoomType.Name + "】";

                logDetail += "【" + (Language == Language.CN ? scene.Name : scene.EnglishName) + "】";

                SaveSystemLog(AUTHORITY_MobileApp, HttpContext.InnerLanguage("EditScene"), logDetail);

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

            }
            catch (Exception ex)
            {
                SaveSystemLog(AUTHORITY_MobileApp, HttpContext.InnerLanguage("EditScene"), ex.Message, false);

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


        public ActionResult SaveEditScene(int id, string name, string engshilname, HttpPostedFileBase icon, bool appapply)
        {
            try
            {

                var scene = RoomTypeSceneManager.Get(id);

                if (scene == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidScene"));
                }

                if (icon != null)
                {
                    if (icon.ContentLength == 0)
                    {
                        throw new ApplicationException(HttpContext.InnerLanguage("InvalidSceneIcon"));
                    }

                    if (icon.ContentType != "image/png" &&
                        icon.ContentType != "image/jpeg" &&
                        icon.ContentType != "image/gif")
                    {
                        throw new ApplicationException(HttpContext.InnerLanguage("InvalidSceneIconFormatSceneIconFormatCanOnlyBe") + "png、jpg/jpeg、gif。");
                    }

                    string filePath = Server.MapPath("~/Uploads/AppIcons/");
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }
					string fileName = Path.GetFileName(icon.FileName);
					filePath += fileName;
                    if (System.IO.File.Exists(filePath))
                    {
						throw new ApplicationException(HttpContext.InnerLanguage("IconFiles") + "【" + fileName + "】" + HttpContext.InnerLanguage("AlreadyExistsRenameAndThenUpload"));
                   
                    }
                    icon.SaveAs(filePath);
					scene.Icon = "Uploads/AppIcons/" + fileName;
                }

                scene.AppApply = appapply;

                RoomTypeSceneManager.Update(scene);

                string logDetail = scene.AppApply ? HttpContext.InnerLanguage("Show") : HttpContext.InnerLanguage("Hide");

                logDetail += "【" + scene.RoomType.Name + "】";

                logDetail += "【" + (Language == Language.CN ? scene.Name : scene.EnglishName) + "】";

                SaveSystemLog(AUTHORITY_MobileApp, HttpContext.InnerLanguage("EditScene"), logDetail);

                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SettingSuccess") }, "text/html");

            }
            catch (Exception ex)
            {
                SaveSystemLog(AUTHORITY_MobileApp, HttpContext.InnerLanguage("EditScene"), ex.Message, false);

				return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("SetFailedbecause") + ex.Message }, "text/html");
            }
        }
        #endregion

        #region  PAD房号设置
        [Authorize]
        public ActionResult LoadAppRoomsByPage(int page, int rows, string order, string sort)
        {
            long total = 0;

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

            return Json(new { total = total, rows = list });
        }

        [Authorize]
        public ActionResult SaveAppRoom(int id, string mac, string roomNumber)
        {
            try
            {
                AppRoom existAppRoom = AppRoomManager.Get(id);
                AppRoom appRoom = null;

                if (id == 0)
                {
                    if (!AppRoomManager.isExistMac(mac))
                    {
                        //新增
                        appRoom = new AppRoom();

                        appRoom.ID = id;
                        appRoom.MAC = mac;
                        appRoom.RoomNumber = roomNumber;

                        if (existAppRoom != null)
                        {
                            return Json(new { IsSuccess = false, Message = String.Format("【{0}】【{1}】" + HttpContext.InnerLanguage("PADRoomNumberSetupInformationAlreadyExists"), appRoom.MAC, appRoom.RoomNumber) });
                        }

                        AppRoomManager.Save(appRoom);

                        string logDetail = HttpContext.InnerLanguage("New") + "【" + appRoom.MAC + "," + appRoom.RoomNumber + "】";

                        SaveSystemLog(AUTHORITY_MobileApp, HttpContext.InnerLanguage("PADRoomNumberSetting"), logDetail);
                    }
                    else
                    {
                        return Json(new { IsSuccess = false, Message = String.Format("【{0}】" + HttpContext.InnerLanguage("AlreadyExist"), mac) });
                    }
                }
                else
                {
                    //更新
                    if (existAppRoom != null && existAppRoom.ID != id)
                    {
                        return Json(new { IsSuccess = false, Message = String.Format("【{0}】【{1}】" + HttpContext.InnerLanguage("PADRoomNumberSetupInformationAlreadyExists"), appRoom.MAC, appRoom.RoomNumber) });
                    }
                    else
                    {
                        appRoom = existAppRoom;
                    }

                    appRoom.MAC = mac;
                    appRoom.RoomNumber = roomNumber;

                    AppRoomManager.Update(appRoom);

                    string logDetail = HttpContext.InnerLanguage("Edit") + "【" + appRoom.MAC + "," + appRoom.RoomNumber + "】";

                    SaveSystemLog(AUTHORITY_MobileApp, HttpContext.InnerLanguage("PADRoomNumberSetting"), logDetail);
                }

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

        [Authorize]
        public ActionResult DeleteAppRoom(IList<int> idList)
        {
            try
            {
                IList<string> appRoomList = new List<string>();

                foreach (int id in idList)
                {
                    var appRoom = AppRoomManager.Get(id);
                    if (appRoom != null)
                    {
                        AppRoomManager.Delete(appRoom.ID);

                        appRoomList.Add("【" + appRoom.MAC + "," + appRoom.RoomNumber + "】");
                    }
                }

                string logDetail = HttpContext.InnerLanguage("Delete") + String.Join(",", appRoomList.ToArray());

                SaveSystemLog(AUTHORITY_MobileApp, HttpContext.InnerLanguage("PADRoomNumberSetting"), logDetail);

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

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

        #endregion

    }
}
