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 System.Linq;

namespace Test.Helper
{
    /// <summary>
    /// 用户帮助类
    /// </summary>
    public class UserHelper
    {

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="cookie"></param>
        public static void GetUserData()
        {
            string cookie = "";
            int pageIndex = 1;
            int pageCount = 2;
            while (pageIndex <= pageCount)
            {
                var tempImgList = GetUserImgList(cookie, pageIndex, out pageCount);
                Console.WriteLine(pageIndex + "/" + pageCount + " Edd");
                if (tempImgList != null && tempImgList.Any())
                {
                    foreach (var subItem in tempImgList)
                    {
                        if (subItem.user_id > 101707 && subItem.user_id <= 106252)
                        {
                            StringBuilder stringBuilder = new StringBuilder();
                            //stringBuilder.AppendFormat("update rb_member_user set Photo = '{0}',Name='{1}',SuperiorId={2} where Id = {3}", subItem.avatar, subItem.nickname, subItem.parent_id, subItem.user_id);
                            stringBuilder.AppendFormat("update rb_member_user set Photo = '{0}',SuperiorId={1} where Id = {2} and SuperiorId not in (5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)", subItem.avatar, subItem.parent_id, subItem.user_id);
                            try
                            {
                                var newResult = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, stringBuilder.ToString(), null);
                                //Console.WriteLine("请求:" + subItem.avatar + "    " + subItem.nickname + "    " + subItem.parent_id);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("失败UserId:" + subItem.user_id + " Msg:" + ex.Message);
                            }
                        }
                    }
                }
                pageIndex++;
                var ranDomNum = new Random().Next(3, 7);
                Thread.Sleep(1000 * ranDomNum);
            }
        }

        /// <summary>
        /// 获取用户头像
        /// </summary>
        /// <param name="cookie"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageCount"></param>
        /// <returns></returns>
        static List<UserImage> GetUserImgList(string cookie, int pageIndex, out int pageCount)
        {
            pageCount = 2;
            List<UserImage> list = new List<UserImage>();
            string newImaApi = "http://wx.weibaoge.cn/web/index.php?r=mall%2Fuser%2Findex&page=" + pageIndex + "&member_level=0&platform=0&keyword=";
            cookie = "search={'keyword':'','status':' - 1','sort_prop':'','sort_type':'','cats':[],'date_start':null,'date_end':null,'type':''}; _identity=c964edefdd891bb281844324071fea4e2c1e7d2b21aef031ed81730f4e753d06a%3A2%3A%7Bi%3A0%3Bs%3A9%3A%22_identity%22%3Bi%3A1%3Bs%3A48%3A%22%5B19740%2C%22Cktp5k6Wf3lVS_yjQI_uTgEEE6_ANe-5%22%2C86400%5D%22%3B%7D; HJ_SESSION_ID=tv09q5jnte4v44ca14bnvdi28s; _csrf=9a1b84c62ffd209719019cca9730bf48f33854d3acc2f31982a5ef51ceda400ca%3A2%3A%7Bi%3A0%3Bs%3A5%3A%22_csrf%22%3Bi%3A1%3Bs%3A32%3A%22QwYL8fmmakdUX981YM7R26-Y5YoMnXxU%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<UserImage>>(dataObj["list"].ToString());

                var pageObj = JObject.Parse(dataObj["pagination"].ToString());
                Int32.TryParse(pageObj["page_count"].ToString(), out pageCount);
            }
            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");
            myRequest.Method = "GET";
                
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            string content = reader.ReadToEnd();
            reader.Close();
            return content;
        }

        /// <summary>
        /// Get获取数据
        /// </summary>
        /// <param name="url">url地址</param>
        /// <param name="encode">编码方式</param>
        /// <param name="Source">来源</param>
        /// <returns></returns>
        public static string HttpGet(string url, Encoding encode, string Source, string cookie = "")
        {
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
            if (!string.IsNullOrEmpty(Source))
            {
                myRequest.Referer = Source;
            }
            if (!string.IsNullOrEmpty(cookie))
            {
                myRequest.Headers.Add("cookie", cookie);
            }
            myRequest.Method = "GET";
            HttpWebResponse myResponse = null;
            try
            {
                myResponse = (HttpWebResponse)myRequest.GetResponse();
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), encode);
                string content = reader.ReadToEnd();
                return content;
            }
            //异常请求  
            catch (WebException e)
            {
                myResponse = (HttpWebResponse)e.Response;
                using (Stream errData = myResponse.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(errData))
                    {
                        string text = reader.ReadToEnd();
                        return text;
                    }
                }
            }
        }

    }
}
