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

namespace WebSite.Controllers
{
    public class RoomControlController : BaseController
    {
        private const int AUTHORITY_RoomControl = 11;

        public IHostManager HostManager { get; set; }
        public IGroupManager GroupManager { get; set; }
        public IRoomStatusManager RoomStatusManager { get; set; }
        public IRoomTypeManager RoomTypeManager { get; set; }
        public IHostTimingControlManager HostTimingControlManager { get; set; }
        public IRoomTypeSceneManager RoomTypeSceneManager { get; set; }
        public ISysUserManager SysUserManager { get; set; }
        public IRoomCardTypeManager RoomCardTypeManager { get; set; }
        public ITestManager TestManager { get; set; }

        #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 LoadByRoomControl(int page, int rows, string order, string sort)
        {
            long total = 0;
            var list = HostTimingControlManager.LoadAllByPage(out total, page, rows, order, sort, CurrentHotelID);
            var restult = list.Select(r => new
            {
                r.ID,
                r.HotelID,
                r.HostIDs,
                RoomNumbers = GetRoomNumberByIDs(r.HostIDs),
                r.GroupID,
                GroupName = r.GroupID > 0 ? GroupManager.Get(r.GroupID).Name : "",
                r.RoomTypeID,
                RoomTypeName = r.RoomTypeID > 0 ? RoomTypeManager.Get(r.RoomTypeID).Name : "",
                r.RoomStatusID,
                RoomStatusName = r.RoomStatusID > 0 ? RoomStatusManager.Get(r.RoomStatusID).Name : "",
                r.RoomCardTypeID,
                RoomCardTypeName = r.RoomCardTypeID > -1 ? RoomCardTypeManager.Get(r.RoomCardTypeID).Name : "",
                r.RoomTypeSceneID,
                RoomTypeSceneName = RoomTypeSceneManager.Get(r.RoomTypeSceneID).Name,
                r.TimingType,
                r.TimingDay,
                r.Timing,
                r.ActiveIndicator,
                ExecStatus = r.ExecStatus ? true : false,
                ExecTime = r.ExecStatus ? Convert.ToDateTime(r.ExecTime).ToString("yyyy-MM-dd HH:mm:ss") : ""
            }).ToList();
            return Json(new { total = restult.Count, rows = restult });
        }

        private string GetRoomNumberByIDs(string hostIDs)
        {
            string roomNumbers = "";
            foreach (string id in hostIDs.Split(','))
            {
                var item = HostManager.Get(Convert.ToInt32(id));
                if (item != null)
                {
                    roomNumbers += item.RoomNumber + ",";
                }
            }
            if (roomNumbers.Length > 0 && roomNumbers.LastIndexOf(",") == roomNumbers.Length - 1)
            {
                roomNumbers = roomNumbers.Substring(0, roomNumbers.Length - 1);
            }
            return roomNumbers;
        }
        /// <summary>
        /// 编辑定时
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult Edit(int? id)
        {
            HostTimingControl model = new HostTimingControl { ID = 0 };
            model.RoomCardTypeID = -1;
            if (id.HasValue && id != 0)
            {
                model = HostTimingControlManager.Get(id);
            }
            return View(model);
        }
        /// <summary>
        /// 保存新增、编辑定时
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult SaveRoomControrl(string jsonData)
        {
            var entity = Newtonsoft.Json.JsonConvert.DeserializeObject<HostTimingControl>(jsonData);
            
            if (entity.ID == 0)
            {
                entity.HotelID = CurrentHotelID;
                entity.ActiveIndicator = false;
                entity.ExecStatus = false;
                entity.ExecTime = Convert.ToDateTime("1999-01-01");
                HostTimingControlManager.Save(entity);
            }
            else
            {
                var timingEntity = HostTimingControlManager.Get(entity.ID);
                timingEntity.HotelID = CurrentHotelID;
                timingEntity.GroupID = entity.GroupID;
                timingEntity.RoomTypeID = entity.RoomTypeID;
                timingEntity.HostIDs = entity.HostIDs;
                timingEntity.RoomStatusID = entity.RoomStatusID;
                timingEntity.RoomCardTypeID = entity.RoomCardTypeID;
                timingEntity.RoomTypeSceneID = entity.RoomTypeSceneID;
                timingEntity.TimingType = entity.TimingType;
                timingEntity.TimingDay = entity.TimingDay;
                timingEntity.Timing = entity.Timing;
                timingEntity.ActiveIndicator = false;

                HostTimingControlManager.Update(timingEntity);
            }
            TestManager.Save(new Test() { MyName="nihao"});
            return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
        }
        /// <summary>
        /// 刪除定时记录
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult Delete(IList<int> idList)
        {
            HostTimingControlManager.Delete(idList.Cast<object>().ToList());
            return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("DeleteSuccess") });
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult SetActiveIndicator(IList<int> idList)
        {
            foreach (Int32 id in idList)
            {
                var item = HostTimingControlManager.Get(id);
                item.ActiveIndicator = !item.ActiveIndicator;
                HostTimingControlManager.Update(item);
            }
            return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
        }

        #endregion

        #region 编辑框下拉选择
        /// <summary>
        /// 当酒店楼层改变时房号改变
        /// </summary>
        /// <param name="groupID"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult loadRoomNumber(int groupID)
        {
            var roomNumber = HostManager.LoadAll().Where(r => r.Group.ID == groupID && r.SysHotel.ID == CurrentHotelID).ToList();
            var result = roomNumber.Select(r => new { 
                ID = r.ID,
                RoomNumber = r.RoomNumber
            }).ToList();
            return Json(result);
        }

        /// <summary>
        /// 房号
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadRoomNumberCombobox(int? roomTypeID)
        {
            var result = new List<object>();
            if (roomTypeID.HasValue && roomTypeID > 0)
            {
                //var currentUser = SysUserManager.Get(User.Identity.Name);//获取当前用户
                //var sysUserHotel = SysUserHotelManager.Get(currentUser.ID, CurrentHotelID);//获取当前用户所在酒店
                var currentGroup = GroupManager.LoadAll().FirstOrDefault(r => r.Parent == null && r.HotelID == CurrentHotelID); //Get(sysUserHotel != null ? sysUserHotel.GroupID : 0);//获取当前用户所在酒店的楼层

                DataTable table = HostManager.LoadRoomNumbers(currentGroup != null ? currentGroup : null, CurrentHotelID);

                foreach (DataRow row in table.Rows)
                {
                    if (Convert.ToInt16(row["RoomTypeID"]) == roomTypeID)
                    {
                        result.Add(new { ID = row["ID"], RoomNumber = row["RoomNumber"], GroupName = row["GroupName"], RoomTypeName = row["RoomTypeName"] });
                    }
                }
            }
            return Json(result);
        }
        /// <summary>
        /// 当前酒店场景
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadRoomTypeScene(int? roomTypeID)
        {
            var result = new List<object>();
            if (roomTypeID.HasValue && roomTypeID > 0)
            {
                var list = RoomTypeSceneManager.LoadAll().Where(r => r.HotelID == CurrentHotelID && r.RoomType.ID == roomTypeID).ToList();
                result = list.Select(r => new { r.ID, Name = ReturnNameByLanguage(r.Name, r.EnglishName, r.TWName) }).ToList<object>();
            }
            result.Insert(0, new { ID = 0, Name = HttpContext.InnerLanguage("Choice") });
            return Json(result);
        }
        /// <summary>
        /// 获取日期（星期几或几号）
        /// </summary>
        /// <param name="timeType"></param>
        /// <returns></returns>
        public ActionResult LoadTimeDay(int? timeType)
        {
            var result = new List<object>();
            switch (timeType)
            {
                case 1:
                    result.Add(new { ID = 0, Name = "日" });
                    result.Add(new { ID = 1, Name = "一" });
                    result.Add(new { ID = 2, Name = "二" });
                    result.Add(new { ID = 3, Name = "三" });
                    result.Add(new { ID = 4, Name = "四" });
                    result.Add(new { ID = 5, Name = "五" });
                    result.Add(new { ID = 6, Name = "六" });
                    break;
                case 2:
                    for (int i = 1; i < 32; i++)
                    {
                        result.Add(new { ID = i, Name = i.ToString() });
                    }
                    break;
                default:
                    result.Add(new { ID = 0, Name = HttpContext.InnerLanguage("EveryDay") });
                    break;
            }
            return Json(result);
        }
        /// <summary>
        /// 获取时间（时:分）
        /// </summary>
        /// <returns></returns>
        public ActionResult LoadTiming()
        {
            DateTime dt = Convert.ToDateTime("1999-01-01 00:00:00");
            var result = new List<object>();
            for (int i = 0; i < 96; i++)
            {
                result.Add(new { Value = dt.ToString("HH:mm") });
                dt = dt.AddMinutes(15);
            }

            return Json(result);
        }
        #endregion

        #region Private Methods

        private IList<Host> FindHosts(int? hostID, int? groupID, int? roomStatusID, int? roomTypeID)
        {
            IList<Host> hosts = new List<Host>();

            if (hostID.HasValue && hostID > 0)
            {
                var host = HostManager.Get(hostID.GetValueOrDefault());
                if (host != null)
                {
                    hosts.Add(host);
                }
            }
            else
            {
                IList<Group> groups = new List<Group>();
                if (groupID.HasValue)
                {
                    groups = GroupManager.GetGroupList(GroupManager.Get(groupID));
                }

                RoomStatus roomStatus = null;
                if (roomStatusID.HasValue)
                {
                    roomStatus = RoomStatusManager.Get(roomStatusID);
                }

                RoomType roomType = null;
                if (roomTypeID.HasValue)
                {
                    roomType = RoomTypeManager.Get(roomTypeID);
                }

                hosts = HostManager.LoadAll(groups, roomStatus, roomType);
            }

            return hosts;
        }

        #endregion
    }
}
