using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Timers;
using System.Xml;
using BLWWS_BLL;
using System.Data.SqlTypes;
using System.Text;
using System.Xml.Linq;
using Newtonsoft.Json;
using System.Net.NetworkInformation;
using System.Text.RegularExpressions;
using System.ServiceModel.Channels;
using System.Configuration;
using Common;
using Quartz;
using System.Threading.Tasks;
using Common.Logging;
using System.Net;
using RestSharp;
using BLWWS_BLL.Common;

namespace BLWWS
{
    /// <summary>
    /// blwws 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://www.blw.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class blwws : System.Web.Services.WebService
    {
        public static string GetClientIP(HttpRequest Request)
        {
            string IP = "";
            string PPP = Request.UserHostAddress;
            string III = Request.ServerVariables["REMOTE_ADDR"];
            if (string.IsNullOrEmpty(III))
            {
                IP = PPP;
            }
            else
            {
                IP = III;
            }
            return IP;
        }
        /// <summary>
        /// 验证码
        /// </summary>
        private static readonly string _key = System.Configuration.ConfigurationManager.AppSettings["key"];
        private static int pmsid = 0;
        [WebMethod(Description = "开房<br/>key：验证码（我方提供），code：编码（我方提供），roomNumber：房号，checkInDate：入住日期，xmlString：客人信息，errorMsg：返回错误信息，phoneNumber：手机号码（多个以英文逗号,隔开），idNumber：身份证号（多个以英文逗号,隔开）：获取微信登录验证码")]
        //没有人脸机的接口
        public bool CheckIn(string key, string code, string roomNumber, DateTime checkInDate, string xmlString, ref string errorMsg, string phoneNumber = "", string idNumber = "")
        {
            CheckInYuanShidata data1 = new CheckInYuanShidata();
            data1.CommandType = "CheckIn";
            string msgid = Guid.NewGuid().ToString("N");

            string IP = GetClientIP(HttpContext.Current.Request);
            GlobalCache.Init();
            string order_original = "";
            ExtraData EEE = null;
            try
            {
                var cookie = HttpContext.Current.Request.Cookies["cookiedomain"];
                if (cookie != null)
                {
                    order_original = HttpUtility.UrlDecode(cookie.Value);
                    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;
        }

        [WebMethod(Description = "开房<br/>key：验证码（我方提供），code：编码（我方提供），roomNumber：房号，checkInDate：入住日期，xmlString：客人信息，errorMsg：返回错误信息，checkInID：返回入住记录ID，phoneNumber：手机号码（多个以英文逗号,隔开），idNumber：身份证号（多个以英文逗号,隔开）：获取微信登录验证码")]
        //有人脸机的接口
        public bool CheckIn2(string key, string code, string roomNumber, DateTime checkInDate, string xmlString, ref string errorMsg, ref long checkInID, string phoneNumber = "", string idNumber = "")
        {

            CheckInYuanShidata data1 = new CheckInYuanShidata();
            data1.CommandType = "CheckIn2";
            string msgid = Guid.NewGuid().ToString("N");
            string IP = GetClientIP(HttpContext.Current.Request);

            ExtraData EEE = null;
            string order_original = "";
            try
            {
                var cookie = HttpContext.Current.Request.Cookies["cookiedomain"];
                if (cookie != null)
                {
                    order_original = HttpUtility.UrlDecode(cookie.Value);
                    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)
            {
                _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;
        }

        [WebMethod(Description = "上传入住人信息<br/>key：验证码（我方提供），code：编码（我方提供），checkInID：入住记录ID，idType：证件类型(0身份证，1护照，2军官证，3其他)，idCard：证件号码，name：姓名，sex：性别(0女，1男，2其他)，birthday：出生日期(1999-01-01)，photoUrl：图片路径（与photo二选一），photo：图片（二进制），errorMsg：错误信息")]
        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 = "";
                if (BLL.UploadPhoto(idType, idCard, name, sex, birthday, photoUrl, photo, checkInID, pmsid, ref msg) > 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;
            }

        }

        [WebMethod(Description = "变更手机号<br/>key：验证码（我方提供），code：编码（我方提供），roomNumber：房号，errorMsg：错误信息，phoneNumber：手机号码（多个以英文逗号,隔开），idNumber：身份证号：获取验证码")]
        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;
        }

        [WebMethod(Description = "退房<br/>key：验证码（我方提供），code：编码（我方提供），roomNumber：房号，checkOutDate：退房日期，errorMsg：错误信息")]
        public bool CheckOut(string key, string code, string roomNumber, DateTime checkOutDate, ref string errorMsg)
        {

            CheckInYuanShidata data1 = new CheckInYuanShidata();
            data1.CommandType = "CheckOut";
            string msgid = Guid.NewGuid().ToString("N");
            string IP = GetClientIP(HttpContext.Current.Request);

            ExtraData EEE = null;
            string order_original = "";
            try
            {
                var cookie = HttpContext.Current.Request.Cookies["cookiedomain"];
                if (cookie != null)
                {
                    order_original = HttpUtility.UrlDecode(cookie.Value);
                    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;
        }

        [WebMethod(Description = "待租<br/>key：验证码（我方提供），code：编码（我方提供），roomNumber：房号，rentDate：变更待租日期，errorMsg：错误信息")]
        public bool RentRoom(string key, string code, string roomNumber, DateTime rentDate, ref string errorMsg)
        {

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



            ExtraData EEE = null;
            string order_original = "";
            try
            {
                var cookie = HttpContext.Current.Request.Cookies["cookiedomain"];
                if (cookie != null)
                {
                    order_original = HttpUtility.UrlDecode(cookie.Value);
                    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;
        }

        [WebMethod(Description = "推送数据到宝镜")]
        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);
            }
        }

        [WebMethod(Description = "获取是否推送PMS数据到宝镜")]
        public int GetPushBaoJing_IsEnable(string key, string code)
        {
            int a = 0;
            if (key.Equals("7e533rU:#3721M7%"))
            {
                a = BLL.GetEnableBaoJing(code);
            }
            return a;
        }

        [WebMethod()]
        public int AddHotelInfo(string key, string Code, string HotelName, int HotelId)
        {

            int a = 0;
            try
            {
                if (key.Equals("7e533rU:#3721M7%"))
                {
                    a = BLL.AddHotelInfo(Code, HotelName, HotelId);
                }
            }
            catch (Exception ex)
            {
                a = 0;
                LogHelper.WriteLog("addhotelinfo error: " + ex.ToString());
            }
            return a;
        }

        public static readonly string username = ConfigurationManager.AppSettings["BaoJing_username"];
        public static readonly string password = ConfigurationManager.AppSettings["BaoJing_password"];
        /// <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)
            {

            }
        }


        /// <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());
            }
        }

        private static readonly NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();
        public string Task(string key)
        {
            return "";
            //DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.connectionString, CommandType.Text, "select * from tb_RoomCheck where ID=0");
            //if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            //{

            //}
            //DataTable DT = ds.Tables[0];
            //if (DT != null && DT.Rows.Count > 0)
            //{
            //}
            //var N = LogManager.GetCurrentClassLogger();
            //Task t = System.Threading.Tasks.Task.Factory.StartNew(() =>
            //{
            //    N.Error("ewr21894328fdklsafaskldhfskadjfhweuiqrweyiur");
            //});
            //t.Wait();
            //var client1 = new RestSharp.RestClient("http://face.blv-oa.com");
            //var request1 = new RestSharp.RestRequest("/FaceRoom/RoomIdbyRoom", RestSharp.Method.POST);
            //request1.AddParameter("HotelId", "1101");
            //request1.AddParameter("RoomNum", "1001");
            //var Response = client1.Execute(request1).Content;
            //var LLL = JsonConvert.DeserializeObject<List<FaceStatus>>(Response);
            //GlobalCache.HttpSendDataNew.Add("111");

            //if (key.Equals("aaccee^_^aaccee"))
            //{
            //    GlobalCache.Add("aaaaaaaaaaaaaa");
            //}

            //ssl 协议不兼容
            //var A = (SecurityProtocolType)48;
            //var B = (SecurityProtocolType)192;
            //var C = (SecurityProtocolType)768;
            //var D = (SecurityProtocolType)3072;
            //var E = (SecurityProtocolType)12288;
            //ServicePointManager.SecurityProtocol = A | B | C | D | E;
            //PMSDataBase data = new PMSDataBase()
            //{
            //    hotel_code = "2079",
            //    time = "1751426235",
            //    sign = "a68b2596ce7c1ca970e82a00626c16e3",
            //    hotel_id = "1101",
            //    order_no = "",
            //    room_no = "1102",
            //    check_out_original = ""
            //};

            //string BaseURL = "https://f.blv-oa.com:8099/rcu_pms_api/v1";
            //var client123 = new RestClient(BaseURL);
            //var request123 = new RestRequest("/order/checkOut", Method.POST);
            //request123.AddJsonBody(data);
            //var Response = client123.Execute(request123).Content;
            //string content12345 = Response;
            //return content12345;
        }

    }
}
