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

namespace Test.Helper
{
    public class FreightRulesHelper
    {
        /// <summary>
        /// 获取数据
        /// </summary>
        public static void GetData()
        {
            string cookie = "_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=tnajne35hev8qdajddg9pkg2cu; _csrf=df6aaa8c5fdb2364e3cd74f8e1a6e3036d4553a3e2ad7df9e5934907a5beabd8a%3A2%3A%7Bi%3A0%3Bs%3A5%3A%22_csrf%22%3Bi%3A1%3Bs%3A32%3A%22URmzdlSexWftTrS829hdWnMLSiKhY0gP%22%3B%7D";
            //  GetGategoryImgList(cookie);
            GetRemitsList(cookie);
        }

        #region 物流规则

        static void GetFreightRules(string cookie)
        {
            int pageIndex = 1;
            int pageCount = 1;
            List<FreightRules> imgList = new List<FreightRules>();
            int priceId = 1;
            while (pageIndex <= pageCount)
            {

                var tempImgList = GetFreightRulesList(cookie, pageIndex, out pageCount);
                Console.WriteLine(pageIndex + "/" + pageCount + "运费规则ing");
                if (tempImgList != null && tempImgList.Count > 0)
                {
                    foreach (var subItem in tempImgList)
                    {
                        try
                        {
                            FreightRules model = GetFreightRulesList(cookie, subItem.id);
                            if (model != null)
                            {
                                StringBuilder stringBuilder = new StringBuilder();

                                stringBuilder.AppendFormat("INSERT INTO rb_logistics_rules(ID,MallBaseId,TenantId,CreateDate,UpdateDate,RulesName,ChargeMode,IsDefault,RulesType)");
                                stringBuilder.AppendFormat(" VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}');", model.id, 1, 1, model.created_at, model.updated_at, model.name, model.type, model.status, 1);


                                if (model.detail != null && model.detail.Any())
                                {
                                    foreach (var itemdetail in model.detail)
                                    {
                                        stringBuilder.AppendFormat("INSERT INTO rb_logistics_rulesprice(First,FirstPrice,CreateDate,UpdateDate,Second,SecondPrice,RulesId,MallBaseId,TenantId,ID)");
                                        stringBuilder.AppendFormat(" VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}',{9});", itemdetail.first, itemdetail.firstPrice, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), itemdetail.second, itemdetail.secondPrice, model.id, 1, 1, priceId);

                                        if (itemdetail.list != null && itemdetail.list.Any())
                                        {
                                            foreach (var itemlist in itemdetail.list)
                                            {
                                                stringBuilder.AppendFormat("INSERT INTO rb_logistics_rulesregion(TenantId,MallBaseId,RulesPriceId,RegionId,CreateDate,UpdateDate,RulesType)");
                                                stringBuilder.AppendFormat(" VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}');", 1, 1, priceId, itemlist.id, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), 1);

                                            }
                                        }
                                        priceId += 1;
                                    }
                                }
                                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);
            }
        }


        static List<FreightRules> GetFreightRulesList(string cookie, int pageIndex, out int pageCount)
        {
            pageCount = 0;
            List<FreightRules> list = new List<FreightRules>();
            string imgApi = "https://wx.weibaoge.cn/web/index.php?r=mall%2Fpostage-rule%2Findex&page={0}&keyword=";
            string newImaApi = string.Format(imgApi, pageIndex);
            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<FreightRules>>(dataObj["list"].ToString());

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

        static FreightRules GetFreightRulesList(string cookie, int id)
        {

            FreightRules model = new FreightRules();
            string imgApi = "https://wx.weibaoge.cn/web/index.php?r=mall%2Fpostage-rule%2Fedit&id={0}";
            string newImaApi = string.Format(imgApi, id);
            string jsonData = HttpGet(newImaApi, cookie);
            if (jsonData != null && !string.IsNullOrEmpty(jsonData))
            {
                JObject obj = JObject.Parse(jsonData);
                JObject dataObj = JObject.Parse(obj["data"].ToString());
                model = Newtonsoft.Json.JsonConvert.DeserializeObject<FreightRules>(dataObj["model"].ToString());
            }
            return model;
        }
        #endregion







        #region 佣金

        static void GetRemitsList(string cookie)
        {
            int pageIndex = 1;
            int pageCount = 1;
            List<Remit> imgList = new List<Remit>();
            while (pageIndex <= pageCount)
            {
                var tempImgList = GetRemits(cookie, pageIndex, out pageCount);
                Console.WriteLine(pageIndex + "/" + pageCount + "分销提现ing");
                if (tempImgList != null && tempImgList.Count > 0)
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    foreach (var subItem in tempImgList)
                    {
                        try
                        {

                            int userId = 0;

                            //获取用户信息
                            try
                            {
                                string existsSubSql = string.Format("SELECT Id FROM rb_member_user WHERE Photo='{0}' ", subItem.user.avatar);
                                var existsSubObj = DBHelper.MySqlHelper.ExecuteScalar(DBHelper.MySqlHelper.defaultConnection, System.Data.CommandType.Text, existsSubSql, null);
                                if (existsSubObj != null && Convert.ToInt32(existsSubObj) > 0)
                                {
                                    userId = Convert.ToInt32(existsSubObj);
                                }
                            }
                            catch (Exception ex)
                            {
                            }
                            if (userId == 0)
                            {
                                try
                                {
                                    string existsSubSql = string.Format("SELECT Id FROM rb_member_user WHERE Name='{0}' ", subItem.user.nickname);
                                    var existsSubObj = DBHelper.MySqlHelper.ExecuteScalar(DBHelper.MySqlHelper.defaultConnection, System.Data.CommandType.Text, existsSubSql, null);
                                    if (existsSubObj != null && Convert.ToInt32(existsSubObj) > 0)
                                    {
                                        userId = Convert.ToInt32(existsSubObj);
                                    }
                                }
                                catch (Exception ex)
                                {
                                }
                            }
                            int WithdrawalWay = subItem.type == "auto" ? 1 : 2;

                            stringBuilder.AppendFormat("INSERT INTO rb_distributor_remit(Id,OrderNum,UserId,WithdrawalWay,AppliedMoney,Fee,RemitMoney,AuditStatus,AuditDate,RemitDate,RejectDate,AuditRemark,RemitRemark,RejectRemark,TenantId,MallBaseId,CreateDate,AccountName,AccountNumber)");
                            stringBuilder.AppendFormat($" VALUES('{subItem.id}','{subItem.order_no}','{userId}','{WithdrawalWay}','{subItem.cash.actual_price}','{subItem.cash.service_charge}','{subItem.cash.actual_price}','{subItem.status + 1}','{subItem.time.apply_at}','{subItem.time.remittance_at}','{subItem.time.reject_at}','{subItem.content.apply_content}','{subItem.content.remittance_content}','{subItem.content.reject_content}','{1}','{1}','{subItem.time.created_at}','{subItem.extra.mobile}','{subItem.extra.name}');");

                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                        }
                    }
                    var newResult = DBHelper.MySqlHelper.ExecuteNonQuery(DBHelper.MySqlHelper.defaultConnection, System.Data.CommandType.Text, stringBuilder.ToString(), null);
                }
                pageIndex++;
                var ranDomNum = new Random().Next(1, 20);
                Thread.Sleep(1000 * ranDomNum);
            }
        }



        static List<Remit> GetRemits(string cookie, int pageIndex, out int pageCount)
        {

            pageCount = 0;
            List<Remit> list = new List<Remit>();
            string imgApi = "http://wx.weibaoge.cn/web/index.php?r=mall%2Fshare%2Fcash-data&status=-1&page={0}";
            string newImaApi = string.Format(imgApi, pageIndex);
            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<Remit>>(dataObj["list"].ToString());

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

        #endregion












        /// <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;
        }








    }
}
