using Common;
using CommonEntity;
using DAL.New_Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.VisualBasic;
using Newtonsoft.Json;

namespace UseSQLQueryData.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class BaoYiController : ControllerBase
    {
        public static string TimerReportData = "TimerReportData";
        public RicsContext db { get; set; }
        public IMemoryCache _memorycache { get; set; }
        public BaoYiController(RicsContext context, IMemoryCache cache)
        {
            this.db = context;
            this._memorycache = cache;
        }
        [HttpPost()]
        public async Task<ReturnInfo> SaveRoomTypeModal()
        {

            ReturnInfo r = new ReturnInfo();
            try
            {
                using var reader = new StreamReader(Request.Body);
                string jsonString = await reader.ReadToEndAsync();

                var userlist = Newtonsoft.Json.JsonConvert.DeserializeObject<List<BaoYiModel>>(jsonString);
                var QQQ = userlist.GroupBy(A => A.roomTypeID).Select(A => A.Key);

                using var tran = this.db.Database.BeginTransaction();
                int roomTypeID = 0;
                foreach (var item in QQQ)
                {
                    roomTypeID = item;
                    await db.TbRoomTypeModals.Where(A => A.RoomTypeId == item).ExecuteDeleteAsync();
                }

                var roomType = db.TbRoomTypes.Find(roomTypeID);

                foreach (var item in userlist)
                {
                    var id = item.id;
                    var modalAddress = item.modalAddress; ;
                    var outlet = item.outlet;
                    var name = item.name;
                    var englishName = item.englishName;
                    var power = item.power;
                    var twName = item.twName;
                    var aliasName = item.aliasName;
                    var type = item.type;
                    var sort = item.sort;
                    var color = item.color;

                    var OfflineDisplay = item.OfflineDisplay;

                    var LowPower = item.LowPower;
                    //低电保存显示
                    var LowPowerDisplay = item.LowPowerDisplay;

                    //是否声音报警
                    var Beep = item.Beep;
                    //是否异常判断
                    var Abnormal = item.Abnormal;

                    var MultipleGroupID = item.MultipleGroupID;
                    var MultipleTCLName = item.MultipleTCLName;
                    var TCLDeviceName = item.TCLDeviceName;
                    var WXActiveIndicator = item.WXActiveIndicator;
                    var ActiveIndicator = item.ActiveIndicator;

                    var roomTypeModal = new TbRoomTypeModal();
                    roomTypeModal.RoomType = roomType;
                    roomTypeModal.ModalAddress = modalAddress;
                    roomTypeModal.Outlet = outlet;
                    roomTypeModal.Name = name;
                    roomTypeModal.EnglishName = englishName;
                    roomTypeModal.Twname = twName;
                    roomTypeModal.AliasName = aliasName;
                    roomTypeModal.Power = power;
                    roomTypeModal.Default1 = false;
                    roomTypeModal.Type = (int)type;
                    roomTypeModal.Subtype = null;
                    roomTypeModal.Sort = sort;
                    roomTypeModal.Color = color;
                    roomTypeModal.ActiveIndicator = ActiveIndicator;//新增时默认显示
                    roomTypeModal.WxactiveIndicator = true;//只要显示，微信默认允许控制
                    roomTypeModal.OfflineDisplay = OfflineDisplay;
                    roomTypeModal.LowPowerDisplay = LowPowerDisplay;
                    roomTypeModal.Beep = Beep;
                    roomTypeModal.Abnormal = Abnormal;


                    roomTypeModal.SourceType = 0;
                    roomTypeModal.MultipleTclname = MultipleTCLName;
                    roomTypeModal.TcldeviceName = TCLDeviceName;
                    roomTypeModal.IsUploadBaoJing = item.IsUploadBaoJing;
                    int a = 0;
                    int.TryParse(MultipleGroupID, out a);
                    roomTypeModal.MultipleGroupId = a;


                    db.TbRoomTypeModals.Add(roomTypeModal);
                    UpdateHostModals(roomTypeModal);
                }
                await db.SaveChangesAsync();
                await this.db.Database.CommitTransactionAsync();

                var TBL = db.TbHosts.Where(A => A.RoomTypeId == roomTypeID).Select(A => A.Id);
                foreach (var item in TBL)
                {
                    CSRedisCacheHelper.Del_Partition("TimerReportData_" + item, 3);
                }
                r.isok = true;
            }
            catch (Exception ex)
            {
                r.message = ex.Message + "\r\n" + ex.StackTrace;
                r.isok = false;
            }
            return r;
        }

        private void UpdateHostModals(TbRoomTypeModal roomTypeModal)
        {
            if (roomTypeModal.RoomType == null)
            {
                return;
            }
            //List<Host> hosts = HostManager.LoadAll().Where(t => t.RoomType.ID == roomTypeModal.RoomType.ID).ToList();
            List<TbHost> hosts = db.TbHosts.Where(A => A.RoomType != null && A.RoomType.Id == roomTypeModal.RoomType.Id).ToList();
            foreach (TbHost host in hosts)//该房型下所有主机关联回路
            {
                //var hostModal = HostModalManager.GetByModalAddress(host.ID, roomTypeModal.ModalAddress);
                var hostModal = db.TbHostModals.FirstOrDefault(A => A.HostId == host.Id && A.RoomTypeModal.ModalAddress.Equals(roomTypeModal.ModalAddress));
                if (null == hostModal)
                {
                    //HostModalManager.Save(new HostModal { HostID = host.ID, Modal = roomTypeModal, Status = 2, Time = 0, UpdateTime = DateTime.Now });
                    var n = new TbHostModal() { HostId = host.Id, RoomTypeModal = roomTypeModal, Status = 2, Time = 0, UpdateTime = DateTime.Now };
                    db.TbHostModals.Add(n);
                }
            }
        }

        [HttpPost()]
        public void CacheTest_Add()
        {
            _memorycache.Set("A", "aaaa", DateTimeOffset.Now.AddMinutes(10));
        }
        [HttpPost()]
        public string CacheTest()
        {
            _memorycache.TryGetValue("A", out string AAA);
            return AAA;
        }
    }


    public class BaoYiModel
    {
        public int id { get; set; }
        public int roomTypeID { get; set; }
        public string modalAddress { get; set; }
        public string outlet { get; set; }
        public string name { get; set; }
        public string englishName { get; set; }
        public int power { get; set; }
        public string twName { get; set; }
        public string aliasName { get; set; }
        public DeviceType type { get; set; }
        public int sort { get; set; }
        public string color { get; set; }

        public int LowPower { get; set; }
        //离线保存显示
        public bool OfflineDisplay { get; set; }

        /// <summary>
        /// 是否低电显示
        /// </summary>
        public bool LowPowerDisplay { get; set; }

        public bool Beep { get; set; }
        /// <summary>
        /// 是否异常判断
        /// </summary>
        public virtual bool Abnormal { get; set; }



        public bool WXActiveIndicator { get; set; }
        public bool ActiveIndicator { get; set; }
        public string? MultipleGroupID { get; set; }
        public string? MultipleTCLName { get; set; }
        public string? TCLDeviceName { get; set; }

        /// <summary>
        /// 是否上传到宝镜
        /// </summary>
        public bool IsUploadBaoJing { get; set; }
    }
}
