
using BLWWS;
using BLWWS_BLL;
using BLWWS_BLL.Common;
using Newtonsoft.Json;
using NLog;
using System.Net.NetworkInformation;
using System.Text;
using System.Web;
using System.Xml.Linq;

namespace BLWWSCore.SOAP
{
    public class BLWWebServices : IWebServices
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private IWebHostEnvironment _env;
        private IConfiguration _configuration;
        public static Logger _logger = LogManager.GetCurrentClassLogger();

        private readonly string _key = "";
        private static int pmsid = 0;
        public readonly string username = "";
        public readonly string password = "";
        public BLWWebServices(IHttpContextAccessor httpContextAccessor, IConfiguration configuration, IWebHostEnvironment env)
        {
            _httpContextAccessor = httpContextAccessor;
            _configuration = configuration;
            _key = _configuration.GetValue<string>("key");
            username = _configuration.GetValue<string>("username");
            password = _configuration.GetValue<string>("password");
            _env = env;
        }
        //public static string GetClientIP(HttpRequest Request)
        public static string GetClientIP(HttpContext context)
        {
            // 优先级：X-Forwarded-For > X-Real-IP > RemoteIpAddress
            var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();

            if (!string.IsNullOrEmpty(ip))
            {
                // 可能有多个IP，取第一个
                var ips = ip.Split(',', StringSplitOptions.RemoveEmptyEntries);
                if (ips.Length > 0)
                    return ips[0].Trim();
            }

            ip = context.Request.Headers["X-Real-IP"].FirstOrDefault();
            if (!string.IsNullOrEmpty(ip))
                return ip;

            ip = context.Connection.RemoteIpAddress?.ToString();

            // 处理 IPv6 本地地址
            if (ip == "::1")
                ip = "127.0.0.1";

            return ip ?? "Unknown";
        }
        public int AddHotelInfo(string key, string Code, string HotelName, int HotelId)
        {
            int a = 0;
            if (key.Equals("7e533rU:#3721M7%"))
            {
                a = BLL.GetEnableBaoJing(Code);
            }
            return a;
        }

        /// <summary>
        /// 变更手机号
        /// </summary>
        /// <param name="key"></param>
        /// <param name="code"></param>
        /// <param name="roomNumber"></param>
        /// <param name="phoneNumber"></param>
        /// <param name="idNumber"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public bool ChangePhoneNumber(string key, string code, string roomNumber, string phoneNumber, string idNumber, ref string errorMsg)
        {

            if (_key != key)
            {
                errorMsg = "验证码key(" + key + ")有误";
                return false;
            }
            if (string.IsNullOrEmpty(code))
            {
                errorMsg = "编码不能为空";
                return false;
            }
            if (string.IsNullOrEmpty(roomNumber))
            {
                errorMsg = "房号不能为空";
                return false;
            }
            if (string.IsNullOrEmpty(phoneNumber))
            {
                errorMsg = "手机号不能为空，多个以英文逗号,隔开";
                return false;
            }
            try
            {
                if (BLL.GetHotelCode(code).Rows.Count == 0)
                {
                    errorMsg = "编码code(" + code + ")有误";
                    return false;
                }
                if (BLL.ChangePhoneNumber(code, roomNumber, phoneNumber, idNumber) > 0)
                {
                    LogHelper.WriteLog("变更手机号成功：" + code + "-" + roomNumber);
                    return true;
                }
                else
                {
                    errorMsg = "变更手机号失败";
                    return false;
                }
            }
            catch (Exception ex)
            {
                errorMsg = ex.Message;
                LogHelper.WriteLog(code + "-" + ex.ToString());
            }
            return false;
        }

        public bool CheckIn(string key, string code, string roomNumber, DateTime checkInDate, string xmlString, ref string errorMsg, string phoneNumber = "", string idNumber = "")
        {

            var httpContext = _httpContextAccessor.HttpContext;
            if (httpContext == null)
            {

            }

            // 获取所有 Cookie
            var cookies = httpContext.Request.Cookies;

            CheckInYuanShidata data1 = new CheckInYuanShidata();
            data1.CommandType = "CheckIn";
            string msgid = Guid.NewGuid().ToString("N");

            string IP = GetClientIP(httpContext);
            GlobalCache.Init();
            string order_original = "";
            ExtraData EEE = null;
            try
            {
                if (cookies != null && cookies.Count > 0)
                {
                    cookies.TryGetValue("cookiedomain", out var cookieValue);
                    order_original = System.Web.HttpUtility.UrlDecode(cookieValue);
                    EEE = Newtonsoft.Json.JsonConvert.DeserializeObject<ExtraData>(order_original);
                    order_original = EEE.OriginalData;
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Cookie 出错");
            }

            if (EEE != null)
            {
                IP = EEE.RequestIP;
                data1.JianJieData = new JianJie() { OriginallData = EEE.OriginalData };
            }
            else
            {
                data1.ZhiJieData = new ZhiJie()
                {
                    CheckInData = new CheckInData()
                    {
                        key = key,
                        checkInDate = checkInDate,
                        code = code,
                        idNumber = idNumber,
                        phoneNumber = phoneNumber,
                        roomNumber = roomNumber,
                        xmlString = xmlString
                    }
                };
            }
            data1.IP = IP;
            data1.Step = 1;
            data1.RequestId = msgid;
            data1.CurrentTime = DateTime.Now;

            var vvv = JsonConvert.SerializeObject(data1);
            CSRedisCacheHelper.Publish(StaticData.PMSLogMonitor, vvv);


            int YesNoFace = 1;
            if (_key != key)
            {
                errorMsg = "验证码key(" + key + ")有误";
                return false;
            }
            if (string.IsNullOrEmpty(code))
            {
                errorMsg = "编码不能为空";
                return false;
            }
            if (string.IsNullOrEmpty(roomNumber))
            {
                errorMsg = "房号不能为空";
                return false;
            }
            if (string.IsNullOrEmpty(xmlString))
            {
                errorMsg = "客人信息不能为空";
                return false;
            }
            try
            {
                var T = BLL.GetHotelCode(code);

                string hotelid = "";
                string Is_Push_BaoJing = "";
                if (T.Rows.Count == 0)
                {
                    errorMsg = "编码code(" + code + ")有误";
                    return false;
                }
                else
                {
                    string HotelID = T.Rows[0]["HotelID"].ToString();
                    Is_Push_BaoJing = T.Rows[0]["Is_Push_BaoJing"].ToString();
                    hotelid = HotelID;
                }

                long checkInID = 0;
                if (BLL.CheckIn(code, roomNumber, checkInDate, xmlString, YesNoFace, key, ref checkInID, phoneNumber, idNumber, msgid) > 0)
                {
                    if (Is_Push_BaoJing.Equals("1"))
                    {
                        ConstructPushData(code, roomNumber, checkInDate, xmlString, phoneNumber, idNumber, hotelid, order_original);

                        CheckInYuanShidata data2 = new CheckInYuanShidata();
                        data2.RequestId = msgid;
                        data2.Step = 4;
                        data2.CurrentTime = DateTime.Now;
                    }
                    LogHelper.WriteLog("开房成功：" + code + "-" + roomNumber);

                    CheckInYuanShidata data3 = new CheckInYuanShidata();
                    data3.RequestId = msgid;
                    data3.Step = 5;
                    data3.CurrentTime = DateTime.Now;
                    data3.ReturnMsg = "开房成功";


                    var vvv1 = JsonConvert.SerializeObject(data1);
                    CSRedisCacheHelper.Publish(StaticData.PMSLogMonitor, vvv1);
                    return true;
                }
                else
                {
                    errorMsg = "开房失败";

                    CheckInYuanShidata data3 = new CheckInYuanShidata();
                    data3.RequestId = msgid;
                    data3.Step = 5;
                    data3.CurrentTime = DateTime.Now;
                    data3.ReturnMsg = "开房失败";


                    var vvv1 = JsonConvert.SerializeObject(data1);
                    CSRedisCacheHelper.Publish(StaticData.PMSLogMonitor, vvv1);
                    return false;
                }
            }
            catch (Exception ex)
            {
                errorMsg = ex.Message;
                LogHelper.WriteLog(code + "-" + ex.ToString());
            }
            return false;
        }

        public bool CheckIn2(string key, string code, string roomNumber, DateTime checkInDate, string xmlString, ref string errorMsg, ref long checkInID, string phoneNumber = "", string idNumber = "")
        {
            var httpContext = _httpContextAccessor.HttpContext;
            // 获取所有 Cookie
            var cookie = httpContext.Request.Cookies;
            CheckInYuanShidata data1 = new CheckInYuanShidata();
            data1.CommandType = "CheckIn2";
            string msgid = Guid.NewGuid().ToString("N");
            string IP = GetClientIP(httpContext);

            ExtraData EEE = null;
            string order_original = "";
            try
            {

                if (cookie != null && cookie.Count > 0)
                {
                    cookie.TryGetValue("cookiedomain", out var cookieValue);
                    order_original = HttpUtility.UrlDecode(cookieValue);
                    EEE = JsonConvert.DeserializeObject<ExtraData>(order_original);
                    order_original = EEE.OriginalData;
                    IP = EEE.RequestIP;
                    data1.JianJieData = new JianJie() { OriginallData = order_original };
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Cookie 出错" + ex.Message);
            }
            if (EEE == null)
            {
                data1.ZhiJieData = new ZhiJie()
                {
                    CheckInData = new CheckInData()
                    {
                        key = key,
                        checkInDate = checkInDate,
                        code = code,
                        idNumber = idNumber,
                        phoneNumber = phoneNumber,
                        roomNumber = roomNumber,
                        xmlString = xmlString
                    }
                };
            }

            data1.Step = 1;
            data1.RequestId = msgid;
            data1.CurrentTime = DateTime.Now;
            data1.IP = IP;
            var vvv = JsonConvert.SerializeObject(data1);
            CSRedisCacheHelper.Publish(StaticData.PMSLogMonitor, vvv);

            PmsInterface info = new PmsInterface()
            {
                pmstype = 1,
                DateTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                pmsContent = xmlString,
                hotelid = -1,
            };
            pmsid = SqlSugarBase.GesmartDb().Insertable(info).ExecuteReturnIdentity();
            List<pmsLog> pmsinfo = new List<pmsLog>();
            pmsLog pmslog = new pmsLog
            {
                pmsid = pmsid,
                app = 1,
                step = 103,
                Data = xmlString,
                Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                message = "收到上传人pms信息",

            };
            pmsinfo.Add(pmslog);
            int YesNoFace = 0;
            if (_key != key)
            {
                errorMsg = "验证码key(" + key + ")有误";
                pmsLog pmsn = new pmsLog
                {
                    pmsid = pmsid,
                    app = 1,
                    step = 110,
                    Data = "false" + errorMsg + "=验证码key(" + key + ")有误",
                    Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                    message = "开房接口pms回复信息",
                };
                pmsinfo.Add(pmsn);
                SqlSugarBase.GesmartDb().Insertable(pmsinfo).ExecuteCommand();
                return false;
            }
            if (string.IsNullOrEmpty(code))
            {
                errorMsg = "编码不能为空";
                pmsLog pmsn = new pmsLog
                {
                    pmsid = pmsid,
                    app = 1,
                    step = 111,
                    Data = "false" + errorMsg + "=编码不能为空",
                    Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                    message = "开房接口pms回复信息",
                };
                pmsinfo.Add(pmsn);
                SqlSugarBase.GesmartDb().Insertable(pmsinfo).ExecuteCommand();
                return false;
            }
            if (string.IsNullOrEmpty(roomNumber))
            {
                errorMsg = "房号不能为空";
                pmsLog pmsn = new pmsLog
                {
                    pmsid = pmsid,
                    app = 1,
                    step = 112,
                    Data = "false" + errorMsg + "=房号不能为空",
                    Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                    message = "开房接口pms回复信息",
                };
                pmsinfo.Add(pmsn);
                SqlSugarBase.GesmartDb().Insertable(pmsinfo).ExecuteCommand();
                return false;
            }
            if (string.IsNullOrEmpty(xmlString))
            {
                errorMsg = "客人信息不能为空";
                pmsLog pmsn = new pmsLog
                {
                    pmsid = pmsid,
                    app = 1,
                    step = 113,
                    Data = "false" + errorMsg + "=客人信息不能为空",
                    Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                    message = "开房接口pms回复信息",
                };
                pmsinfo.Add(pmsn);
                SqlSugarBase.GesmartDb().Insertable(pmsinfo).ExecuteCommand();
                return false;
            }
            try
            {


                var T = BLL.GetHotelCode(code);

                string hotelid = "";
                string Is_Push_BaoJing = "";
                if (T.Rows.Count == 0)
                {
                    errorMsg = "编码code(" + code + ")有误";
                    return false;
                }
                else
                {
                    string HotelID = T.Rows[0]["HotelID"].ToString();
                    Is_Push_BaoJing = T.Rows[0]["Is_Push_BaoJing"].ToString();
                    hotelid = HotelID;
                }
                //if (BLL.GetHotelCode(code).Rows.Count == 0)
                //{
                //    errorMsg = "编码code(" + code + ")有误";
                //    return false;
                //}
                if (BLL.CheckIn(code, roomNumber, checkInDate, xmlString, YesNoFace, key, ref checkInID, phoneNumber, idNumber, msgid) > 0)
                {
                    //LogHelper.WriteLog("有人脸机的接口回复信息:true,开房成功：" + code + "-" + roomNumber);
                    pmsLog pmsn = new pmsLog
                    {
                        pmsid = pmsid,
                        app = 1,
                        step = 116,
                        Data = "true",
                        Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                        message = "开房接口pms回复信息",
                    };
                    pmsinfo.Add(pmsn);
                    SqlSugarBase.GesmartDb().Insertable(pmsinfo).ExecuteCommand();

                    if (Is_Push_BaoJing.Equals("1"))
                    {
                        ConstructPushData(code, roomNumber, checkInDate, xmlString, phoneNumber, idNumber, hotelid, order_original);
                    }

                    CheckInYuanShidata data3 = new CheckInYuanShidata();
                    data3.RequestId = msgid;
                    data3.Step = 5;
                    data3.CurrentTime = DateTime.Now;
                    data3.ReturnMsg = "开房成功";


                    var vvv1 = JsonConvert.SerializeObject(data1);
                    CSRedisCacheHelper.Publish(StaticData.PMSLogMonitor, vvv1);
                    return true;
                }
                else
                {
                    //LogHelper.WriteLog("有人脸机的接口回复信息:false,errorMsg = 开房失败");
                    pmsLog pmsn = new pmsLog
                    {
                        pmsid = pmsid,
                        app = 1,
                        step = 120,
                        Data = "false" + errorMsg + "=开房失败",
                        Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                        message = "开房接口pms回复信息",
                    };
                    pmsinfo.Add(pmsn);
                    SqlSugarBase.GesmartDb().Insertable(pmsinfo).ExecuteCommand();
                    errorMsg = "开房失败";


                    CheckInYuanShidata data3 = new CheckInYuanShidata();
                    data3.RequestId = msgid;
                    data3.Step = 5;
                    data3.CurrentTime = DateTime.Now;
                    data3.ReturnMsg = errorMsg;


                    var vvv1 = JsonConvert.SerializeObject(data1);
                    CSRedisCacheHelper.Publish(StaticData.PMSLogMonitor, vvv1);
                    return false;
                }
            }
            catch (Exception ex)
            {
                errorMsg = ex.Message;
                LogHelper.WriteLog(code + "-" + ex.ToString());
            }
            return false;
        }

        public bool CheckOut(string key, string code, string roomNumber, DateTime checkOutDate, ref string errorMsg)
        {

            var httpContext = _httpContextAccessor.HttpContext;
            // 获取所有 Cookie
            var cookie = httpContext.Request.Cookies;
            CheckInYuanShidata data1 = new CheckInYuanShidata();
            data1.CommandType = "CheckOut";
            string msgid = Guid.NewGuid().ToString("N");
            string IP = GetClientIP(httpContext);


            ExtraData EEE = null;
            string order_original = "";
            try
            {
                if (cookie != null && cookie.Count > 0)
                {
                    cookie.TryGetValue("cookiedomain", out var cookieValue);
                    order_original = HttpUtility.UrlDecode(cookieValue);
                    EEE = Newtonsoft.Json.JsonConvert.DeserializeObject<ExtraData>(order_original);
                    order_original = EEE.OriginalData;
                    IP = EEE.RequestIP;

                    data1.JianJieData = new JianJie() { OriginallData = order_original };
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("cookie 出错");
            }

            if (EEE == null)
            {
                data1.ZhiJieData = new ZhiJie()
                {
                    CheckOutData = new CheckOutData()
                    {
                        checkOutDate = checkOutDate,
                        code = code,
                        key = key,
                        roomNumber = roomNumber,
                    }
                };
            }

            data1.IP = IP;
            data1.Step = 1;
            data1.RequestId = msgid;
            var vvv = JsonConvert.SerializeObject(data1);
            CSRedisCacheHelper.Publish(StaticData.PMSLogMonitor, vvv);

            StringBuilder sb = new StringBuilder();
            var rlinfo = new
            {
                keys = key,
                codes = code,
                roomNumbers = roomNumber,
                checkOutDates = checkOutDate,
            };

            sb.Append(Newtonsoft.Json.JsonConvert.SerializeObject(rlinfo));
            PmsInterface info = new PmsInterface
            {
                pmstype = 0,
                DateTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                pmsContent = sb.ToString(),
                hotelid = -1

            };
            int pmsids = SqlSugarBase.GesmartDb().Insertable(info).ExecuteReturnIdentity();
            string ip = "";

            // 获取所有网络接口
            NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();

            // 遍历每个网络接口
            foreach (NetworkInterface networkInterface in interfaces)
            {
                // 获取IP地址
                IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();
                UnicastIPAddressInformationCollection ipAddresses = ipProperties.UnicastAddresses;

                // 遍历每个IP地址
                foreach (UnicastIPAddressInformation ipAddress in ipAddresses)
                {
                    // 判断是否为IPv4地址
                    if (ipAddress.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        //过滤本地ip
                        if (ipAddress.Address.ToString() != "127.0.0.1")
                        {
                            //局域网ip
                            ip = ipAddress.Address.ToString();
                        }

                    }
                }
            }
            pmsLog pmslog = new pmsLog
            {
                pmsid = pmsids,
                app = 1,
                step = 101,
                Data = sb.ToString(),
                Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                message = "pms服务收到信息",
                Ip = ip
                //HotelCode = dr["Code"].ToString(),
                //roomid = dr["RoomNumber"].ToString()
            };
            SqlSugarBase.GesmartDb().Insertable(pmslog).ExecuteCommand();



            if (_key != key)
            {
                errorMsg = "验证码key(" + key + ")有误";

                pmsLog pms = new pmsLog
                {
                    pmsid = pmsids,
                    app = 1,
                    step = 130,
                    Data = "false," + errorMsg + "=验证码key(" + key + ")有误",
                    Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                    message = "退房接口pms回复信息",
                };


                SqlSugarBase.GesmartDb().Insertable(pms).ExecuteCommand();
                return false;
            }
            if (string.IsNullOrEmpty(code))
            {
                errorMsg = "编码不能为空";
                pmsLog pms = new pmsLog
                {
                    pmsid = pmsids,
                    app = 1,
                    step = 131,
                    Data = "false," + errorMsg + "=编码不能为空",
                    Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                    message = "上传入住人信息pms回复信息",
                };

                SqlSugarBase.GesmartDb().Insertable(pms).ExecuteCommand();

                return false;
            }
            if (string.IsNullOrEmpty(roomNumber))
            {
                errorMsg = "房号不能为空";
                pmsLog pms = new pmsLog
                {
                    pmsid = pmsids,
                    app = 1,
                    step = 132,
                    Data = "false," + errorMsg + "=房号不能为空",
                    Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                    message = "退房接口pms回复信息",
                };
                SqlSugarBase.GesmartDb().Insertable(pms).ExecuteCommand();
                return false;
            }
            try
            {

                var T = BLL.GetHotelCode(code);

                string hotelid = "";

                string Is_Push_BaoJing = "";
                if (T.Rows.Count == 0)
                {
                    errorMsg = "编码code(" + code + ")有误";
                    pmsLog pms = new pmsLog
                    {
                        pmsid = pmsids,
                        app = 1,
                        step = 133,
                        Data = "false," + errorMsg + "=编码code(" + code + ")有误",
                        Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                        message = "退房接口pms回复信息",
                    };

                    SqlSugarBase.GesmartDb().Insertable(pms).ExecuteCommand();

                    return false;
                }
                else
                {
                    string HotelID = T.Rows[0]["HotelID"].ToString();
                    Is_Push_BaoJing = T.Rows[0]["Is_Push_BaoJing"].ToString();
                    hotelid = HotelID;
                }
                if (BLL.CheckOut(code, roomNumber, checkOutDate, pmsids, msgid) > 0)
                {
                    pmsLog pms = new pmsLog
                    {
                        pmsid = pmsids,
                        app = 1,
                        step = 136,
                        Data = "true",
                        Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                        message = "退房接口pms回复信息",
                    };


                    SqlSugarBase.GesmartDb().Insertable(pms).ExecuteCommand();
                    LogHelper.WriteLog("退房成功：" + code + "-" + roomNumber);


                    if (Is_Push_BaoJing.Equals("1"))
                    {
                        PMSDataBase b = new PMSDataBase();
                        b.hotel_code = code;
                        b.hotel_id = hotelid;
                        b.room_no = roomNumber;
                        b.order_no = System.Guid.NewGuid().ToString("N");
                        b.check_out_original = order_original;
                        PMSDataPushBaoJing(b, 2);
                    }


                    CheckInYuanShidata data3 = new CheckInYuanShidata();
                    data3.RequestId = msgid;
                    data3.Step = 5;
                    data3.CurrentTime = DateTime.Now;
                    data3.ReturnMsg = "退房成功";


                    var vvv1 = JsonConvert.SerializeObject(data1);
                    CSRedisCacheHelper.Publish(StaticData.PMSLogMonitor, vvv1);
                    return true;
                }
                else
                {
                    pmsLog pms = new pmsLog
                    {
                        pmsid = pmsids,
                        app = 1,
                        step = 134,
                        Data = "false,errorMsg=退房失败",
                        Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                        message = "退房接口pms回复信息",
                    };


                    SqlSugarBase.GesmartDb().Insertable(pms).ExecuteCommand();
                    errorMsg = "退房失败";

                    CheckInYuanShidata data3 = new CheckInYuanShidata();
                    data3.RequestId = msgid;
                    data3.Step = 5;
                    data3.CurrentTime = DateTime.Now;
                    data3.ReturnMsg = errorMsg;


                    var vvv1 = JsonConvert.SerializeObject(data1);
                    CSRedisCacheHelper.Publish(StaticData.PMSLogMonitor, vvv1);
                    return false;
                }

            }
            catch (Exception ex)
            {
                errorMsg = ex.Message;
                LogHelper.WriteLog(code + "-" + ex.ToString());
            }
            return false;
        }

        /// <summary>
        ///获取是否推送PMS数据到宝镜 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public int GetPushBaoJing_IsEnable(string key, string code)
        {

            int a = 0;
            if (key.Equals("7e533rU:#3721M7%"))
            {
                a = BLL.GetEnableBaoJing(code);
            }
            return a;
        }

        /// <summary>
        ///推送数据到宝镜 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="code"></param>
        /// <param name="isable"></param>
        public void PushBaoJing_IsEnable(string key, string code, bool isable)
        {
            if (key.Equals("7e533rU:#3721M7%"))
            {
                int a = 0;
                if (isable)
                {
                    a = 1;
                }
                BLL.EnableBaoJing(code, a);
            }
        }

        public bool RentRoom(string key, string code, string roomNumber, DateTime rentDate, ref string errorMsg)
        {

            var httpContext = _httpContextAccessor.HttpContext;
            var cookie = httpContext.Request.Cookies;

            CheckInYuanShidata data1 = new CheckInYuanShidata();
            data1.CommandType = "RentRoom";
            string msgid = Guid.NewGuid().ToString("N");
            string IP = GetClientIP(httpContext);


            ExtraData EEE = null;
            string order_original = "";
            try
            {
                if (cookie != null && cookie.Count > 0)
                {
                    cookie.TryGetValue("cookiedomain", out var cookieValue);
                    order_original = HttpUtility.UrlDecode(cookieValue);
                    EEE = Newtonsoft.Json.JsonConvert.DeserializeObject<ExtraData>(order_original);
                    order_original = EEE.OriginalData;
                    IP = EEE.RequestIP;

                    data1.JianJieData = new JianJie() { OriginallData = order_original };
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("cookie 出错");
            }

            if (EEE == null)
            {
                data1.ZhiJieData = new ZhiJie()
                {
                    RentData = new RentData()
                    {
                        code = code,
                        key = key,
                        roomNumber = roomNumber,
                        rentDate = rentDate
                    }
                };
            }

            data1.Step = 1;
            data1.IP = IP;
            data1.RequestId = msgid;
            var vvv = JsonConvert.SerializeObject(data1);
            CSRedisCacheHelper.Publish(StaticData.PMSLogMonitor, vvv);
            if (_key != key)
            {
                errorMsg = "验证码key(" + key + ")有误";
                return false;
            }
            if (string.IsNullOrEmpty(code))
            {
                errorMsg = "编码不能为空";
                return false;
            }
            if (string.IsNullOrEmpty(roomNumber))
            {
                errorMsg = "房号不能为空";
                return false;
            }
            try
            {
                if (BLL.GetHotelCode(code).Rows.Count == 0)
                {
                    errorMsg = "编码code(" + code + ")有误";
                    return false;
                }
                if (BLL.RentRoom(code, roomNumber, rentDate, msgid) > 0)
                {
                    CheckInYuanShidata data3 = new CheckInYuanShidata();
                    data3.RequestId = msgid;
                    data3.Step = 5;
                    data3.CurrentTime = DateTime.Now;
                    data3.ReturnMsg = "变更待租成功：" + code + "-" + roomNumber;

                    var vvv1 = JsonConvert.SerializeObject(data1);
                    CSRedisCacheHelper.Publish(StaticData.PMSLogMonitor, vvv1);

                    LogHelper.WriteLog("变更待租成功：" + code + "-" + roomNumber);
                    return true;
                }
                else
                {

                    errorMsg = "变更房态失败";

                    CheckInYuanShidata data3 = new CheckInYuanShidata();
                    data3.RequestId = msgid;
                    data3.Step = 5;
                    data3.CurrentTime = DateTime.Now;
                    data3.ReturnMsg = errorMsg;
                    var vvv1 = JsonConvert.SerializeObject(data1);
                    CSRedisCacheHelper.Publish(StaticData.PMSLogMonitor, vvv1);

                    return false;
                }

            }
            catch (Exception ex)
            {
                errorMsg = ex.Message;
                LogHelper.WriteLog(code + "-" + ex.ToString());
            }
            return false;
        }

        public bool UploadPhoto(string key, string code, long checkInID, int idType, string idCard, string name, int sex, string birthday, string photoUrl, byte[] photo, ref string errorMsg)
        {

            try
            {
                string photoData = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8}", key, code, checkInID, idType, idCard, name, sex, birthday, photoUrl);

                LogHelper.WriteLog("UploadPhoto 传过的数据为:" + photoData);

                //if (photo.Length > 0)
                //{
                //    //string ImageByte = Tools.ByteToString(photo);

                //    //LogHelper.WriteLog("UploadPhoto 传过的图片数据为:" + ImageByte);
                //}

                #region 新添加的代码

                string ip = "";
                List<pmsLog> ts = new List<pmsLog>();
                // 获取所有网络接口
                NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();

                // 遍历每个网络接口
                foreach (NetworkInterface networkInterface in interfaces)
                {
                    // 获取IP地址
                    IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();
                    UnicastIPAddressInformationCollection ipAddresses = ipProperties.UnicastAddresses;

                    // 遍历每个IP地址
                    foreach (UnicastIPAddressInformation ipAddress in ipAddresses)
                    {
                        // 判断是否为IPv4地址
                        if (ipAddress.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        {
                            //过滤本地ip
                            if (ipAddress.Address.ToString() != "127.0.0.1")
                            {
                                //局域网ip
                                ip = ipAddress.Address.ToString();
                            }

                        }
                    }
                }


                if (idCard.Contains("*") || string.IsNullOrEmpty(idCard))
                {
                    idCard = Tools.GetCurrentTimeStamp(DateTime.Now).ToString();
                    //idCard = idworker.nextId().ToString();
                }
                Uploadinfo uploadinfo = new Uploadinfo()
                {
                    key = key,
                    code = code,
                    checkInID = checkInID,
                    idType = idType,
                    idCard = idCard,
                    name = name,
                    sex = sex,
                    birthday = birthday,
                    photoUrl = photoUrl,
                    //photo = "photo.Length_"+ photo.Length,
                };
                string jsonString = JsonConvert.SerializeObject(uploadinfo);

                pmsLog pmslog = new pmsLog
                {
                    pmsid = pmsid,
                    app = 1,
                    step = 101,
                    Data = jsonString,
                    Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                    message = "pms服务收到信息",
                    Ip = ip
                };
                ts.Add(pmslog);
                //SqlSugarBase.GesmartDb().Insertable(pmslog).ExecuteCommand();
                #endregion


                if (_key != key)
                {
                    errorMsg = "验证码key(" + key + ")有误";
                    pmsLog pmsn = new pmsLog
                    {
                        pmsid = pmsid,
                        app = 1,
                        step = 110,
                        Data = "false," + errorMsg + "=验证码key(" + key + ")有误",
                        Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                        message = "上传入住人信息pms回复信息",
                    };
                    ts.Add(pmsn);
                    SqlSugarBase.GesmartDb().Insertable(ts).ExecuteCommand();
                    return false;
                }
                if (string.IsNullOrEmpty(code))
                {
                    errorMsg = "编码不能为空";
                    pmsLog pmsn = new pmsLog
                    {
                        pmsid = pmsid,
                        app = 1,
                        step = 111,
                        Data = "false," + errorMsg + "=编码不能为空",
                        Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                        message = "上传入住人信息pms回复信息",
                    };
                    ts.Add(pmsn);
                    SqlSugarBase.GesmartDb().Insertable(ts).ExecuteCommand();
                    return false;
                }
                string msg = "";

                //这里要
                string PICPath = _env.WebRootPath + "\\pic";
                if (BLL.UploadPhoto(idType, idCard, name, sex, birthday, photoUrl, photo, checkInID, pmsid, ref msg, PICPath) > 0)
                {
                    pmsLog pmsn = new pmsLog
                    {
                        pmsid = pmsid,
                        app = 1,
                        step = 116,
                        Data = "true",
                        Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                        message = "上传入住人信息pms回复信息",
                    };
                    ts.Add(pmsn);
                    SqlSugarBase.GesmartDb().Insertable(ts).ExecuteCommand();
                    return true;
                }
                else
                {
                    errorMsg = msg;
                    pmsLog pmsn = new pmsLog
                    {
                        pmsid = pmsid,
                        app = 1,
                        step = 114,
                        Data = "false，errorMsg=开房失败",
                        Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                        message = "上传入住人信息pms回复信息" + msg,
                    };
                    ts.Add(pmsn);
                    SqlSugarBase.GesmartDb().Insertable(ts).ExecuteCommand();
                    return false;
                }
            }
            catch (Exception ex)
            {
                errorMsg = ex.Message;
                LogHelper.WriteLog(ex.ToString());
                return false;
            }


        }


        /// <summary>
        /// 发送数据到宝镜，
        /// 本来应该是宝镜 和PMS数据对接的
        /// </summary>
        /// <param name="code"></param>
        /// <param name="roomNumber"></param>
        /// <param name="checkInDate"></param>
        /// <param name="xmlString"></param>
        /// <param name="phoneNumber"></param>
        /// <param name="idNumber"></param>
        /// <param name="hotelid"></param>
        private void ConstructPushData(string code, string roomNumber, DateTime checkInDate, string xmlString, string phoneNumber, string idNumber, string hotelid, string order_original = "")
        {
            try
            {
                //<interface orderno="" cost="费 用" roomtype="房型" breakfast="1" occupancy="入住人数" deposit="押金">
                //  <item idtype="0" idcard="441323xxxxxxxxxxxx" customer="张三" sex="男" country="0" checkindate="2015-07-01 13:45:20" checkoutdate="2015-07-02 13:45:20"></item>
                //  </interface>
                List<Info> llla = new List<Info>();

                //<items><item customer="安赞同" idcard="2110**********222X" sex="女" country="0" checkindate="2025-06-19 16:26:14" checkoutdate="2025-06-20 12:00:00"/></items>

                XDocument doc1 = XDocument.Parse(xmlString);
                XElement Root = doc1.Root;
                string orderno = Root.Attribute("orderno")?.Value;
                string cost = Root.Attribute("cost")?.Value;

                //是否有早餐
                string breakfast = Root.Attribute("breakfast")?.Value;
                //押金
                string deposit = Root.Attribute("deposit")?.Value;

                var LES = Root.Elements("item");
                foreach (var item in LES)
                {
                    Info iia = new Info();
                    string customer = item.Attribute("customer").Value;
                    string sex = item.Attribute("sex").Value;
                    int sss = 0;
                    if (sex.Equals("男") || sex.Equals("male"))
                    {
                        sss = 1;
                    }
                    else
                    {
                        sss = 0;
                    }
                    iia.sex = sss;
                    iia.name = customer;
                    if (string.IsNullOrEmpty(phoneNumber))
                    {
                        phoneNumber = "16618780987";
                    }

                    iia.mobile = phoneNumber;
                    if (string.IsNullOrEmpty(idNumber))
                    {
                        idNumber = "410881188908809321";
                    }
                    iia.idcard = idNumber;
                    iia.address = "";
                    llla.Add(iia);
                }

                PMSData p = new PMSData();
                p.hotel_code = code;
                p.hotel_id = hotelid;
                if (string.IsNullOrEmpty(orderno))
                {
                    p.order_no = Guid.NewGuid().ToString("N");
                }
                else
                {
                    p.order_no = orderno;
                }
                p.room_no = roomNumber;
                p.checkIn = checkInDate.ToString("yyyy-MM-dd HH:mm:ss");
                p.checkOut = checkInDate.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss");
                p.is_breakfast = 0;
                if (!string.IsNullOrEmpty(breakfast) && breakfast.Equals("1"))
                {
                    p.is_breakfast = 1;
                }
                p.breakfast = 1;
                p.rateCode = "";
                p.amount = deposit;
                p.order_original = order_original;
                p.infos = llla;

                _logger.Error("给宝镜推送开房数据");
                PMSDataPushBaoJing(p, 1);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("XmlString: " + xmlString + "," + code + "," + roomNumber);
                LogHelper.WriteLog("给宝镜推送数据 error: " + ex.ToString());
            }
        }


        /// <summary>
        /// 推送数据到 宝镜系统
        /// </summary>
        /// <param name="p"></param>
        public void PMSDataPushBaoJing(PMSDataBase p, int abc)
        {
            //签名加密规则：hotel_code=酒店编码&time=时间戳&key=密钥


            //String = ‘blv001-123456’
            //密钥 = MD5(String);
            string str = string.Format("{0}-{1}", username, password);

            long lll = Common.GetCurrentTimeStamp(DateTime.Now);
            string Key = Common.MD5Encrypt(str);
            string SignOriginal = string.Format("hotel_code={0}&time={1}&key={2}", p.hotel_code, lll, Key);
            string SignStr = Common.MD5Encrypt(SignOriginal);
            p.time = lll.ToString();
            p.sign = SignStr;


            List<pmsLog> pmsinfobj = new List<pmsLog>();
            pmsLog pmslogbj = new pmsLog
            {
                pmsid = pmsid,
                app = 1,
                step = abc == 1 ? 146 : 147, // 146开房 147退房
                Data = p.ToString(),
                Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                message = abc == 1 ? "推送开房信息到宝镜" : "推送退房信息到宝镜",

            };
            pmsinfobj.Add(pmslogbj);

            try
            {
                if (abc == 1)
                {
                    HttpSendData.SendData(p);
                }
                else if (abc == 2)
                {
                    HttpSendData.SendData_CheckOut(p);
                }
                else
                {

                }
            }
            catch (Exception ex)
            {

            }
        }



    }
}
