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

namespace WebSite.Controllers
{
    public class RoomServiceController : BaseController
    {
        private const int AuthorityID = 10;

        public IRoomServiceManager RoomServiceManager { get; set; }

        public IRoomServiceRecordManager RoomServiceRecordManager { get; set; }

        public IAlarmSettingManager AlarmSettingManager { get; set; }

        public IHostManager HostManager { get; set; }

        public IHostModalManager HostModalManager { get; set; }

        public ActionResult Index()
        {
            return View();
        }

        #region 服务记录

        /// <summary>
        /// 服务记录
        /// </summary>
        /// <returns></returns>
        public ActionResult ServiceRecords()
        {
            return View();
        }

        /// <summary>
        /// 加载服务记录
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadServiceRecords(int page, int rows, string order, string sort, string roomNumber, string startTime, string endTime, string alarmCodes)
        {
            Models.QueryConditionModel model = new Models.QueryConditionModel();
            model.Order = order;
            model.Sort = sort;
            model.RoomNumber = roomNumber;
            model.StartTime = startTime;
            model.EndTime = endTime;
            model.AlarmCodes = alarmCodes;

            Session["QueryConditionModel"] = model;

            long total = 0;

            string[] services = null;

            if (!String.IsNullOrWhiteSpace(alarmCodes))
            {
                services = alarmCodes.Split(',');
            }

            var list = RoomServiceRecordManager.LoadAllByPage(out total, page, rows, order, sort, roomNumber, startTime, endTime, services);

            //list = (IList<RoomServiceRecord>)list.Where(r => r.HostID == CurrentHotelID);

            var result = list.Select(r => new
            {
                r.RoomNumber,
                r.Name,
                r.StartTime,
                r.EndTime,
                Time = r.EndTime.HasValue ? (r.EndTime.Value - r.StartTime).TotalMinutes : (DateTime.Now - r.StartTime).TotalMinutes,
            });

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

        #endregion

        /// <summary>
        /// 获取当前服务信息
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadCurrentMsg()
        {
            var result = new List<object>();

            var table = RoomServiceManager.LoadCurrentRoomServicesCount(CurrentHotelID, this.User.Identity.Name);

            if (table != null)
            {
                foreach (System.Data.DataRow row in table.Rows)
                {
                    result.Add(new { Name = (bool)Session["isCN"] ? row["Name"] : row["EName"], Count = row["Number"] });
                }
            }

            return Json(new { IsSuccess = true, Data = result }, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 获取当前设备故障信息
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadCurrentHostFault()
        {
            IList<object> faults = new List<object>();
            //外设离线
            IList<object[]> list = RoomServiceManager.LoadCurrentHostFaultStatistics(CurrentHotelID, this.User.Identity.Name, 1);
            foreach (object obj in list)
            {
                faults.Add(new { RoomNumber = Convert.ToString(((object[])(obj))[0]), Name = HttpContext.InnerLanguage("PeripheralOffline") });
            }
            //外设低电
            list = RoomServiceManager.LoadCurrentHostFaultStatistics(CurrentHotelID, this.User.Identity.Name, 2);
            foreach (object obj in list)
            {
                faults.Add(new { RoomNumber = Convert.ToString(((object[])(obj))[0]), Name = HttpContext.InnerLanguage("PeripheralLowPower") });
            }

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

        //[Authorize]
        //public ActionResult LoadDeviceFault()
        //{
        //    IList<object[]> list = RoomServiceManager.LoadCurrentHostFaultStatistics(CurrentHotelID, this.User.Identity.Name);
        //    var result = list.Select(r => new
        //    {
        //        RoomNumber = r[0]
        //    }).ToList();
        //    return Json(new { total = result.Count, rows = result });
        //}
        /// <summary>
        /// 加载当前请求的服务
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadCurrentRoomServices()
        {
            IList<object[]> list = RoomServiceManager.LoadCurrentRoomServices(CurrentHotelID, this.User.Identity.Name);
            var result = list.Select(r => new TempLinShiClass()
            {
                HostID = r[0].ToString(),
                RoomTypeModalID = r[1].ToString(),
                RoomNumber = r[2].ToString(),
                Name = ReturnNameByLanguage(r[3].ToString(), r[4].ToString(), r[6].ToString()), //(bool)Session["isCN"] ? r[3] : r[4],
                Time = r[5],
                HostNumber = r[7].ToString(),
                ModalAddress = r[8].ToString()
            }).ToList();

            foreach (var item in result)
            {
                if (item.Time == null)
                {
                    string KKey = CacheKey.HostModalStatus_Prefix + "_" + item.HostID + "_" + item.ModalAddress;
                    var hostModal = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(KKey);
                    if (hostModal != null)
                    {
                        HostModal_Cache hhh = hostModal as HostModal_Cache;
                        item.Time = hhh.UpdateTime;
                    }
                }
            }
            return Json(new { total = result.Count, rows = result });
        }

        /// <summary>
        /// 加载当前客房异常
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadCurrentRoomAbnormities()
        {
            IList<object[]> list = RoomServiceManager.LoadCurrentRoomAbnormities(CurrentHotelID, User.Identity.Name);

            var result = list.Select(r => new { ID = r[0], Name = (bool)Session["isCN"] ? r[1] : r[4], RoomNumber = r[2], Time = r[3] }).ToList();

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

        [Authorize]
        public ActionResult LoadServicesForCombobox()
        {
            //var list = AlarmSettingManager.LoadAll()
            //                            .Where(r => r.HotelID == CurrentHotelID && r.Type == 'B')
            //                            .OrderBy(o => o.Sort)
            //                            .Select(s => new { Name = (Language == Language.CN) ? s.Name : s.EName, s.Code, s.Color })
            //                            .ToList();

            IList<object> services = new List<object>();
            var table = RoomServiceManager.LoadCurrentRoomServicesCount(CurrentHotelID, this.User.Identity.Name);
            if (table != null)
            {
                foreach (System.Data.DataRow row in table.Rows)
                {
                    services.Add(new
                    {
                        Code = row["Code"],
                        Name = ReturnNameByLanguage(row["Name"].ToString(), row["EName"].ToString(), row["TWName"].ToString()),// (bool)Session["isCN"] ? row["Name"] : row["EName"],
                        Color = row["Color"]
                    });
                }
            }
            services.Insert(0, new { Name = HttpContext.InnerLanguage("Service"), Code = "", Color = "#FFFFFF" });
            return Json(services);
        }

        /// <summary>
        /// 清除服务
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult ClearRoomService(long id, string roomNumber, string name)
        {
            try
            {
                var host = HostManager.GetByRoomNumber(roomNumber, CurrentHotelID);
                if (host == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidRoom"));
                }

                var service = RoomServiceManager.Get(id);
                if (service == null)
                {
                    throw new ApplicationException(HttpContext.InnerLanguage("InvalidService"));
                }

                RoomServiceManager.ClearRoomService(host, service, User.Identity.Name);

                // 清除相连通主机的服务
                //if (host.IsConnectingRoom)
                //{
                //    var hostList = HostManager.GetConnectRoomHosts(host);

                //    foreach (var item in hostList)
                //    {
                //        var service1 = RoomServiceManager.Get(host.ID, service.AlarmCode);
                //        RoomServiceManager.ClearRoomService(item, service1, User.Identity.Name);
                //    }
                //}

                SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("CleanupServices"), name);

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


        public ActionResult ExportExcel()
        {
            try
            {

                NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();

                NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");

                sheet1.SetColumnWidth(0, 10 * 256);
                sheet1.SetColumnWidth(1, 20 * 256);
                sheet1.SetColumnWidth(2, 20 * 256);
                sheet1.SetColumnWidth(3, 20 * 256);

                NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
                row1.CreateCell(0).SetCellValue(HttpContext.InnerLanguage("RoomNumber"));
                row1.CreateCell(1).SetCellValue(HttpContext.InnerLanguage("ServiceType"));
                row1.CreateCell(2).SetCellValue(HttpContext.InnerLanguage("StartDate"));
                row1.CreateCell(3).SetCellValue(HttpContext.InnerLanguage("Deadline"));
                row1.CreateCell(4).SetCellValue(HttpContext.InnerLanguage("TotalTime"));

                Models.QueryConditionModel model = Session["QueryConditionModel"] as Models.QueryConditionModel;
                //var list = Session["ServiceList"] as IList<RoomServiceRecord>;

                long total = 0;
                string[] services = null;
                if (!String.IsNullOrWhiteSpace(model.AlarmCodes))
                {
                    services = model.AlarmCodes.Split(',');
                }

                var list = RoomServiceRecordManager.LoadAllByPage(out total, 1, 10000, model.Order, model.Sort, model.RoomNumber,
                    model.StartTime, model.EndTime, services);

                list = (IList<RoomServiceRecord>)list.Where(r => r.HostID == CurrentHotelID);

                if (list != null)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        NPOI.SS.UserModel.IRow row = sheet1.CreateRow(i + 1);
                        row.CreateCell(0).SetCellValue(list[i].RoomNumber);
                        row.CreateCell(1).SetCellValue(list[i].Name);
                        row.CreateCell(2).SetCellValue(list[i].StartTime.ToString("yyyy-MM-dd HH:mm:ss"));
                        row.CreateCell(3).SetCellValue(list[i].EndTime.HasValue ? list[i].EndTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "");
                        Double totalMinutes = list[i].EndTime.HasValue ? (list[i].EndTime.Value - list[i].StartTime).TotalMinutes : (DateTime.Now - list[i].StartTime).TotalMinutes;
                        row.CreateCell(4).SetCellValue(Math.Floor(totalMinutes / 60) + HttpContext.InnerLanguage("Hour") + Math.Ceiling(totalMinutes % 60) + HttpContext.InnerLanguage("Minute"));
                    }
                }

                using (MemoryStream stream = new MemoryStream())
                {
                    book.Write(stream);
                    stream.Seek(0, SeekOrigin.Begin);

                    string filename = Common.Tools.ToUtf8String(HttpContext.InnerLanguage("ServiceQuery") + ".xls");

                    return File(stream, "application/vnd.ms-excel", filename);
                }
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("Export") + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
    }
    public class TempLinShiClass
    {
        public string HostID;
        public string RoomTypeModalID;
        public string RoomNumber;
        public string Name;
        public object Time;
        public string HostNumber { get; set; }
        public string ModalAddress { get; set; }
    }
}
