using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;
//using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using System.Data.SqlTypes;
using System.Xml.Linq;
using System.Net.NetworkInformation;
using System.Text.RegularExpressions;
using System.IO;
using MySql.Data.MySqlClient;
using System.Runtime.CompilerServices;
using Quartz;
using BLWWS_BLL.Job;
using BLWWS_BLL.Common;
using RestSharp;
using BLLCore;
using Microsoft.Extensions.Caching.Memory;

namespace BLWWS_BLL
{
    public static class BLL
    {
        //设置APPID/AK/SK，可以到百度申请,链接:https://console.bce.baidu.com/ai/?fromai=1#/ai/face/app/list
        //var APP_ID = "10461316";
        //private static string API_KEY = "2HDaFPcV5cY3mXqwLf4UeuVW";//用于人脸识别
        //private static string SECRET_KEY = "B122PgXT6GBif67mTGztURZoKDC9XEe3";//用于人脸识别

        private static readonly string _face_url = System.Configuration.ConfigurationManager.AppSettings["face_url"];
        private static readonly string _face_url_new = System.Configuration.ConfigurationManager.AppSettings["face_url_new"];
        private static readonly int ImageMaxHeight = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ImageMaxHeight"]);
        private static readonly int ImageMaxWidth = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ImageMaxWidth"]);
        private static readonly int ImageMinHeight = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ImageMinHeight"]);
        private static readonly int ImageMinWidth = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ImageMinWidth"]);
        /// <summary>
        /// 获取酒店记录
        /// </summary>
        /// <param name="code">酒店编码</param>
        /// <returns></returns>
        public static DataTable GetHotelCode(string code)
        {
            string sql = "select * from tb_HotelCode where code='" + code + "'";
            return SqlHelper.ExecuteDataset(SqlHelper.connectionString, CommandType.Text, sql).Tables[0];
        }
        /// <summary>
        /// 获取所有酒店
        /// </summary>
        /// <returns></returns>
        public static DataSet GetHotelCode()
        {
            string sql = "select Code,Remark,HotelID from tb_HotelCode order by Remark";
            return SqlHelper.ExecuteDataset(SqlHelper.connectionString, CommandType.Text, sql);
        }

        public static void EnableBaoJing(string hotelcode, int isenable)
        {
            string sql = "update tb_HotelCode set Is_Push_BaoJing=@baojing where Code=@code;";
            SqlParameter p1 = new SqlParameter("@code", hotelcode);
            SqlParameter p2 = new SqlParameter("@baojing", isenable);
            SqlHelper.ExecuteNonQuery(SqlHelper.connectionString, CommandType.Text, sql, new SqlParameter[] { p1, p2 });
        }
        public static int AddHotelInfo(string hotelcode, string hotelname, int hotelid)
        {
            string sql = "insert into tb_HotelCode(Code,Remark,HotelID) values(@code,@hotelName,@hotelid)";
            SqlParameter p1 = new SqlParameter("@code", hotelcode);
            SqlParameter p2 = new SqlParameter("@hotelName", hotelname);
            SqlParameter p3 = new SqlParameter("@hotelid", hotelid);
            return SqlHelper.ExecuteNonQuery(SqlHelper.connectionString, CommandType.Text, sql, new SqlParameter[] { p1, p2, p3 });
        }

        public static int GetEnableBaoJing(string code)
        {
            string sql = "select Is_Push_BaoJing from tb_HotelCode where code=@code;";
            SqlParameter p1 = new SqlParameter("@code", code);
            object ooo = SqlHelper.ExecuteScalar(SqlHelper.connectionString, CommandType.Text, sql, new SqlParameter[] { p1 });
            int ia = 0;
            int.TryParse(ooo.ToString(), out ia);
            return ia;
        }
        /// <summary>
        /// 开房
        /// </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="checkInID">入住记录ID</param>
        /// <returns></returns>
        public static int CheckIn(string code, string roomNumber, DateTime checkInDate, string xmlString, int YesNoFace, string key, ref long checkInID, string phoneNumber = "", string idNumber = "", string MsgId = "")
        {

            CheckInYuanShidata data1 = new CheckInYuanShidata();
            data1.RequestId = MsgId;
            data1.Step = 2;
            data1.CurrentTime = DateTime.Now;
            var vvv = JsonConvert.SerializeObject(data1);
            CSRedisCacheHelper.Publish(StaticData.PMSLogMonitor, vvv);

            //判断该房号是否已退房
            string sql = "select ID from tb_RoomCheck where Code='" + code + "' and RoomNumber='" + roomNumber + "' and isnull(CheckOutDate,'')=''";
            DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.connectionString, CommandType.Text, sql);
            #region 新添加的代码
            if (YesNoFace == 1)
            {
                try
                {
                    bool containsInvalidChar = Regex.IsMatch(xmlString, @"[\x00-\x08\x0B-\x0C\x0E-\x1F]");
                    if (containsInvalidChar)
                    {
                        LogHelper.WriteLog("传递的xml文件格式不正确");
                    }
                    XDocument doc = XDocument.Parse(xmlString);
                    Dictionary<string, string> customerInfo = new Dictionary<string, string>();
                    foreach (var item in doc.Descendants("item"))
                    {
                        string customer = item.Attribute("customer").Value;
                        string sex = item.Attribute("sex").Value;
                        customerInfo[customer] = sex;
                    }
                    foreach (var kvp in customerInfo)
                    {
                        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();
                                    }
                                }
                            }
                        }
                        Uploadinfo uploadinfo = new Uploadinfo()
                        {
                            key = key,
                            code = code,
                            checkInID = checkInID,
                            idType = 0,
                            idCard = idNumber,
                            name = kvp.Key,
                            sex = kvp.Value == "男" ? 1 : 0,
                            //birthday = birthday,
                            //photoUrl = photoUrl,
                            //photo = "photo.Length_"+ photo.Length,
                        };
                        string jsonString = JsonConvert.SerializeObject(uploadinfo);
                        PmsInterface info = new PmsInterface()
                        {
                            pmstype = 1,
                            DateTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                            pmsContent = jsonString,
                            hotelid = -1,
                        };
                        int pmsid = SqlSugarBase.GesmartDb().Insertable(info).ExecuteReturnIdentity();
                        if (containsInvalidChar)
                        {
                            pmsLog pmslog1 = new pmsLog
                            {
                                pmsid = pmsid,
                                app = 1,
                                step = 100,
                                Data = xmlString,
                                Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                                message = "XML文件格式不正确",
                                Ip = ip
                            };
                            SqlSugarBase.GesmartDb().Insertable(pmslog1).ExecuteCommand();
                        }
                        pmsLog pmslogs = new pmsLog
                        {
                            pmsid = pmsid,
                            app = 1,
                            step = 101,
                            Data = jsonString,
                            Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                            message = "pms CheckIn服务收到信息",
                            Ip = ip
                        };
                        SqlSugarBase.GesmartDb().Insertable(pmslogs).ExecuteCommand();
                        //Console.WriteLine($"Customer: {kvp.Key}, Sex: {kvp.Value}");
                        StringBuilder sb = new StringBuilder();
                        sb.Append("/checkinInterface?key=abc&data=");
                        var postData = new
                        {
                            LodgerNmae = kvp.Key,
                            IDNumber = idNumber,
                            Sex = kvp.Value == "男" ? 1 : 0,
                            picture = "",
                            HotelCode = code,
                            roomid = roomNumber,
                            phonenumber = phoneNumber,
                            CheckTime = Convert.ToDateTime(checkInDate).ToString("yyyy-MM-dd HH:mm:ss"),
                            pmsinfoid = pmsid
                        };
                        sb.Append(Newtonsoft.Json.JsonConvert.SerializeObject(postData));
                        pmsLog pmslog = new pmsLog
                        {
                            pmsid = pmsid,
                            app = 1,
                            step = 102,
                            Data = sb.ToString(),
                            Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                            message = "pms CheckIn 服务转发信息成功",
                            HotelCode = code,
                            roomid = roomNumber
                        };
                        SqlSugarBase.GesmartDb().Insertable(pmslog).ExecuteCommand();
                        string strResult = Tools.PostWebRequest(_face_url + sb.ToString(), "");//调用人脸机接口
                        LogHelper.WriteLog("没有人脸机的开房信息：" + sb.ToString());
                        LogHelper.WriteLog(_face_url + sb.ToString() + "，没有人脸机的开房信息结果：" + strResult);
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog("没有人脸机的推送给服务器信息错误:" + ex.ToString());
                }
            }
            #endregion
            //如果该房号尚未退房，只是更新客人信息
            if (ds.Tables[0].Rows.Count > 0)
            {
                sql = "update tb_RoomCheck set XmlString='" + xmlString + "' where Code='" + code + "' and RoomNumber='" + roomNumber + "' and isnull(CheckOutDate,'')=''";
                checkInID = Convert.ToInt64(ds.Tables[0].Rows[0]["ID"]);



                CheckInYuanShidata data2 = new CheckInYuanShidata();
                data2.RequestId = MsgId;
                data2.Step = 3;
                data2.CurrentTime = DateTime.Now;


                var vvv1 = JsonConvert.SerializeObject(data1);
                CSRedisCacheHelper.Publish(StaticData.PMSLogMonitor, vvv1);
                return SqlHelper.ExecuteNonQuery(SqlHelper.connectionString, CommandType.Text, sql);
            }
            else
            {
                string validateCode = "8888";
                //判断是否使用微信功能，如果是发送验证码，默认取身份证后四位
                if (Convert.ToBoolean(GetHotelCode(code).Rows[0]["UserWX"]))
                {
                    if (!string.IsNullOrEmpty(idNumber))
                    {
                        validateCode = "";
                        foreach (string id in idNumber.Split(','))
                        {
                            if (id.Length > 3)
                            {
                                validateCode += id.Substring(id.Length - 4) + ",";
                            }
                        }
                    }
                    //if (code == "1001" || code == "BLW_Hotel")//云端默认酒店和200服务器
                    //{
                    //    if (!string.IsNullOrEmpty(phoneNumber))
                    //    {
                    //        validateCode = Tools.CreateValidateCode(4);
                    //        AliyunSMSHelper.SendVerifySMS(phoneNumber, validateCode);//发送短信验证码
                    //    }
                    //}
                }
                sql = "insert into tb_RoomCheck(Code,RoomNumber,XmlString,CheckInDate,PhoneNumber,IDNumber,ValidateCode) values('" + code + "','" +
                    roomNumber + "','" + xmlString + "','" + checkInDate.ToString("yyyy-MM-dd HH:mm:ss") + "','" + phoneNumber + "','" + idNumber + "','" + validateCode + "');";
                //LogHelper.WriteLog(sql);
                object result = SqlHelper.ExecuteScalar(SqlHelper.connectionString, CommandType.Text, sql + "select @@IDENTITY as 'ID'");
                checkInID = Convert.ToInt64(result);
                if (checkInID > 0)
                {
                    //同步房态
                    return 1;
                }


                CheckInYuanShidata data2 = new CheckInYuanShidata();
                data2.RequestId = MsgId;
                data2.Step = 3;
                data2.CurrentTime = DateTime.Now;


                var vvv1 = JsonConvert.SerializeObject(data1);
                CSRedisCacheHelper.Publish(StaticData.PMSLogMonitor, vvv1);
                return 0;
            }
        }
        /// <summary>
        /// 更改住客手机号码
        /// </summary>
        /// <param name="code">酒店编码</param>
        /// <param name="roomNumber">房号</param>
        /// <param name="phoneNumber">新手机号码，多个已逗号,隔开</param>
        /// <param name="idNumber">身份证号：用于获取验证码</param>
        /// <returns></returns>
        public static int ChangePhoneNumber(string code, string roomNumber, string phoneNumber = "", string idNumber = "")
        {
            //判断该房号是否已退房
            string sql = "select ID from tb_RoomCheck where Code='" + code + "' and RoomNumber='" + roomNumber + "' and isnull(CheckOutDate,'')=''";
            DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.connectionString, CommandType.Text, sql);
            //如果该房号尚未退房，只是更新客人电话号码信息
            if (ds.Tables[0].Rows.Count > 0)
            {
                string validateCode = "8888";
                //判断是否使用微信功能，如果是发送验证码，默认取身份证后四位
                if (Convert.ToBoolean(GetHotelCode(code).Rows[0]["UserWX"]))
                {
                    if (!string.IsNullOrEmpty(idNumber))
                    {
                        validateCode = "";
                        foreach (string id in idNumber.Split(','))
                        {
                            if (id.Length > 4)
                            {
                                validateCode += id.Substring(id.Length - 4) + ",";
                            }
                        }
                    }
                    if (code == "1001" || code == "BLW_Hotel")//云端默认酒店和200服务器
                    {
                        if (!string.IsNullOrEmpty(phoneNumber))
                        {
                            validateCode = Tools.CreateValidateCode(4);
                            AliyunSMSHelper.SendVerifySMS(phoneNumber, validateCode);//发送短信验证码
                        }
                    }
                }
                sql = "update tb_RoomCheck set PhoneNumber='" + phoneNumber + "',IDNumber='" + idNumber + "',ValidateCode='" + validateCode + "'  where Code='" +
                    code + "' and RoomNumber='" + roomNumber + "' and isnull(CheckOutDate,'')=''";

                return SqlHelper.ExecuteNonQuery(SqlHelper.connectionString, CommandType.Text, sql);
            }
            return 0;
        }
        /// <summary>
        /// 退房
        /// </summary>
        /// <param name="code">酒店编码</param>
        /// <param name="roomNumber">房号</param>
        /// <param name="checkOutDate">退房日期</param>
        ///  /// <param name="pmsid">pms编号</param>
        /// <returns></returns>
        public static int CheckOut(string code, string roomNumber, DateTime checkOutDate, int pmsid, string MsgId)
        {

            CheckInYuanShidata data1 = new CheckInYuanShidata();
            data1.CommandType = "CheckOut";
            data1.RequestId = MsgId;
            data1.Step = 2;
            data1.CurrentTime = DateTime.Now;

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

            string sqls = " select * from tb_RoomCheck   where Code='" + code + "' and RoomNumber='" + roomNumber + "' and isnull(CheckOutDate,'')=''";
            DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.connectionString, CommandType.Text, sqls);
            int result = 0;
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                string sql = "update tb_RoomCheck set CheckOutDate='" + checkOutDate.ToString("yyyy-MM-dd HH:mm:ss") + "'  where Code='" + code + "' and RoomNumber='" + roomNumber + "' and isnull(CheckOutDate,'')=''";
                result = SqlHelper.ExecuteNonQuery(SqlHelper.connectionString, CommandType.Text, sql);
                if (result > 0 && !string.IsNullOrEmpty(_face_url))
                {
                    try
                    {

                        StringBuilder sb = new StringBuilder();
                        sb.Append("/CheckOut?key=abc&data=");
                        var postData = new { HotelCode = code, roomid = roomNumber, checkOutTime = checkOutDate.ToString("yyyy-MM-dd HH:mm:ss"), pmsinfoid = pmsid };
                        sb.Append(Newtonsoft.Json.JsonConvert.SerializeObject(postData));
                        pmsLog pmslog = new pmsLog
                        {
                            pmsid = pmsid,
                            app = 1,
                            step = 102,
                            Data = sb.ToString(),
                            Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                            message = "pms服务转发信息成功",
                            HotelCode = code,
                            roomid = roomNumber
                        };
                        SqlSugarBase.GesmartDb().Insertable(pmslog).ExecuteCommand();
                        LogHelper.WriteLog("新添加的代码：" + sb.ToString());
                        string strResult = Tools.PostWebRequest(_face_url + sb.ToString(), "");//调用人脸机接口
                        LogHelper.WriteLog(_face_url + sb.ToString() + "，结果：" + strResult);
                    }
                    catch (Exception ex)
                    {
                        pmsLog pmslog = new pmsLog
                        {
                            pmsid = pmsid,
                            app = 1,
                            step = 140,
                            //Data = sb.ToString(),
                            Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                            message = "pms服务转发信息失败",
                            HotelCode = code,
                            roomid = roomNumber
                        };
                        SqlSugarBase.GesmartDb().Insertable(pmslog).ExecuteCommand();
                        LogHelper.WriteLog(ex.ToString());
                    }
                }

                CheckInYuanShidata data2 = new CheckInYuanShidata();
                data2.RequestId = MsgId;
                data2.Step = 3;
                data2.CurrentTime = DateTime.Now;

                var vvv1 = JsonConvert.SerializeObject(data2);
                CSRedisCacheHelper.Publish(StaticData.PMSLogMonitor, vvv1);
            }
            else
            {
                string sql = "insert into tb_RoomCheck (CheckOutDate,Code,RoomNumber,CheckInDate,SyncCheckIn,SyncCheckOut,SyncRent) values " +
                         "('" + checkOutDate.ToString("yyyy-MM-dd HH:mm:ss") +
                         "','" + code +
                         "','" + roomNumber +
                         "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") +
                         "'," + 0 +
                         "," + 1 +
                         "," + 0 +
                         ")";
                result = SqlHelper.ExecuteNonQuery(SqlHelper.connectionString, CommandType.Text, sql);
                if (result > 0 && !string.IsNullOrEmpty(_face_url))
                {
                    try
                    {

                        StringBuilder sb = new StringBuilder();
                        sb.Append("/CheckOut?key=abc&data=");
                        var postData = new { HotelCode = code, roomid = roomNumber, checkOutTime = checkOutDate.ToString("yyyy-MM-dd HH:mm:ss"), pmsinfoid = pmsid };
                        sb.Append(Newtonsoft.Json.JsonConvert.SerializeObject(postData));
                        pmsLog pmslog = new pmsLog
                        {
                            pmsid = pmsid,
                            app = 1,
                            step = 102,
                            Data = sb.ToString(),
                            Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                            message = "pms服务转发信息成功",
                            HotelCode = code,
                            roomid = roomNumber
                        };
                        SqlSugarBase.GesmartDb().Insertable(pmslog).ExecuteCommand();
                        LogHelper.WriteLog("新添加的代码：" + sb.ToString());
                        string strResult = Tools.PostWebRequest(_face_url + sb.ToString(), "");//调用人脸机接口
                        LogHelper.WriteLog(_face_url + sb.ToString() + "，结果：" + strResult);
                    }
                    catch (Exception ex)
                    {
                        pmsLog pmslog = new pmsLog
                        {
                            pmsid = pmsid,
                            app = 1,
                            step = 141,
                            //Data = sb.ToString(),
                            Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                            message = "pms服务转发信息失败",
                            HotelCode = code,
                            roomid = roomNumber
                        };
                        LogHelper.WriteLog(ex.ToString());
                    }
                }

                CheckInYuanShidata data2 = new CheckInYuanShidata();
                data2.CommandType = "CheckOut";
                data2.RequestId = MsgId;
                data2.Step = 3;
                data2.CurrentTime = DateTime.Now;

                var vvv1 = JsonConvert.SerializeObject(data2);
                CSRedisCacheHelper.Publish(StaticData.PMSLogMonitor, vvv1);
            }
            return result;
        }
        /// <summary>
        /// 待租
        /// </summary>
        /// <param name="code">酒店编码</param>
        /// <param name="roomNumber">房号</param>
        /// <param name="checkOutDate">变更待租日期</param>
        /// <returns></returns>
        public static int RentRoom(string code, string roomNumber, DateTime rentDate, string MsgId)
        {
            try
            {

                CheckInYuanShidata data1 = new CheckInYuanShidata();
                data1.CommandType = "RentRoom";
                data1.RequestId = MsgId;
                data1.Step = 2;
                data1.CurrentTime = DateTime.Now;

                var vvv = JsonConvert.SerializeObject(data1);
                CSRedisCacheHelper.Publish(StaticData.PMSLogMonitor, vvv);
                string sql = " select * from tb_RoomCheck   where Code='" + code + "' and RoomNumber='" + roomNumber + "' and isnull(CheckOutDate,'')=''";
                DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.connectionString, CommandType.Text, sql);
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    sql = "update tb_RoomCheck set RentDate='" + rentDate.ToString("yyyy-MM-dd HH:mm:ss") + "' where Code='" + code + "' and RoomNumber='" + roomNumber + "'";
                    LogHelper.WriteLog("修改待租信息");
                }
                else
                {
                    sql = "insert into tb_RoomCheck (RentDate,Code,RoomNumber,CheckInDate,SyncCheckIn,SyncCheckOut,SyncRent) values " +
                        "('" + rentDate.ToString("yyyy-MM-dd HH:mm:ss") +
                        "','" + code +
                        "','" + roomNumber +
                        "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") +
                        "'," + 0 +
                        "," + 0 +
                        "," + 1 +
                        ")";
                    LogHelper.WriteLog("添加待租信息");
                }

                CheckInYuanShidata data2 = new CheckInYuanShidata();
                data2.CommandType = "RentRoom";
                data2.RequestId = MsgId;
                data2.Step = 3;
                data2.CurrentTime = DateTime.Now;

                var vvv2 = JsonConvert.SerializeObject(data2);
                CSRedisCacheHelper.Publish(StaticData.PMSLogMonitor, vvv2);

                return SqlHelper.ExecuteNonQuery(SqlHelper.connectionString, CommandType.Text, sql);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("变更待租错误：" + ex);
                return 0;
            }
        }
        /// <summary>
        /// 获取客房记录
        /// </summary>
        /// <param name="code"></param>
        /// <param name="roomNumber"></param>
        /// <returns></returns>
        public static DataSet GetRoomRecords(string code, string roomNumber, string tableName)
        {
            //if (string.IsNullOrEmpty(tableName))
            //{
            //    tableName = "tb_RoomCheck";
            //}
            //string sql = "select ID,RoomNumber,CheckInDate,SyncCheckIn,CheckOutDate,SyncCheckOut,RentDate,SyncRent,PhoneNumber,IDNumber,ValidateCode from " + 
            //    tableName + " where Code='" + code + "' and RoomNumber like '%" + roomNumber + "%' order by ID desc";
            string sql = string.Format("select * from(" +
                "select ID,RoomNumber,CheckInDate,SyncCheckIn,CheckOutDate,SyncCheckOut,RentDate,SyncRent,PhoneNumber,IDNumber,ValidateCode " +
                "from tb_RoomCheck where Code='{0}' and RoomNumber like '%{1}%' " +
                "union " +
                "select ID,RoomNumber,CheckInDate,SyncCheckIn,CheckOutDate,SyncCheckOut,RentDate,SyncRent,PhoneNumber,IDNumber,ValidateCode " +
                "from tb_RoomCheck_bak where Code='{2}' and RoomNumber like '%{3}%') x " +
                "order by x.ID desc", code, roomNumber, code, roomNumber);
            return SqlHelper.ExecuteDataset(SqlHelper.connectionString, CommandType.Text, sql);
        }
        /// <summary>
        /// 获取入住人信息
        /// </summary>
        /// <param name="checkInID"></param>
        /// <returns></returns>
        public static DataSet GetRoomCustomer(long checkInID)
        {
            string sql = string.Format("select *,'' as StatusName,'' as SexName from tb_RoomCustomer where CheckInID={0}", checkInID);
            return SqlHelper.ExecuteDataset(SqlHelper.connectionString, CommandType.Text, sql);
        }
        /// <summary>
        /// 定时获取酒店新的开房/退房/待租记录
        /// </summary>
        /// <param name="code">酒店编码</param>
        /// <returns></returns>
        public static DataSet GetCheckInOrOutRecord(string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                return null;
            }
            SqlParameter[] parameters = { new SqlParameter("@code", SqlDbType.VarChar, 30) };
            parameters[0].Value = code;
            return SqlHelper.ExecuteDataset(SqlHelper.connectionString, CommandType.StoredProcedure, "sp_GetCheckInOrOutRecord", parameters);
        }
        /// <summary>
        /// 更新已同步的新开房/退房/待租状态
        /// </summary>
        /// <param name="code">酒店编码</param>
        /// <param name="id">记录ID</param>
        /// <param name="flag">0开房，1退房，2待租</param>
        /// <returns></returns>
        public static int UpdateCheckInOrOutRecord(string code, Int64 id, int flag)
        {
            string cloumnName = "";
            switch (flag)
            {
                case 0:
                    cloumnName = "SyncCheckIn";
                    break;
                case 1:
                    cloumnName = "SyncCheckOut";
                    break;
                case 2:
                    cloumnName = "SyncRent";
                    break;
            }
            if (!string.IsNullOrEmpty(cloumnName))
            {
                string sql = "update tb_RoomCheck set " + cloumnName + "=1 where ID=" + id + " and Code='" + code + "'";
                return SqlHelper.ExecuteNonQuery(SqlHelper.connectionString, CommandType.Text, sql);
            }
            //string sql = "";
            //switch (flag)
            //{
            //    case 0:
            //         sql = "update tb_RoomCheck set SyncRent=0,SyncCheckOut=0,SyncCheckIn=1 where ID=" + id + " and Code='" + code + "'";
            //        LogHelper.WriteLog("同步开房状态");
            //        break;
            //    case 1:
            //         sql = "update tb_RoomCheck set SyncRent=0,SyncCheckOut=1,SyncCheckIn=0 where ID=" + id + " and Code='" + code + "'";
            //        LogHelper.WriteLog("同步退房状态");
            //        break;
            //    case 2:
            //         sql = "update tb_RoomCheck set SyncRent=1,SyncCheckOut=0,SyncCheckIn=0 where ID=" + id + " and Code='" + code + "'";
            //        LogHelper.WriteLog("同步待租状态");
            //        break;
            //}
            //int count = SqlHelper.ExecuteNonQuery(SqlHelper.connectionString, CommandType.Text, sql);
            //if (count>0)
            //{
            //    return count;
            //}
            return 0;
        }
        /// <summary>
        /// 根据酒店ID，房号获取当前入住人信息
        /// </summary>
        /// <param name="hotelID">酒店ID</param>
        /// <param name="roomNumber">房号</param>
        /// <returns></returns>
        public static string GetRoomCustomer(int hotelID, string roomNumber, ref string phoneNumber)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append("select r.XmlString,r.PhoneNumber from tb_RoomCheck r inner join tb_HotelCode h on r.Code=h.Code where h.HotelID=" + hotelID + " and r.RoomNumber='" + roomNumber + "' and isnull(r.CheckOutDate,'')=''");
            sql.Append(" union ");
            sql.Append("select r.XmlString,r.PhoneNumber from tb_RoomCheck_bak r inner join tb_HotelCode h on r.Code=h.Code where h.HotelID=" + hotelID + " and r.RoomNumber='" + roomNumber + "' and isnull(r.CheckOutDate,'')=''");

            DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.connectionString, CommandType.Text, sql.ToString());

            if (ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    phoneNumber = row[1].ToString();
                    return row[0].ToString();
                }
            }
            return "";
        }
        /// <summary>
        /// 判断验证码是否正确
        /// </summary>
        /// <param name="hotelID">酒店ID</param>
        /// <param name="roomNumber">房号</param>
        /// <param name="validateCode">用户输入验证码</param>
        /// <returns></returns>
        public static bool ValidateNumber(int hotelID, string roomNumber, string validateCode)
        {
            //根据酒店ID，房号和手机验证码查找记录
            StringBuilder sql = new StringBuilder();
            sql.Append("select r.ValidateCode from tb_RoomCheck r inner join tb_HotelCode h on r.Code=h.Code where h.HotelID=" + hotelID + " and r.RoomNumber='" + roomNumber + "' and isnull(r.CheckOutDate,'')=''");
            sql.Append(" union ");
            sql.Append("select r.ValidateCode from tb_RoomCheck_bak r inner join tb_HotelCode h on r.Code=h.Code where h.HotelID=" + hotelID + " and r.RoomNumber='" + roomNumber + "' and isnull(r.CheckOutDate,'')=''");

            DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.connectionString, CommandType.Text, sql.ToString());

            if (ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    if (null != row[0] && !string.IsNullOrEmpty(row[0].ToString()))
                    {
                        foreach (string v1 in row[0].ToString().Split(','))
                        {
                            if (v1 == validateCode)
                            {
                                return true;
                            }
                        }
                    }
                }
            }
            return false;
        }
        /// <summary>
        /// 判断验证码是否正确
        /// </summary>
        /// <param name="code">酒店编码</param>
        /// <param name="roomNumber">房号</param>
        /// <param name="validateCode">用户输入验证码</param>
        /// <returns></returns>
        public static bool ValidateNumberByCode(string code, string roomNumber, string validateCode)
        {
            //根据酒店Code，房号和手机验证码查找记录
            StringBuilder sql = new StringBuilder();
            sql.Append("select r.ValidateCode from tb_RoomCheck r where r.Code='" + code + "' and r.RoomNumber='" + roomNumber + "' and isnull(r.CheckOutDate,'')=''");
            sql.Append(" union ");
            sql.Append("select r.ValidateCode from tb_RoomCheck_bak r where r.Code='" + code + "' and r.RoomNumber='" + roomNumber + "' and isnull(r.CheckOutDate,'')=''");

            DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.connectionString, CommandType.Text, sql.ToString());

            if (ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    if (null != row[0] && !string.IsNullOrEmpty(row[0].ToString()))
                    {
                        foreach (string v1 in row[0].ToString().Split(','))
                        {
                            if (v1 == validateCode)
                            {
                                return true;
                            }
                        }
                    }
                }
            }
            return false;
        }
        /// <summary>
        /// 根据手机号获取当前入住记录信息
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public static DataTable GetCodeAndRoomNumberByPhone(string phone)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append("select r.* from tb_RoomCheck r where r.PhoneNumber like '%" + phone + "%' and isnull(r.CheckOutDate,'')=''");
            sql.Append(" union ");
            sql.Append("select r.* from tb_RoomCheck_bak r where r.PhoneNumber like '%" + phone + "%' and isnull(r.CheckOutDate,'')=''");

            DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.connectionString, CommandType.Text, sql.ToString());

            if (ds.Tables.Count > 0)
            {
                return ds.Tables[0];
            }
            return null;
        }
        /// <summary>
        /// 上传/变更图像及信息
        /// </summary>
        /// <param name="idType">证件类型：0身份证，1护照</param>
        /// <param name="idCard">证件号码</param>
        /// <param name="name">姓名</param>
        /// <param name="sex">性别：0女，1男</param>
        /// <param name="photo">图像</param>
        /// <returns></returns>
        public static int UploadPhoto(int idType, string idCard, string name, int sex, string birthday, byte[] photo)
        {
            //根据身份类型和编号获取记录
            string sql = "select r.ID from tb_RoomCustomer r where r.IDType=" + idType + " and r.IDCard='" + idCard + "'";
            DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.connectionString, CommandType.Text, sql);

            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                sql = "update tb_RoomCustomer set IDType=@IDType,IDCard=@IDCard,Name=@Name,Sex=@Sex,Birthday=@Birthday,Photo=@Photo,ModifiedDate=getdate() where ID=" + Convert.ToInt16(ds.Tables[0].Rows[0][0]);
            }
            else
            {
                sql = "insert into tb_RoomCustomer (IDType,IDCard,[Name],Sex,Birthday,Photo) values (@IDType,@IDCard,@Name,@Sex,@Birthday,@Photo)";
            }
            SqlParameter[] sqlParams = new SqlParameter[6] {
                    new SqlParameter("@IDType", idType),
                    new SqlParameter("@IDCard", idCard),
                    new SqlParameter("@Name", name),
                    new SqlParameter("@Sex", sex),
                    new SqlParameter("@Birthday", birthday),
                    new SqlParameter("@Photo", photo)};
            return SqlHelper.ExecuteNonQuery(SqlHelper.connectionString, CommandType.Text, sql, sqlParams);
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="idType"></param>
        /// <param name="idCard"></param>
        /// <param name="name"></param>
        /// <param name="sex"></param>
        /// <param name="birthday"></param>
        /// <param name="photoUrl"></param>
        /// <param name="photo"></param>
        /// <param name="checkInID"></param>
        /// <param name="pmsid"></param>
        /// <returns></returns>
        public static int UploadPhoto(int idType, string idCard, string name, int sex, string birthday, string photoUrl, byte[] photo, long checkInID, int pmsid, ref string msg, string PicturePath)
        {

            if (!string.IsNullOrEmpty(photoUrl))//取云端图片内容保存在数据库
            {
                try
                {
                    System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(photoUrl);
                    webRequest.Method = "GET";
                    System.Net.HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse();
                    System.IO.Stream s = webResponse.GetResponseStream();
                    List<byte> list = new List<byte>();
                    while (true)
                    {
                        int data = s.ReadByte();
                        if (data == -1)
                            break;
                        else
                        {
                            byte b = (byte)data;
                            list.Add(b);
                        }
                    }
                    photo = list.ToArray();
                }
                catch (Exception)
                {
                    pmsLog pms = new pmsLog
                    {
                        pmsid = pmsid,
                        app = 1,
                        step = 142,
                        //Data = sb.ToString(),
                        Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                        message = "读取云端图片失败",
                    };
                    SqlSugarBase.GesmartDb().Insertable(pms).ExecuteCommand();
                }
            }
            else
            {
                if (photo == null)
                {
                    pmsLog pmsinfo = new pmsLog
                    {
                        pmsid = pmsid,
                        app = 1,
                        step = 143,
                        //Data = sb.ToString(),
                        Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                        message = "图片内容为空",
                    };
                    SqlSugarBase.GesmartDb().Insertable(pmsinfo).ExecuteCommand();
                    //LogHelper.WriteLog(string.Format("图片内容不能为空。checkInID:{0}", checkInID));
                    return 0;
                }
                string picName = idCard + "_" + checkInID.ToString() + ".jpg";//二进制转换为本地图片
                using (System.IO.FileStream fs = new System.IO.FileStream(PicturePath + "\\" + picName, System.IO.FileMode.Create, System.IO.FileAccess.Write))
                {
                    fs.Write(photo, 0, photo.Length);
                    photoUrl = "http://pms.boonlive-rcu.com:89/pic/" + picName;
                }
            }


            string sql = "insert into tb_RoomCustomer (IDType,IDCard,[Name],Sex,Birthday,PhotoUrl,Photo,CheckInID) values (@IDType,@IDCard,@Name,@Sex,@Birthday,@PhotoUrl,@Photo,@CheckInID)";
            SqlParameter[] sqlParams = new SqlParameter[8] {
                    new SqlParameter("@IDType", idType),
                    new SqlParameter("@IDCard", idCard),
                    new SqlParameter("@Name", name),
                    new SqlParameter("@Sex", sex),
                    new SqlParameter("@Birthday", birthday),
                    new SqlParameter("@PhotoUrl", photoUrl),
                    new SqlParameter("@Photo", photo),
                    new SqlParameter("@CheckInID", checkInID)};
            int result = SqlHelper.ExecuteNonQuery(SqlHelper.connectionString, CommandType.Text, sql, sqlParams);
            if (result > 0 && !string.IsNullOrEmpty(_face_url))
            {
                try
                {

                    DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.connectionString, CommandType.Text, "select * from tb_RoomCheck where ID=" + checkInID);
                    //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)
                    {
                        //DataRow dr = ds.Tables[0].Rows[0];
                        DataRow dr = DT.Rows[0];
                        StringBuilder sb = new StringBuilder();
                        sb.Append("/checkinInterface?key=abc&data=");
                        var postData = new
                        {
                            LodgerNmae = name,
                            IDNumber = idCard,
                            Sex = sex,
                            picture = photoUrl,
                            HotelCode = dr["Code"].ToString(),
                            roomid = dr["RoomNumber"].ToString(),
                            phonenumber = dr["PhoneNumber"].ToString(),
                            CheckTime = Convert.ToDateTime(dr["CheckInDate"]).ToString("yyyy-MM-dd HH:mm:ss"),
                            pmsinfoid = pmsid
                        };
                        sb.Append(Newtonsoft.Json.JsonConvert.SerializeObject(postData));

                        #region  新添加代码
                        pmsLog pmslog = new pmsLog
                        {
                            pmsid = pmsid,
                            app = 1,
                            step = 102,
                            Data = sb.ToString(),
                            Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                            message = "pms服务转发信息成功",
                            HotelCode = dr["Code"].ToString(),
                            roomid = dr["RoomNumber"].ToString()
                        };
                        SqlSugarBase.GesmartDb().Insertable(pmslog).ExecuteCommand();
                        //LogHelper.WriteLog("新添加的代码：" + sb.ToString());


                        //查询人脸 机的状态 和故障
                        string hotelid = "";
                        DataTable dt = GetHotelCode(postData.HotelCode);
                        string Key = "HotelCode_" + postData.HotelCode;
                        object ooo = MyMemoryCache.Cache.Get(Key);
                        //object ooo = HttpContext.Current.Cache.Get(Key);
                        if (ooo != null)
                        {
                            hotelid = ooo.ToString();
                        }
                        else
                        {
                            if (dt != null && dt.Rows.Count > 0)
                            {
                                hotelid = dt.Rows[0]["HotelID"].ToString();
                                //HttpContext.Current.Cache.Insert(Key, hotelid, null, DateTime.Now.AddMinutes(20), Cache.NoSlidingExpiration);
                                MyMemoryCache.Cache.Set(Key, hotelid, TimeSpan.FromMinutes(20));
                            }
                        }



                        //查询人脸机连接状态
                        LogHelper.WriteLog("查询人脸机在线：" + hotelid + ":" + postData.roomid);
                        var client1 = new RestSharp.RestClient(_face_url_new);
                        var request1 = new RestSharp.RestRequest("/FaceRoom/RoomIdbyRoom", RestSharp.Method.Post);
                        request1.AddParameter("HotelId", hotelid);
                        request1.AddParameter("RoomNum", postData.roomid);
                        var Response = client1.Execute(request1).Content;
                        var LLL = JsonConvert.DeserializeObject<List<FaceStatus>>(Response);
                        FaceResult r = new FaceResult();
                        var DDD = LLL.FirstOrDefault();
                        if (DDD != null)
                        {
                            //人脸机 是否在线
                            bool Is_OnLine = DDD.Status;
                            int GuZhang = DDD.maintainStatus;
                            if (Is_OnLine)
                            {
                                r.Status = 200;
                                r.Message = "人脸机在线";
                            }
                            else
                            {
                                r.Status = 403;
                                r.Message = "人脸机离线";
                            }

                            //人脸机出故障了
                            /*if (GuZhang == 0)
                            {
                                r.Status = 200;
                                r.Message = "人脸机无故障，正常使用";
                            }
                            else
                            {
                                r.Status = 403;
                                r.Message = "人脸机不可用";
                            }*/
                        }
                        else
                        {
                            r.Status = 403;
                            r.Message = "找不到该房间的人脸机数据";
                        }

                        //分辨率 判断
                        using (var ms = new MemoryStream(photo))
                        {
                            ms.Write(photo, 0, photo.Length);
                            using (System.Drawing.Image image = System.Drawing.Image.FromStream(ms, false, false)) // 不加载图像数据
                            {
                                decimal nnn1 = Convert.ToDecimal(photo.Length);
                                decimal lll = nnn1 / 1024;
                                decimal a = Math.Round(lll, 2);
                                string message = "图片分辨率 W:" + image.Width + " H:" + image.Height + "图片大小: " + a + "KB";
                                LogHelper.WriteLog(message);
                                pmsLog pmslog_fenbianlv = new pmsLog
                                {
                                    pmsid = pmsid,
                                    app = 1,
                                    step = 144,
                                    Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                                    message = message + " " + r.Message,
                                };
                                SqlSugarBase.GesmartDb().Insertable(pmslog_fenbianlv).ExecuteCommand();

                                #region 分辨率判断
                                //bool bf = image.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg);
                                //if (image.Width > ImageMaxWidth || image.Height > ImageMaxHeight)
                                //{
                                //    LogHelper.WriteLog("图片分辨率太大");
                                //    pmsLog pmslog = new pmsLog
                                //    {
                                //        pmsid = pmsid,
                                //        app = 1,
                                //        step = 0,
                                //        Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                                //        message = "图片分辨率太大 W:" + image.Width + " H:" + image.Height,
                                //    };
                                //    SqlSugarBase.GesmartDb().Insertable(pmslog).ExecuteCommand();
                                //    return 0;
                                //}

                                //if (image.Width < ImageMinWidth || image.Height < ImageMinHeight)
                                //{
                                //    LogHelper.WriteLog("图片分辨率太小 W:" + image.Width + " H:" + image.Height);
                                //    pmsLog pmslog = new pmsLog
                                //    {
                                //        pmsid = pmsid,
                                //        app = 1,
                                //        step = 0,
                                //        Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                                //        message = "图片分辨率太小",
                                //    };
                                //    SqlSugarBase.GesmartDb().Insertable(pmslog).ExecuteCommand();
                                //    return 0;
                                //}
                                #endregion
                            }
                        }

                        LogHelper.WriteLog("人脸机在线结果：" + Response);
                        #endregion

                        #region 原来的人脸机判定结果
                        //string strResult = "";
                        //if (pmslog.HotelCode.Equals("2079"))
                        //{
                        //    strResult = Tools.PostWebRequestNew(_face_url + sb.ToString(), "");//调用人脸机接口
                        //}
                        //else
                        //{
                        //    strResult = Tools.PostWebRequest(_face_url + sb.ToString(), "");//调用人脸机接口
                        //}
                        //LogHelper.WriteLog(_face_url + sb.ToString() + "，结果：" + strResult);
                        //FaceResult faceReslut = Newtonsoft.Json.JsonConvert.DeserializeObject<FaceResult>(strResult);

                        //if (faceReslut != null && faceReslut.Status == 200)
                        //{
                        //    result = 1;
                        //}
                        //else
                        //{
                        //    result = 0;
                        //}
                        #endregion

                        #region 换成后台任务
                        try
                        {
                            if (sb != null)
                            {
                                string sbstr = sb.ToString();
                                string pullstr = _face_url + sbstr;
                                LogHelper.WriteLog("face pull data:" + pullstr);
                                if (!string.IsNullOrEmpty(pullstr))
                                {
                                    GlobalCache.Add(pullstr);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.WriteLog("Error: " + ex.Message);
                        }
                        if (r != null && r.Status == 200)
                        {
                            result = 1;
                        }
                        else
                        {
                            result = 0;
                            msg = r.Status + " " + r.Message;
                        }
                        #endregion
                    }
                    else if (checkInID == 0)
                    {
                        pmsLog pms_111 = new pmsLog
                        {
                            pmsid = pmsid,
                            app = 1,
                            step = 100,
                            Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                            message = "checkinId 为 0"
                        };
                        SqlSugarBase.GesmartDb().Insertable(pms_111).ExecuteCommand();
                        result = 0;
                        msg = pms_111.message;
                        return result;
                    }
                }
                catch (Exception ex)
                {
                    pmsLog pmslog = new pmsLog
                    {
                        pmsid = pmsid,
                        app = 1,
                        step = 145,
                        //Data = sb.ToString(),
                        Creationtime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                        message = "pms服务转发信息失败",
                        //HotelCode = dr["Code"].ToString(),
                        //roomid = dr["RoomNumber"].ToString()
                    };
                    SqlSugarBase.GesmartDb().Insertable(pmslog).ExecuteCommand();
                    result = 0;
                    LogHelper.WriteLog(ex.ToString());
                }
            }
            return result;
        }
        /// <summary>
        /// 人脸识别
        /// </summary>
        /// <param name="photo"></param>
        /// <param name="idType"></param>
        /// <param name="idCard"></param>
        /// <param name="name"></param>
        /// <param name="sex"></param>
        /// <param name="matchPhoto"></param>
        /// <returns></returns>
        public static bool FaceMatch(byte[] photo, ref int idType, ref string idCard, ref string name, ref int sex, ref byte[] matchPhoto)
        {
            if (!photo.Equals(null))
            {
                string sql = "select * from tb_RoomCustomer";
                DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.connectionString, CommandType.Text, sql);
                //if (ds != null && ds.Tables.Count > 0)
                //{
                //    var client = new Baidu.Aip.Face.Face(API_KEY, SECRET_KEY);

                //    foreach (DataRow dr in ds.Tables[0].Rows)
                //    {
                //        var images = new byte[][] { photo, (byte[])dr["Photo"] };
                //        var result = double.Parse(client.FaceMatch(images).First.First.Last.Last.First.ToString());
                //        if (result >= 90)
                //        {
                //            idType = (int)dr["IDType"];
                //            idCard = dr["IDCard"].ToString();
                //            name = dr["Name"].ToString();
                //            sex = (int)dr["Sex"];
                //            matchPhoto = (byte[])dr["Photo"];
                //            return true;
                //        }
                //    }
                //}
                return false;
            }
            return false;
        }
        /// <summary>
        /// 获取人脸机信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static DataSet GetDevices(string code)
        {
            string sql = string.Format("select a.*,b.Remark from tb_Devices a left join tb_HotelCode b on a.HotelCode=b.Code where isnull(a.HotelCode,'')='' or isnull(a.HotelCode,'') like '%{0}%' order by a.HotelCode desc,a.RoomNumber,a.SerialNo", code);
            return SqlHelper.ExecuteDataset(SqlHelper.connectionString, CommandType.Text, sql);
        }
        /// <summary>
        /// 人脸机绑定房号
        /// </summary>
        /// <param name="id"></param>
        /// <param name="hotelCode"></param>
        /// <param name="roomNumber"></param>
        /// <returns></returns>
        public static int SaveDevice(long id, string hotelCode, string roomNumber)
        {
            string sql = string.Format("update tb_Devices set HotelCode='{1}',RoomNumber='{2}',ModifiedDate=getdate() where ID={0}", id, hotelCode, roomNumber);
            return SqlHelper.ExecuteNonQuery(SqlHelper.connectionString, CommandType.Text, sql);
        }
    }
    public class FaceResult
    {
        /// <summary>
        /// 
        /// </summary>
        public int Status { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string Message { get; set; }
    }
    public class FaceStatus
    {
        public int Facelid { get; set; }
        public string SerialNo { get; set; }
        public string CreatedDate { get; set; }
        public int RoomId { get; set; }
        public bool Status { get; set; }
        public bool bindingStatus { get; set; }
        public int maintainStatus { get; set; }
        public string ROOM_NUMBER { get; set; }
    }
}