using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Domain;
using Service;
using System;
using System.IO;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using CommonEntity;
using Common;
using WebSite.Models;
using RestSharp;
using System.Configuration;

namespace WebSite.Controllers
{
    public class SysHotelController : BaseController
    {
        private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(SysHotelController));
        private const int AuthorityID = 54;
        /// <summary>
        /// 酒店编辑权限ID
        /// </summary>
        private const int AUTHORITY_EditHotel = 1005;

        public ISysHotelManager SysHotelManager { get; set; }
        public IGroupManager GroupManager { get; set; }
        public IAlarmSettingManager AlarmSettingManager { get; set; }
        public IAppMenuManager AppMenuManager { get; set; }
        public IRoomTypeManager RoomTypeManager { get; set; }
        public ISysHotelGroupManager SysHotelGroupManager { get; set; }
        public ISysUserManager SysUserManager { get; set; }
        public ISysProvinceManager SysProvinceManager { get; set; }
        public IHostManager HostManager { get; set; }

        /// <summary>
        /// 空调ECO
        /// 
        /// 阿宝添加的
        /// </summary>
        public IECO_SettingMananger Air_ECO_SettingManager { get; set; }
        public IECO_RoomDetailManager RoomDetailManager { get; set; }
        public ILieECOMananger LieECOManager { get; set; }

        public ActionResult Index()
        {
            ViewData["EditHotel"] = SysUserManager.HasAuthority(User.Identity.Name, AUTHORITY_EditHotel);
            return View();
        }

        public ActionResult Edit(int? id)
        {
            ViewData["IsApprove"] = false;
            switch (User.Identity.Name.ToLower())
            {
                case "admin":
                case "leo":
                case "blw":
                    ViewData["IsApprove"] = true;
                    break;
            }
            if (id.HasValue)
            {
                return View(SysHotelManager.Get(id.Value));
            }
            var lastHotel = SysHotelManager.LoadAll().OrderByDescending(r => r.Code).FirstOrDefault();
            int code = Convert.ToInt16(lastHotel.Code) + 1;
            return View(new SysHotel { ID = 0, Code = code.ToString(), Sort = code, Styles = "0", ValidateDate = DateTime.Now.AddYears(1).AddMonths(4), Status = 2, IsApprove = false });
        }

        public ActionResult EditDockingInfo()
        {
            var q = SysHotelManager.Get(CurrentHotelID);
            return View(q);
        }

        public ActionResult LoadAll()
        {
            var list = SysHotelManager.LoadAll().OrderBy(o => o.Sort).ToList();
            var result = list.Select(r => new { r.ID, Name = r.Code + "-" + ReturnNameByLanguage(r.Name, r.EName, r.TWName), r.Code }).ToList();
            //result.Insert(0, new { ID = 0, Name = HttpContext.InnerLanguage("All") });
            return Json(result);
        }

        [Authorize]
        public ActionResult LoadAllByPage(int page, int rows, string order, string sort, string query, int? groupId)
        {
            if (groupId.HasValue)
            {
                long total = 0;
                IList<SysHotel> list = this.SysHotelManager.LoadAllByPage(out total, page, rows, order, sort, query, groupId);
                IList<SysProvince> province = SysProvinceManager.LoadAll();
                IList<SysCity> city = SysProvinceManager.LoadAllCity();
                IList<SysCounty> county = SysProvinceManager.LoadAllCounty();
                foreach (SysHotel hotel in list)
                {
                    hotel.SysHotelGroupName = hotel.SysHotelGroup == null ? "" : hotel.SysHotelGroup.Name;
                    if (!string.IsNullOrEmpty(hotel.ProvinceCode))
                    {
                        hotel.Address = province.Where(r => r.Code == hotel.ProvinceCode).FirstOrDefault().Name +
                            city.Where(r => r.Code == hotel.CityCode).FirstOrDefault().Name +
                            county.Where(r => r.Code == hotel.CountyCode).FirstOrDefault().Name + hotel.Address;
                    }
                }
                return Json(new { total = total, rows = list });
            }
            else
            {
                return Json(new { total = 0, rows = new List<object>() });
            }
        }

        [Authorize]
        public ActionResult Save(string jsonData)
        {
            var entity = Newtonsoft.Json.JsonConvert.DeserializeObject<SysHotel>(jsonData);
            var existCode = SysHotelManager.GetByCode(entity.Code);
            if (entity.ID == 0 && existCode != null)//如果新增酒店，并且code已存在，则自动取最新的酒店code+1
            {
                var lastHotel = SysHotelManager.LoadAll().OrderByDescending(r => r.Code).FirstOrDefault();
                entity.Sort = Convert.ToInt16(lastHotel.Code) + 1;
                entity.Code = entity.Sort.ToString();
            }
            string action = HttpContext.InnerLanguage("New");
            if (entity.ID == 0)
            {
                entity.ParentID = 0;
                entity.ActiveIndicator = true;
                entity.CreatedBy = entity.ModifiedBy = this.User.Identity.Name;
                entity.CreatedDate = entity.ModifiedDate = DateTime.Now;
                entity.LogoPath = "../Uploads/logo/1001.png";
                SysHotelManager.Save(entity);
            }
            else
            {
                var sysHotel = SysHotelManager.Get(entity.ID);
                sysHotel.Code = entity.Code;
                sysHotel.Name = entity.Name;
                sysHotel.EName = entity.EName;
                sysHotel.TWName = entity.TWName;
                sysHotel.Contact = entity.Contact;
                sysHotel.Phone = entity.Phone;
                sysHotel.Address = entity.Address;
                //sysHotel.AssociatedAccount = entity.AssociatedAccount;
                //sysHotel.Styles = entity.Styles;
                sysHotel.Sort = entity.Sort;
                sysHotel.ModifiedBy = this.User.Identity.Name;
                sysHotel.ModifiedDate = DateTime.Now;
                //sysHotel.IsAutoGetKey = entity.IsAutoGetKey;
                //sysHotel.WelcomeSpeech = entity.WelcomeSpeech;
                //sysHotel.GoodbyeSpeech = entity.GoodbyeSpeech;
                //sysHotel.DomainUrl = entity.DomainUrl;
                sysHotel.ValidateDate = entity.ValidateDate;
                //sysHotel.TVControlToken = entity.TVControlToken;
                //sysHotel.TVControlUrl = entity.TVControlUrl;
                //sysHotel.IsSyncPMS = entity.IsSyncPMS;
                //sysHotel.DeviceStatusPushURL = entity.DeviceStatusPushURL;
                sysHotel.SysHotelGroup = entity.SysHotelGroup;
                sysHotel.ProvinceCode = entity.ProvinceCode;
                sysHotel.CityCode = entity.CityCode;
                sysHotel.CountyCode = entity.CountyCode;
                sysHotel.Remark = entity.Remark;
                sysHotel.Status = entity.Status;
                sysHotel.IsApprove = entity.IsApprove;

                SysHotelManager.Update(sysHotel);
                action = HttpContext.InnerLanguage("Edit");
            }
            SaveSystemLog(AuthorityID, action, entity.Name);
            return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
        }


        /// <summary>
        /// 上传BGM
        /// </summary>
        /// <returns></returns>
        [Authorize()]
        public ActionResult UploadWebcomeBGM()
        {
            try
            {
                var sysHotel = SysHotelManager.Get(CurrentHotelID);

                HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;

                if (hfc.Count < 1 || hfc[0].ContentLength <= 0 || String.IsNullOrEmpty(hfc[0].FileName))
                {
                    return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("PleaseSelectAuthorizationFile") });
                }
                string start_timeddd = DateTime.Now.ToString("yyyyMMddHHmmss");
                string NewFileName = start_timeddd + hfc[0].FileName;
                string file = string.Format(Tools.GetApplicationPath() + @"welcomebgm\{0}", NewFileName);
                string path = Path.GetDirectoryName(file);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                hfc[0].SaveAs(file);

                var LLL = HostManager.LoadAll(CurrentHotelID);
                foreach (Host item in LLL)
                {
                    Host TakeOut = null;
                    string HostNumberOnly = item.HostNumber;
                    string Key = CacheKey.HostInfo_Key_HostNumber + "_" + HostNumberOnly;
                    object obj = MemoryCacheHelper.Get(Key);
                    if (obj != null)
                    {
                        TakeOut = obj as Host;
                        TakeOut.SysHotel.WelcomeBGM = NewFileName;
                    }
                }

                sysHotel.WelcomeBGM = NewFileName;

                SysHotelManager.Update(sysHotel);
                return Json(new { IsSuccess = true, FileName = NewFileName }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                if (logger.IsErrorEnabled)
                {
                    logger.Error(ex);
                }

                return Json(new { IsSuccess = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
            }

        }



        [Authorize()]
        public ActionResult DeleteBGM()
        {
            try
            {
                var sysHotel = SysHotelManager.Get(CurrentHotelID);
                string vvv = sysHotel.WelcomeBGM;
                sysHotel.WelcomeBGM = "";

                string file = string.Format(Tools.GetApplicationPath() + @"welcomebgm\{0}", vvv);
                string path = Path.GetDirectoryName(file);
                if (Directory.Exists(path))
                {
                    System.IO.File.Delete(path);
                }

                SysHotelManager.Update(sysHotel);
                return Json(new { IsSuccess = true }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
            }

        }
        /// <summary>
        /// 保存第三方对接信息
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult SaveDockingInfo(string jsonData)
        {
            var entity = Newtonsoft.Json.JsonConvert.DeserializeObject<SysHotel>(jsonData);
            var sysHotel = SysHotelManager.Get(entity.ID);
            sysHotel.IsAutoGetKey = entity.IsAutoGetKey;
            sysHotel.WelcomeSpeech = entity.WelcomeSpeech;
            sysHotel.GoodbyeSpeech = entity.GoodbyeSpeech;
            sysHotel.TVControlToken = entity.TVControlToken;
            sysHotel.TVControlUrl = entity.TVControlUrl;
            sysHotel.DeviceStatusPushURL = entity.DeviceStatusPushURL;
            sysHotel.FaultPushURL = entity.FaultPushURL;
            sysHotel.IsVoincePowerOn = entity.IsVoincePowerOn;//语音取电控制
            sysHotel.IsPowerOffResetXiaoDu = entity.IsPowerOffResetXiaoDu;//断电重置小度
            sysHotel.FCSPushEnable = entity.FCSPushEnable;
            sysHotel.IsNewVersionProtocol = entity.IsNewVersionProtocol;

            sysHotel.FCS_PropertyID = entity.FCS_PropertyID;
            sysHotel.FCSLoginUrl = entity.FCSLoginUrl;
            sysHotel.FCSLoginUserName = entity.FCSLoginUserName;
            sysHotel.FCSLoginPassWord = entity.FCSLoginPassWord;

            sysHotel.FCS_Carbon_UUID = entity.FCS_Carbon_UUID;
            sysHotel.FCS_SOS_UUID = entity.FCS_SOS_UUID;
            sysHotel.FCS_TouSu_UUID = entity.FCS_TouSu_UUID;
            sysHotel.FCS_Clean_UUID = entity.FCS_Clean_UUID;
            sysHotel.FCS_TiSongWuPin = entity.FCS_TiSongWuPin;
            sysHotel.FCS_RCU_Device_Offline = entity.FCS_RCU_Device_Offline;
            sysHotel.FCS_RCU_Offline = entity.FCS_RCU_Offline;
            sysHotel.FCS_RCU_Online = entity.FCS_RCU_Online;
            sysHotel.FCS_MenCi_Close = entity.FCS_MenCi_Close;
            sysHotel.FCS_MenCi_Open = entity.FCS_MenCi_Open;


            sysHotel.IsUseSkyworthTV = entity.IsUseSkyworthTV;
            sysHotel.IsUseTCLTV = entity.IsUseTCLTV;
            sysHotel.SkyworthTVauthCode = entity.SkyworthTVauthCode;
            sysHotel.TouSuResponseData = entity.TouSuResponseData;
            sysHotel.IsUseQianLiMa = entity.IsUseQianLiMa;
            sysHotel.IsPushPMSData = entity.IsPushPMSData;
            sysHotel.HeTongNumber = entity.HeTongNumber;
            sysHotel.ETV_HotelID = entity.ETV_HotelID;
            sysHotel.SwitchRoomStatus_PowerOff2 = entity.SwitchRoomStatus_PowerOff2;
            sysHotel.SwitchRoomStatus_PowerOff4 = entity.SwitchRoomStatus_PowerOff4;
            sysHotel.SwitchRoomStatus_PowerOff8 = entity.SwitchRoomStatus_PowerOff8;
            sysHotel.SwitchRoomStatus_PowerOff16 = entity.SwitchRoomStatus_PowerOff16;
            //sysHotel.TCLAppId = entity.TCLAppId;
            //sysHotel.TCLAppSecret = entity.TCLAppSecret;
            SysHotelManager.Update(sysHotel);

            //if (!string.IsNullOrEmpty(entity.WelcomeBGM))
            //{
            //    //string hotelid111=entity. .Split('&')[0], 
            //    //string  RoomNo = cuid.Split('&')[1];
            //    string ffg = "https://www.boonlive-rcu.com/welcomebgm/" + entity.WelcomeBGM;
            //    TianMaoOperation.PostWebRequestToTianMao("AddOrUpdateWelcomeText",
            //                                       Newtonsoft.Json.JsonConvert.SerializeObject(new { HotelId = CurrentHotelID, MusicUrl = ffg, WelcomeText = entity.WelcomeSpeech }), CurrentHotelCode, "");//通知天猫精灵播放欢迎词
            //}
            if (sysHotel.IsUseQianLiMa)
            {
                QianLiMa_PMS.QiYong(sysHotel.Code, "add");
            }
            else
            {
                QianLiMa_PMS.QiYong(sysHotel.Code, "remove");
            }

            //推送数据到PMS
            if (sysHotel.IsPushPMSData)
            {
                ServiceReference1.blwwsSoapClient b = new ServiceReference1.blwwsSoapClient();
                b.PushBaoJing_IsEnable("7e533rU:#3721M7%", sysHotel.Code, true);
            }
            else
            {
                ServiceReference1.blwwsSoapClient b = new ServiceReference1.blwwsSoapClient();
                b.PushBaoJing_IsEnable("7e533rU:#3721M7%", sysHotel.Code, false);
            }

            try
            {
                string code = sysHotel.Code;
                var LLL = HostManager.LoadAll(code);
                foreach (Host item in LLL)
                {
                    Host TakeOut = null;
                    string HostNumberOnly = item.HostNumber;
                    string XiaoDuKongZhiKey = CacheKey.XiaoDuYuYin + "_" + item.XiaoDuCUID;
                    HttpContext.Cache.Remove(XiaoDuKongZhiKey);
                    string Key = CacheKey.HostInfo_Key_HostNumber + "_" + HostNumberOnly;
                    object obj = MemoryCacheHelper.Get(Key);
                    if (obj != null)
                    {
                        TakeOut = obj as Host;
                        TakeOut.SysHotel.WelcomeSpeech = entity.WelcomeSpeech;
                        TakeOut.SysHotel.IsAutoGetKey = entity.IsAutoGetKey;
                        TakeOut.SysHotel.WelcomeSpeech = entity.WelcomeSpeech;
                        TakeOut.SysHotel.GoodbyeSpeech = entity.GoodbyeSpeech;
                        TakeOut.SysHotel.TVControlToken = entity.TVControlToken;
                        TakeOut.SysHotel.TVControlUrl = entity.TVControlUrl;
                        TakeOut.SysHotel.DeviceStatusPushURL = entity.DeviceStatusPushURL;
                        TakeOut.SysHotel.FaultPushURL = entity.FaultPushURL;
                        TakeOut.SysHotel.IsVoincePowerOn = entity.IsVoincePowerOn;//语音取电控制
                        TakeOut.SysHotel.IsPowerOffResetXiaoDu = entity.IsPowerOffResetXiaoDu;//断电重置小度
                        TakeOut.SysHotel.FCSPushEnable = entity.FCSPushEnable;//断电重置小度
                        TakeOut.SysHotel.IsNewVersionProtocol = entity.IsNewVersionProtocol;


                        TakeOut.SysHotel.FCS_PropertyID = entity.FCS_PropertyID;
                        TakeOut.SysHotel.FCSLoginUrl = entity.FCSLoginUrl;
                        TakeOut.SysHotel.FCSLoginUserName = entity.FCSLoginUserName;
                        TakeOut.SysHotel.FCSLoginPassWord = entity.FCSLoginPassWord;

                        TakeOut.SysHotel.FCS_Carbon_UUID = entity.FCS_Carbon_UUID;
                        TakeOut.SysHotel.FCS_SOS_UUID = entity.FCS_SOS_UUID;
                        TakeOut.SysHotel.FCS_TouSu_UUID = entity.FCS_TouSu_UUID;
                        TakeOut.SysHotel.FCS_Clean_UUID = entity.FCS_Clean_UUID;
                        TakeOut.SysHotel.FCS_TiSongWuPin = entity.FCS_TiSongWuPin;
                        TakeOut.SysHotel.FCS_RCU_Device_Offline = entity.FCS_RCU_Device_Offline;
                        TakeOut.SysHotel.FCS_RCU_Offline = entity.FCS_RCU_Offline;
                        TakeOut.SysHotel.FCS_RCU_Online = entity.FCS_RCU_Online;
                        TakeOut.SysHotel.FCS_MenCi_Close = entity.FCS_MenCi_Close;
                        TakeOut.SysHotel.FCS_MenCi_Open = entity.FCS_MenCi_Open;

                        TakeOut.SysHotel.IsUseSkyworthTV = entity.IsUseSkyworthTV;//断电重置小度
                        TakeOut.SysHotel.IsUseTCLTV = entity.IsUseTCLTV;//断电重置小度
                        TakeOut.SysHotel.SkyworthTVauthCode = entity.SkyworthTVauthCode;//断电重置小度
                        TakeOut.SysHotel.TouSuResponseData = entity.TouSuResponseData; //投诉反馈语音
                        TakeOut.SysHotel.IsUseQianLiMa = entity.IsUseQianLiMa;//断电重置小度
                        TakeOut.SysHotel.IsPushPMSData = entity.IsPushPMSData;
                        TakeOut.SysHotel.HeTongNumber = entity.HeTongNumber;
                        TakeOut.SysHotel.ETV_HotelID = entity.ETV_HotelID;


                        TakeOut.SysHotel.SwitchRoomStatus_PowerOff2 = entity.SwitchRoomStatus_PowerOff2;
                        TakeOut.SysHotel.SwitchRoomStatus_PowerOff4 = entity.SwitchRoomStatus_PowerOff4;
                        TakeOut.SysHotel.SwitchRoomStatus_PowerOff8 = entity.SwitchRoomStatus_PowerOff8;
                        TakeOut.SysHotel.SwitchRoomStatus_PowerOff16 = entity.SwitchRoomStatus_PowerOff16;
                        //TakeOut.SysHotel.TCLAppId = entity.TCLAppId;
                        //TakeOut.SysHotel.TCLAppSecret = entity.TCLAppSecret;

                    }
                }
            }
            catch (Exception)
            {

            }
            SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("Edit"), entity.Name + "：第三方对接信息");
            return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
        }
        /// <summary>
        /// 保存上下午时间，并下发给本酒店下所有主机
        /// </summary>
        /// <param name="morningTime"></param>
        /// <param name="afternoonTime"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult SaveHotelTime(int morningTime, int afternoonTime)
        {
            var sysHotel = SysHotelManager.Get(CurrentHotelID);
            sysHotel.StartDayTime = morningTime;
            sysHotel.EndDayTime = afternoonTime;
            SysHotelManager.UpdateDayTime(sysHotel);
            SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("Edit"), sysHotel.Name + "：白天时间信息");
            return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
        }

        /// <summary>
        /// 空调节能模式
        /// </summary>
        /// <param name="morningTime"></param>
        /// <param name="afternoonTime"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult SaveAirConditionECO(int id, string StartTime, string EndTime, string Action, string TempVal, bool IsEnable)
        {
            var sysHotel = SysHotelManager.Get(CurrentHotelID);
            ECO_Setting se = new ECO_Setting();
            se.HotelID = CurrentHotelID;
            se.StartTime = StartTime;
            se.EndTime = EndTime;
            se.AddOrCutDown = Action;

            int fg = 0;
            int.TryParse(TempVal, out fg);
            se.ActValue = fg;
            se.IsEnable = IsEnable;
            string ti = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            se.CreateTime = ti;

            if (id == 0)
            {
                Air_ECO_SettingManager.Add(se);
            }
            else
            {
                se.ID = id;
                Air_ECO_SettingManager.Update(se);
            }


            //启动ECO任务
            string[] s_st = StartTime.Split(':');

            //开始时间
            int sh = 0;
            int.TryParse(s_st[0], out sh);
            int sm = 0;
            int.TryParse(s_st[1], out sm);


            //任务管理系统 需要在结束后2分钟发送 重置 指令
            string[] str = EndTime.Split(':');

            //结束时间
            int hh = 0;
            int.TryParse(str[0], out hh);
            int mm = 0;
            int.TryParse(str[1], out mm);


            int new_mm = mm + 2;
            //一般是结束时间小于开始时间

            DateTime ct = DateTime.Now;
            DateTime d_st = new DateTime(ct.Year, ct.Month, ct.Day, sh, sm, 0);
            DateTime d_et = new DateTime(ct.Year, ct.Month, ct.Day, hh, mm, 0);

            if (d_et > d_st)
            {
                Air_ECO_SettingManager.ECO_Start_Mission(CurrentHotelID.ToString(), sh, sm, hh, mm, IsEnable);
            }
            else if (d_et < d_st)
            {
                Air_ECO_SettingManager.ECO_Start_Mission(CurrentHotelID.ToString(), sh, sm, 00, 00, IsEnable);
                Air_ECO_SettingManager.ECO_Start_Mission(CurrentHotelID.ToString(), 0, 1, hh, mm, IsEnable);
            }
            else
            {

            }
            Air_ECO_SettingManager.ECO_Reset_Mission(CurrentHotelID.ToString(), hh, new_mm, IsEnable);

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

        }

        /// <summary>
        /// 欺骗式ECO
        /// </summary>
        /// <param name="id"></param>
        /// <param name="StartTime"></param>
        /// <param name="EndTime"></param>
        /// <param name="Action"></param>
        /// <param name="TempVal"></param>
        /// <param name="IsEnable"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult SaveConditionLieECO(string BiaoShiFlag, string StartTime, string EndTime, string AbsEnable, string AbsValue, string RelativeEnable, string RelativeValue, bool IsEnable, string Delay)
        {
            try
            {
                //启动ECO任务
                string[] s_st = StartTime.Split(':');

                //开始时间
                int sh = 0;
                int.TryParse(s_st[0], out sh);
                int sm = 0;
                int.TryParse(s_st[1], out sm);


                //任务管理系统 需要在结束后2分钟发送 重置 指令
                string[] str = EndTime.Split(':');

                //结束时间
                int hh = 0;
                int.TryParse(str[0], out hh);
                int mm = 0;
                int.TryParse(str[1], out mm);

                DateTime ct = DateTime.Now;
                DateTime d_st = new DateTime(ct.Year, ct.Month, ct.Day, sh, sm, 0);
                DateTime d_et = new DateTime(ct.Year, ct.Month, ct.Day, hh, mm, 0);
                if (d_st > d_et)
                {
                    return Json(new { IsSuccess = false, Message = " \"结束时间\"须大于\"开始时间\"" });
                }


                var sysHotel = SysHotelManager.Get(CurrentHotelID);


                LieECO se = new LieECO();
                se.HotelID = CurrentHotelID;
                se.StartTime = StartTime;
                se.EndTime = EndTime;
                se.AbsEnable = bool.Parse(AbsEnable);
                se.AbsValue = int.Parse(AbsValue);
                se.RelativeEnable = bool.Parse(RelativeEnable);
                se.RelativeValue = int.Parse(RelativeValue);
                se.IsEnable = IsEnable;
                int ddd = 20;
                int.TryParse(Delay, out ddd);
                se.DelayTime = ddd;
                string ti = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                se.CreateTime = DateTime.Now;

                if (BiaoShiFlag == "0")
                {
                    LieECOManager.Add(se);
                }
                else
                {
                    se.ID = int.Parse(BiaoShiFlag);
                    LieECOManager.Update(se);
                }
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = ex.Message });
            }
        }

        public static string missionsys_address = ConfigurationManager.AppSettings["missionsys_address"];
        /// <summary>
        /// 凌晨ECO
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult SaveConditionTimerECO()
        {
            try
            {
                Request.InputStream.Position = 0;
                byte[] reqBody = new byte[Request.InputStream.Length];
                Request.InputStream.Read(reqBody, 0, reqBody.Length);
                string reqData = System.Text.Encoding.UTF8.GetString(reqBody);
                if (!string.IsNullOrEmpty(reqData))
                {
                    var T = JsonConvert.DeserializeObject<List<LingChenECO>>(reqData);
                    //T.ForEach(A => A.HotelCode = CurrentHotelCode);
                    string GGG = CacheKey.KT_Timer_Controller + "_" + CurrentHotelCode;
                    CSRedisCacheHelper.Set_PartitionWithForever<List<LingChenECO>>(GGG, T, 5);
                    var client1 = new RestClient(missionsys_address);
                    foreach (var item in T)
                    {
                        string[] tt = item.StartTime.Split(':');
                        string st_h = tt[0];
                        string st_m = tt[1];
                        if (item.IsEnable)
                        {

                            //内存中 保存着 code 和 时间的
                            CSRedisCacheHelper.HMSet(5, MvcApplication.LingChenECO_IntervalKey, item.HotelCode + "#" + item.StartTime, item.RelativeValue);
                            //给任务管理系统发送数据
                            var tq = new RedisTongJiData();
                            tq.url = "api/LingChenECO";
                            tq.cron_exp = string.Format("*{0} {1} * * *", st_h, st_m);
                            tq.mission_key = MvcApplication.LingChenECO_IntervalKey + "_" + item.HotelCode + "_" + item.StartTime;

                            string ts = Newtonsoft.Json.JsonConvert.SerializeObject(tq);
                            CSRedisCacheHelper.HMSet(1, MvcApplication.LingChenECO_MissionSysKey, item.HotelCode + "#" + item.StartTime, ts);

                            var request1 = new RestRequest("api/declare_mission", Method.POST);
                            request1.AddParameter("url", tq.url);
                            request1.AddParameter("mission_key", tq.mission_key);
                            request1.AddParameter("mission_name", tq.mission_key);
                            request1.AddParameter("cron_exp", tq.cron_exp);
                            client1.ExecuteAsync(request1, (response) =>
                            {
                                string result = response.Content;
                            });
                        }
                    }
                }

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


        [Authorize]
        public ActionResult Delete(IList<int> idList)
        {
            try
            {
                SysHotelManager.Delete(idList.Cast<object>().ToList());
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("DeleteSuccess") });
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("OperationFailed") });
            }
        }
        /// <summary>
        /// 上传logo
        /// </summary>
        /// <param name="file"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult UploadLogo(HttpPostedFileBase file, int id)
        {
            try
            {
                if (file == null || file.ContentLength <= 0)
                {
                    throw new ApplicationException("请选择Logo");
                }
                string ext = System.IO.Path.GetExtension(file.FileName).ToLower();
                if (ext != ".png")
                {
                    throw new ApplicationException("Logo格式必须是.png");
                }
                SysHotel entity = SysHotelManager.Get(id);
                if (entity == null)
                {
                    throw new ApplicationException("未指定酒店");
                }
                entity.LogoPath = "../Uploads/logo/" + entity.Code + ".png";

                string filePath = Server.MapPath("~/Uploads/logo/");
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                filePath += entity.Code + ".png"; //file.FileName;
                if (System.IO.File.Exists(filePath))
                {
                    System.IO.File.Delete(filePath);
                    //throw new ApplicationException(HttpContext.InnerLanguage("TheUpgradePackageHasBeenUploadedPleaseReSelect"));
                }

                SysHotelManager.Update(entity);

                file.SaveAs(filePath);

                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("UploadSuccessful") });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = HttpUtility.HtmlEncode(ex.Message) });
            }
        }
        [Authorize]
        public ActionResult LoadSysHotelGroupTree()
        {
            SysUsers user = SysUserManager.Get(User.Identity.Name);
            if (user.SysHotelGroup == null)
            {
                return Json(new List<object>(), JsonRequestBehavior.AllowGet);
            }
            //IList<SysHotelGroup> groups = SysHotelGroupManager.LoadAll();
            //return Json(BuildGroupTree(groups, null), JsonRequestBehavior.AllowGet);
            IList<object> result = new List<object>();
            result.Add(SysHotelGroupManager.CreateGroupTree2(user.SysHotelGroup));
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [Authorize]
        public ActionResult LoadGroupTree2()
        {
            SysUsers user = SysUserManager.Get(User.Identity.Name);
            if (user.SysHotelGroup == null)
            {
                return Json(new List<object>(), JsonRequestBehavior.AllowGet);
            }
            return Json(SysHotelGroupManager.CreateGroupTree(user.SysHotelGroup), JsonRequestBehavior.AllowGet);
        }

        public ActionResult EditSysHotelGroup(int? id, int? parentId)
        {
            if (id.HasValue)
            {
                return View(SysHotelGroupManager.Get(id));
            }
            return View(new SysHotelGroup { ID = 0, Name = "", Parent = new SysHotelGroup { ID = parentId.GetValueOrDefault() }, Sort = 1 });
        }

        [Authorize]
        [HttpPost]
        public ActionResult DeleteSysHotelGroup(int id)
        {
            try
            {
                SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("Delete"), SysHotelGroupManager.Get(id).Name);
                SysHotelGroupManager.Delete(id);
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("DeleteSuccess") });
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("OperationFailed") });
            }
        }

        [Authorize]
        [HttpPost]
        public ActionResult SaveSysHotelGroup(string jsonData)
        {
            try
            {
                SysHotelGroup entity = Newtonsoft.Json.JsonConvert.DeserializeObject<SysHotelGroup>(jsonData);
                if (entity.ID == 0)
                {
                    SysHotelGroupManager.Save(entity);
                }
                else
                {
                    SysHotelGroupManager.Update(entity);
                }
                SaveSystemLog(AuthorityID, HttpContext.InnerLanguage("Edit"), entity.Name);
                return Json(new { IsSuccess = true, Message = HttpContext.InnerLanguage("SaveSuccess") });
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                return Json(new { IsSuccess = false, Message = HttpContext.InnerLanguage("SaveFailedBecause") });
            }
        }

        public ActionResult GetProvince()
        {
            IList<SysProvince> list = SysProvinceManager.LoadAll();
            return Json(list.Select(r => new { r.Code, Name = ReturnNameByLanguage(r.Name, r.EName, r.TWName) }).ToList(), JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetCity(string provinceCode)
        {
            IList<SysCity> list = SysProvinceManager.GetCity(provinceCode);
            return Json(list.Select(r => new { r.Code, Name = ReturnNameByLanguage(r.Name, r.EName, r.TWName) }).ToList(), JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetCounty(string cityCode)
        {
            IList<SysCounty> list = SysProvinceManager.GetCounty(cityCode);
            return Json(list.Select(r => new { r.Code, Name = ReturnNameByLanguage(r.Name, r.EName, r.TWName) }).ToList(), JsonRequestBehavior.AllowGet);
        }
    }
}
