using COMMON;
using DB_Server;
using Microsoft.EntityFrameworkCore;
using Models;
using Models.Models;
using Models.Models.LOGDB;
using Newtonsoft.Json;
using SERVER.LIB;
using SERVER.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using UtilsSharp;
using static DB_Server.DbHelperSQL;

namespace SERVER
{
    public static class GlobalSyncLockTest
    {
        public static bool isInProcessing = false;
        public static object testLock = new object();
        public static string recentErrMsg = "";
    }

    public static class SYNC_DATA
    {
        public static DateTime? SX = null;          //上一次同步时间
        public static object locks = new object();




        /// <summary>
        /// 同步数据总方法
        /// </summary>
        /// <returns></returns>
        public static bool SYNC_DATA_ALL(int stepid=0)
        {
            if (SYNC_DATA.SX != null && DateTime.Now - SYNC_DATA.SX <= TimeSpan.FromMinutes(0))
            {
                GlobalSyncLockTest.recentErrMsg = "同步失败，同步任务忙";
                return false;
            }


            //排队测试，并抢flag.
            //只有第一个能通过测试，并抢到。
            //后面的都不能通过测试。
            lock (GlobalSyncLockTest.testLock)
            {
                if (GlobalSyncLockTest.isInProcessing)
                {
                    GlobalSyncLockTest.recentErrMsg = "同步失败，同步任务忙";
                    return false;
                }
                GlobalSyncLockTest.isInProcessing = true;
            }

            DateTime startTime = DateTime.Now;

            try
            {
                SYNC_DATA.SX = DateTime.Now;

                LogHelp.Error("0/8 同步开始");
                // 一般情况下都会从控制器传入过来
                var db = XC_Data.GetMinDataBase();
                LogHelp.Error("1/8 取到mysql的dbcontext");

                // 使用sqlserver 的话可以采用 sql脚本同步 当然也可以采用代码同步  耗时久一点    暂不考虑
                if (ConfigEntity.Instance.DBTYPE == 1 && 1 != 1)
                {
                    try
                    {
                        db.Database.ExecuteSqlRaw(File.ReadAllText(Directory.GetCurrentDirectory() + "\\App_Data\\SQL\\asycn_data.sql"));
                        return false;
                    }
                    catch (Exception ex)
                    {
                        LogHelp.Error("数据库同步错误" + ex.ToString());
                        SYNC_DATA.SX = null;
                        var optionsBuilder = new DbContextOptionsBuilder<LOG_DBContext>();
                        optionsBuilder.UseSqlServer(ConfigEntity.Instance.LogDB);
                        var message = String.Join("", ex.Message.Take(255));
                        using (var context = new LOG_DBContext(optionsBuilder.Options))
                        {
                            context.TBL_SYS_ERR_REPORTS.Add(new TBL_SYS_ERR_REPORT { EVENT = "同步巫工数据库出错~", DESCRIPTION = message, LEVEL = 1, TYPE = 1, ERROR_ID = DateTime.Now.ToString("yyyyMMddHHmmssfff") });
                            context.SaveChanges();
                        }
                    }
                }
                else
                {
                    if(stepid == 0)
                    {
                        SyncHotelAll(db, startTime);
                        LogHelp.Error("2/8 同步酒店表完成");

                        SyncHotelGroupAll(db, startTime);
                        LogHelp.Error("3/8 同步酒店组表完成");

                        SyncRoomTypeAll(db, startTime);
                        LogHelp.Error("4/8 同步房型表完成");

                        SyncMainDeviceAll(db, startTime);
                        LogHelp.Error("5/8 同步主机表完成");

                        SyncSeasonAll(db, startTime);
                        LogHelp.Error("6/8 同步季节表完成");

                        SyncHotelSeasonAll(db, startTime);
                        LogHelp.Error("7/8 同步酒店季节表完成");
                    }
                    else
                    {
                        if(stepid == 1)
                        {
                            SyncHotelAll(db, startTime);
                            LogHelp.Error("2/8 同步酒店表完成");
                        }
                        else if(stepid == 2)
                        {
                            SyncHotelGroupAll(db, startTime);
                            LogHelp.Error("3/8 同步酒店组表完成");
                        }
                        else if (stepid == 3)
                        {
                            SyncRoomTypeAll(db, startTime);
                            LogHelp.Error("4/8 同步房型表完成");
                        }
                        else if (stepid == 4)
                        {
                            SyncMainDeviceAll(db, startTime);
                            LogHelp.Error("5/8 同步主机表完成");
                        }
                        else if (stepid == 5)
                        {
                            SyncSeasonAll(db, startTime);
                            LogHelp.Error("6/8 同步季节表完成");
                        }
                        else if (stepid == 6)
                        {
                            SyncHotelSeasonAll(db, startTime);
                            LogHelp.Error("7/8 同步酒店季节表完成");
                        }
                    }
                    
                    LogHelp.Error("8/8 同步完成");
                }


                GlobalSyncLockTest.isInProcessing = false;
                GlobalSyncLockTest.recentErrMsg = "同步成功";
                return true;

            }
            catch (Exception ex)
            {
                GlobalSyncLockTest.isInProcessing = false;
                GlobalSyncLockTest.recentErrMsg = "同步失败，触发异常:"+ex.ToString();
                LogHelp.Error(ex.ToString());
                return false;
            }

        }
        public static void SyncHotelAll(HotelServiceContext db, DateTime stTime) {
            string lasttime = String.Empty;
            
            //取到酒店表上次更新时间
            var row = db.NEW_TABLE_UPDATE_TIME_MARKS.AsTracking()       //开启跟踪查询，因为后面要更新时间
            .First(x => x.NEW_DB_TABLE_NAME == "TBL_HOTEL_BASIC_INFO");
            if (row.LAST_UPDATE_TIME == null)
                lasttime = "2022-04-01";
            else
            {
                var time = Convert.ToDateTime(row.LAST_UPDATE_TIME);
                if (time.Year < 2022)
                    lasttime = "2022-04-01";
                else
                    lasttime = time.ToString("yyyy-MM-dd HH:mm:ss.fff");
            }

            //为什么不用EF取，，而是用sql取数据然后转成实体列表。
            //因为连的是巫工那边数据库，可能不支持EF。
            //因为巫工那边数据库表结构和这边表结构不一致。
            //使用巫工数据库数据，通过utilsharp来进行转换成我们这边数据实体列表
            var hoteldata = DataTableHelper.ToEntities<TBL_HOTEL_BASIC_INFO>(
                SQLSERVER_Helper.GetDatatable(ConfigEntity.Instance.OtherDB, $@"select 
                                                                 IDOLD = b.id,
                                                                 LOG_IMAGE = b.LogoPath,
                                                                 HOTEL_NAME_CN = b.[name],
                                                                 SORT = b.sort,
                                                                 HOTEL_NAME_EN = b.ename,
                                                                 KEY_IN_DATETIME = b.createddate,
                                                                 [IsApprove] = b.IsApprove,
                                                                 VALID_DATETIME = b.ValidateDate,
                                                                 PROJECT_NUMBER = b.[code],
                                                                 [STATUS] = b.[STATUS],
                                                                 [KEY_nAME] = CreatedBy,
                                                                 DETAIL_ADD = b.[Address],
                                                                 HOTEL_CONTACT_PHONE = b.[Phone],
                                                                 HOTEL_OLD_GROUP = b.SysHotelGroupID,
                                                                 UPDATE_TIMEMARK = GETDATE()
                                                                 from tb_Sys_Hotels b where                                                    LAST_MODIFIED_TIME > '{lasttime}'")
                );

            var oldidlist = db.TBL_HOTEL_BASIC_INFOS.Select(x => x.IDOLD).ToArray();//我们这边数据库的所有IDOLD（对应那边的主键id）列表
            if (hoteldata.Count > 0)// 如果那边数据有新记录出现
            {
                string retStr = "";
                for (int i = 0; i < hoteldata.Count; i++)
                {
                    retStr += "编号：" + hoteldata[i].IDOLD + "名字：" + hoteldata[i].HOTEL_NAME_CN;
                }
                LogHelp.Error("酒店表如下记录有更新：" + retStr);
                var jsdata = hoteldata.Select(x => x.IDOLD).ToArray();//那边数据库的所有新记录的主键ID

                // 我们这边数据里面有那边新记录主键ID的，，进行更新
                List<TBL_HOTEL_BASIC_INFO> olddata = db.TBL_HOTEL_BASIC_INFOS.Where(X => jsdata.Contains(X.IDOLD)).ToList();
                for (int i = 0; i < olddata.Count; i++)
                {
                    var tump = hoteldata.First(x => x.IDOLD == olddata[i].IDOLD);
                    var item = olddata[i];
                    GetVal(ref item, tump, "HOTEL_OLD_GROUP", "LOG_IMAGE", "HOTEL_NAME_CN", "SORT", "HOTEL_NAME_EN", "KEY_IN_DATETIME", "IsApprove", "VALID_DATETIME", "PROJECT_NUMBER", "STATUS", "KEY_nAME", "DETAIL_ADD", "HOTEL_CONTACT_PHONE", "HOTEL_GROUP", "UPDATE_TIMEMARK");
                    // 标记修复
                    db.Entry(item).State = EntityState.Modified;
                }
                //// 添加
                db.TBL_HOTEL_BASIC_INFOS.AddRange(
                    hoteldata.Where(
                        item => oldidlist.FirstOrDefault(y => y == item.IDOLD) == 0     //oldidlist.IDOLD为个数为零
                        )
                    );
                row.LAST_UPDATE_TIME = stTime;
                // 标记修复
                db.Entry(row).State = EntityState.Modified;
                db.SaveChanges();
            }
            
        }
        public static void SyncHotelGroupAll(HotelServiceContext db, DateTime stTime)
        {
            string lasttime = String.Empty;

            var group_row = db.NEW_TABLE_UPDATE_TIME_MARKS.AsTracking().First(x => x.NEW_DB_TABLE_NAME == "TBL_HOTEL_GROUP_INFO");
            if (group_row.LAST_UPDATE_TIME == null)
                lasttime = "2022-04-01";
            else
            {
                var time = Convert.ToDateTime(group_row.LAST_UPDATE_TIME);
                if (time.Year < 2022)
                    lasttime = "2022-04-01";
                else
                    lasttime = time.ToString("yyyy-MM-dd HH:mm:ss.fff");
            }
            // 获取改动过的酒店信息
            var groupdata = DataTableHelper.ToEntities<TBL_HOTEL_GROUP_INFO>(SQLSERVER_Helper.GetDatatable(ConfigEntity.Instance.OtherDB,
                $@"select HOTEL_GROUP_OLD_ID = b.id,  HOTEL_GROUP_NAME = b.[Name] ,SORT = b.SORT,PARENT_OLD_ID = b.ParentID,UPDATE_TIMEMARK = GETDATE() from  tb_Sys_HotelGroups  b where                 LAST_MODIFIED_TIME > '{lasttime}'"));
            if (groupdata.Count > 0)
            {
                string retStr = "";
                for (int i = 0; i < groupdata.Count; i++)
                {
                    retStr += "编号：" + groupdata[i].HOTEL_GROUP_OLD_ID + "名字：" + groupdata[i].HOTEL_GROUP_NAME;
                }
                LogHelp.Error("酒店组表如下记录有更新：" + retStr);

                string group_str = "'" + string.Join("','", groupdata.Select(x => x.HOTEL_GROUP_OLD_ID)) + "'";
                var group_old_data = db.TBL_HOTEL_GROUP_INFOS.FromSqlRaw($"select * from TBL_HOTEL_GROUP_INFO where HOTEL_GROUP_OLD_ID in ({group_str})").AsNoTracking().Select(X => new { X.HOTEL_GROUP_ID, X.HOTEL_GROUP_OLD_ID }).ToArray();
                foreach (var item in groupdata)
                {
                    var OLD_DATA = group_old_data.FirstOrDefault(x => x.HOTEL_GROUP_OLD_ID == item.HOTEL_GROUP_OLD_ID);
                    //部分更新
                    if (OLD_DATA != null)
                    {
                        item.HOTEL_GROUP_ID = OLD_DATA.HOTEL_GROUP_ID;
                        db.Attach(item);
                        db.Entry(item).Property(p => p.HOTEL_GROUP_NAME).IsModified = true;
                        db.Entry(item).Property(p => p.PARENT_OLD_ID).IsModified = true;
                        db.Entry(item).Property(p => p.PARENT_ID).IsModified = true;
                        db.Entry(item).Property(p => p.SORT).IsModified = true;
                        db.Entry(item).Property(p => p.UPDATE_TIMEMARK).IsModified = true;
                    }
                    else
                        db.Entry(item).State = EntityState.Added;
                }
                group_row.LAST_UPDATE_TIME = stTime;
                db.Entry(group_row).State = EntityState.Modified;
                db.SaveChanges();
            }
            db.SaveChanges();
        }
        public static void SyncRoomTypeAll(HotelServiceContext db, DateTime stTime)
        {
            string lasttime = String.Empty;
            var roomtype_row = db.NEW_TABLE_UPDATE_TIME_MARKS.AsTracking().First(x => x.NEW_DB_TABLE_NAME == "TBL_ROOM_TYPE_LIST");
            if (roomtype_row.LAST_UPDATE_TIME == null)
                lasttime = "2022-04-01";
            else
            {
                var time = Convert.ToDateTime(roomtype_row.LAST_UPDATE_TIME);
                if (time.Year < 2022)
                    lasttime = "2022-04-01";
                else
                    lasttime = time.ToString("yyyy-MM-dd HH:mm:ss.fff");
            }
            var roomtypedata = DataTableHelper.ToEntities<TBL_ROOM_TYPE_LIST>(
                SQLSERVER_Helper.GetDatatable(ConfigEntity.Instance.OtherDB,
                $@"select ROOM_TYPE_OLD_ID = B.ID, HOTEL_OLD_ID = b.[HOTELID] ,ROOM_TYPE_NAME = b.[NAME],UPDATE_TIMEMARK = GETDATE(),Creation_Time = GETDATE()  from TB_ROOMTYPE  b  where LAST_MODIFIED_TIME > '{lasttime}'"));

            if (roomtypedata.Count > 0)
            {
                string retStr = "";
                for (int i = 0; i < roomtypedata.Count; i++)
                {
                    retStr += "编号：" + roomtypedata[i].ROOM_TYPE_OLD_ID + "名字：" + roomtypedata[i].ROOM_TYPE_NAME;
                }
                LogHelp.Error("房型表如下记录有更新：" + retStr);

                string group_str = "'" + string.Join("','", roomtypedata.Select(x => x.ROOM_TYPE_OLD_ID)) + "'";
                var room_old_data = db.TBL_ROOM_TYPE_LISTS.FromSqlRaw($"select * from TBL_ROOM_TYPE_LIST where ROOM_TYPE_OLD_ID  in ({group_str})").AsNoTracking().Select(X => new
                {
                    X.ROOM_TYPE_ID,
                    X.ROOM_TYPE_OLD_ID
                }).ToArray();
                foreach (var item in roomtypedata)
                {
                    item.Creation_Time = DateTime.Now;
                    var OLD_DATA = room_old_data.FirstOrDefault(X => X.ROOM_TYPE_OLD_ID == item.ROOM_TYPE_OLD_ID);
                    if (OLD_DATA != null)
                    {
                        item.ROOM_TYPE_ID = OLD_DATA.ROOM_TYPE_ID;
                        db.Attach(item);
                        db.Entry(item).Property(p => p.UPDATE_TIMEMARK).IsModified = true;
                        db.Entry(item).Property(p => p.Creation_Time).IsModified = true;
                        db.Entry(item).Property(p => p.HOTEL_OLD_ID).IsModified = true;
                        db.Entry(item).Property(p => p.ROOM_TYPE_NAME).IsModified = true;
                    }
                    else
                        db.Entry(item).State = EntityState.Added;
                }
                roomtype_row.LAST_UPDATE_TIME = stTime;
                db.Entry(roomtype_row).State = EntityState.Modified;
                db.SaveChanges();
            }

        }
        public static void SyncMainDeviceAll(HotelServiceContext db, DateTime stTime)
        {
            string lasttime = String.Empty;
            var room_row = db.NEW_TABLE_UPDATE_TIME_MARKS.AsTracking().First(x => x.NEW_DB_TABLE_NAME == "TBL_ROOM_BASIC_INFO");
            if (room_row.LAST_UPDATE_TIME == null)
                lasttime = "2022-04-01";
            else
            {
                var time = Convert.ToDateTime(room_row.LAST_UPDATE_TIME);
                if (time.Year < 2022)
                    lasttime = "2022-04-01";
                else
                    lasttime = time.ToString("yyyy-MM-dd HH:mm:ss.fff");
            }
            var roomdata = DataTableHelper.ToEntities<Host_>(SQLSERVER_Helper.GetDatatable(ConfigEntity.Instance.OtherDB, $@"select  * from tb_Hosts b  where  LAST_MODIFIED_TIME > '{lasttime}'"));
            if (roomdata.Count > 0)
            {
                string retStr = "";
                for (int i = 0; i < roomdata.Count; i++)
                {
                    retStr += "编号：" + roomdata[i].ID + "房号：" + roomdata[i].RoomNumber;
                }
                LogHelp.Error("主机表如下记录有更新：" + retStr);

                #region 同步房间表数据

                string room_str = "'" + string.Join("','", roomdata.Select(x => x.ID)) + "'";
                var room_old_data = db.TBL_ROOM_BASIC_INFOS.FromSqlRaw($"select * from TBL_ROOM_BASIC_INFO where ROOM_OLD_ID  in ({room_str})").AsNoTracking().ToArray();
                var ROOM_SET_CONFIG = db.TBL_ROOM_SET_CONFIGS.FromSqlRaw($"select * from TBL_ROOM_SET_CONFIG where ROOM_OLD_ID  in ({room_str})").AsNoTracking().ToArray();
                foreach (var item in roomdata)
                {

                    var DATA_OLD = room_old_data.FirstOrDefault(X => X.ROOM_OLD_ID == item.ID);
                    if (DATA_OLD == null)
                    {
                        DATA_OLD = new TBL_ROOM_BASIC_INFO();
                    }
                    DATA_OLD.RoomStatusID = item.RoomStatusID;
                    DATA_OLD.MAC = item.MAC;
                    DATA_OLD.AUTH_DATETIME = item.ExpireTime;
                    DATA_OLD.UPDATE_TIMEMARK = DateTime.Now;
                    DATA_OLD.REMARK = item.Remark;
                    DATA_OLD.ROOM_NUMBER = item.RoomNumber;
                    DATA_OLD.ROOM_TYPE_OLD_ID = item.RoomTypeID;
                    DATA_OLD.HOTEL_OLD_ID = item.HOTELID;
                    DATA_OLD.ROOM_OLD_ID = item.ID;

                    if (DATA_OLD.ROOM_ID > 0)
                    {
                        db.Attach(DATA_OLD);
                        db.Entry(DATA_OLD).Property(p => p.AUTH_DATETIME).IsModified = true;
                        db.Entry(DATA_OLD).Property(p => p.UPDATE_TIMEMARK).IsModified = true;
                        db.Entry(DATA_OLD).Property(p => p.RoomStatusID).IsModified = true;
                        db.Entry(DATA_OLD).Property(p => p.HOTEL_OLD_ID).IsModified = true;
                        db.Entry(DATA_OLD).Property(p => p.ROOM_TYPE_OLD_ID).IsModified = true;
                        db.Entry(DATA_OLD).Property(p => p.REMARK).IsModified = true;
                        db.Entry(DATA_OLD).Property(p => p.MAC).IsModified = true;
                        db.Entry(DATA_OLD).Property(p => p.ROOM_NUMBER).IsModified = true;
                    }
                    else
                    {
                        db.Entry(DATA_OLD).State = EntityState.Added;
                    }
                    //添加房间配置信息表
                    var ROOM_SET_CONFIGS = ROOM_SET_CONFIG.FirstOrDefault(X => X.ROOM_OLD_ID == item.ID);
                    if (ROOM_SET_CONFIGS == null)
                    {
                        ROOM_SET_CONFIGS = new TBL_ROOM_SET_CONFIG();
                    }
                    ROOM_SET_CONFIGS.RCU_ROOM = item.RoomNumber;
                    ROOM_SET_CONFIGS.PRODUCT_CODE = item.HostNumber;
                    ROOM_SET_CONFIGS.FW_VER = item.Version;
                    ROOM_SET_CONFIGS.CONFIG_VER = item.ConfigVersion;
                    ROOM_SET_CONFIGS.RCU_SUB_MASK = item.SubnetMask;
                    ROOM_SET_CONFIGS.RCU_CLOUD_SVR_IP = item.ServerIP;
                    ROOM_SET_CONFIGS.RCU_CLOUD_SVR_PORT_MODE = item.ServerPort.ToString();
                    ROOM_SET_CONFIGS.RCU_LOCAL_IP = item.LanIP;
                    ROOM_SET_CONFIGS.RCU_LOCAL_PORT = item.LanPort.ToString();
                    ROOM_SET_CONFIGS.RCU_GETWAY = item.Gateway;
                    ROOM_SET_CONFIGS.RCU_DNS_SERVER = item.DNS;
                    ROOM_SET_CONFIGS.REMARK = item.Remark;
                    ROOM_SET_CONFIGS.ROOM_OLD_ID = item.ID;
                    ROOM_SET_CONFIGS.UPDATE_TIMEMARK = DateTime.Now;
                    ROOM_SET_CONFIGS.IPType = item.IPType;
                    ROOM_SET_CONFIGS.RCU_CLOUD_SVR_PORT = item.ServerPort.ToString();
                    if (ROOM_SET_CONFIGS.ID > 0)
                    {
                        db.Attach(ROOM_SET_CONFIGS);
                        db.Entry(ROOM_SET_CONFIGS).Property(p => p.RCU_ROOM).IsModified = true;
                        db.Entry(ROOM_SET_CONFIGS).Property(p => p.PRODUCT_CODE).IsModified = true;
                        db.Entry(ROOM_SET_CONFIGS).Property(p => p.FW_VER).IsModified = true;
                        db.Entry(ROOM_SET_CONFIGS).Property(p => p.CONFIG_VER).IsModified = true;
                        db.Entry(ROOM_SET_CONFIGS).Property(p => p.RCU_SUB_MASK).IsModified = true;
                        db.Entry(ROOM_SET_CONFIGS).Property(p => p.RCU_CLOUD_SVR_IP).IsModified = true;
                        db.Entry(ROOM_SET_CONFIGS).Property(p => p.RCU_CLOUD_SVR_PORT_MODE).IsModified = true;
                        db.Entry(ROOM_SET_CONFIGS).Property(p => p.RCU_LOCAL_IP).IsModified = true;
                        db.Entry(ROOM_SET_CONFIGS).Property(p => p.RCU_LOCAL_PORT).IsModified = true;
                        db.Entry(ROOM_SET_CONFIGS).Property(p => p.RCU_GETWAY).IsModified = true;
                        db.Entry(ROOM_SET_CONFIGS).Property(p => p.RCU_DNS_SERVER).IsModified = true;
                        db.Entry(ROOM_SET_CONFIGS).Property(p => p.REMARK).IsModified = true;
                        db.Entry(ROOM_SET_CONFIGS).Property(p => p.ROOM_OLD_ID).IsModified = true;
                        db.Entry(ROOM_SET_CONFIGS).Property(p => p.UPDATE_TIMEMARK).IsModified = true;
                        db.Entry(ROOM_SET_CONFIGS).Property(p => p.IPType).IsModified = true;
                        db.Entry(ROOM_SET_CONFIGS).Property(p => p.RCU_CLOUD_SVR_PORT).IsModified = true;
                    }
                    else
                        db.Entry(ROOM_SET_CONFIGS).State = EntityState.Added;
                }
                room_row.LAST_UPDATE_TIME = stTime;
                db.Entry(room_row).State = EntityState.Modified;
                db.SaveChanges();
                #endregion 同步房间表数据同步完毕  
                #region 同步配置表数据

                #endregion

                #region 同步过来的 将房间表的 mac  地址插入 主机表  或者更新
                // 清除旧数据    获取库里最新的mac
                CacheData.Clear(CacheData.CacheDataEnum.TBL_RCU_BASIC_INFO);
                // 获取查询出的 mac 
                var macdata = roomdata.Select(x => new { MAC = x.MAC.ToUpper(), x.RegisterDate });
                // 取出库里的mac
                var mac_data = CacheData.TBL_RCU_BASIC_INFO.Where(x => x.IsImport == 1);
                // 获取同步的数据中不存的 mac
                //macdata = macdata.Where(x => !mac_data.Contains(x.MAC));
                // 遍历添加
                foreach (var item in macdata)
                {
                    if (item.MAC.Length < 0)
                        continue;
                    var DA = mac_data.FirstOrDefault(X => X.MAC.ToUpper() == item.MAC);
                    if (DA != null)
                    {
                        db.Attach(DA);
                        DA.REGISTER_DATE = item.RegisterDate;
                        db.Entry(DA).Property(p => p.REGISTER_DATE).IsModified = true;
                    }
                    else
                        db.TBL_RCU_BASIC_INFOS.Add(new TBL_RCU_BASIC_INFO { MAC = item.MAC, IsImport = 1, REGISTER_DATE = item.RegisterDate });
                }
                db.SaveChanges();
                #endregion

            }
        }
        public static void SyncSeasonAll(HotelServiceContext db, DateTime stTime)
        {
            string lasttime = String.Empty;
            var season_row = db.NEW_TABLE_UPDATE_TIME_MARKS.AsTracking().First(x => x.NEW_DB_TABLE_NAME == "TBL_SEASON");
            

            //暂时使用永远更新的方式，因为只有4条记录，并且两边记录，格式，个数完全一样。
            var season_data = DataTableHelper.ToEntities<TBL_SEASON>(SQLSERVER_Helper.GetDatatable(ConfigEntity.Instance.OtherDB, $@"select * from tb_Season b"));
            string retStr1 = "";
            for (int i = 0; i < season_data.Count; i++)
            {
                retStr1 += "编号：" + season_data[i].ID + "名字：" + season_data[i].NAME;
            }
            LogHelp.Error("季度表总是更新：" + retStr1);

            List<TBL_SEASON> my_old_data = db.TBL_SEASONS.ToList();
            foreach (var it in my_old_data)
            {
                var srcDataIt = season_data.FirstOrDefault(x => x.ID == it.ID);
                it.NAME = srcDataIt.NAME;
                it.BeginDate = srcDataIt.BeginDate;
                it.EndDate = srcDataIt.EndDate;
            }

            season_row.LAST_UPDATE_TIME = stTime;
            db.Entry(season_row).State = EntityState.Modified;
            db.SaveChanges();
        }
        public static void SyncHotelSeasonAll(HotelServiceContext db, DateTime stTime) {
            string lasttime = String.Empty;
            var tbl_hotel_season_row = db.NEW_TABLE_UPDATE_TIME_MARKS.AsTracking().First(x => x.NEW_DB_TABLE_NAME == "TBL_HOTEL_SEASON");
            if (tbl_hotel_season_row == null || tbl_hotel_season_row.LAST_UPDATE_TIME == null)
                lasttime = "2022-04-01";
            else
            {
                var time = Convert.ToDateTime(tbl_hotel_season_row.LAST_UPDATE_TIME);
                if (time.Year < 2022)
                    lasttime = "2022-04-01";
                else
                    lasttime = time.ToString("yyyy-MM-dd HH:mm:ss.fff");
            }

            //总是全部更新过来
            //表结构
            //ID    HotelID Month1-12   IsDeleted
            //对象结构
            //ID    HOTELID HOTELID_OLD MONTH1-12
            var tbl_hotel_season_data = DataTableHelper.ToEntities<TBL_HOTEL_SEASON>(
                SQLSERVER_Helper.GetDatatable(
                    ConfigEntity.Instance.OtherDB,
                    $@"select * from tb_HotelSeason b"));

            if (tbl_hotel_season_data.Count > 0)
            {
                string retStr = "";
                for (int i = 0; i < tbl_hotel_season_data.Count; i++)
                {
                    retStr += "编号：" + tbl_hotel_season_data[i].ID + "酒店id：" + tbl_hotel_season_data[i].HOTELID;
                }
                LogHelp.Error("酒店季度表如下记录有更新：" + retStr);
                string room_str = "'" + string.Join("','", tbl_hotel_season_data.Select(x => x.ID)) + "'";
                var room_old_data = db.TBL_HOTEL_SEASONS.FromSqlRaw($"select * from TBL_HOTEL_SEASON where ID  in ({room_str})").AsNoTracking().Select(X => new { X.ID }).ToArray();
                foreach (var item in tbl_hotel_season_data)
                {
                    var DATA_OLD = room_old_data.FirstOrDefault(X => X.ID == item.ID);
                    if (DATA_OLD != null)
                    {
                        item.ID = DATA_OLD.ID;
                        db.Attach(item);
                        db.Entry(item).Property(p => p.MONTH1).IsModified = true;
                        db.Entry(item).Property(p => p.MONTH2).IsModified = true;
                        db.Entry(item).Property(p => p.MONTH3).IsModified = true;
                        db.Entry(item).Property(p => p.MONTH4).IsModified = true;
                        db.Entry(item).Property(p => p.MONTH5).IsModified = true;
                        db.Entry(item).Property(p => p.MONTH6).IsModified = true;
                        db.Entry(item).Property(p => p.MONTH7).IsModified = true;
                        db.Entry(item).Property(p => p.MONTH8).IsModified = true;
                        db.Entry(item).Property(p => p.MONTH9).IsModified = true;
                        db.Entry(item).Property(p => p.MONTH10).IsModified = true;
                        db.Entry(item).Property(p => p.MONTH11).IsModified = true;
                        db.Entry(item).Property(p => p.MONTH12).IsModified = true;
                    }
                    else
                        db.Entry(item).State = EntityState.Added;
                }
                tbl_hotel_season_row.LAST_UPDATE_TIME = stTime;
                db.Entry(tbl_hotel_season_row).State = EntityState.Modified;
                db.SaveChanges();
            }

        }



        //        public static ReturnResult SYNC_DATA_ALLs()
        //        {
        //            ReturnResult result = new ReturnResult();
        //            try
        //            {
        //                if (SYNC_DATA.SX == null || DateTime.Now - SYNC_DATA.SX > TimeSpan.FromMinutes(0))
        //                {
        //                    lock (SYNC_DATA.locks)
        //                    {
        //                        if (SYNC_DATA.SX == null || DateTime.Now - SYNC_DATA.SX > TimeSpan.FromMinutes(0))
        //                        {
        //                            SYNC_DATA.SX = DateTime.Now;
        //                            try
        //                            {
        //                                // 一般情况下都会从控制器传入过来
        //                                var db = XC_Data.GetMinDataBase();

        //                                // 使用sqlserver 的话可以采用 sql脚本同步 当然也可以采用代码同步  耗时久一点    暂不考虑
        //                                if (ConfigEntity.Instance.DBTYPE == 1 && 1 != 1)
        //                                {
        //                                    try
        //                                    {
        //                                        db.Database.ExecuteSqlRaw(File.ReadAllText(Directory.GetCurrentDirectory() + "\\App_Data\\SQL\\asycn_data.sql"));
        //                                    }
        //                                    catch (Exception ex)
        //                                    {
        //                                        LogHelp.Error("数据库同步错误" + ex.ToString());
        //                                        SYNC_DATA.SX = null;
        //                                        var optionsBuilder = new DbContextOptionsBuilder<LOG_DBContext>();
        //                                        optionsBuilder.UseSqlServer(ConfigEntity.Instance.LogDB);
        //                                        var message = String.Join("", ex.Message.Take(255));
        //                                        using (var context = new LOG_DBContext(optionsBuilder.Options))
        //                                        {
        //                                            context.TBL_SYS_ERR_REPORTS.Add(new TBL_SYS_ERR_REPORT { EVENT = "同步巫工数据库出错~", DESCRIPTION = message, LEVEL = 1, TYPE = 1, ERROR_ID = DateTime.Now.ToString("yyyyMMddHHmmssfff") });
        //                                            context.SaveChanges();
        //                                        }
        //                                    }
        //                                }
        //                                else
        //                                {
        //                                    string lasttime = String.Empty;
        //                                    #region 酒店表同步数据
        //                                    var row = db.NEW_TABLE_UPDATE_TIME_MARKS.AsTracking().First(x => x.NEW_DB_TABLE_NAME == "TBL_HOTEL_BASIC_INFO");
        //                                    if (row.LAST_UPDATE_TIME == null)
        //                                        lasttime = "2022-04-01";
        //                                    else
        //                                    {
        //                                        var time = Convert.ToDateTime(row.LAST_UPDATE_TIME);
        //                                        if (time.Year < 2022)
        //                                            lasttime = "2022-04-01";
        //                                        else
        //                                            lasttime = time.ToString("yyyy-MM-dd HH:mm:ss.fff");
        //                                    }
        //                                    var hoteldata = DataTableHelper.ToEntities<TBL_HOTEL_BASIC_INFO>(SQLSERVER_Helper.GetDatatable(ConfigEntity.Instance.OtherDB, $@"select 
        //                                                                 IDOLD = b.id,
        //                                                                 LOG_IMAGE = b.LogoPath,
        //                                                                 HOTEL_NAME_CN = b.[name],
        //                                                                 SORT = b.sort,
        //                                                                 HOTEL_NAME_EN = b.ename,
        //                                                                 KEY_IN_DATETIME = b.createddate,
        //                                                                 [IsApprove] = b.IsApprove,
        //                                                                 VALID_DATETIME = b.ValidateDate,
        //                                                                 PROJECT_NUMBER = b.[code],
        //                                                                 [STATUS] = b.[STATUS],
        //                                                                 [KEY_nAME] = CreatedBy,
        //                                                                 DETAIL_ADD = b.[Address],
        //                                                                 HOTEL_CONTACT_PHONE = b.[Phone],
        //                                                                 HOTEL_OLD_GROUP = b.SysHotelGroupID,
        //                                                                 UPDATE_TIMEMARK = GETDATE()
        //                                                                 from tb_Sys_Hotels b where                                                    LAST_MODIFIED_TIME > '{lasttime}'"));
        //                                    var oldidlist = db.TBL_HOTEL_BASIC_INFOS.Select(x => x.IDOLD).ToArray();
        //                                    if (hoteldata.Count > 0)
        //                                    {
        //                                        var jsdata = hoteldata.Select(x => x.IDOLD).ToArray();
        //                                        // 旧数据 更新 
        //                                        List<TBL_HOTEL_BASIC_INFO> olddata = db.TBL_HOTEL_BASIC_INFOS.Where(X => jsdata.Contains(X.IDOLD)).ToList();
        //                                        for (int i = 0; i < olddata.Count; i++)
        //                                        {
        //                                            var tump = hoteldata.First(x => x.IDOLD == olddata[i].IDOLD);
        //                                            var item = olddata[i];
        //                                            GetVal(ref item, tump, "HOTEL_OLD_GROUP", "LOG_IMAGE", "HOTEL_NAME_CN", "SORT", "HOTEL_NAME_EN", "KEY_IN_DATETIME", "IsApprove", "VALID_DATETIME", "PROJECT_NUMBER", "STATUS", "KEY_nAME", "DETAIL_ADD", "HOTEL_CONTACT_PHONE", "HOTEL_GROUP", "UPDATE_TIMEMARK");
        //                                            // 标记修复
        //                                            db.Entry(item).State = EntityState.Modified;
        //                                        }
        //                                        //// 添加
        //                                        db.TBL_HOTEL_BASIC_INFOS.AddRange(hoteldata.Where(item => oldidlist.FirstOrDefault(y => y == item.IDOLD) == 0));
        //                                        row.LAST_UPDATE_TIME = DateTime.Now;
        //                                        // 标记修复
        //                                        db.Entry(row).State = EntityState.Modified;
        //                                        db.SaveChanges();
        //                                    }
        //                                    #endregion

        //                                    #region 酒店组表同步数据
        //                                    var group_row = db.NEW_TABLE_UPDATE_TIME_MARKS.AsTracking().First(x => x.NEW_DB_TABLE_NAME == "TBL_HOTEL_GROUP_INFO");
        //                                    if (group_row.LAST_UPDATE_TIME == null)
        //                                        lasttime = "2022-04-01";
        //                                    else
        //                                    {
        //                                        var time = Convert.ToDateTime(group_row.LAST_UPDATE_TIME);
        //                                        if (time.Year < 2022)
        //                                            lasttime = "2022-04-01";
        //                                        else
        //                                            lasttime = time.ToString("yyyy-MM-dd HH:mm:ss.fff");
        //                                    }
        //                                    // 获取改动过的酒店信息
        //                                    var groupdata = DataTableHelper.ToEntities<TBL_HOTEL_GROUP_INFO>(SQLSERVER_Helper.GetDatatable(ConfigEntity.Instance.OtherDB,
        //                                        $@"select HOTEL_GROUP_OLD_ID = b.id,  HOTEL_GROUP_NAME = b.[Name] ,SORT = b.SORT,PARENT_OLD_ID = b.ParentID,UPDATE_TIMEMARK = GETDATE() from  tb_Sys_HotelGroups  b where                 LAST_MODIFIED_TIME > '{lasttime}'"));
        //                                    if (groupdata.Count > 0)
        //                                    {
        //                                        string group_str = "'" + string.Join("','", groupdata.Select(x => x.HOTEL_GROUP_OLD_ID)) + "'";
        //                                        var group_old_data = db.TBL_HOTEL_GROUP_INFOS.FromSqlRaw($"select * from TBL_HOTEL_GROUP_INFO where HOTEL_GROUP_OLD_ID in ({group_str})").AsNoTracking().Select(X => new { X.HOTEL_GROUP_ID, X.HOTEL_GROUP_OLD_ID }).ToArray();
        //                                        foreach (var item in groupdata)
        //                                        {
        //                                            var OLD_DATA = group_old_data.FirstOrDefault(x => x.HOTEL_GROUP_OLD_ID == item.HOTEL_GROUP_OLD_ID);
        //                                            //部分更新
        //                                            if (OLD_DATA != null)
        //                                            {
        //                                                item.HOTEL_GROUP_ID = OLD_DATA.HOTEL_GROUP_ID;
        //                                                db.Attach(item);
        //                                                db.Entry(item).Property(p => p.HOTEL_GROUP_NAME).IsModified = true;
        //                                                db.Entry(item).Property(p => p.PARENT_OLD_ID).IsModified = true;
        //                                                db.Entry(item).Property(p => p.PARENT_ID).IsModified = true;
        //                                                db.Entry(item).Property(p => p.SORT).IsModified = true;
        //                                                db.Entry(item).Property(p => p.UPDATE_TIMEMARK).IsModified = true;
        //                                            }
        //                                            else
        //                                                db.Entry(item).State = EntityState.Added;
        //                                        }
        //                                        group_row.LAST_UPDATE_TIME = DateTime.Now;
        //                                        db.Entry(group_row).State = EntityState.Modified;
        //                                        db.SaveChanges();
        //                                    }
        //                                    db.SaveChanges();
        //                                    #endregion

        //                                    #region 同步房型数据 
        //                                    var roomtype_row = db.NEW_TABLE_UPDATE_TIME_MARKS.AsTracking().First(x => x.NEW_DB_TABLE_NAME == "TBL_ROOM_TYPE_LIST");
        //                                    if (roomtype_row.LAST_UPDATE_TIME == null)
        //                                        lasttime = "2022-04-01";
        //                                    else
        //                                    {
        //                                        var time = Convert.ToDateTime(roomtype_row.LAST_UPDATE_TIME);
        //                                        if (time.Year < 2022)
        //                                            lasttime = "2022-04-01";
        //                                        else
        //                                            lasttime = time.ToString("yyyy-MM-dd HH:mm:ss.fff");
        //                                    }
        //                                    var roomtypedata = DataTableHelper.ToEntities<TBL_ROOM_TYPE_LIST>(SQLSERVER_Helper.GetDatatable(ConfigEntity.Instance.OtherDB, $@"select ROOM_TYPE_OLD_ID = B.ID, HOTEL_OLD_ID = b.[HOTELID] ,ROOM_TYPE_NAME = b.[NAME],UPDATE_TIMEMARK = GETDATE(),Creation_Time = GETDATE()  from TB_ROOMTYPE  b  where LAST_MODIFIED_TIME > '{lasttime}'"));

        //                                    if (roomtypedata.Count > 0)
        //                                    {
        //                                        string group_str = "'" + string.Join("','", roomtypedata.Select(x => x.ROOM_TYPE_OLD_ID)) + "'";
        //                                        var room_old_data = db.TBL_ROOM_TYPE_LISTS.FromSqlRaw($"select * from TBL_ROOM_TYPE_LIST where ROOM_TYPE_OLD_ID  in ({group_str})").AsNoTracking().Select(X => new
        //                                        {
        //                                            X.ROOM_TYPE_ID,
        //                                            X.ROOM_TYPE_OLD_ID
        //                                        }).ToArray();
        //                                        foreach (var item in roomtypedata)
        //                                        {
        //                                            item.Creation_Time = DateTime.Now;
        //                                            var OLD_DATA = room_old_data.FirstOrDefault(X => X.ROOM_TYPE_OLD_ID == item.ROOM_TYPE_OLD_ID);
        //                                            if (OLD_DATA != null)
        //                                            {
        //                                                item.ROOM_TYPE_ID = OLD_DATA.ROOM_TYPE_ID;
        //                                                db.Attach(item);
        //                                                db.Entry(item).Property(p => p.UPDATE_TIMEMARK).IsModified = true;
        //                                                db.Entry(item).Property(p => p.Creation_Time).IsModified = true;
        //                                                db.Entry(item).Property(p => p.HOTEL_OLD_ID).IsModified = true;
        //                                                db.Entry(item).Property(p => p.ROOM_TYPE_NAME).IsModified = true;
        //                                            }
        //                                            else
        //                                                db.Entry(item).State = EntityState.Added;
        //                                        }
        //                                        roomtype_row.LAST_UPDATE_TIME = DateTime.Now;
        //                                        db.Entry(roomtype_row).State = EntityState.Modified;
        //                                        db.SaveChanges();
        //                                    }

        //                                    #endregion

        //                                    #region 同步巫工  主机表数据  很多数据需要取到这个

        //                                    var room_row = db.NEW_TABLE_UPDATE_TIME_MARKS.AsTracking().First(x => x.NEW_DB_TABLE_NAME == "TBL_ROOM_BASIC_INFO");
        //                                    if (room_row.LAST_UPDATE_TIME == null)
        //                                        lasttime = "2022-04-01";
        //                                    else
        //                                    {
        //                                        var time = Convert.ToDateTime(room_row.LAST_UPDATE_TIME);
        //                                        if (time.Year < 2022)
        //                                            lasttime = "2022-04-01";
        //                                        else
        //                                            lasttime = time.ToString("yyyy-MM-dd HH:mm:ss.fff");
        //                                    }
        //                                    var roomdata = DataTableHelper.ToEntities<Host_>(SQLSERVER_Helper.GetDatatable(ConfigEntity.Instance.OtherDB, $@"select  * from tb_Hosts b  where  LAST_MODIFIED_TIME > '{lasttime}'"));
        //                                    if (roomdata.Count > 0)
        //                                    {
        //                                        #region 同步房间表数据

        //                                        string room_str = "'" + string.Join("','", roomdata.Select(x => x.ID)) + "'";
        //                                        var room_old_data = db.TBL_ROOM_BASIC_INFOS.FromSqlRaw($"select * from TBL_ROOM_BASIC_INFO where ROOM_OLD_ID  in ({room_str})").AsNoTracking().ToArray();
        //                                        var ROOM_SET_CONFIG = db.TBL_ROOM_SET_CONFIGS.FromSqlRaw($"select * from TBL_ROOM_SET_CONFIG where ROOM_OLD_ID  in ({room_str})").AsNoTracking().ToArray();
        //                                        foreach (var item in roomdata)
        //                                        {

        //                                            var DATA_OLD = room_old_data.FirstOrDefault(X => X.ROOM_OLD_ID == item.ID);
        //                                            if (DATA_OLD == null)
        //                                            {
        //                                                DATA_OLD = new TBL_ROOM_BASIC_INFO();
        //                                            }

        //                                            DATA_OLD.RoomStatusID = item.RoomStatusID;
        //                                            DATA_OLD.MAC = item.MAC;
        //                                            DATA_OLD.AUTH_DATETIME = item.ExpireTime;
        //                                            DATA_OLD.UPDATE_TIMEMARK = DateTime.Now;
        //                                            DATA_OLD.REMARK = item.Remark;
        //                                            DATA_OLD.ROOM_NUMBER = item.RoomNumber;
        //                                            DATA_OLD.ROOM_TYPE_OLD_ID = item.RoomTypeID;
        //                                            DATA_OLD.HOTEL_OLD_ID = item.HOTELID;
        //                                            DATA_OLD.ROOM_OLD_ID = item.ID;

        //                                            if (DATA_OLD.ROOM_ID > 0)
        //                                            {
        //                                                db.Attach(DATA_OLD);
        //                                                db.Entry(DATA_OLD).Property(p => p.AUTH_DATETIME).IsModified = true;
        //                                                db.Entry(DATA_OLD).Property(p => p.UPDATE_TIMEMARK).IsModified = true;
        //                                                db.Entry(DATA_OLD).Property(p => p.RoomStatusID).IsModified = true;
        //                                                db.Entry(DATA_OLD).Property(p => p.HOTEL_OLD_ID).IsModified = true;
        //                                                db.Entry(DATA_OLD).Property(p => p.ROOM_TYPE_OLD_ID).IsModified = true;
        //                                                db.Entry(DATA_OLD).Property(p => p.REMARK).IsModified = true;
        //                                                db.Entry(DATA_OLD).Property(p => p.MAC).IsModified = true;
        //                                                db.Entry(DATA_OLD).Property(p => p.ROOM_NUMBER).IsModified = true;
        //                                            }
        //                                            else
        //                                            {
        //                                                db.Entry(DATA_OLD).State = EntityState.Added;
        //                                            }
        //                                            //添加房间配置信息表
        //                                            var ROOM_SET_CONFIGS = ROOM_SET_CONFIG.FirstOrDefault(X => X.ROOM_OLD_ID == item.ID);
        //                                            if (ROOM_SET_CONFIGS == null)
        //                                            {
        //                                                ROOM_SET_CONFIGS = new TBL_ROOM_SET_CONFIG();
        //                                            }
        //                                            ROOM_SET_CONFIGS.RCU_ROOM = item.RoomNumber;
        //                                            ROOM_SET_CONFIGS.PRODUCT_CODE = item.HostNumber;
        //                                            ROOM_SET_CONFIGS.FW_VER = item.Version;
        //                                            ROOM_SET_CONFIGS.CONFIG_VER = item.ConfigVersion;
        //                                            ROOM_SET_CONFIGS.RCU_SUB_MASK = item.SubnetMask;
        //                                            ROOM_SET_CONFIGS.RCU_CLOUD_SVR_IP = item.ServerIP;
        //                                            ROOM_SET_CONFIGS.RCU_CLOUD_SVR_PORT_MODE = item.ServerPort.ToString();
        //                                            ROOM_SET_CONFIGS.RCU_LOCAL_IP = item.LanIP;
        //                                            ROOM_SET_CONFIGS.RCU_LOCAL_PORT = item.LanPort.ToString();
        //                                            ROOM_SET_CONFIGS.RCU_GETWAY = item.Gateway;
        //                                            ROOM_SET_CONFIGS.RCU_DNS_SERVER = item.DNS;
        //                                            ROOM_SET_CONFIGS.REMARK = item.Remark;
        //                                            ROOM_SET_CONFIGS.ROOM_OLD_ID = item.ID;
        //                                            ROOM_SET_CONFIGS.UPDATE_TIMEMARK = DateTime.Now;
        //                                            ROOM_SET_CONFIGS.IPType = item.IPType;
        //                                            ROOM_SET_CONFIGS.RCU_CLOUD_SVR_PORT = item.ServerPort.ToString();
        //                                            if (ROOM_SET_CONFIGS.ID > 0)
        //                                            {
        //                                                db.Attach(ROOM_SET_CONFIGS);
        //                                                db.Entry(ROOM_SET_CONFIGS).Property(p => p.RCU_ROOM).IsModified = true;
        //                                                db.Entry(ROOM_SET_CONFIGS).Property(p => p.PRODUCT_CODE).IsModified = true;
        //                                                db.Entry(ROOM_SET_CONFIGS).Property(p => p.FW_VER).IsModified = true;
        //                                                db.Entry(ROOM_SET_CONFIGS).Property(p => p.CONFIG_VER).IsModified = true;
        //                                                db.Entry(ROOM_SET_CONFIGS).Property(p => p.RCU_SUB_MASK).IsModified = true;
        //                                                db.Entry(ROOM_SET_CONFIGS).Property(p => p.RCU_CLOUD_SVR_IP).IsModified = true;
        //                                                db.Entry(ROOM_SET_CONFIGS).Property(p => p.RCU_CLOUD_SVR_PORT_MODE).IsModified = true;
        //                                                db.Entry(ROOM_SET_CONFIGS).Property(p => p.RCU_LOCAL_IP).IsModified = true;
        //                                                db.Entry(ROOM_SET_CONFIGS).Property(p => p.RCU_LOCAL_PORT).IsModified = true;
        //                                                db.Entry(ROOM_SET_CONFIGS).Property(p => p.RCU_GETWAY).IsModified = true;
        //                                                db.Entry(ROOM_SET_CONFIGS).Property(p => p.RCU_DNS_SERVER).IsModified = true;
        //                                                db.Entry(ROOM_SET_CONFIGS).Property(p => p.REMARK).IsModified = true;
        //                                                db.Entry(ROOM_SET_CONFIGS).Property(p => p.ROOM_OLD_ID).IsModified = true;
        //                                                db.Entry(ROOM_SET_CONFIGS).Property(p => p.UPDATE_TIMEMARK).IsModified = true;
        //                                                db.Entry(ROOM_SET_CONFIGS).Property(p => p.IPType).IsModified = true;
        //                                                db.Entry(ROOM_SET_CONFIGS).Property(p => p.RCU_CLOUD_SVR_PORT).IsModified = true;

        //                                            }
        //                                            else
        //                                                db.Entry(ROOM_SET_CONFIGS).State = EntityState.Added;


        //                                        }
        //                                        room_row.LAST_UPDATE_TIME = DateTime.Now;
        //                                        db.Entry(room_row).State = EntityState.Modified;
        //                                        db.SaveChanges();
        //                                        #endregion 同步房间表数据同步完毕  
        //                                        #region 同步配置表数据

        //                                        #endregion

        //                                        #region 同步过来的 将房间表的 mac  地址插入 主机表  或者更新
        //                                        // 清除旧数据    获取库里最新的mac
        //                                        CacheData.Clear(CacheData.CacheDataEnum.TBL_RCU_BASIC_INFO);
        //                                        // 获取查询出的 mac 
        //                                        var macdata = roomdata.Select(x => new { MAC = x.MAC.ToUpper(), x.RegisterDate });
        //                                        // 取出库里的mac
        //                                        var mac_data = CacheData.TBL_RCU_BASIC_INFO.Where(x => x.IsImport == 1);
        //                                        // 获取同步的数据中不存的 mac
        //                                        //macdata = macdata.Where(x => !mac_data.Contains(x.MAC));
        //                                        // 遍历添加
        //                                        foreach (var item in macdata)
        //                                        {
        //                                            if (item.MAC.Length < 0)
        //                                                continue;
        //                                            var DA = mac_data.FirstOrDefault(X => X.MAC.ToUpper() == item.MAC);
        //                                            if (DA != null)
        //                                            {
        //                                                db.Attach(DA);
        //                                                DA.REGISTER_DATE = item.RegisterDate;
        //                                                db.Entry(DA).Property(p => p.REGISTER_DATE).IsModified = true;
        //                                            }
        //                                            else
        //                                                db.TBL_RCU_BASIC_INFOS.Add(new TBL_RCU_BASIC_INFO { MAC = item.MAC, IsImport = 1, REGISTER_DATE = item.RegisterDate });
        //                                        }
        //                                        db.SaveChanges();
        //                                        #endregion

        //                                    }

        //                                    #endregion

        //                                    #region 同步季节表  这个表目前可能未曾使用
        //                                    var season_row = db.NEW_TABLE_UPDATE_TIME_MARKS.AsTracking().First(x => x.NEW_DB_TABLE_NAME == "TBL_SEASON");
        //                                    if (room_row.LAST_UPDATE_TIME == null)
        //                                        lasttime = "2022-04-01";
        //                                    else
        //                                    {
        //                                        var time = Convert.ToDateTime(room_row.LAST_UPDATE_TIME);
        //                                        if (time.Year < 2022)
        //                                            lasttime = "2022-04-01";
        //                                        else
        //                                            lasttime = time.ToString("yyyy-MM-dd HH:mm:ss.fff");
        //                                    }
        //                                    // 这里待巫工完善
        //                                    var season_data = DataTableHelper.ToEntities<TBL_SEASON>(SQLSERVER_Helper.GetDatatable(ConfigEntity.Instance.OtherDB, $@"select * from tb_Season b  where (1=1 or 'LAST_MODIFIED_TIME' > '{lasttime}')"));

        //                                    if (season_data.Count > 0)
        //                                    {
        //                                        string room_str = "'" + string.Join("','", season_data.Select(x => x.ID)) + "'";
        //                                        var room_old_data = db.TBL_SEASONS.FromSqlRaw($"select * from TBL_SEASON where ID  in ({room_str})").AsNoTracking().Select(X => new { X.ID }).ToArray();
        //                                        foreach (var item in season_data)
        //                                        {
        //                                            var DATA_OLD = room_old_data.FirstOrDefault(X => X.ID == item.ID);
        //                                            if (DATA_OLD != null)
        //                                            {
        //                                                item.ID = DATA_OLD.ID;
        //                                                db.Attach(item);
        //                                                db.Entry(item).Property(p => p.NAME).IsModified = true;
        //                                                db.Entry(item).Property(p => p.BeginDate).IsModified = true;
        //                                                db.Entry(item).Property(p => p.EndDate).IsModified = true;
        //                                            }
        //                                            else
        //                                                db.Entry(item).State = EntityState.Added;
        //                                        }
        //                                        season_row.LAST_UPDATE_TIME = DateTime.Now;
        //                                        db.Entry(season_row).State = EntityState.Modified;
        //                                        db.SaveChanges();
        //                                    }

        //                                    #endregion

        //                                    #region 同步酒店季节表 TBL_HOTEL_SEASON    这个才是季节表
        //                                    var tbl_hotel_season_row = db.NEW_TABLE_UPDATE_TIME_MARKS.AsTracking().First(x => x.NEW_DB_TABLE_NAME == "TBL_HOTEL_SEASON");
        //                                    if (room_row == null || room_row.LAST_UPDATE_TIME == null)
        //                                        lasttime = "2022-04-01";
        //                                    else
        //                                    {
        //                                        var time = Convert.ToDateTime(room_row.LAST_UPDATE_TIME);
        //                                        if (time.Year < 2022)
        //                                            lasttime = "2022-04-01";
        //                                        else
        //                                            lasttime = time.ToString("yyyy-MM-dd HH:mm:ss.fff");
        //                                    }
        //                                    // 这里待巫工完善 时间信息
        //                                    var tbl_hotel_season_data = DataTableHelper.ToEntities<TBL_HOTEL_SEASON>(SQLSERVER_Helper.GetDatatable(ConfigEntity.Instance.OtherDB, $@"select * from tb_HotelSeason b  where (1=1 or 'LAST_MODIFIED_TIME' > '{lasttime}')"));

        //                                    if (season_data.Count > 0)
        //                                    {
        //                                        string room_str = "'" + string.Join("','", tbl_hotel_season_data.Select(x => x.ID)) + "'";
        //                                        var room_old_data = db.TBL_HOTEL_SEASONS.FromSqlRaw($"select * from TBL_HOTEL_SEASON where ID  in ({room_str})").AsNoTracking().Select(X => new { X.ID }).ToArray();
        //                                        foreach (var item in tbl_hotel_season_data)
        //                                        {
        //                                            var DATA_OLD = room_old_data.FirstOrDefault(X => X.ID == item.ID);
        //                                            if (DATA_OLD != null)
        //                                            {
        //                                                item.ID = DATA_OLD.ID;
        //                                                db.Attach(item);
        //                                                db.Entry(item).Property(p => p.MONTH1).IsModified = true;
        //                                                db.Entry(item).Property(p => p.MONTH2).IsModified = true;
        //                                                db.Entry(item).Property(p => p.MONTH3).IsModified = true;
        //                                                db.Entry(item).Property(p => p.MONTH4).IsModified = true;
        //                                                db.Entry(item).Property(p => p.MONTH5).IsModified = true;
        //                                                db.Entry(item).Property(p => p.MONTH6).IsModified = true;
        //                                                db.Entry(item).Property(p => p.MONTH7).IsModified = true;
        //                                                db.Entry(item).Property(p => p.MONTH8).IsModified = true;
        //                                                db.Entry(item).Property(p => p.MONTH9).IsModified = true;
        //                                                db.Entry(item).Property(p => p.MONTH10).IsModified = true;
        //                                                db.Entry(item).Property(p => p.MONTH11).IsModified = true;
        //                                                db.Entry(item).Property(p => p.MONTH12).IsModified = true;
        //                                            }
        //                                            else
        //                                                db.Entry(item).State = EntityState.Added;
        //                                        }
        //                                        tbl_hotel_season_row.LAST_UPDATE_TIME = DateTime.Now;
        //                                        db.Entry(tbl_hotel_season_row).State = EntityState.Modified;
        //                                        db.SaveChanges();
        //                                    }

        //                                    #endregion
        //                                }
        //                            }
        //                            catch (Exception ex)
        //                            {
        //                                LogHelp.Error(ex.ToString());
        //                                //throw;
        //                            }
        //                            result.Status = true;
        //                            result.messages = "同步成功";
        //                            return result
        //;
        //                        }

        //                    }
        //                }
        //                result.Status = false;
        //                result.messages = "不能频繁刷新";
        //                return result;
        //            }
        //            catch (Exception ex)
        //            {
        //                result.Status = false;
        //                result.messages = ex.Message;
        //                return result;
        //            }

        //        }
        public static List<HotelGroups> Get_HotelGroups()
        {
            try
            {
                var res = new Dictionary<string, Object>();
                res.Add("jsonData", JsonConvert.SerializeObject(new { key = ConfigEntity.Instance.url_key }));
                WEBHELP s = new WEBHELP();
                var resdata = s.Post<ReturnData<List<HotelGroups>>>(ConfigEntity.Instance.url_api + "GetHotelGroupList", res).Result;
                return resdata;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// api同步酒店组 暂未使用
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static bool SYNC_HotelGroups(HotelServiceContext context)
        {
            try
            {
                var data = Get_HotelGroups();
                List<TBL_HOTEL_GROUP_INFO> res = new List<TBL_HOTEL_GROUP_INFO>();
                var old_DATA = CacheData.TBL_HOTEL_GROUP_INFO;

                foreach (var item in data)
                {
                    var old = old_DATA.FirstOrDefault(x => x.HOTEL_GROUP_ID == item.Id);
                    if (old != null)
                    {
                        old.PARENT_ID = item.ParentId;
                        old.REMARK = item.Desc;
                        old.HOTEL_GROUP_NAME = item.Name;
                        context.Entry<TBL_HOTEL_GROUP_INFO>(old).State = EntityState.Unchanged;
                        //res.Add(old);
                        continue;
                    }
                    res.Add(new TBL_HOTEL_GROUP_INFO
                    {
                        PARENT_ID = item.ParentId,
                        REMARK = item.Desc,
                        HOTEL_GROUP_ID = item.Id,
                        HOTEL_GROUP_NAME = item.Name,
                    });
                }
                DbHelperSQL db = new DbHelperSQL(DBSel.BLV_RCU_DB);
                context.Database.OpenConnection();
                var com = context.TBL_HOTEL_GROUP_INFOS.CreateDbCommand();
                try
                {
                    com.CommandText = "SET IDENTITY_INSERT dbo.TBL_HOTEL_GROUP_INFO ON";
                    com.ExecuteNonQuery();
                    context.TBL_HOTEL_GROUP_INFOS.AddRange(res);
                    context.SaveChanges();
                    com.CommandText = ("SET IDENTITY_INSERT dbo.TBL_HOTEL_GROUP_INFO OFF");
                    com.ExecuteNonQuery();

                    return true;
                }
                catch (Exception ex)
                {
                    throw new Exception("保存酒店组信息出错~" + ex.InnerException.Message + ex.Message + JsonConvert.SerializeObject(res));
                }
                finally
                {
                    context.Database.CloseConnection();
                    com.Dispose();
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                CacheData.Clear(CacheData.CacheDataEnum.TBL_HOTEL_GROUP_INFO);
            }
        }

        /// <summary>
        /// api 接口获取同步酒店组 
        /// </summary>
        /// <returns></returns>
        public static List<HotelsAsync> GetHotelList()
        {
            try
            {
                var res = new Dictionary<string, Object>();
                res.Add("jsonData", JsonConvert.SerializeObject(new { key = ConfigEntity.Instance.url_key }));
                WEBHELP s = new WEBHELP();
                var resdata = s.Post<ReturnData<List<HotelsAsync>>>(ConfigEntity.Instance.url_api + "GetHotelList", res).Result;
                return resdata;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 同步酒店  暂未使用
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static bool SYNC_Hotels(HotelServiceContext context)
        {
            try
            {
                var data = GetHotelList();
                List<TBL_HOTEL_BASIC_INFO> res = new List<TBL_HOTEL_BASIC_INFO>();
                var OLD_DATA = CacheData.TBL_HOTEL_BASIC_INFO;
                foreach (HotelsAsync item in data)
                {
                    string str = item.ValidateDate.Replace("Date(", "").Replace(")", "").Replace("/", "");
                    var S = new DateTime(1970, 1, 1, 8, 0, 0).AddMilliseconds(double.Parse(str));
                    var OLDATA = OLD_DATA.FirstOrDefault(x => x.IDOLD == item.ID);
                    if (OLDATA != null)
                    {
                        OLDATA.KEY_IN_DATETIME = item.CreatDate;
                        OLDATA.HOTEL_NAME_CN = item.Name;
                        OLDATA.HOTEL_NAME_EN = item.EName;
                        OLDATA.HOTEL_NAME_TW = item.EName;
                        OLDATA.HOTEL_GROUP = item.SysHotelGroupID;
                        OLDATA.PROJECT_NUMBER = item.Code;
                        OLDATA.HOTEL_CONTACT_PHONE = item.Phone;
                        OLDATA.DETAIL_ADD = item.Address;
                        OLDATA.VALID_DATETIME = S;
                        OLDATA.STATUS = item.Status;
                        OLDATA.IsApprove = item.IsApprove;
                        res.Add(OLDATA);
                        continue;
                    }
                    res.Add(new TBL_HOTEL_BASIC_INFO
                    {
                        KEY_IN_DATETIME = item.CreatDate,
                        HOTEL_NAME_CN = item.Name,
                        HOTEL_NAME_EN = item.EName,
                        HOTEL_NAME_TW = item.EName,
                        HOTEL_GROUP = item.SysHotelGroupID,
                        IDOLD = item.ID,
                        PROJECT_NUMBER = item.Code,
                        HOTEL_CONTACT_PHONE = item.Phone,
                        DETAIL_ADD = item.Address,
                        VALID_DATETIME = S,
                        STATUS = item.Status,
                        IsApprove = item.IsApprove,
                    });
                }
                context.TBL_HOTEL_BASIC_INFOS.UpdateRange(res);
                try
                {
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    throw new Exception("保存酒店信息出错~" + ex.Message + JsonConvert.SerializeObject(res));
                }

                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                CacheData.Clear(CacheData.CacheDataEnum.TBL_HOTEL_BASIC_INFO);
            }
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="ipaddress"></param>
        /// <param name="UserAgent"></param>
        /// <param name="userName"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static Root<Datainfo> SYNC_GetUserinfo(string ipaddress, string UserAgent, string userName, string pwd)
        {
            WEBHELP s = new WEBHELP();
            var res = s.Post<Root<Datainfo>>(ConfigEntity.Instance.Url + "/OTApi/Login", new Dictionary<string, dynamic>() { { "Ip", ipaddress }, { "Uid", userName }, { "Pwd", pwd }, { "appid", ConfigEntity.Instance.Appid }, { "UserAgent", UserAgent }, { "moreLogin", true } });
            return res;
        }
        /// <summary>
        /// api同步房型表   api暂未使用
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static bool SYNC_RoomTypeAndModalsList(HotelServiceContext context)
        {
            try
            {
                var hostedata = CacheData.TBL_HOTEL_BASIC_INFO;
                var old_data = CacheData.TBL_ROOM_TYPE_LIST;
                var RoomTypedata = new List<TBL_ROOM_TYPE_LIST>();
                foreach (var item in hostedata)
                {
                    var data = GetRoomType(item.PROJECT_NUMBER, item.KEY_IN_DATETIME.ToString("yyyy-MM-dd"));
                    if (data == null) { continue; }
                    foreach (var RoomType in data)
                    {
                        var olddata = old_data.FirstOrDefault(x => x.ROOM_TYPE_OLD_ID == RoomType.Code);
                        if (olddata != null)
                        {
                            olddata.HOTEL_ID = item.HOTEL_ID;
                            olddata.ROOM_TYPE_OLD_ID = RoomType.Code;
                            olddata.ROOM_TYPE_NAME = RoomType.Name;
                            RoomTypedata.Add(olddata);
                            continue;
                        }
                        else
                        {
                            RoomTypedata.Add(new TBL_ROOM_TYPE_LIST
                            {
                                ROOM_TYPE_OLD_ID = RoomType.Code,
                                ROOM_TYPE_NAME = RoomType.Name,
                                HOTEL_ID = item.HOTEL_ID
                            });
                        }
                    }
                }
                try
                {
                    context.TBL_ROOM_TYPE_LISTS.UpdateRange(RoomTypedata);
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    throw new Exception("添加保存房型出错：" + ex.Message + JsonConvert.SerializeObject(RoomTypedata));
                }
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                CacheData.Clear(CacheData.CacheDataEnum.TBL_ROOM_TYPE_LIST);
            }
        }
        /// <summary>
        /// api同步房型
        /// </summary>
        /// <param name="code"></param>
        /// <param name="creatDate"></param>
        /// <returns></returns>
        public static List<asyncroomtype> GetRoomType(string code, string creatDate)
        {
            try
            {
                var res = new Dictionary<string, Object>();
                res.Add("jsonData", JsonConvert.SerializeObject(new { code = code, creatDate = creatDate }));
                WEBHELP s = new WEBHELP();
                var resdata = s.Post<ReturnData<List<asyncroomtype>>>(ConfigEntity.Instance.url_api + "GetRoomTypeAndModalsList", res).Result;
                return resdata;
            }
            catch (Exception ex)
            {
                LogHelp.Error(ex.Message);
                return null;
                throw ex;
            }
        }

        public static void GetVal<T>(ref T data, T model, params string[] property)
        {
            Type t = model.GetType();
            PropertyInfo[] PropertyList = t.GetProperties();
            foreach (PropertyInfo item in PropertyList)
            {
                string name = item.Name;
                if (property.Contains(name))
                    item.SetValue(data, item.GetValue(model));
            }
        }
    }
}
