using MySql.Data.MySqlClient;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Test.DBHelper;

namespace Test.Helper
{
    /// <summary>
    /// 会麦
    /// </summary>
    public class HuiMaiHelper
    {
        static string ApiUrl = "https://oc.huimaihuishou.com";

        static List<string> tempArray = new List<string>() { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };

        static string cookie = "PHPSESSID=6ou76sh2d4ccceleic177iojo6; expires=Fri, 22-Jul-2022 18:18:51 GMT; Max-Age=54000; path=/";


        public static void GetCategoryList()
        {
            string url = ApiUrl + "/apiv1/Category/get_category_list";
            string jsonData = HttpPost(url, cookie, "");
            var list = ParseCategoryList(jsonData);
            List<brandItem> brandList = new List<brandItem>();
            if (list != null && list.Count > 0)
            {
                //string deleteSql = " TRUNCATE TABLE RB_Assess_Category; ";
                //Test.DBHelper.MySqlHelper.ExecuteNonQuery(Test.DBHelper.MySqlHelper.defaultConnection, System.Data.CommandType.Text, deleteSql, null);
            }
            foreach (var item in list)
            {
                //string sql = string.Format("INSERT INTO RB_Assess_Category(Id, Name,Image,CreateDate,UpdateDate) VALUES({0},'{1}','{2}','{3}','{3}')", item.id, item.name, item.logo, DateTime.Now);
                //Test.DBHelper.MySqlHelper.ExecuteNonQuery(Test.DBHelper.MySqlHelper.defaultConnection, System.Data.CommandType.Text, sql, null);
                GetBrandList(item, brandList);
            }
            string str = "";
        }

        private static List<cateGoryListItem> ParseCategoryList(string json)
        {
            List<cateGoryListItem> list = new List<cateGoryListItem>();
            if (!string.IsNullOrEmpty(json))
            {
                JObject rootObj = JObject.Parse(json);
                if (rootObj!=null&&!string.IsNullOrEmpty(rootObj["result"].ToString()))
                {
                    JObject resultObj = JObject.Parse(rootObj["result"].ToString());
                    if (resultObj != null && !string.IsNullOrEmpty(resultObj["data"].ToString()))
                    {
                        JObject dataObj = JObject.Parse(resultObj["data"].ToString());
                        if (dataObj != null && !string.IsNullOrEmpty(dataObj["list"].ToString()))
                        {
                            var tempList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<cateGoryListItem>>(dataObj["list"].ToString());
                            if (tempList != null && tempList.Count > 0)
                            {
                                list.AddRange(tempList);
                            }
                        }
                       
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取商品详情
        /// </summary>
        /// <returns></returns>
        public static void GetBrandList(cateGoryListItem rootItem, List<brandItem> brandList)
        {
            string newImaApi = ApiUrl + "/apiv1/Brand/get_brand_list_by_category";
            var data = new
            {
                category_id = rootItem.id
            };
            var postMsg = new { data };
            string jsonData = HttpPost(newImaApi, cookie, Newtonsoft.Json.JsonConvert.SerializeObject(postMsg));

            var list = ParseCategory(jsonData);
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    GetBrandInfo(item);
                }
            }
            if (list != null && list.Count > 0)
            {
                brandList.AddRange(list);
            }
        }

        /// <summary>
        /// 获取分类详情
        /// </summary>
        /// <param name="item"></param>
        public static void GetBrandInfo(brandItem item)
        {
            string newImaApi = ApiUrl + "/apiv1/Brand/get_brand_img";
            var data = new
            {
                category_id = item.category_id,
                brand_id = item.id
            };
            var postMsg = new
            {
                data
            };
            string jsonData = HttpPost(newImaApi, cookie, Newtonsoft.Json.JsonConvert.SerializeObject(postMsg));
            if (!string.IsNullOrEmpty(jsonData))
            {
                JObject rootObj = JObject.Parse(jsonData);
                if (rootObj != null && !string.IsNullOrEmpty(rootObj["result"].ToString()))
                {
                    JObject resultObj = JObject.Parse(rootObj["result"].ToString());
                    if (resultObj != null&&!string.IsNullOrEmpty(resultObj["data"].ToString()))
                    {
                        JObject dataObj = JObject.Parse(resultObj["data"].ToString());
                        if (dataObj != null)
                        {
                            JArray imgArray = JArray.Parse(dataObj["img_array"].ToString());
                            List<object> imgList = new List<object>();
                            if (imgArray != null && imgArray.Count > 0)
                            {
                                foreach (var jItem in imgArray)
                                {
                                    JObject imgObj = JObject.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(jItem));
                                    string sort = imgObj["sort"].ToString();
                                    Int32.TryParse(sort, out int newSort);
                                    imgList.Add(new
                                    {
                                        Name = imgObj["name"].ToString(),
                                        Path = imgObj["full_image"].ToString(),
                                        Sort = newSort,
                                    });
                                }
                            }
                            string upload_remark = dataObj["upload_remark"].ToString();
                            string remark = dataObj["remark"].ToString();
                            string bottom_remark = dataObj["bottom_remark"].ToString();

                            string selectSql = "SELECT Id FROM rb_assess_brand WHERE Id=" + item.id;
                            var obj= Test.DBHelper.MySqlHelper.ExecuteScalar(Test.DBHelper.MySqlHelper.defaultConnection, System.Data.CommandType.Text, selectSql,null);
                            int Id = 0;
                            if (obj != null && Convert.ToInt32(obj.ToString()) > 0)
                            {
                                Id = Convert.ToInt32(obj.ToString());
                            }
                            if (Id <= 0)
                            {
                                string sql = @" INSERT INTO rb_assess_brand(Id,CategoryId,Name,Logo,PinYin,IsHot,BrandImg,CreateDate,UpdateDate,MoreDesc,RemarkDesc) ";
                                sql += string.Format(@"          VALUES(@Id,@CategoryId,@Name,@Logo,@PinYin,@IsHot,@BrandImg,@CreateDate,@UpdateDate,@MoreDesc,@RemarkDesc) ");
                                var parameters = new List<MySqlParameter>();
                                parameters.Add(new MySqlParameter() { ParameterName = "Id", Value = item.id });
                                parameters.Add(new MySqlParameter() { ParameterName = "CategoryId", Value = item.category_id });
                                parameters.Add(new MySqlParameter() { ParameterName = "Name", Value = item.brand_name });
                                parameters.Add(new MySqlParameter() { ParameterName = "Logo", Value = item.logo });
                                parameters.Add(new MySqlParameter() { ParameterName = "PinYin", Value = item.initial });
                                parameters.Add(new MySqlParameter() { ParameterName = "IsHot", Value = item.ishot });
                                parameters.Add(new MySqlParameter() { ParameterName = "BrandImg", Value = Newtonsoft.Json.JsonConvert.SerializeObject(imgList) });
                                parameters.Add(new MySqlParameter() { ParameterName = "CreateDate", Value = DateTime.Now });
                                parameters.Add(new MySqlParameter() { ParameterName = "UpdateDate", Value = DateTime.Now });
                                parameters.Add(new MySqlParameter() { ParameterName = "MoreDesc", Value = bottom_remark });
                                parameters.Add(new MySqlParameter() { ParameterName = "RemarkDesc", Value = remark });
                                var res = Test.DBHelper.MySqlHelper.ExecuteNonQuery(Test.DBHelper.MySqlHelper.defaultConnection, System.Data.CommandType.Text, sql, parameters.ToArray());
                            }
                            else
                            {
                                string str = "";
                            }
                        }
                    }
                }
            }
        }
     
        public static List<brandItem> ParseCategory(string jsonData)
        {
            List<brandItem> list = new List<brandItem>();
            if (!string.IsNullOrEmpty(jsonData))
            {
                JObject jobj = JObject.Parse(jsonData);
                if (jobj != null && !string.IsNullOrEmpty(jobj["result"].ToString()))
                {
                    JObject subObj = JObject.Parse(jobj["result"].ToString());
                    if (subObj != null && subObj["code"].ToString() == "1")
                    {
                        JObject dataObj = JObject.Parse(subObj["data"].ToString());

                        var hotListStr = dataObj["hot_list"].ToString();
                        var listStr = dataObj["list"].ToString();
                        if (!string.IsNullOrEmpty(hotListStr))
                        {
                            var hotList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<brandItem>>(hotListStr);
                            if (hotList != null && hotList.Count > 0)
                            {
                                foreach (var item in hotList)
                                {
                                    item.ishot = 1;
                                }
                                list.AddRange(hotList);
                            }
                        }
                        if (!string.IsNullOrEmpty(listStr))
                        {
                            JObject lObj = JObject.Parse(listStr);
                            foreach (var item in tempArray)
                            {
                                if (lObj[item] != null)
                                {
                                    string str = lObj[item].ToString();
                                    if (!string.IsNullOrEmpty(str))
                                    {
                                        var dataList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<brandItem>>(str);
                                        if (dataList != null && dataList.Count > 0)
                                        {
                                            list.AddRange(dataList);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// Post提交数据
        /// </summary>
        /// <param name="url">url地址</param>
        /// <param name="body">参数</param>
        /// <param name="contenttype">参数</param>
        /// <returns></returns>
        public static string HttpPost(string url,string cookie, string body)
        {
            try
            {
                Encoding encoding = Encoding.UTF8;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Headers.Add("Cookie", cookie);
                request.Method = "POST";
                request.Accept = "application/json, text/javascript, */*"; //"text/html, application/xhtml+xml, */*";
                request.ContentType = "application/json; charset=utf-8";
                request.Timeout = 600000;// 600秒 超时时长
                
                byte[] buffer = encoding.GetBytes(body);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (WebException ex)
            {
                var res = (HttpWebResponse)ex.Response;
                StringBuilder sb = new StringBuilder();
                StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
                sb.Append(sr.ReadToEnd());
                throw new Exception(sb.ToString());
            }
        }
    }

    /// <summary>
    /// 分类列表
    /// </summary>
    public class cateGoryListItem
    {
        public int id { get; set; }

        public string category_name { get; set; }

        public string name { get; set; }

        public string logo { get; set; }

    }

    public class brandItem
    {
        public int id { get; set; }

        public string brand_name { get; set; }

        public int parent_id { get; set; }

        public string logo { get; set; }

        public int category_id { get; set; }

        public string initial { get; set; }

        public int is_head_character { get; set; }

        public string head_character_url { get; set; }

        public string brand_name_alpha { get; set; }

        public string brand_name_title { get; set; }

        public string name { get; set; }

        /// <summary>
        /// 是否热门
        /// </summary>
       public int ishot { get; set; }

    }
}
