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

namespace WebSite.Controllers
{
    public class FaultTypeController : BaseController
    {
		private const int AuthorityID = 22;

		public IFaultTypeManager FaultTypeManager { get; set; }

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

		/// <summary>
		/// 维修登记页面
		/// </summary>
		/// <returns></returns>
		public ActionResult RepairRecord()
		{
			return View();
		}

		[Authorize]
		public ActionResult LoadAllForCombobox()
		{
			return Json(FaultTypeManager.LoadAll().Select(r => new { r.ID, r.Code, r.Name }).ToList());
		}

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

            var list = FaultTypeManager.LoadAllByPage(out total, page, rows, order, sort, CurrentHotelID);

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

		[Authorize]
		public ActionResult Save(string jsonData)
		{
			FaultType entity = Newtonsoft.Json.JsonConvert.DeserializeObject<FaultType>(jsonData);

			FaultType existFaultType = FaultTypeManager.Get(entity.Code);

			if (existFaultType != null)
			{
				if (entity.ID == 0 || entity.ID != existFaultType.ID)
				{
                    return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("FaultID") + "【" + entity.Code + "】" + HttpContext.InnerLanguage("AlreadyExist") });
				}
			}

			if (entity.ID == 0)
			{
                entity.HotelID = CurrentHotelID;
				FaultTypeManager.Save(entity);
                SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("New"), String.Format(HttpContext.InnerLanguage("FaultID") + "：{0}，" + HttpContext.InnerLanguage("FaultType") + "：{1}。", entity.Code, entity.Name));
			}
			else
			{
				FaultType faultType = FaultTypeManager.Get(entity.ID);
				faultType.Code = entity.Code;
				faultType.Name = entity.Name;
				faultType.Remark = entity.Remark;
                faultType.HotelID = CurrentHotelID;

				FaultTypeManager.Update(faultType);
                SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("Edit"), String.Format(HttpContext.InnerLanguage("FaultID") + "：{0}，" + HttpContext.InnerLanguage("FaultType") + "：{1}。", entity.Code, entity.Name));
			}

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

		[Authorize]
		public ActionResult Delete(IList<int> idList, IList<string> nameList)
		{
			try
			{
                SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("Delete"), String.Join(",", nameList.ToArray()));

				FaultTypeManager.Delete(idList.Cast<object>().ToList());

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

