using DoWhatPlc;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace DtWebApi
{
    public class OutGUID
    {
        /// <summary>
        /// 2021.10.25.LLX
        /// </summary>
        /// <returns></returns>
        public static string Get_CS_GUID()
        {
            return Guid.NewGuid().ToString().ToUpper();
        }

    }
    public partial class CallWebApi
    {
        public string InvokeWebapiString(string controlStr, string actionStr, string api, string type, Dictionary<string, string> dics)
        {
            string url = GetUrlWebApi(controlStr, actionStr, dics);
            Task<string> task = InvokeWebapi(url, api, type, dics);
            string result = task.Result;
            return result;
        }
        public DataTable InvokeWebapiDataTable(string controlStr, string actionStr, string api, string type, Dictionary<string, string> dics)
        {
            string url = GetUrlWebApi(controlStr, actionStr, dics);
            Task<string> task = InvokeWebapi(url, api, type, dics);
            var result = task.Result;
            //反序列化Json
            DataTable dt = new DataTable();
            dt = JsonConvert.DeserializeObject<DataTable>(task.Result);
            return dt;
        }
        public DataSet InvokeWebapiDataSet(string controlStr, string actionStr, string api, string type, Dictionary<string, string> dics)
        {
            DataSet ds = new DataSet();
            try
            {
                string url = GetUrlWebApi(controlStr, actionStr, dics);
                Task<string> task = InvokeWebapi(url, api, type, dics);
                var result = task.Result;
                //反序列化Json
                ds = JsonConvert.DeserializeObject<DataSet>(task.Result);
            }
            catch
            {

            }
            return ds;


        }

        public SqlDataReader InvokeWebapiSqlDataReader(string controlStr, string actionStr, string api, string type, Dictionary<string, string> dics)
        {
            string url = GetUrlWebApi(controlStr, actionStr, dics);
            Task<string> task = InvokeWebapi(url, api, type, dics);
            var result = task.Result;
            //反序列化Json
            SqlDataReader dr;
            dr = JsonConvert.DeserializeObject<SqlDataReader>(task.Result);
            return dr;
        }

        public bool InvokeWebapiBool(string controlStr, string actionStr, string api, string type, Dictionary<string, string> dics)
        {
            string url = GetUrlWebApi(controlStr, actionStr, dics);
            Task<string> task = InvokeWebapi(url, api, type, dics);
            string result = task.Result;
            return Convert.ToBoolean(result);
        }
        public int InvokeWebapiInt(string controlStr, string actionStr, string api, string type, Dictionary<string, string> dics)
        {
            string url = GetUrlWebApi(controlStr, actionStr, dics);
            Task<string> task = InvokeWebapi(url, api, type, dics);
            string result = task.Result;
            return Convert.ToInt32(result);
        }
        #region WinFrom调用webapi接口通用方法
        public EngineValue InvokeWebapiEngineValue(string controlStr, string actionStr, string api, string type, Dictionary<string, string> dics)
        {
            string url = GetUrlWebApi(controlStr, actionStr, dics);
            Task<string> task = InvokeWebapi(url, api, type, dics);
            //反序列化Json
            var rt = JsonConvert.DeserializeObject<EngineValue>(task.Result);
            return rt;
        }
        public ReturnValueObject InvokeWebapiReturnValueObject(string controlStr, string actionStr, string api, string type, Dictionary<string, string> dics)
        {
            string url = GetUrlWebApi(controlStr, actionStr, dics);
            Task<string> task = InvokeWebapi(url, api, type, dics);
            //反序列化Json
            var rs = JsonConvert.DeserializeObject<ReturnValueString>(task.Result);
            if (rs == null) return null;
            var ro = rs.ReturnValueToObject();
            return ro;
        }
        public List<ReturnValueObject> InvokeWebapiReturnValueObjectList(string controlStr, string actionStr, string api, string type, Dictionary<string, string> dics)
        {
            string url = GetUrlWebApi(controlStr, actionStr, dics);
            Task<string> task = InvokeWebapi(url, api, type, dics);
            //反序列化Json
            var rsList = JsonConvert.DeserializeObject< List < ReturnValueString >  >(task.Result);
            List<ReturnValueObject> roList = new List<ReturnValueObject>();
            foreach(var rs in rsList)
            {
                var ro = rs.ReturnValueToObject();
                roList.Add(ro);
            }

            return roList;
        }
        public void InvokeWebapiWritePLC(string controlStr, string actionStr, string api, string type, Dictionary<string, string> dics)
        {
            string url = GetUrlWebApi(controlStr, actionStr, dics);
            Task<string> task = InvokeWebapi(url, api, type, dics);

        }
        //public List<ReturnValueObject> InvokeWebapiReturnValueObjectList(string controlStr, string actionStr, string api, string type, Dictionary<string, string> dics)
        //{
        //    string url = GetUrlWebApi(controlStr, actionStr, dics);
        //    Task<string> task = InvokeWebapi(url, api, type, dics);
        //    //反序列化Json
        //    var rtList = JsonConvert.DeserializeObject<List<ReturnValueString>>(task.Result);

        //    List<ReturnValueObject> roList = new List<ReturnValueObject>();
        //    foreach(var rt in rtList)
        //    {
        //        var ro = rt.ReturnValueToObject();
        //        roList.Add(ro);
        //    }
        //    return roList;
        //}

        public HashtableList InvokeWebapiHashtableList(string controlStr, string actionStr, string api, string type, Dictionary<string, string> dics = null)
        {
            try
            {
                string url = GetUrlWebApi(controlStr, actionStr, dics);
                Task<string> task = InvokeWebapi(url, api, type, dics);
                //反序列化Json
                var rtList = JsonConvert.DeserializeObject<HashtableList>(task.Result);

                return rtList;
            }
            catch
            {
                return new HashtableList();
            }

        }
        public List<TagIDTagFormat> InvokeWebapiListTagFormat(string controlStr, string actionStr, string api, string type, Dictionary<string, string> dics=null)
        {
            string url = GetUrlWebApi(controlStr, actionStr, dics);
            Task<string> task = InvokeWebapi(url, api, type, dics);
            //反序列化Json
            var rtList = JsonConvert.DeserializeObject<List<TagIDTagFormat>>(task.Result);

            return rtList;
        }
        public QualityDataSaveList InvokeWebapiQualityDataSaveList(string controlStr, string actionStr, string api, string type, Dictionary<string, string> dics = null)
        {
            string url = GetUrlWebApi(controlStr, actionStr, dics);
            Task<string> task = InvokeWebapi(url, api, type, dics);
            //反序列化Json
            var rtList = JsonConvert.DeserializeObject<QualityDataSaveList>(task.Result);

            return rtList;
        }
        public List<string> InvokeWebapiListString(string controlStr, string actionStr, string api, string type, Dictionary<string, string> dics = null)
        {
            try
            {
                string url = GetUrlWebApi(controlStr, actionStr, dics);
                Task<string> task = InvokeWebapi(url, api, type, dics);
                //反序列化Json
                var rtList = JsonConvert.DeserializeObject<List<string>>(task.Result);

                return rtList;
            }
            catch(Exception err)
            {
                return new List<string>();

            }

        }

        public ConcurrentDictionary<string, TagFormat> InvokeWebapiConcurrentDictionaryTagFormat(string controlStr, string actionStr, string api, string type, Dictionary<string, string> dics = null)
        {

            string url = GetUrlWebApi(controlStr, actionStr, dics);
            Task<string> task = InvokeWebapi(url, api, type, dics);
            //反序列化Json
            var rtList = JsonConvert.DeserializeObject<ConcurrentDictionary<string, TagFormat>>(task.Result);

            return rtList;
        }

        private async Task<string> InvokeWebapi(string url, string api, string type, Dictionary<string, string> dics)
        {
            string result = string.Empty;
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Add("authorization", "Basic YWRtaW46cGFzc3dvcmRAcmljZW50LmNvbQ==");//basic编码后授权码
            client.BaseAddress = new Uri(url);

            client.Timeout = TimeSpan.FromSeconds(510);

            if (type.ToLower() == "put")
            {
                HttpResponseMessage response;
                //包含复杂类型
                if (dics.Keys.Contains("input"))
                {
                    if (dics != null)
                    {
                        foreach (var item in dics.Keys)
                        {
                            api = api.Replace(item, dics[item]).Replace("{", "").Replace("}", "");
                        }
                    }
                    var contents = new StringContent(dics["input"], Encoding.UTF8, "application/json");
                    response = client.PutAsync(api, contents).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        result = await response.Content.ReadAsStringAsync();
                        return result;
                    }
                    return result;
                }

                var content = new FormUrlEncodedContent(dics);
                response = client.PutAsync(api, content).Result;
                if (response.IsSuccessStatusCode)
                {
                    result = await response.Content.ReadAsStringAsync();
                    return result;
                }
            }
            else if (type.ToLower() == "post")
            {
                var content = new FormUrlEncodedContent(dics);

                HttpResponseMessage response = client.PostAsync(api, content).Result;
                if (response.IsSuccessStatusCode)
                {
                    result = await response.Content.ReadAsStringAsync();
                    return result;
                }
            }
            else if (type.ToLower() == "get")
            {
                HttpResponseMessage response = client.GetAsync(api).Result;

                if (response.IsSuccessStatusCode)
                {
                    result = await response.Content.ReadAsStringAsync();
                    return result;
                }
            }
            else
            {
                return result;
            }
            return result;
        }
        #endregion
        public static string Url_WebApi = System.Configuration.ConfigurationManager.AppSettings["Url_WebApi"];
        private  string GetUrlWebApi(string controlStr,string actionStr,Dictionary<string,string> dic=null)
        {
            string url = Url_WebApi + "//api//" + controlStr + "//"+actionStr;
            //string url = Url_WebApi + "//api//" + controlStr+"1" + "//"+actionStr;
            StringBuilder builder = new StringBuilder();
            int i = 0;
            if(dic!=null)
            {
                foreach (var item in dic)
                {
                    string item_Value = Utils.UrlEncode(item.Value);

                    if (i > 0)
                        builder.Append("&");
                    builder.AppendFormat("{0}={1}", item.Key, item_Value);
                    i++;
                }
                if (i > 0)
                {
                    url = url + "//?" + builder.ToString();
                }
            }

            return url;
        }
        private string GetUrlWebApi(string controlStr, string actionStr)
        {
            string url = Url_WebApi + "//api//" + controlStr + "//" + actionStr;
           
            return url;
        }

        
        #region 获取APP升级版本信息
        //public List<Versions> GetVersList()
        //{
        //    string api = "";
        //    List<Versions> list = new List<Versions>();
        //    string url = "http://域名/api/Config/GetVersionList?ClientType=android";
        //    Dictionary<string, string> dics = new Dictionary<string, string>();
        //    Task<string> task = InvokeWebapi(url, api, "GET", dics);
        //    string result = task.Result;
        //    #region 解析结果集
        //    if (result != null)
        //    {
        //        JObject jsonObj = null;
        //        jsonObj = JObject.Parse(result);
        //        DataInfo info = new DataInfo();
        //        info.statusCode = Convert.ToInt32(jsonObj["statusCode"]);
        //        info.message = jsonObj["message"].ToString();
        //        if (info.statusCode == 1)
        //        {
        //            JArray jlist = JArray.Parse(jsonObj["data"].ToString());
        //            for (int i = 0; i < jlist.Count; ++i)  //遍历JArray  
        //            {
        //                Versions ver = new Versions();
        //                JObject tempo = JObject.Parse(jlist[i].ToString());
        //                ver.VersionId = Convert.ToInt32(tempo["versionId"]);
        //                ver.VersionNumber = tempo["versionNumber"].ToString();
        //                ver.Description = tempo["description"].ToString();
        //                ver.FilePath = tempo["filePath"].ToString();
        //                ver.ClientType = tempo["clientType"].ToString();
        //                ver.IsForce = Convert.ToInt32(tempo["isForce"]);
        //                list.Add(ver);
        //            }
        //        }
        //    }
        //    #endregion
        //    return list;
        //}

        #endregion
    }

    public class Post
    {
        public static string Postring(string url, Dictionary<string, string> dic)
        {
            string result = "";
            //url = "http://172.16.22.15:8000/" + url;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.Proxy = null;

            req.KeepAlive = false;

            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();

            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }

        public static string Postring1(string url, string token, Dictionary<string, string> dic)
        {
            string results = "";
            //url = "http://172.16.22.15:8000/" + url;

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.Headers.Add("Authorization", "Bearer " + token);
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            try
            {
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
                #endregion
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                //获取响应内容
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    results = reader.ReadToEnd();
                }
                return results;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return e.Message;
                throw;
            }

        }

    }

}
