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

namespace Test.Helper
{
    /// <summary>
    /// 商城帮助类
    /// </summary>
    public class MallHelper
    {
        /// <summary>
        /// 获取数据
        /// </summary>
        public static void GetData()
        {
            string cookie = "__login_route=%2Fadmin%2Fpassport%2Flogin; __login_role=admin; HJ_SESSION_ID=7vk71fa0f18fbqh525spku825f; _csrf=a8195370a076c6ca402e1bcfe99202bab6fe6db797e12d3b3c962b8ab05858c6a%3A2%3A%7Bi%3A0%3Bs%3A5%3A%22_csrf%22%3Bi%3A1%3Bs%3A32%3A%22LKtJyYWEFsOkis_aatuA-fbrGZvhC3fp%22%3B%7D";
            GetGategoryImgList(cookie);
        }

        public static void GetPage(string cookie)
        {
            var list = GetPageList(cookie);
            if (list != null && list.Count > 0)
            {
                var index = 1;
                foreach (var item in list)
                {
                    Console.WriteLine(index + "/" + list.Count + item.title + "分类Start");
                    StringBuilder builder = new StringBuilder();
                    builder.AppendFormat(" INSERT INTO RB_Miniprogram_Page_Templ(PageName,IsUse,IsShowNav,IsHome,TenantId,MallBaseId,CreateDate,CreateBy,Status)");
                    builder.AppendFormat(" VALUES('{0}',{1},{2},{3},1,1,'{4}',1,0);SELECT LAST_INSERT_ID()", item.title,item.is_disable,item.show_navs,item.is_home_page, DateTime.Now);
                    List<MySqlParameter> paramsList = new List<MySqlParameter>();
            
                    try
                    {
                        var res = DBHelper.MySqlHelper.ExecuteScalar(DBHelper.MySqlHelper.defaultConnection, System.Data.CommandType.Text, builder.ToString(), paramsList.ToArray());
                        if (res != null && Convert.ToInt32(res) > 0)
                        {
                            string updateSql = string.Format("UPDATE RB_Miniprogram_Page_Templ SET Id={0} WHERE Id={1}", item.id, Convert.ToInt32(res));
                            var res1 = DBHelper.MySqlHelper.ExecuteScalar(DBHelper.MySqlHelper.defaultConnection, System.Data.CommandType.Text, updateSql, null);
                        }
                        if (item.navs != null && item.navs.Count > 0)
                        {
                            foreach (var subItem in item.navs)
                            {
                                StringBuilder builder2 = new StringBuilder();
                                builder2.AppendFormat(" INSERT INTO rb_miniprogram_page_templ_details(PageTemplID,NavName,TemplateId,TemplateShowName)");
                                builder2.AppendFormat(" VALUES({0},'{1}',{2},'{3}');SELECT LAST_INSERT_ID()", item.id, subItem.template, subItem.template_id, string.Format("#{0}:{1}",subItem.template_id,subItem.template));
                                
                                var res2 = DBHelper.MySqlHelper.ExecuteScalar(DBHelper.MySqlHelper.defaultConnection, System.Data.CommandType.Text, builder2.ToString(), null);
                            }
                        }
                     
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(index + "/" + ex.Message);
                    }
                    index++;
                    Console.WriteLine(index + "/" + list.Count + item.title + "分类End");
                }
            }
        }
        
        /// <summary>
        /// 获取页面数据
        /// </summary>
        /// <param name="cookie"></param>
        /// <returns></returns>
        public static List<PageData> GetPageList(string cookie)
        {
            List<PageData> list = new List<PageData>();
            string ApiUrl = "https://wx.weibaoge.cn/web/index.php?r=plugin%2Fdiy%2Fmall%2Fpage%2Findex&page={0}";
            string url1 = string.Format(ApiUrl, "1");
            string jsonData = HttpGet(url1, cookie);
            if (jsonData != null && !string.IsNullOrEmpty(jsonData))
            {
                JObject obj = JObject.Parse(jsonData);
                JObject dataObj = JObject.Parse(obj["data"].ToString());
                list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<PageData>>(dataObj["list"].ToString());
            }
            if (list == null)
            {
                list = new List<PageData>();
            }
            Thread.Sleep(1000 * 5);
            string url2 = string.Format(ApiUrl, "2");
            string jsonData2 = HttpGet(url2, cookie);
            if (jsonData2 != null && !string.IsNullOrEmpty(jsonData2))
            {
                JObject obj = JObject.Parse(jsonData2);
                JObject dataObj = JObject.Parse(obj["data"].ToString());
                var list2 = Newtonsoft.Json.JsonConvert.DeserializeObject<List<PageData>>(dataObj["list"].ToString());
                if (list2 != null && list2.Count > 0)
                {
                    list.AddRange(list2);
                }
            }
            return list;
        }

        
        /// <summary>
        /// 获取模板
        /// </summary>
        public static void GetTemplate(string cookie)
        {
            var list = GetTemplateList(cookie);
            if (list != null && list.Count > 0)
            {
                var index = 1;
                foreach (var item in list)
                {
                    Console.WriteLine(index + "/" + list.Count + item.name + "分类Start");
                    StringBuilder builder = new StringBuilder();
                    builder.AppendFormat(" INSERT INTO rb_miniprogram_template(TenantId,MallBaseId,TemplateName,TemplateData,CreateDate,CreateBy,Status)");
                    builder.AppendFormat(" VALUES(1,1,'{0}',@data,'{1}',1,0);SELECT LAST_INSERT_ID()", item.name,  DateTime.Now);
                    List<MySqlParameter> paramsList = new List<MySqlParameter>();
                    paramsList.Add(new MySqlParameter()
                    {
                         ParameterName= "@data",
                         Value= item.data.Replace(@"\", "")
                    });
                    try
                    {
                        var res = DBHelper.MySqlHelper.ExecuteScalar(DBHelper.MySqlHelper.defaultConnection, System.Data.CommandType.Text, builder.ToString(), paramsList.ToArray());
                        if (res != null && Convert.ToInt32(res) > 0)
                        {
                            string updateSql = string.Format("UPDATE rb_miniprogram_template SET Id={0} WHERE Id={1}", item.id, Convert.ToInt32(res));
                            var res1 = DBHelper.MySqlHelper.ExecuteScalar(DBHelper.MySqlHelper.defaultConnection, System.Data.CommandType.Text, updateSql, null);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(index + "/" + ex.Message);
                    }
                    index++;
                    Console.WriteLine(index + "/" + list.Count + item.name + "分类End");
                }
            }
        }

        /// <summary>
        /// 获取模板列表
        /// </summary>
        /// <param name="cookie"></param>
        /// <returns></returns>
        public static List<TemplateData> GetTemplateList(string cookie)
        {
            List<TemplateData> list = new List<TemplateData>();
            string ApiUrl = "https://wx.weibaoge.cn/web/index.php?r=plugin%2Fdiy%2Fmall%2Ftemplate%2Findex&page={0}";
            string url1 = string.Format(ApiUrl, "1");
            string jsonData = HttpGet(url1, cookie);
            if (jsonData != null && !string.IsNullOrEmpty(jsonData))
            {
                JObject obj = JObject.Parse(jsonData);
                JObject dataObj = JObject.Parse(obj["data"].ToString());
                list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<TemplateData>>(dataObj["list"].ToString());
            }
            if (list == null)
            {
                list = new List<TemplateData>();
            }
            Thread.Sleep(1000 * 5);
            string url2 = string.Format(ApiUrl, "2");
            string jsonData2 = HttpGet(url2, cookie);
            if (jsonData2 != null && !string.IsNullOrEmpty(jsonData2))
            {
                JObject obj = JObject.Parse(jsonData2);
                JObject dataObj = JObject.Parse(obj["data"].ToString());
                var list2 = Newtonsoft.Json.JsonConvert.DeserializeObject<List<TemplateData>>(dataObj["list"].ToString());
                if (list2 != null && list2.Count > 0)
                {
                    list.AddRange(list2);
                }
            }
            return list;
        }


        /// <summary>
        /// 获取分类
        /// </summary>
        /// <param name="cookie"></param>
        static void GetGategoryImgList(string cookie)
        {
            var CategoryList = GetCategoryList(cookie);
            if (CategoryList != null && CategoryList.Count > 0)
            {
                var index = 1;
                foreach (var item in CategoryList)
                {
                    Console.WriteLine(index+"/"+ CategoryList.Count + item.name + "分类Start");
                    StringBuilder builder = new StringBuilder();
                    builder.AppendFormat(" INSERT INTO rb_material_group(Name,Type,Sort,Recycled,Status,TenantId,MallBaseId,CreateDate,UpdateDate)");
                    builder.AppendFormat(" VALUES('{0}',{1},{2},1,0,1,1,'{3}','{4}');SELECT LAST_INSERT_ID()", item.name, item.type, item.is_recycle, DateTime.Now, DateTime.Now);
                    int parentId = 0;
                    try
                    {
                        string existsSql = string.Format("SELECT Id FROM rb_material_group WHERE Name='{0}' ", item.name.Trim());
                        var existsObj = DBHelper.MySqlHelper.ExecuteScalar(DBHelper.MySqlHelper.defaultConnection, System.Data.CommandType.Text, existsSql, null);
                        if (existsObj != null && Convert.ToInt32(existsObj) > 0)
                        {
                            Int32.TryParse(existsObj.ToString(), out parentId);
                        }
                        else
                        {
                            var res = DBHelper.MySqlHelper.ExecuteScalar(DBHelper.MySqlHelper.defaultConnection, System.Data.CommandType.Text, builder.ToString(), null);
                            if (res != null && Convert.ToInt32(res) > 0)
                            {
                                Int32.TryParse(res.ToString(), out parentId);
                            }
                        }

                    }
                    catch (Exception ex)
                    {

                    }
                    int pageIndex = 1;
                    int pageCount = 1;
                    List<CategoryImg> imgList = new List<CategoryImg>();
                    while (pageIndex <= pageCount)
                    {
                        var tempImgList = GetCategoryImgList(cookie, pageIndex, item.id, out pageCount);
                        Console.WriteLine(pageIndex + "/" + pageCount + item.name + "分类ing");
                        if (tempImgList != null && tempImgList.Count > 0)
                        {
                            foreach (var subItem in tempImgList)
                            {
                                string existsSubSql = string.Format("SELECT Id FROM rb_material_info WHERE Name='{0}' AND Type={1} AND GroupId={2} ", subItem.name, subItem.type, parentId);
                                var existsSubObj = DBHelper.MySqlHelper.ExecuteScalar(DBHelper.MySqlHelper.defaultConnection, System.Data.CommandType.Text, existsSubSql, null);
                                if (existsSubObj != null && Convert.ToInt32(existsSubObj) > 0)
                                {
                                   // Int32.TryParse(existsSubObj.ToString(), out parentId);
                                }
                                else
                                {
                                    try
                                    {
                                        CreateImage(subItem.url);
                                        string path = "https://viitto-1301420277.cos.ap-chengdu.myqcloud.com" + GetFileUrl(subItem.url);
                                        StringBuilder stringBuilder = new StringBuilder();
                                        stringBuilder.AppendFormat("INSERT INTO rb_material_info(Name,Type,GroupId,Path,Image,VideoTime,WithHeight,TenantId,MallBaseId,CreateDate,UpdateDate,Recycled,Status)");
                                        stringBuilder.AppendFormat(" VALUES('{0}',{1},{2},'{3}','{4}',0,0,1,1,'{5}','{6}',1,0)", subItem.name, subItem.type, parentId, path, "", DateTime.Now, DateTime.Now);
                                        var newResult = DBHelper.MySqlHelper.ExecuteNonQuery(DBHelper.MySqlHelper.defaultConnection, System.Data.CommandType.Text, stringBuilder.ToString(), null);
                                    }
                                    catch (Exception ex)
                                    {

                                    }
                                }
                            }
                        }
                        pageIndex++;
                        var ranDomNum = new Random().Next(1, 20);
                        Thread.Sleep(1000 * ranDomNum);
                    }
                    index++;
                    Console.WriteLine(index + "/" + CategoryList.Count + item.name + "分类End");
                }
            }
        }

        /// <summary>
        /// 生成图片
        /// </summary>
        /// <param name="url"></param>
        static void CreateImage(string url)
        {
            string tempPath = GetFileUrl(url);
            string path = Environment.CurrentDirectory + tempPath;//下载到的地址+文件名                                                // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            Stream responseStream = response.GetResponseStream();
            string newFilePath = path.Substring(0, path.LastIndexOf("/"));
            if (!System.IO.Directory.Exists(newFilePath))//如果不存在就创建file文件夹
            {
                System.IO.Directory.CreateDirectory(newFilePath);
            }
            //创建本地文件写入流
            Stream stream = new FileStream(path, FileMode.Create);
            byte[] bArr = new byte[1024];
            int size = responseStream.Read(bArr, 0, (int)bArr.Length);
            while (size > 0)
            {
                stream.Write(bArr, 0, size);
                size = responseStream.Read(bArr, 0, (int)bArr.Length);
            }
            stream.Close();
            responseStream.Close();
        }

        /// <summary>
        /// 获取Oss文件全路径
        /// </summary>
        /// <param name="path">文件相对路径</param>
        /// <returns></returns>
        public static string GetFileUrl(string path)
        {
            return path.Replace("https://cdnimg.iotweixin.com", "");
        }

        /// <summary>
        /// 获取分类图片
        /// </summary>
        /// <param name="cookie"></param>
        /// <param name="pageIndex"></param>
        /// <param name="Id">分类编号</param>
        /// <param name="pageCount"></param>
        /// <returns></returns>
        static List<CategoryImg> GetCategoryImgList(string cookie, int pageIndex, int Id, out int pageCount)
        {
            pageCount = 0;
            List<CategoryImg> list = new List<CategoryImg>();
            string imgApi = "https://wx.weibaoge.cn/web/index.php?r=common%2Fattachment%2Flist&page={0}&attachment_group_id={1}&type=image&is_recycle=0&keyword=";
            string newImaApi = string.Format(imgApi, pageIndex, Id);
           // cookie = "__login_route=%2Fadmin%2Fpassport%2Flogin; __login_role=admin; search={'keyword':'','status':'-1','sort_prop':'','sort_type':'','cats':[],'date_start':null,'date_end':null}; HJ_SESSION_ID=kmmormovvm2u9qh5drkgsbj1ta; _csrf=7a980bb65eabe0ac3d77199092030044b17ae9779de00eaed628c8095ab2fe0ca%3A2%3A%7Bi%3A0%3Bs%3A5%3A%22_csrf%22%3Bi%3A1%3Bs%3A32%3A%22rsnZWVWkZkpfvVhLBXu8sGG3px0Dgcsx%22%3B%7D";
            string jsonData = HttpGet(newImaApi, cookie);
            if (jsonData != null && !string.IsNullOrEmpty(jsonData))
            {
                JObject obj = JObject.Parse(jsonData);
                JObject dataObj = JObject.Parse(obj["data"].ToString());
                list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<CategoryImg>>(dataObj["list"].ToString());

                var pageObj = JObject.Parse(dataObj["pagination"].ToString());
                Int32.TryParse(pageObj["page_count"].ToString(), out pageCount);
            }
            return list;
        }

        /// <summary>
        /// 获取商品分类
        /// </summary>
        /// <param name="cookie"></param>
        /// <returns></returns>
        static List<Category> GetCategoryList(string cookie)
        {
            List<Category> list = new List<Category>();
            string ApiUrl = "https://wx.weibaoge.cn/web/index.php?r=common%2Fattachment%2Fgroup-list&is_recycle=0&type=image";
            string jsonData = HttpGet(ApiUrl, cookie);
            if (jsonData != null && !string.IsNullOrEmpty(jsonData))
            {
                JObject obj = JObject.Parse(jsonData);
                JObject dataObj = JObject.Parse(obj["data"].ToString());
                list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Category>>(dataObj["list"].ToString());
            }
            return list;
        }

        /// <summary>
        /// Get获取数据
        /// </summary>
        /// <param name="url">url地址</param>
        /// <param name="encode">编码方式</param>
        /// <param name="Source">来源</param>
        /// <returns></returns>
        static string HttpGet(string url, string cookie)
        {
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
            myRequest.Headers.Add("cookie", cookie);
            myRequest.Headers.Add("x-requested-with", "XMLHttpRequest");
            //x-requested-with: XMLHttpRequest
            myRequest.Method = "GET";
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            string content = reader.ReadToEnd();
            reader.Close();
            return content;
        }
    }
}
