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


        #region 处理徐总说的二级返佣

        /// <summary>
        /// 返佣
        /// </summary>
        public static void SetOrderTwoCommissionData()
        {
            string citySql = $@"
SELECT o.OrderId,o.OrderNo,od.Id AS DetailId,o.UserId,u.`Name`,o.Income,o.Consignee,o.Mobile,o.ShoppingAddress,od.GoodsName,od.Specification,od.Final_Price,
od.Number,
CASE WHEN d1.Id IS NULL THEN d2.OneCommission * od.Number ELSE d1.OneCommission * od.Number END AS OneCommission,
CASE WHEN d1.Id IS NULL THEN d2.TwoCommission * od.Number ELSE d1.TwoCommission * od.Number END AS TwoCommission
 FROM rb_goods_order o
INNER JOIN rb_goods_orderdetail od on o.OrderId=od.OrderId
INNER JOIN rb_member_user u on o.UserId = u.Id
LEFT JOIN rb_goods_distributioncommission d1 on d1.GoodsId=od.GoodsId AND d1.DistributorGrade=74 and d1.SpecificationSort=od.SpecificationSort
LEFT JOIN rb_goods_distributioncommission d2 on d2.GoodsId=od.GoodsId AND d2.DistributorGrade=74 and d2.SpecificationSort=''
WHERE o.OrderId in(
SELECT t.OrderId FROM(
SELECT cm.OrderId,cm.UserId FROM rb_goods_ordercommission cm WHERE CommissionState = 2 AND TenantId =1 AND MallBaseId =1
GROUP BY cm.OrderId,cm.UserId
)t GROUP BY t.OrderId HAVING COUNT(0)=1)
AND o.OrderId >=34137 and o.OrderId <=80622 and o.OrderId <> 63803 AND o.OrderId <> 63839
AND o.UserId in(
	SELECT Id FROM rb_member_user WHERE SuperiorId BETWEEN 1 and 20
) AND o.UserId <> 39370
ORDER BY o.OrderId ASC ";

            string commSql2 = $@"SELECT o.OrderId,o.OrderNo,od.Id AS DetailId,o.UserId,u.`Name`,o.Income,o.Consignee,o.Mobile,o.ShoppingAddress,od.GoodsName,od.Specification,od.Final_Price,
od.Number,
CASE WHEN d1.Id IS NULL THEN d2.OneCommission * od.Number ELSE d1.OneCommission * od.Number END AS OneCommission,
CASE WHEN d1.Id IS NULL THEN d2.TwoCommission * od.Number ELSE d1.TwoCommission * od.Number END AS TwoCommission
 FROM rb_goods_order o
INNER JOIN rb_goods_orderdetail od on o.OrderId=od.OrderId
INNER JOIN rb_member_user u on o.UserId = u.Id
LEFT JOIN rb_goods_distributioncommission d1 on d1.GoodsId=od.GoodsId AND d1.DistributorGrade=74 and d1.SpecificationSort=od.SpecificationSort
LEFT JOIN rb_goods_distributioncommission d2 on d2.GoodsId=od.GoodsId AND d2.DistributorGrade=74 and d2.SpecificationSort=''
WHERE o.OrderId in(
SELECT t.OrderId FROM(
SELECT cm.OrderId,cm.UserId FROM rb_goods_ordercommission cm WHERE CommissionState = 2 AND TenantId =1 AND MallBaseId =1
AND cm.OrderId in(SELECT cm1.OrderId FROM rb_goods_ordercommission cm1 WHERE cm1.UserId in(SELECT Id FROM rb_member_user WHERE Id <> 39370 AND SuperiorId BETWEEN 1 and 20))
GROUP BY cm.OrderId,cm.UserId
)t GROUP BY t.OrderId HAVING COUNT(0)=1)
AND o.OrderId >=34137 and o.OrderId <=80622 and o.OrderId <> 63803 AND o.OrderId <> 63839
AND o.UserId in(
	SELECT mu2.Id FROM rb_member_user mu1
INNER JOIN rb_member_user mu2 on mu1.Id = mu2.SuperiorId
 WHERE mu1.Id <> 39370 AND mu1.SuperiorId BETWEEN 1 and 20
)
ORDER BY o.OrderId ASC;";

            string sql3 = $@"SELECT o.OrderId,o.OrderNo,od.Id AS DetailId,o.UserId,u.`Name`,o.Income,o.Consignee,o.Mobile,o.ShoppingAddress,od.GoodsName,od.Specification,od.Final_Price,
od.Number,
CASE WHEN d1.Id IS NULL THEN d2.OneCommission * od.Number ELSE d1.OneCommission * od.Number END AS OneCommission,
CASE WHEN d1.Id IS NULL THEN d2.TwoCommission * od.Number ELSE d1.TwoCommission * od.Number END AS TwoCommission,
u21.Id AS FUserId,
u21.`Name` AS FName
 FROM rb_goods_order o
INNER JOIN rb_goods_orderdetail od on o.OrderId=od.OrderId
INNER JOIN rb_member_user u on o.UserId = u.Id
INNER JOIN rb_member_user u21 on u.SuperiorId = u21.Id
LEFT JOIN rb_goods_distributioncommission d1 on d1.GoodsId=od.GoodsId AND d1.DistributorGrade=74 and d1.SpecificationSort=od.SpecificationSort
LEFT JOIN rb_goods_distributioncommission d2 on d2.GoodsId=od.GoodsId AND d2.DistributorGrade=74 and d2.SpecificationSort=''
WHERE o.OrderId in(
SELECT t.OrderId FROM(
SELECT cm.OrderId,cm.UserId FROM rb_goods_ordercommission cm WHERE CommissionState = 2 AND TenantId =1 AND MallBaseId =1
AND cm.OrderId in(SELECT cm1.OrderId FROM rb_goods_ordercommission cm1 WHERE cm1.UserId in(SELECT Id FROM rb_member_user WHERE Id <> 39370 AND SuperiorId BETWEEN 1 and 20))
GROUP BY cm.OrderId,cm.UserId
)t GROUP BY t.OrderId HAVING COUNT(0)=1)
AND o.OrderId >=34137 and o.OrderId <=80622 and o.OrderId <> 63803 AND o.OrderId <> 63839
AND o.UserId in(
	SELECT mu2.Id FROM rb_member_user mu1
INNER JOIN rb_member_user mu2 on mu1.Id = mu2.SuperiorId
 WHERE mu1.Id <> 39370 AND mu1.SuperiorId BETWEEN 1 and 20
)
ORDER BY o.OrderId ASC;";
            DataSet OrderCommList = MySqlHelper.ExecuteDataset(MySqlHelper.defaultConnection, System.Data.CommandType.Text, citySql, null);
            DataSet OrderComm2List = MySqlHelper.ExecuteDataset(MySqlHelper.defaultConnection, System.Data.CommandType.Text, sql3, null);
            string Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            foreach (DataRow item in OrderCommList.Tables[0].Rows)
            {
                int OrderId = Convert.ToInt32(item["OrderId"].ToString());
                int DetailId = Convert.ToInt32(item["DetailId"].ToString());
                int UserId = Convert.ToInt32(item["UserId"].ToString());
                decimal TwoCommission = Convert.ToDecimal(item["TwoCommission"].ToString());
                if (TwoCommission > 0)
                {
                    //插入返佣
                    string InertComm = $@"
insert into rb_goods_ordercommission (OrderId,OrderDetailId,UserId,Grade,Commission,IsGoodsDistribution,CommissionState,Remark,TenantId,MallBaseId,CreateDate,UpdateDate,Type,IsRemit)
values ({OrderId},{DetailId},{UserId},2,{TwoCommission},2,2,'自购补充二级返佣',1,1,'{Time}','{Time}',1,2);
";
                    var InertCommResult = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, InertComm, null);
                    if (InertCommResult > 0)
                    {
                        string UserComm = $@"update rb_distributor_info set TotalCommission=TotalCommission+{TwoCommission},CommissionWithdrawal=CommissionWithdrawal+{TwoCommission}";
                        var UserCommResult = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, UserComm, null);
                        if (UserCommResult <= 0)
                        {
                            Console.WriteLine("更新用户返佣失败  OrderId:" + OrderId + ",DetailId:" + DetailId + ",UserId:" + UserId + "   TwoCommission:" + TwoCommission);
                        }
                    }
                    else
                    {
                        Console.WriteLine("返佣插入失败  OrderId:" + OrderId + ",DetailId:" + DetailId + ",UserId:" + UserId + "   TwoCommission:" + TwoCommission);
                    }
                }
                else
                {
                    Console.WriteLine("OrderId:" + OrderId + ",DetailId:" + DetailId + ",UserId:" + UserId + "   TwoCommission:" + TwoCommission);
                }
            }

            foreach (DataRow item in OrderComm2List.Tables[0].Rows)
            {
                int OrderId = Convert.ToInt32(item["OrderId"].ToString());
                int DetailId = Convert.ToInt32(item["DetailId"].ToString());
                int UserId = Convert.ToInt32(item["FUserId"].ToString());
                decimal TwoCommission = Convert.ToDecimal(item["TwoCommission"].ToString());
                if (TwoCommission > 0)
                {
                    //插入返佣
                    string InertComm = $@"
insert into rb_goods_ordercommission (OrderId,OrderDetailId,UserId,Grade,Commission,IsGoodsDistribution,CommissionState,Remark,TenantId,MallBaseId,CreateDate,UpdateDate,Type,IsRemit)
values ({OrderId},{DetailId},{UserId},2,{TwoCommission},2,2,'下级购买补充二级返佣',1,1,'{Time}','{Time}',1,2);
";
                    var InertCommResult = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, InertComm, null);
                    if (InertCommResult > 0)
                    {
                        string UserComm = $@"update rb_distributor_info set TotalCommission=TotalCommission+{TwoCommission},CommissionWithdrawal=CommissionWithdrawal+{TwoCommission}";
                        var UserCommResult = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, UserComm, null);
                        if (UserCommResult <= 0)
                        {
                            Console.WriteLine("更新用户返佣失败  OrderId:" + OrderId + ",DetailId:" + DetailId + ",UserId:" + UserId + "   TwoCommission:" + TwoCommission);
                        }
                    }
                    else
                    {
                        Console.WriteLine("返佣插入失败  OrderId:" + OrderId + ",DetailId:" + DetailId + ",UserId:" + UserId + "   TwoCommission:" + TwoCommission);
                    }
                }
                else
                {
                    Console.WriteLine("OrderId:" + OrderId + ",DetailId:" + DetailId + ",UserId:" + UserId + "   TwoCommission:" + TwoCommission);
                }
            }
        }

        #endregion

    }
}
