using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using System.Web.Routing;

namespace Common
{
    /// <summary>
    /// FreeGo对接
    /// </summary>
    public static class FreeGoOperation
    {
        private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(FreeGoOperation));

        private static string freego_url = System.Configuration.ConfigurationManager.AppSettings["freego_url"];
        private static string freego_codes = System.Configuration.ConfigurationManager.AppSettings["freego_codes"];
        private static string freego_appid = System.Configuration.ConfigurationManager.AppSettings["freego_appid"];
        private static string freego_appsecret = System.Configuration.ConfigurationManager.AppSettings["freego_appsecret"];
        /// <summary>
        /// 调用freego获取设备密钥等信息
        /// </summary>
        /// <param name="mac">主机mac地址，如34-D0-00-00-00-01格式</param>
        /// <returns></returns>
        public static DeviceRegisterResult DeviceRegister(string mac)
        {
            string deviceName = mac.Replace("-", "").ToUpper();
            DeviceRegisterPostData postData = new DeviceRegisterPostData()
            {
                appid = freego_appid,
                timestamp = TimeHelper.DateTimeToStamp(DateTime.Now).ToString(),
                nonce_str = Guid.NewGuid().ToString(),
                device_name = deviceName
            };
            var dic = new RouteValueDictionary();
            dic["appid"] = postData.appid;
            dic["timestamp"] = postData.timestamp;
            dic["nonce_str"] = postData.nonce_str;
            dic["device_name"] = postData.device_name;
            postData.sign = HttpWebRequestHelper.GetFreeGoSignature(dic, freego_appsecret);
            try
            {
                string result = HttpWebRequestHelper.PostWebRequest(freego_url, Newtonsoft.Json.JsonConvert.SerializeObject(postData));
                return JsonConvert.DeserializeObject<DeviceRegisterResult>(result);
            }
            catch (Exception ex)
            {
                logger.Error("调用FreeGo接口失败：" + ex.ToString());
                return new DeviceRegisterResult() { errcode = "-1", msg = ex.Message }; ;
            }
        }
        /// <summary>
        /// 给FreeGo（福瑞狗）上报SOS和DND状态
        /// </summary>
        /// <param name="hotelCode"></param>
        /// <param name="roomNumber"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void UploadService(string hotelCode, string roomNumber, string key, string value)
        {
            foreach (string freego_code in freego_codes.Split(','))
            {
                if (freego_code == hotelCode)
                {
                    UploadServicePostData postData = new UploadServicePostData()
                    {
                        appid = freego_appid,
                        appsecret = freego_appsecret,
                        code = freego_code,
                        room_number = roomNumber,
                        timestamp = TimeHelper.DateTimeToStamp(DateTime.Now).ToString(),
                        key = key,
                        value = value
                    };
                    try
                    {
                        HttpWebRequestHelper.PostWebRequest(freego_url, Newtonsoft.Json.JsonConvert.SerializeObject(postData));
                    }
                    catch (Exception ex)
                    {
                        logger.Error("调用FreeGo接口失败：" + ex.ToString());
                    }
                    break;
                }
            }
        }
    }

    internal class DeviceRegisterPostData
    {
        /// <summary>
        /// 分配的请求id
        /// </summary>
        public string appid { get; set; }
        /// <summary>
        /// 当前unix时间戳
        /// </summary>
        public string timestamp { get; set; }
        /// <summary>
        /// 随机字符串
        /// </summary>
        public string nonce_str { get; set; }
        /// <summary>
        /// 设备名称
        /// </summary>
        public string device_name { get; set; }
        /// <summary>
        /// 签名
        /// </summary>
        public string sign { get; set; }
    }

    public class DeviceRegisterResult
    {
        /// <summary>
        /// 错误代码，0表示成功
        /// </summary>
        public string errcode { get; set; }
        /// <summary>
        /// 设备名称
        /// </summary>
        public string device_name { get; set; }
        /// <summary>
        /// 设备密钥
        /// </summary>
        public string device_secret { get; set; }
        /// <summary>
        /// 阿里云物联网id
        /// </summary>
        public string iot_id { get; set; }
        /// <summary>
        /// 产品key
        /// </summary>
        public string product_key { get; set; }
        /// <summary>
        /// 错误信息
        /// </summary>
        public string msg { get; set; }
    }

    internal class UploadServicePostData
    {
        public string appid { get; set; }
        public string appsecret { get; set; }
        /// <summary>
        /// 酒店编码
        /// </summary>
        public string code { get; set; }
        /// <summary>
        /// 房号
        /// </summary>
        public string room_number { get; set; }
        /// <summary>
        /// 当前unix时间戳
        /// </summary>
        public string timestamp { get; set; }
        /// <summary>
        /// SOS/DND
        /// </summary>
        public string key { get; set; }
        /// <summary>
        /// 当前服务值
        /// </summary>
        public string value { get; set; }
    }
}
