using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RestSharp;
using Common;
using System.Configuration;

namespace CommonEntity
{
    public class TCLToken
    {
        public int errno { get; set; }
        public string errmsg { get; set; }
        public TCLTokenData data { get; set; }
    }
    public class TCLTokenData
    {
        public string access_token { get; set; }
        public long expires_in { get; set; }
        public long deadline { get; set; }
        public string refresh_token { get; set; }
    }
    public class TCLBell
    {
        public string cuid { get; set; }
        public string sceneCode { get; set; }
        public string botId { get; set; }
        public PPP @params { get; set; }
    }
    public class PPP
    {
        public string url { get; set; }
    }

    public class TCLCommon
    {
        public static string TCLLoginUrl = ConfigurationManager.AppSettings["TCLLoginUrl"];
        public static string TCLAppId = ConfigurationManager.AppSettings["TCLAppId"];
        public static string TCLAppSecret = ConfigurationManager.AppSettings["TCLAppSecret"];
        private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(TCLCommon));

        /// <summary>
        /// 获取TCL Token
        /// </summary>
        public static void GetTCLTV_Token()
        {
            try
            {
                var client1 = new RestClient(TCLLoginUrl);
                var request1 = new RestRequest("oauth/token", Method.GET);

                request1.AddParameter("app_id", TCLAppId);
                request1.AddParameter("app_secret", TCLAppSecret);
                var QQQ = client1.Execute(request1);
                string ddd = QQQ.Content;
                var FFFA = Newtonsoft.Json.JsonConvert.DeserializeObject<TCLToken>(ddd);
                string TokenKey = CacheKey.TCLToken;
                CSRedisCacheHelper.Set_Partition<TCLToken>(TokenKey, FFFA, 1);
            }
            catch (Exception ex)
            {
                logger.Error("TCL Token Error" + ex.Message);
            }
        }
        /// <summary>
        /// 给TCL发送数据
        /// </summary>
        /// <param name="CUID"></param>
        /// <param name="skillid"></param>
        /// <param name="sceneCode"></param>
        /// <param name="count"></param>
        public static void SendData(string hotelcode, string roomnum, string CUID, string skillid, string sceneCode, int count = 0, Dictionary<string, string> extra_params = null)
        {
            try
            {
                string ID = Guid.NewGuid().ToString("N");
                string ti = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                Dictionary<string, string> dicg = new Dictionary<string, string>();
                dicg.Add("Step", "1");
                dicg.Add("HotelCode", hotelcode);
                dicg.Add("RoomNumber", roomnum);
                dicg.Add("RequestTime", roomnum);
                dicg.Add("CmdType", sceneCode);
                dicg.Add("RequestId", ID);

                var dic1 = new Dictionary<string, string>();
                dic1.Add("cuid", roomnum);
                dic1.Add("sceneCode", sceneCode);
                dic1.Add("botId", skillid);
                dic1.Add("params", Newtonsoft.Json.JsonConvert.SerializeObject(extra_params));


                logger.Error("TCL send data");
                string TokenKey = CacheKey.TCLToken;
                var T = CSRedisCacheHelper.Get_Partition<TCLToken>(TokenKey, 1);
                if (T != null)
                {
                    logger.Equals("TCL Token是" + T.data.access_token);
                    dic1.Add("token", T.data.access_token);

                    var jsondic = Newtonsoft.Json.JsonConvert.SerializeObject(dic1);
                    dicg.Add("RequestCmd", jsondic);

                    //LogRecorrd.WebAPI_DataSend(dicg, "api/tcl_tv");

                    Interface3Log w1 = new Interface3Log();
                    w1.HotelCode = hotelcode;
                    w1.RoomNumber = roomnum;
                    w1.TriggerTime = DateTime.Now;
                    w1.ActionData = new HttpActionData() { RequestData = Newtonsoft.Json.JsonConvert.SerializeObject(dicg) };
                    w1.CommandType = ChangLiangValue.TCL;

                    var q1 = Newtonsoft.Json.JsonConvert.SerializeObject(w1);
                    CSRedisCacheHelper.Publish(CacheKey.InvokeHttpInterface, q1);

                    var client1 = new RestClient(TCLLoginUrl);
                    var request1 = new RestRequest("open/countercontrol/scene_trigger", Method.POST);

                    request1.AddHeader("Authorization", "Bearer " + T.data.access_token);

                    //Dictionary<string, string> dic = new Dictionary<string, string>();
                    //dic.Add("cuid", CUID);
                    //dic.Add("sceneCode", sceneCode);
                    //dic.Add("botId", skillid);
                    //dic.Add("params", Newtonsoft.Json.JsonConvert.SerializeObject(extra_params));

                    TCLBell tsa = new TCLBell();
                    tsa.cuid = CUID;
                    tsa.sceneCode = sceneCode;
                    tsa.botId = skillid;
                    if (extra_params != null && extra_params.Count > 0)
                    {
                        tsa.@params = new PPP() { url = extra_params["url"] };
                    }

                    logger.Error("TCL send data" + Newtonsoft.Json.JsonConvert.SerializeObject(tsa));
                    request1.AddJsonBody(tsa);
                    var QQQ = client1.Execute(request1);
                    string ddd = QQQ.Content;


                    //string ti1 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                    //Dictionary<string, string> dicg1 = new Dictionary<string, string>();
                    //dicg1.Add("HotelCode", hotelcode);
                    //dicg1.Add("RoomNumber", roomnum);
                    //dicg1.Add("RequestId", ID);
                    //dicg1.Add("ResponseMsg", ddd);
                    //dicg1.Add("ResponseTime", ti1);
                    //LogRecorrd.WebAPI_DataSend(dicg1, "api/tcl_tv");
                    logger.Error("TCL 电视触发了 情景。返回数据为：" + ddd);


                    Interface3Log ww = new Interface3Log();
                    ww.HotelCode = hotelcode;
                    ww.RoomNumber = roomnum;
                    ww.TriggerTime = DateTime.Now;
                    ww.ActionData = new HttpActionData() { ResponseData = ddd };
                    ww.CommandType = ChangLiangValue.TCL;

                    var qq = Newtonsoft.Json.JsonConvert.SerializeObject(ww);
                    CSRedisCacheHelper.Publish(CacheKey.InvokeHttpInterface, qq);
                }
                else
                {
                    logger.Equals("TCL Token 为空");
                    if (count == 0)
                    {
                        GetTCLTV_Token();
                        count = count + 1;
                        SendData(hotelcode, roomnum, CUID, skillid, sceneCode, count++);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("TCL SenData" + ex.Message);
            }
        }
    }
}
