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

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="cookie"></param>
        public static void GetGoodsData()
        {
            string cookie = "";
            int pageIndex = 1;
            int pageCount = 7;
            while (pageIndex <= pageCount)
            {
                string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                var tempImgList = GetGoodsList(cookie, pageIndex, out pageCount);
                Console.WriteLine(pageIndex + "/" + pageCount + " Edd");
                if (tempImgList != null && tempImgList.Any())
                {
                    foreach (var subItem in tempImgList)
                    {
                        //查询商品详情
                        var GModel = GetGoodsModel(subItem.id);
                        try
                        {
                            if (!string.IsNullOrEmpty(GModel.name))
                            {

                                #region 创建商品信息
                                string CarouselImage = JsonConvert.SerializeObject(GModel.pic_url.Select(x => x.pic_url));
                                int status = 1;
                                if (GModel.status == 0) {
                                    status = 2;
                                }
                                string DefaultSpecificationName = "";
                                string goods_no = "";
                                int goods_weight = 0;
                                if (GModel.use_attr == 0) {
                                    DefaultSpecificationName = GModel.attr_groups.FirstOrDefault()?.attr_list?.FirstOrDefault()?.attr_name ?? "";
                                    goods_no = GModel.goods_no;
                                    goods_weight = GModel.goods_weight;
                                }

                                string Name = GModel.name;
                                if (Name.Contains("'"))
                                {
                                    Name = Name.Replace("'", "");
                                }

                                string sqlOrder = $@"
        insert into rb_goods_1 ( Id,Name,CarouselImage,VideoAddress,CustomShareTitles,CustomShareImage,GoodsStatus,InventoryNum,DefaultSpecificationName,IsCustomSpecification,
Sort,SellingPrice,OriginalPrice,Unit,CostPrice,IsGoodsNegotiable,SalesNum,GoodsNumbers,GoodsWeight,IsDefaultService,GoodsService,FreightId,FormsId,LimitBuyGoodsNum,LimitBuyOrderNum,
FullNumPinkage,FullMoneyPinkage,IsAreaBuy,IntegralPresent,IntegralPresentType,PointsDeduction,PointsDeductionType,IsMultipleDeduction,GoodsDetails,Status,TenantId,MallBaseId,CreateDate,UpdateDate,
SeparateDistribution,SeparateDistributionType,SeparateDistributionMoneyType,EnjoyMember,SeparateSetMember,IsQuickBuy,IsSellWell,GoodsType,SupplierId,IsProxy,ProxyType,ProxyRises,ProxyMoney,IsProcurement)
                VALUES ({subItem.id},'{Name}','{CarouselImage}','{GModel.video_url}','{GModel.app_share_title}','{GModel.app_share_pic}',{status},{GModel.goods_stock},'{DefaultSpecificationName}',{(GModel.use_attr==0?2:1)},
{GModel.sort},{GModel.price},{GModel.original_price},'{GModel.unit}',{GModel.cost_price},2,{GModel.virtual_sales},'{goods_no}',{goods_weight},1,'[]',{GModel.freight_id},0,{GModel.confine_count},{GModel.confine_order_count},
{GModel.pieces},{GModel.forehead},{(GModel.is_area_limit==1?1:2)},0,1,0,1,2,'{GModel.detail}',0,1,1,'{GModel.created_at}','{GModel.updated_at}',
{(GModel.individual_share==1?1:2)},{(GModel.attr_setting_type==0?1:2)},{(GModel.share_type==1?1:2)},2,2,{(GModel.is_quick_shop==1?1:2)},2,1,0,2,1,0,0,2);
        ";
                                var sqlOrderResult = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, sqlOrder, null);
                                #endregion

                                if (sqlOrderResult > 0)
                                {
                                    #region 创建商品规格
                                    if (GModel.use_attr == 1) {

                                        foreach (var item in GModel.attr_groups) {
                                            int EnabledImage = 2;
                                            if (item.attr_list.Where(x => x.pic_url != "").Any()) {
                                                EnabledImage = 1;
                                            }
                                            string sqlGroups =$@"
insert into rb_goods_specification_1 (GoodsId,Name,Sort,EnabledImage,Status,TenantId,MallBaseId,CreateDate)
values ({subItem.id},'{item.attr_group_name}',{item.attr_group_id},{EnabledImage},0,1,1,'{dt}');
";
                                            var sqlGroupsResult = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, sqlGroups, null);
                                            if (sqlGroupsResult > 0)
                                            {
                                                //查询规格id
                                                string selectSp = $@" select * from rb_goods_specification_1 order by Id desc limit 1;";
                                                DataSet ds = MySqlHelper.ExecuteDataset(MySqlHelper.defaultConnection, System.Data.CommandType.Text, selectSp, null);
                                                int Sid = Convert.ToInt32(ds.Tables[0].Rows[0]["Id"]);
                                                foreach (var qitem in item.attr_list)
                                                {
                                                    string sqlValue = $@"
insert into rb_goods_specificationvalue_1 (GoodsId,SpecificationId,Name,Image,Sort,Status,TenantId,MallBaseId,CreateDate)
values ({subItem.id},{Sid},'{qitem.attr_name}','{qitem.pic_url}',{qitem.attr_id},0,1,1,'{dt}');
";
                                                    var sqlValueResult = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, sqlValue, null);
                                                }
                                            }
                                        }

                                        foreach (var item in GModel.attr) {
                                            string sqlPrice = $@"
insert into rb_goods_specificationprice_1 (GoodsId,SpecificationSort,SellingPrice,InventoryNum,GoodsWeight,GoodsNumbers,Status,TenantId,MallBaseId,CreateDate,UpdateDate)
values ({subItem.id},'{item.sign_id}',{item.price},{item.stock},{item.weight},'{item.no}',0,1,1,'{dt}','{dt}');
";
                                            var sqlPriceResult = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, sqlPrice, null);
                                        }
                                    }
                                    if (GModel.individual_share == 1) {
                                        if (GModel.attr_setting_type == 1)
                                        {
                                            foreach (var item in GModel.attr)
                                            {
                                                foreach (var qitem in item.shareLevelList) {
                                                    if (qitem.level <= 1)
                                                    {
                                                        string sqlCommission = $@"
insert into rb_goods_distributioncommission_1 (GoodsId,SpecificationSort,DistributorGrade,OneCommission,TwoCommission,ThreeCommission,Status,TenantId,MallBaseId,CreateDate,UpdateDate)
values ({subItem.id},'{item.sign_id}',{(qitem.level == 0 ? 0 : 74)},{qitem.share_commission_first},{qitem.share_commission_second},{qitem.share_commission_third},0,1,1,'{dt}','{dt}');
";
                                                        var sqlCommissionResult = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, sqlCommission, null);
                                                    }
                                                }
                                            }
                                        }
                                        else {
                                            foreach (var item in GModel.shareLevelList) {
                                                if (item.level <= 1)
                                                {
                                                    string sqlCommission = $@"
insert into rb_goods_distributioncommission_1 (GoodsId,SpecificationSort,DistributorGrade,OneCommission,TwoCommission,ThreeCommission,Status,TenantId,MallBaseId,CreateDate,UpdateDate)
values ({subItem.id},'',{(item.level == 0 ? 0 : 74)},{item.share_commission_first},{item.share_commission_second},{item.share_commission_third},0,1,1,'{dt}','{dt}');
";
                                                    var sqlCommissionResult = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, sqlCommission, null);
                                                }
                                            }
                                        }
                                    }
                                    #endregion

                                    if (GModel.is_area_limit == 1) {
                                        foreach (var item in GModel.area_limit) {
                                            foreach (var qitem in item.list) {
                                                string sqlArea = $@"
insert into rb_goods_area_1 (GoodsId,AreaId,AreaType,Status,TenantId,MallBaseId,CreateDate)
values ({subItem.id},{qitem.id},0,0,1,1,'{dt}');
";
                                                var sqlAreaResult = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, sqlArea, null);
                                            }
                                        }
                                    }

                                    if (GModel.cats.Any()) {
                                        foreach (var item in GModel.cats) {
                                            string sqlCategory = $@"
insert into rb_goods_category_1 (GoodsId,CategoryId,Status,TenantId,MallBaseId,CreateDate)
values ({subItem.id},{item.value},0,1,1,'{dt}');
";
                                            var sqlCategoryResult = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, sqlCategory, null);
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("失败:" + subItem.id + " Msg:" + ex.Message);
                        }
                    }
                }
                pageIndex++;
                var ranDomNum = new Random().Next(2, 5);
                Thread.Sleep(1000 * ranDomNum);
            }
        }

        /// <summary>
        /// 获取商品详情
        /// </summary>
        /// <returns></returns>
        static GoodsDetail GetGoodsModel(int GoodsId)
        {
            string newImaApi = "http://wx.weibaoge.cn/web/index.php?r=mall%2Fgoods%2Fedit&id=" + GoodsId;
            string cookie = "__login_route=%2Fadmin%2Fpassport%2Flogin; __login_role=admin; search={'keyword':'','status':' - 1','sort_prop':'','sort_type':'','cats':[],'date_start':null,'date_end':null,'type':''}; HJ_SESSION_ID=dbt76ms3goebfvqvouuif422b7; _csrf=70ddcc0e844a90aa2a29abd8a3316b48ec0f793fd604ed5d0c85f81962f7f824a%3A2%3A%7Bi%3A0%3Bs%3A5%3A%22_csrf%22%3Bi%3A1%3Bs%3A32%3A%228h-0Fxng5HbHJyaQW_SQDbV4NNFs7ku_%22%3B%7D";
            string jsonData = HttpGet(newImaApi, cookie);
            GoodsDetail list = new GoodsDetail();
            if (jsonData != null && !string.IsNullOrEmpty(jsonData))
            {
                JObject obj = JObject.Parse(jsonData);
                JObject dataObj = JObject.Parse(obj["data"].ToString());
                list = Newtonsoft.Json.JsonConvert.DeserializeObject<GoodsDetail>(dataObj["detail"].ToString());
            }
            return list;
        }

        static List<Goods> GetGoodsList(string cookie, int pageIndex, out int pageCount)
        {
            pageCount = 2;
            List<Goods> list = new List<Goods>();
            string newImaApi = "http://wx.weibaoge.cn/web/index.php?r=mall%2Fgoods%2Findex&page="+ pageIndex + "&search=%7B%22keyword%22:%22%22,%22status%22:%22-1%22,%22sort_prop%22:%22%22,%22sort_type%22:%22%22,%22cats%22:[],%22date_start%22:null,%22date_end%22:null,%22type%22:%22%22%7D";
            cookie = "__login_route=%2Fadmin%2Fpassport%2Flogin; __login_role=admin; search={'keyword':'','status':' - 1','sort_prop':'','sort_type':'','cats':[],'date_start':null,'date_end':null,'type':''}; HJ_SESSION_ID=dbt76ms3goebfvqvouuif422b7; _csrf=70ddcc0e844a90aa2a29abd8a3316b48ec0f793fd604ed5d0c85f81962f7f824a%3A2%3A%7Bi%3A0%3Bs%3A5%3A%22_csrf%22%3Bi%3A1%3Bs%3A32%3A%228h-0Fxng5HbHJyaQW_SQDbV4NNFs7ku_%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<Goods>>(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;
                    }
                }
            }
        }

    }
}
