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

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

        private const int AUTHORITY_HostRoomCard = 1004;

		public IHostRoomCardManager HostRoomCardManager { get; set; }

        public IRoomCardManager RoomCardManager { get; set; }

        public IRoomCardTypeManager RoomCardTypeManager { get; set; }

        public ISysUserManager SysUserManager { get; set; }

        public ActionResult Index()
        {
            ViewData["EnableDelData"] = SysUserManager.HasAuthority(User.Identity.Name, AUTHORITY_HostRoomCard);
			#if SIMON
			return View("SimonIndex");
			#else
            return View();
			#endif
        }

        /// <summary>
        /// 加载刷卡记录数据
        /// </summary>
        /// <param name="roomNumber"></param>
        /// <param name="userName"></param>
        /// <param name="cardNumber"></param>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="order"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        public ActionResult LoadAllByPage(int page, int rows, string order, string sort, string roomNumber = "", string cardTypeID = "", string cardNumber = "", string startDate = "", string endDate = "")
        {
            long total = 0;

            var lists = HostRoomCardManager.LoadAllByPage(out total, page, rows, order, sort, CurrentHotelID, roomNumber, 
                Convert.ToInt16(cardTypeID), cardNumber, "", Convert.ToDateTime(startDate), Convert.ToDateTime(endDate));

            var result = lists.Select(r => new
            {
                r.ID,
                r.RoomNumber,
                CardType = ReturnNameByLanguage(r.CardType.Name, r.CardType.EName, r.CardType.TWName),
                r.CardNumber,
                r.UserNumber,
                r.UserName,
                InCardTime = Convert.ToDateTime(r.InCardTime).ToString("yyyy-MM-dd HH:mm:ss"),
                OutCardTime = Convert.ToDateTime(r.OutCardTime).ToString("yyyy-MM-dd HH:mm:ss"),
                r.Duration

            }).ToList<object>();

            //var table = HostRoomCardManager.LoadHostRoomCard(out total, page, rows, order, sort, CurrentHotelID, CardType, RoomNumber, UserName, CardNumber, StartDate, EndDate);
            //IList<object> services = new List<object>();
            //if (lists != null)
            //{
            //    foreach (System.Data.DataRow row in table.Rows)
            //    {
            //        services.Add(new
            //        {
            //            ID = row[0],
            //            RoomNumber = row[1],
            //            CardNumber = row[2],
            //            CardType = ReturnNameByLanguage(row[3].ToString(), row[4].ToString(), row[5].ToString()),
            //            UserNumber = row[6],
            //            UserName = row[7],
            //            InCardTime = Convert.ToDateTime(row[8]).ToString("yyyy-MM-dd HH:mm:ss"),
            //            OutCardTime = Convert.ToDateTime(row[9]).ToString("yyyy-MM-dd HH:mm:ss"),
            //            Duration = row[10]
            //        });
            //    }
            //}
            return Json(new { total = total, rows = result }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 删除多条数据
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult Delete(IList<long> idList)
        {
            HostRoomCardManager.Delete(idList.Cast<object>().ToList());
            SaveSystemLog(AUTHORITY_HostRoomCard, HttpContext.InnerLanguage("Delete"), "【" + String.Join(",", CurrentHotelID) + "】");
            return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("DeleteSuccess") });
        }

        /// <summary>
        /// 清空数据
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult DeleteAll()
        {
            HostRoomCardManager.DeleteAll(CurrentHotelID);
            SaveSystemLog(AUTHORITY_HostRoomCard, HttpContext.InnerLanguage("Delete"), "【" + String.Join(",", CurrentHotelID) + "】");
            return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("EmptySuccess") });
        }

        /// <summary>
        ///导出刷卡记录信息 
        /// </summary>
        /// <param name="roomNumber"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
		[Authorize]
        public ActionResult Export(string roomNumber, string userName)
		{
            var list = HostRoomCardManager.LoadAll(CurrentHotelID, roomNumber, userName);

			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, 10 * 256);
			sheet1.SetColumnWidth(2, 10 * 256);
			sheet1.SetColumnWidth(3, 10 * 256);
			sheet1.SetColumnWidth(4, 10 * 256);
			sheet1.SetColumnWidth(5, 20 * 256);
			sheet1.SetColumnWidth(6, 20 * 256);
			sheet1.SetColumnWidth(7, 10 * 256);

			NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
            row1.CreateCell(0).SetCellValue(HttpContext.InnerLanguage("RoomNumber"));
            row1.CreateCell(1).SetCellValue(HttpContext.InnerLanguage("CardNumber"));
			row1.CreateCell(2).SetCellValue(HttpContext.InnerLanguage("CardType"));
			row1.CreateCell(3).SetCellValue(HttpContext.InnerLanguage("UserNumber"));
			row1.CreateCell(4).SetCellValue(HttpContext.InnerLanguage("UserName"));
			row1.CreateCell(5).SetCellValue(HttpContext.InnerLanguage("InCardTime"));
			row1.CreateCell(6).SetCellValue(HttpContext.InnerLanguage("OutCardTime"));
            row1.CreateCell(7).SetCellValue(HttpContext.InnerLanguage("DurationMinute"));

			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].CardNumber);
				row.CreateCell(2).SetCellValue(list[i].CardType != null ? list[i].CardType.Name : "");
				row.CreateCell(3).SetCellValue(list[i].UserNumber);
				row.CreateCell(4).SetCellValue(list[i].UserName);
				row.CreateCell(5).SetCellValue(list[i].InCardTime.Value.ToString("yyyy-MM-dd HH:mm:ss"));
				row.CreateCell(6).SetCellValue(list[i].OutCardTime.HasValue ? list[i].OutCardTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "");
				row.CreateCell(7).SetCellValue(list[i].Duration);
			}

            using (MemoryStream stream = new MemoryStream())
            {
                book.Write(stream);
                stream.Seek(0, SeekOrigin.Begin);
                return File(stream, "application/vnd.ms-excel", "刷卡记录.xls");
            }
        }

        #region 加载控件数据
        /// <summary>
        /// 房卡类型
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadDataForCardTypeCombobox()
        {
            var cardType = RoomCardTypeManager.LoadAll();
            var result = cardType.Select(r => new { r.ID, CardType = ReturnNameByLanguage(r.Name,r.EName,r.TWName) }).ToList<object>();
            result.Insert(0, new { ID = -1, CardType = HttpContext.InnerLanguage("Choice") });
            return Json(result);
        }
        /// <summary>
        /// 房卡编号
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadDataForCardNumberCombobox()
        {
            var cardNumber = RoomCardManager.LoadAll().Where(r => r.HotelID == CurrentHotelID && r.RoomCardType != null).ToList();
            var result = cardNumber.Select(r => new
            {
                r.ID,
                CardNumber = r.CardNumber,
                Name = r.CardNumber + "(" + ReturnNameByLanguage(r.RoomCardType.Name, r.RoomCardType.EName, r.RoomCardType.TWName) + "|" + r.UserName + ")"
            }).ToList<object>();

            result.Insert(0, new { ID = 0, CardNumber = "", Name = HttpContext.InnerLanguage("CheckAll") });

            return Json(result);
        }
        /// <summary>
        /// 员工姓名
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult LoadDataForUserNameCombobox()
        {
            var userName = RoomCardManager.LoadAll().Where(r => r.HotelID == CurrentHotelID).ToList();
            var result = userName.Select(r => new { r.ID, UserName = r.UserName }).ToList<object>();
            result.Insert(0, new { ID = 0, UserName = HttpContext.InnerLanguage("CheckAll") });
            return Json(result);
        }
        #endregion
    }
}
