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 OrderHelper
    {

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="cookie"></param>
        public static void GetOrderData()
        {
            string cookie = "";
            int pageIndex = 1;
            int pageCount = 7;
            var ExpressList = GetExpressList("", 1, out pageCount);
            //    if (ExpressList.Any()) {
            //        foreach (var item in ExpressList)
            //        {
            //            string sqlOrder = $@"
            //insert into rb_logistics_express_copy ( ID,Name,ExpressCode,TenantId,MallBaseId,Status )
            //                    VALUES ( {item.id},'{item.name}','{item.code}',1,1,0);
            //";
            //            var sqlOrderResult = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, sqlOrder, null);
            //        }
            //    }
            pageCount = 20;
            while (pageIndex <= pageCount)
            {
                string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                var tempImgList = GetOrderList(cookie, pageIndex, out pageCount);
                Console.WriteLine(pageIndex + "/" + pageCount + " Edd");
                if (tempImgList != null && tempImgList.Any())
                {
                    List<string> CityList = new List<string>();
                    foreach (var subItem in tempImgList) {
                        #region 处理地区
                        if (!string.IsNullOrEmpty(subItem.address))
                        {
                            string[] arr = subItem.address.Split(' ');
                            if (arr.Length >= 4)
                            {
                                CityList.Add("'" + arr[0] + "'");
                                CityList.Add("'" + arr[1] + "'");
                                CityList.Add("'" + arr[2] + "'");
                                subItem.PName = arr[0];
                                subItem.CName = arr[1];
                                subItem.DName = arr[2];

                                subItem.address = "";
                                for (int i = 3; i < arr.Length; i++)
                                {
                                    subItem.address += arr[i] + " ";
                                }
                            }
                        }
                        #endregion
                    }
                    DataSet cityDataList = new DataSet();
                    if (CityList.Any()) {
                        string CityStr = string.Join(",", CityList);
                        string citySql = $@"SELECT * FROM RB_Destination WHERE 1=1 and Status =0 AND Name in({CityStr}) ";
                        cityDataList = MySqlHelper.ExecuteDataset(MySqlHelper.defaultConnection, System.Data.CommandType.Text, citySql, null);
                        //DataRow[] arow = ds.Tables[table_name].Select("Name='" + data_value + "'");
                    }
                    foreach (var subItem in tempImgList)
                    {
                        try
                        {                        
                            if (subItem.id > 0)
                            {

                                #region 创建订单信息

                                //订单状态
                                int OrderStatus = 1;
                                if (subItem.is_confirm == 1)
                                {
                                    OrderStatus = 5;
                                }
                                else if (subItem.is_send == 1)
                                {
                                    OrderStatus = 3;
                                }
                                else if (subItem.is_pay == 1) {
                                    OrderStatus = 2;
                                }

                                #region 获取省市区
                                int pid = 0, cid = 0, did = 0;
                                if (!string.IsNullOrEmpty(subItem.PName))
                                {
                                    DataRow[] dr1 = cityDataList.Tables[0].Select("Name='" + subItem.PName + "'");
                                    if (dr1.Any()) {
                                        pid = Convert.ToInt32(dr1[0]["ID"].ToString());
                                    }
                                }
                                if (!string.IsNullOrEmpty(subItem.CName))
                                {
                                    DataRow[] dr2 = cityDataList.Tables[0].Select("Name='" + subItem.CName + "'");
                                    if (dr2.Any())
                                    {
                                        cid = Convert.ToInt32(dr2[0]["ID"].ToString());
                                    }
                                }
                                if (!string.IsNullOrEmpty(subItem.DName))
                                {
                                    DataRow[] dr3 = cityDataList.Tables[0].Select("Name='" + subItem.DName + "'");
                                    if (dr3.Any())
                                    {
                                        did = Convert.ToInt32(dr3[0]["ID"].ToString());
                                    }
                                }

                                #endregion

                                string sqlOrder = $@"
        insert into rb_goods_order_drcs ( OrderId, OrderNo,MerchantsNo, UserId,OrderSource,PaymentWay,PreferPrice,Income,FreightMoney,Fee,Refund,CouponMoney,CouponsIds,DeliveryMethod,Consignee,Mobile,Country,Province,City,District,ShoppingAddress,BuyerMessage,Remark,OrderStatus,Recycled,Status,TenantId,MallBaseId,CreateDate,UpdateDate,CostMoney,PaymentTime,DeliveryTime,ReceivingTime,FinishTime,CancelTime,IsApplyForCancel,HistoryOrderStatus,CancelRemark,ApplyForCancelStatus,RejectRemark,ChangePrice,RefundOrderNo)
                            VALUES ( {subItem.id}, '{subItem.order_no}','',{subItem.user_id}, 1,1,{subItem.total_goods_price} ,{subItem.total_pay_price},{subItem.express_price},0,0,0,'',1,'{subItem.name}','{subItem.mobile}',1,{pid},{cid},{did},'{subItem.address}','{subItem.remark}','{subItem.seller_remark}',{OrderStatus},{(subItem.is_recycle == 1 ? 1 : 2)},{subItem.is_delete},1,1,'{subItem.created_at}','{subItem.created_at}',0,'{subItem.pay_time}','{subItem.send_time}','{subItem.confirm_time}','{subItem.confirm_time}','{subItem.cancel_time}',0,0,'',0,'',0,'');
        ";
                                var sqlOrderResult = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, sqlOrder, null);
                                #endregion

                                if (sqlOrderResult > 0)
                                {
                                    #region 创建发货信息
                                    foreach (var item in subItem.detailExpress) {

                                        //匹配快递
                                        var expressId = ExpressList.Where(x => x.name == item.express).FirstOrDefault()?.id ?? 0;

                                        string sqlExpress = $@"
        insert into rb_goods_orderexpress_drcs (Id,Type,ExpressId,PostCode,ExpressNumber,Remark,TenantId,MallBaseId,CreateDate,UpdateDate,AfterSaleOrderId)
                            VALUES ( {item.id},{item.send_type},{expressId},'','{item.express_no}','{item.express_content}',1,1,'{item.created_at}','{item.created_at}',0);
        ";
                                        var sqlsqlExpressResult = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, sqlExpress, null);
                                    }
                                    #endregion

                                    #region 创建订单明细
                                    foreach (var item in subItem.detail) {

                                        //组装规格
                                        List<string> Specification = new List<string>();
                                        if (item.goods_info.attr_list.Any()) {
                                            foreach (var qitem in item.goods_info.attr_list)
                                            {
                                                Specification.Add(qitem.attr_group_name + ":" + qitem.attr_name);
                                            }
                                        }
                                        #region 处理单引号
                                        string Name = item.goods_info.goods_attr.name;
                                        if (Name.Contains("'")) {
                                            Name = Name.Replace("'", "");
                                        }
                                        #endregion

                                        string sqlOrderDetail = $@"
        insert into rb_goods_orderdetail_drcs (Id, OrderId, GoodsId,OrderType,GoodsName,CoverImage,Specification,SpecificationSort,ProductCode,Unit_Price,Number,Original_Price,Final_Price,CostMoney,
DiscountRate,IsMemberPrice,TenantId,MallBaseId,CreateDate,UpdateDate,IsComment,FreightMoney,IntegralNumber,IntegralMoney,CouponMoney,FreightCostMoney,SupplierId,CostFinanceId,IntegralGoodsPresent)
                            VALUES ( {item.id}, {item.order_id},{item.goods_id},1,'{Name}','{item.goods_info.goods_attr.cover_pic}','{JsonConvert.SerializeObject(Specification)}',
'{item.goods_info.goods_attr.sign_id}','{item.goods_no}',{item.unit_price},{item.goods_info.goods_attr.number},{item.total_original_price},{item.total_price},0,0,2,1,1,'{item.created_at}',
'{item.created_at}',1,0,0,0,0,0,0,0,0);
        ";
                                        var sqlOrderDetailResult = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, sqlOrderDetail, null);

                                        //创建发货关联
                                        if (item.expressRelation != null) {
                                            string sqlExpress = $@"
        insert into rb_goods_expressrelevance_drcs (OrderId,OrderDetailId,OrderExpressId,TenantId,MallBaseId,CreateDate,UpdateDate) 
                                values ({item.expressRelation.order_id},{item.expressRelation.order_detail_id},{item.expressRelation.order_detail_express_id},1,1,'{dt}','{dt}')";
                                            var sqlExpressResult = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, sqlExpress, null);
                                        }
                                    }
                                    #endregion

                                    
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("失败OrderId:" + subItem.id + " 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<OrderInfo> GetOrderList(string cookie, int pageIndex, out int pageCount)
        {
            pageCount = 2;
            List<OrderInfo> list = new List<OrderInfo>();
            string newImaApi = "http://wx.weibaoge.cn/web/index.php?r=mall%2Forder%2Findex&keyword=&keyword_1=1&date_start=&date_end=&platform=&status=-1&plugin=all&send_type=-1&type=&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<OrderInfo>>(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>
        /// <param name="pageIndex"></param>
        /// <param name="pageCount"></param>
        /// <returns></returns>
        static List<ExpressInfo> GetExpressList(string cookie, int pageIndex, out int pageCount)
        {
            pageCount = 1;
            List<ExpressInfo> list = new List<ExpressInfo>();
            string newImaApi = "http://wx.weibaoge.cn/web/index.php?r=mall%2Forder%2Findex&keyword=&keyword_1=1&date_start=&date_end=&platform=&status=-1&plugin=all&send_type=-1&type=&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<ExpressInfo>>(dataObj["express_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;
                    }
                }
            }
        }

    }
}
