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;
using System.Data;
using Newtonsoft.Json;

namespace Test.Helper
{
    /// <summary>
    /// 订单返佣帮助类
    /// </summary>
    public class OrderCommissionHelper
    {

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="cookie"></param>
        public static void GetOrderCommissionData()
        {
            string cookie = "";
            int pageIndex = 1;
            int pageCount = 7;              
            while (pageIndex <= pageCount)
            {
                string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                var tempImgList = GetOrderCommissionList(cookie, pageIndex, out pageCount);
                Console.WriteLine(pageIndex + "/" + pageCount + " Edd");
                if (tempImgList != null && tempImgList.Any())
                {
                    foreach (var subItem in tempImgList)
                    {
                        try
                        {                        
                            if (subItem.id > 0)
                            {
                                //根据订单号  或者订单id
                                int OrderId = 0;
                                int OrderDetailId = 0;
                                if (subItem.detail.Any()) {
                                    OrderDetailId = subItem.detail?.FirstOrDefault()?.order_detail_id ?? 0;
                                }
                                bool IsSelfBuying = false;
                                if (subItem.user_id == subItem.first_parent_id) {
                                    IsSelfBuying = true;
                                }

                                if (subItem.first_parent_id > 0)
                                {
                                    string sqlOrder = $@"
        insert into rb_goods_ordercommission_drcs ( OrderId, OrderDetailId,UserId,Grade,Commission,IsGoodsDistribution,CommissionState,Type,Remark,TenantId,MallBaseId,CreateDate,UpdateDate)
                            VALUES ({OrderId},{OrderDetailId},{subItem.first_parent_id},{(IsSelfBuying?0:1)},{subItem.first_price},2,{(subItem.is_confirm==1?2:1)},1,'赞羊返佣导入',1,1,'{dt}','{dt}');
        ";
                                    var sqlOrderResult = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, sqlOrder, null);
                                }
                                if (subItem.second_parent_id > 0)
                                {
                                    string sqlOrder = $@"
        insert into rb_goods_ordercommission_drcs ( OrderId, OrderDetailId,UserId,Grade,Commission,IsGoodsDistribution,CommissionState,Type,Remark,TenantId,MallBaseId,CreateDate,UpdateDate)
                            VALUES ({OrderId},{OrderDetailId},{subItem.second_parent_id},{(IsSelfBuying ? 1 : 2)},{subItem.second_price},2,{(subItem.is_confirm == 1 ? 2 : 1)},1,'赞羊返佣导入',1,1,'{dt}','{dt}');
        ";
                                    var sqlOrderResult = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, sqlOrder, null);
                                }
                                if (subItem.third_parent_id > 0)
                                {
                                    string sqlOrder = $@"
        insert into rb_goods_ordercommission_drcs ( OrderId, OrderDetailId,UserId,Grade,Commission,IsGoodsDistribution,CommissionState,Type,Remark,TenantId,MallBaseId,CreateDate,UpdateDate)
                            VALUES ({OrderId},{OrderDetailId},{subItem.third_parent_id},{(IsSelfBuying ? 2 : 3)},{subItem.third_price},2,{(subItem.is_confirm == 1 ? 2 : 1)},1,'赞羊返佣导入',1,1,'{dt}','{dt}');
        ";
                                    var sqlOrderResult = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, sqlOrder, null);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("失败OrderNO:" + subItem.order_no + " Msg:" + ex.Message);
                        }
                    }
                }
                pageIndex++;
                var ranDomNum = new Random().Next(2, 5);
                Thread.Sleep(1000 * ranDomNum);
            }
        }

        /// <summary>
        /// 获取订单列表
        /// </summary>
        /// <param name="cookie"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageCount"></param>
        /// <returns></returns>
        static List<OrderCommissionInfo> GetOrderCommissionList(string cookie, int pageIndex, out int pageCount)
        {
            pageCount = 2;
            List<OrderCommissionInfo> list = new List<OrderCommissionInfo>();
            string newImaApi = "http://wx.weibaoge.cn/web/index.php?r=mall%2Fshare%2Forder&keyword=&keyword_1=order_no&date_start=&date_end=&platform=&status=all&plugin=all&send_type=-1&parent_id=0&page=" + pageIndex;
            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<OrderCommissionInfo>>(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;
                    }
                }
            }
        }

    }
}
