zhaojs
2023-09-27 74098f1401afe40f961d1d167bb18dd0a71c4d59
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using AlibabaSDK.Api;
using AlibabaSDK.Domain;
using AlibabaSDK.Request;
using BaiDuSdk;
using CommonUtil;
using CommonUtil.RabbitMQ;
using HtmlAgilityPack;
using Operater.DAL;
using Operater.DbModel;
using Operater.DTO.System;
using YouZanSDKStandard.Api;
using YouZanSDKStandard.Api.Domain;
using YouZanSDKStandard.Api.Request;
using YouZanSDKStandard.Api.Response;
 
namespace Operater.Service.System
{
    public class ItemDistributionService : IItemDistributionService
    {
 
        /// <summary>
        /// 精选货源铺货
        /// </summary>
        /// <param name="sourcePid"></param>
        public async Task<bool> RunDistribution(DistributionHistory taskInfo, string aliToken, string yzToken, List<ProductFilter> filter)
        {
            DistributionHistory finalHis = new DistributionHistory();
            try
            {
                //任务状态改成执行中
                DistributionHistory distributionHistory = new DistributionHistory()
                {
                    DisStatus = 1,
                    RunTime = DateTime.Now
                };
                new DistributionHistoryDAL().Update(distributionHistory, t => new { t.DisStatus, t.RunTime }, t => t.Id == taskInfo.Id);
                //获取1688商品详情
                List<string> ls = new List<string>();
                ls.Add(taskInfo.ProductId);
                PFTProductDetailRequest request = new PFTProductDetailRequest()
                {
                    offerIds = ls
                };
                var response = AliabaClient.Execute(request, aliToken);
                if (response.IsNull() || !response.result.success || response.result.result.Count == 0)
                {//获取商品详情失败
                    LogUtil.Info($"获取商品详情失败:{taskInfo.Id}", "铺货错误");
                    finalHis.DisStatus = 3;
                    finalHis.Memo = "获取商品详情失败:" + (response.IsNull() ? "null" : response.ErrorMsg);
                    new DistributionHistoryDAL().Update(finalHis, t => new { t.DisStatus, t.Memo }, t => t.Id == taskInfo.Id);
                    return false;
                }
                //判断1688商品状态
                if (response.result.result[0].productInfo.status != "published")
                {//不可铺货
                    LogUtil.Info($"商品状态不对:{response.result.result[0].productInfo.status}", "铺货错误");
                    finalHis.DisStatus = 3;
                    finalHis.Memo = "商品状态不对:" + (response.result.result[0].productInfo.status);
                    new DistributionHistoryDAL().Update(finalHis, t => new { t.DisStatus, t.Memo }, t => t.Id == taskInfo.Id);
                    return false;
                }
                if (!response.result.result[0].productInfo.saleInfo.supportOnlineTrade)
                {
                    LogUtil.Info($"不支持网上交易:{response.result.result[0].productInfo.saleInfo.supportOnlineTrade}", "铺货错误");
                    finalHis.DisStatus = 3;
                    finalHis.Memo = "商品不支持网上交易";
                    new DistributionHistoryDAL().Update(finalHis, t => new { t.DisStatus, t.Memo }, t => t.Id == taskInfo.Id);
                    return false;
                }
                StringBuilder imgError = new StringBuilder();
                //商品图片
                finalHis.ProImg = "https://cbu01.alicdn.com/img/" + response.result.result[0].productInfo.image.images[0];
                //string imgMsg = FilterImg(filter, finalHis.ProImg);
                //if (!imgMsg.IsNullOrEmpty())
                //{
                //    imgError.Append($"主图:[{imgMsg}]");
                //}
                //商品title
                finalHis.ProTitle = response.result.result[0].productInfo.subject;
 
                //根据规则调整字段
                var aliPro = response.result.result[0].productInfo;
                //是否包邮 精选货源默认包邮
                finalHis.IsFreeShipping = 1;
                //调用有赞新增商品接口 youzan.item.add.1.0.1
                YouZanItemAddRequest yzReq = new YouZanItemAddRequest();
                yzReq.param = GetAliInfoToYz(aliPro, yzToken, filter, ref imgError);
                var yzRsp = YouZanClient.Execute(yzReq, yzToken);
                if (yzRsp.IsNull() || !yzRsp.success)
                {//新增失败
                    finalHis.DisStatus = 3;
                    finalHis.Memo = yzRsp.IsNull() ? "有赞接口错误" : yzRsp.message;
                    LogUtil.Info($"有赞错误:{finalHis.Memo}--request:" + JSONUtil.ObjectToJson(yzReq), "铺货错误");
                }
                else
                {
                    //有赞返回商品id
                    string yzProductId = yzRsp.data.item_id;
                    //修改任务状态
                    finalHis.DisStatus = 2;
                    finalHis.YzItemId = yzProductId;
                    finalHis.YzAlias = yzRsp.data.alias;
                    string yzskuInfo = UpdateYzSku(yzProductId, yzToken);
                    if (!imgError.IsNull() && imgError.Length > 0)
                    {
                        finalHis.Memo = imgError.ToString();
                    }
                    yzskuInfo = yzskuInfo.IsNullOrEmpty() ? JSONUtil.ObjectToJson(yzReq.param.sku_list) : yzskuInfo;
                    //记录1688id与有赞id的关系
                    DistributionRelation distributionRelation = new DistributionRelation()
                    {
                        Id = TopUtil.GetId().ToString(),
                        SourceProduct = taskInfo.ProductId,
                        YzProduct = yzProductId,
                        YzAlias = yzRsp.data.alias,
                        ReStatus = 1,
                        InstanceCode = response.result.result[0].instanceCode,
                        CreateTime = DateTime.Now,
                        AliskuInfo = JSONUtil.ObjectToJson(response.result.result[0].productInfo.skuInfos),
                        YzskuInfo = yzskuInfo,
                        ProSource = 0
                    };
                    new DistributionRelationDAL().Insert(distributionRelation);
                    //关注商品
                    AlibabaProductFollowRequest followReq = new AlibabaProductFollowRequest()
                    {
                        productId = long.Parse(taskInfo.ProductId)
                    };
                    var followRsp = AliabaClient.Execute(followReq, aliToken);
                    if (followRsp.IsNull() || followRsp.message != "success")
                    {
                        LogUtil.Info($"关注商品{taskInfo.ProductId}失败,错误:" + (followRsp.IsNull() ? "null" : followRsp.message), "铺货错误");
                    }
                }
            }
            catch (Exception e)
            {
                finalHis.DisStatus = 3;
                finalHis.Memo = e.Message;
                LogUtil.Info($"错误:{e.ToString()}", "铺货错误");
                new DistributionHistoryDAL().Update(finalHis, t => new { t.DisStatus, t.Memo }, t => t.Id == taskInfo.Id);
                return false;
            }
            new DistributionHistoryDAL().Update(finalHis, t => new { t.DisStatus, t.Memo, t.ProImg, t.ProTitle, t.YzAlias, t.YzItemId, t.IsFreeShipping }, t => t.Id == taskInfo.Id);
            return true;
        }
 
        /// <summary>
        /// 精品货源商品属性赋值给有赞
        /// </summary>
        /// <param name="aliPro"></param>
        /// <returns></returns>
        public static YouZanItemAddDomain GetAliInfoToYz(PFTProductDetailDomainProInfo aliPro, string yzToken, List<ProductFilter> filter, ref StringBuilder imgError)
        {
 
            YouZanItemAddDomain yzPara = new YouZanItemAddDomain();
            yzPara.item_no = aliPro.productID.ToString();
            string desc = FilterMsg(filter, aliPro.description);
           // desc = FilterDesc(filter, desc);
            yzPara.desc = desc;
 
            //yzPara.start_sale_num = aliPro.saleInfo.minOrderQuantity;
            yzPara.start_sale_num = 1;
            DeliverySetting deliverySetting = new DeliverySetting()
            {
                express = true
            };
            //售后信息
            PostSaleParam postSaleParam = new PostSaleParam()
            { is_support_barter = 0 };
            postSaleParam.support_unconditional_return = aliPro.sevenDaysRefunds;
            yzPara.post_sale_param = postSaleParam;
            //获取默认运费模板
            var appset = new AppsetDAL().ListGet(t => t.Id != null);
            ItemDeliveryParam itemDeliveryParam = new ItemDeliveryParam
            {
                delivery_setting = deliverySetting,
                delivery_template_id = long.Parse(appset[0].YzPostMould)
            };
            yzPara.item_delivery_param = itemDeliveryParam;
            switch (aliPro.saleInfo.invReduceType)
            {
                case "1"://下单减库存
                    yzPara.stock_deduct_mode = 0;
                    break;
                case "2"://付款减库存
                    yzPara.stock_deduct_mode = 1;
                    break;
            }
            yzPara.title = FilterMsg(filter, aliPro.subject);
            yzPara.is_display = 0;
            //商品库存, 无sku情况下库存必填,如果有sku则无效
            yzPara.quantity = long.Parse(aliPro.saleInfo.amountOnSale.ToString());
            List<SkuList> skuLists = new List<SkuList>();
            List<SkuValueProps> skuValues = new List<SkuValueProps>();
            Dictionary<string, long> imgDic = new Dictionary<string, long>();
            bool isImgShow = false;
            long replaceImgId = 0;
            foreach (var aliSkuItem in aliPro.skuInfos)
            {
                if (aliSkuItem.retailPrice <= 0)
                {
                    continue;
                }
                List<SkuProps> skuPropsList = new List<SkuProps>();
                aliSkuItem.attributes = aliSkuItem.attributes.OrderBy(t => t.skuImageUrl.IsNullOrEmpty()).ToList();
                int index = 0;
                foreach (var attr in aliSkuItem.attributes)
                {//属性信息
                    index++;
                    SkuProps skuProps = new SkuProps()
                    {
                        prop_value_name = attr.attributeValue,
                        prop_name = attr.attributeName,
                        prop_name_id = attr.attValueID,
                        prop_value_id = attr.attributeID
                    };
                    skuPropsList.Add(skuProps);
                    if (index == 1 && !attr.skuImageUrl.IsNullOrEmpty())
                    {
                        isImgShow = true;
                        //处理有赞sku图片信息
                        long imgId = 0;
                        if (imgDic.ContainsKey(attr.skuImageUrl))
                        {
                            imgId = imgDic[attr.skuImageUrl];
                        }
                        else
                        {
                            imgId = UploadImg(yzToken, attr.skuImageUrl);
                            //string imgstr = ImgCheck(filter, attr.skuImageUrl);
                            //if (!imgstr.IsNullOrEmpty())
                            //{
                            //    imgError.Append($"sku:[{imgstr}]");
                            //}
                            imgDic.Add(attr.skuImageUrl, imgId);
                        }
                        SkuValueProps skuValueProps = new SkuValueProps()
                        {
                            name = attr.attributeValue,
                            id = attr.attributeID
                        };
                        if (imgId > 0)
                        {
                            replaceImgId = replaceImgId == 0 ? imgId : replaceImgId;
                            skuValueProps.img_id = imgId;
                        }
                        skuValues.Add(skuValueProps);
                    }
                }
                //价格计算。上涨50%
                long price = long.Parse(Math.Ceiling(aliSkuItem.retailPrice * 100 + aliSkuItem.retailPrice * 100 * 0.5).ToString());
                SkuList skuitem = new SkuList()
                {
                    //price = long.Parse((Math.Round(aliSkuItem.price * 100, 2)).ToString()),
                    price = price,
                    sku_no = aliSkuItem.skuId.ToString(),
                    stock_num = aliSkuItem.amountOnSale,
                    sku_props = skuPropsList
                };
                skuLists.Add(skuitem);
            }
            if (!skuValues.IsNull() && skuValues.Count > 0)
            {
                yzPara.sku_value_props = skuValues;
                yzPara.sku_picture_display_config = isImgShow;
            }
            //sku信息
            yzPara.sku_list = skuLists;
            ItemPriceParam itemPriceParam = new ItemPriceParam()
            {
                price = long.Parse(Math.Round(aliPro.saleInfo.priceRanges[0].price * 100, 2).ToString())
            };
            yzPara.item_price_param = itemPriceParam;
            //处理商品图片
           
            int currentIndex = 0;
            List<long> imageIds = new List<long>();
            foreach (var img in aliPro.image.images)
            {
                currentIndex++;
                long imgId = 0;
                if (currentIndex==1)
                {
                    //检测第一张主图
                    string imgstr = ImgCheck(filter, aliPro.image.images[0]);
                    if (!imgstr.IsNullOrEmpty())
                    {
                        imgError.Append($"主图:[{imgstr}]");
                        imgId = replaceImgId;
                        imageIds.Add(imgId);
                        continue;
                    }
                }
                if (imgDic.ContainsKey(img))
                {
                    imgId = imgDic[img];
                }
                else
                {
                    imgId = UploadImg(yzToken, img);
 
                    imgDic.Add(img, imgId);
                }
                if (imgId == 0)
                {//上传失败
                    continue;
                }
                imageIds.Add(imgId);
            }
            yzPara.image_ids = imageIds;
            return yzPara;
        }
 
        /// <summary>
        /// 代发方案铺货
        /// </summary>
        /// <param name="taskInfo"></param>
        /// <param name="aliToken"></param>
        /// <param name="yzToken"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public async Task<bool> DaiFaRunDistribution(DistributionHistory taskInfo, string aliToken, string yzToken, string yzShopId, List<ProductFilter> filter)
        {
            DistributionHistory finalHis = new DistributionHistory();
            try
            {
                //任务状态改成执行中
                DistributionHistory distributionHistory = new DistributionHistory()
                {
                    DisStatus = 1,
                    RunTime = DateTime.Now
                };
                new DistributionHistoryDAL().Update(distributionHistory, t => new { t.DisStatus, t.RunTime }, t => t.Id == taskInfo.Id);
                //获取1688商品详情
                FenXiaoProductInfoGetRequest request = new FenXiaoProductInfoGetRequest()
                {
                    offerId = long.Parse(taskInfo.ProductId)
                };
                var response = AliabaClient.Execute(request, aliToken);
                if (response.IsNull() || !response.Success)
                {//获取商品详情失败
                    LogUtil.Info($"获取商品详情失败:{taskInfo.Id}", "铺货错误");
                    finalHis.DisStatus = 3;
                    finalHis.Memo = "获取商品详情失败:" + (response.IsNull() ? "null" : response.ErrorMsg);
                    new DistributionHistoryDAL().Update(finalHis, t => new { t.DisStatus, t.Memo }, t => t.Id == taskInfo.Id);
                    return false;
                }
                //判断1688商品状态
                if (response.productInfo.status != "published")
                {//不可铺货
                    LogUtil.Info($"商品状态不对:{response.productInfo.status}", "铺货错误");
                    finalHis.DisStatus = 3;
                    finalHis.Memo = "商品状态不对:" + (response.productInfo.status);
                    new DistributionHistoryDAL().Update(finalHis, t => new { t.DisStatus, t.Memo }, t => t.Id == taskInfo.Id);
                    return false;
                }
                if (!response.productInfo.productSaleInfo.supportOnlineTrade)
                {
                    LogUtil.Info($"不支持网上交易:{response.productInfo.productSaleInfo.supportOnlineTrade}", "铺货错误");
                    finalHis.DisStatus = 3;
                    finalHis.Memo = "商品不支持网上交易";
                    new DistributionHistoryDAL().Update(finalHis, t => new { t.DisStatus, t.Memo }, t => t.Id == taskInfo.Id);
                    return false;
                }
                StringBuilder imgError = new StringBuilder();
                //商品图片
                finalHis.ProImg = response.productInfo.productImage.images[0];
                //string imgMsg = FilterImg(filter, finalHis.ProImg);
                //if (!imgMsg.IsNullOrEmpty())
                //{
                //    imgError.Append($"主图:[{imgMsg}]");
                //}
                //商品title
                finalHis.ProTitle = response.productInfo.subject;
 
                //根据规则调整字段
                var aliPro = response.productInfo;
 
                //是否包邮
                bool isPost = IsPost(aliPro);
                finalHis.IsFreeShipping = isPost ? 1 : 0;
                //调用有赞新增商品接口 youzan.item.add.1.0.1
                YouZanItemAddRequest yzReq = new YouZanItemAddRequest();
                yzReq.param = DaiFaGetAliInfoToYz(aliPro, yzToken, filter, ref imgError);
                var yzRsp = YouZanClient.Execute(yzReq, yzToken);
                if (yzRsp.IsNull() || !yzRsp.success)
                {//新增失败
                    finalHis.DisStatus = 3;
                    finalHis.Memo = yzRsp.IsNull() ? "有赞接口错误" : yzRsp.message;
                    LogUtil.Info($"有赞错误:{finalHis.Memo}--request:" + JSONUtil.ObjectToJson(yzReq), "铺货错误");
                }
                else
                {
                    //有赞返回商品id
                    string yzProductId = yzRsp.data.item_id;
 
                    //添加分销商品关系
                    FenXiaoOutproductRelationAddRequest relaReq = new FenXiaoOutproductRelationAddRequest()
                    {
                        channel = "youzan",
                        offerId = long.Parse(taskInfo.ProductId),
                        outItemCode = yzProductId,
                        outShopCode = yzShopId
                    };
                    var relaRsp = AliabaClient.Execute(relaReq, aliToken);
                    if (relaRsp.IsNull() || !relaRsp.Success)
                    {
                        finalHis.DisStatus = 3;
                        finalHis.Memo = "添加分销商品关系失败:" + (relaRsp.IsNull() ? "null" : relaRsp.ErrorMsg);
                        LogUtil.Info($"添加分销商品关系失败:{JSONUtil.ObjectToJson(relaReq)}--返回:" + (relaRsp.IsNull() ? "null" : relaRsp.ErrorMsg), "铺货错误");
                        new DistributionHistoryDAL().Update(finalHis, t => new { t.DisStatus, t.Memo }, t => t.Id == taskInfo.Id);
                        return false;
                    }
                    //修改任务状态
                    finalHis.DisStatus = 2;
                    finalHis.YzItemId = yzProductId;
                    finalHis.YzAlias = yzRsp.data.alias;
                    string yzskuInfo = UpdateYzSku(yzProductId, yzToken);
 
                    if (!imgError.IsNull() && imgError.Length > 0)
                    {
                        finalHis.Memo = imgError.ToString();
                    }
                    yzskuInfo = yzskuInfo.IsNullOrEmpty() ? JSONUtil.ObjectToJson(yzReq.param.sku_list) : yzskuInfo;
                    //记录1688id与有赞id的关系
                    DistributionRelation distributionRelation = new DistributionRelation()
                    {
                        Id = TopUtil.GetId().ToString(),
                        SourceProduct = taskInfo.ProductId,
                        YzProduct = yzProductId,
                        YzAlias = yzRsp.data.alias,
                        ReStatus = 1,
                        InstanceCode = response.productInfo.sellerId.ToString(),
                        CreateTime = DateTime.Now,
                        AliskuInfo = JSONUtil.ObjectToJson(response.productInfo.productSkuInfos),
                        YzskuInfo = yzskuInfo,
                        ProSource = 1
                    };
                    new DistributionRelationDAL().Insert(distributionRelation);
                    //关注商品
                    AlibabaProductFollowRequest followReq = new AlibabaProductFollowRequest()
                    {
                        productId = long.Parse(taskInfo.ProductId)
                    };
                    var followRsp = AliabaClient.Execute(followReq, aliToken);
                    if (followRsp.IsNull() || followRsp.message != "success")
                    {
                        LogUtil.Info($"关注商品{taskInfo.ProductId}失败,错误:" + (followRsp.IsNull() ? "null" : followRsp.message), "铺货错误");
                    }
                    //修改代发商品表铺货状态
                    DaifaProduct daifaProduct = new DaifaProduct()
                    {
                        IsDistribute = 1
                    };
                    new DaifaProductDAL().Update(daifaProduct, i => new { i.IsDistribute }, t => t.Id == taskInfo.ProductId);
                }
            }
            catch (Exception e)
            {
                finalHis.DisStatus = 3;
                finalHis.Memo = e.Message;
                LogUtil.Info($"错误:{e.ToString()}", "铺货错误");
                new DistributionHistoryDAL().Update(finalHis, t => new { t.DisStatus, t.Memo }, t => t.Id == taskInfo.Id);
                return false;
            }
 
            //修改任务状态
            new DistributionHistoryDAL().Update(finalHis, t => new { t.DisStatus, t.Memo, t.ProImg, t.ProTitle, t.YzAlias, t.YzItemId, t.IsFreeShipping }, t => t.Id == taskInfo.Id);
            return true;
        }
 
        #region 是否包邮
        public bool IsPost(FenXiaoProductInfoGetDomain productInfo)
        {
            if (productInfo.productShippingInfo.freightTemplateID == 1)
            {
                return true;
            }
            double PfMinPrice = productInfo.productSaleInfo.priceRanges.Max(t => t.price);
            double FxMinPrice = productInfo.productSkuInfos.Min(t => t.consignPrice);
            if (FxMinPrice > PfMinPrice && FxMinPrice - PfMinPrice > 2)
            {
                return true;
            }
            return false;
        }
 
        #endregion
 
 
        public static YouZanItemAddDomain DaiFaGetAliInfoToYz(FenXiaoProductInfoGetDomain aliPro, string yzToken, List<ProductFilter> filter, ref StringBuilder imgError)
        {
            YouZanItemAddDomain yzPara = new YouZanItemAddDomain();
            yzPara.item_no = aliPro.productID.ToString();
            yzPara.desc = FilterMsg(filter, aliPro.description);
            //yzPara.start_sale_num = aliPro.saleInfo.minOrderQuantity;
            yzPara.start_sale_num = 1;
            DeliverySetting deliverySetting = new DeliverySetting()
            {
                express = true
            };
            //售后信息
            PostSaleParam postSaleParam = new PostSaleParam()
            { is_support_barter = 0 };
            //是否支持7天无理由退货
            //postSaleParam.support_unconditional_return = aliPro.sevenDaysRefunds;
            bool support_unconditional_return = false;
            foreach (var m in aliPro.productExtendInfos)
            {
                if (!"buyerProtection,buyerProtectionDistribution".Contains(m.key) || m.value.IsNullOrEmpty())
                {
                    continue;
                }
                List<string> arr = JSONUtil.JsonToObject<List<string>>(m.value);
                foreach (var a in arr)
                {
                    if (a.Contains("wlybt"))
                    {
                        support_unconditional_return = true;
                        break;
                    }
                }
                if (support_unconditional_return) break;
            }
            postSaleParam.support_unconditional_return = support_unconditional_return;
            yzPara.post_sale_param = postSaleParam;
            //获取默认运费模板
            var appset = new AppsetDAL().ListGet(t => t.Id != null);
            ItemDeliveryParam itemDeliveryParam = new ItemDeliveryParam
            {
                delivery_setting = deliverySetting,
                delivery_template_id = long.Parse(appset[0].YzPostMould)
            };
            yzPara.item_delivery_param = itemDeliveryParam;
            //默认付款减库存
            yzPara.stock_deduct_mode = 1;
            yzPara.title = FilterMsg(filter, aliPro.subject);
            yzPara.is_display = 0;
            //商品库存, 无sku情况下库存必填,如果有sku则无效
            yzPara.quantity = long.Parse(aliPro.productSkuInfos.Min(t => t.amountOnSale).ToString());
            List<SkuList> skuLists = new List<SkuList>();
            List<SkuValueProps> skuValues = new List<SkuValueProps>();
            Dictionary<string, long> imgDic = new Dictionary<string, long>();
            bool isImgShow = false;
            long replaceImgId = 0;
            foreach (var aliSkuItem in aliPro.productSkuInfos)
            {
                if (aliSkuItem.consignPrice <= 0)
                {
                    continue;
                }
                List<SkuProps> skuPropsList = new List<SkuProps>();
                aliSkuItem.attributes = aliSkuItem.attributes.OrderBy(t => t.skuImageUrl.IsNullOrEmpty()).ToList();
                int index = 0;
                foreach (var attr in aliSkuItem.attributes)
                {//属性信息
                    index++;
                    SkuProps skuProps = new SkuProps()
                    {
                        prop_value_name = attr.attributeValue,
                        prop_name = attr.attributeName,
                        prop_name_id = 0,
                        prop_value_id = attr.attributeID
                    };
                    skuPropsList.Add(skuProps);
                    if (index == 1 && !attr.skuImageUrl.IsNullOrEmpty())
                    {
                        isImgShow = true;
                        //处理有赞sku图片信息
                        long imgId = 0;
                        if (imgDic.ContainsKey(attr.skuImageUrl))
                        {
                            imgId = imgDic[attr.skuImageUrl];
                        }
                        else
                        {
                            imgId = UploadImg(yzToken, attr.skuImageUrl);
                            //string imgstr = ImgCheck(filter, attr.skuImageUrl);
                            //if (!imgstr.IsNullOrEmpty())
                            //{
                            //    imgError.Append($"sku:[{imgstr}]");
                            //}
                            imgDic.Add(attr.skuImageUrl, imgId);
                        }
                        SkuValueProps skuValueProps = new SkuValueProps()
                        {
                            name = attr.attributeValue,
                            id = attr.attributeID
                        };
                        if (imgId > 0)
                        {
                            replaceImgId = replaceImgId == 0 ? imgId : replaceImgId;
                            skuValueProps.img_id = imgId;
                        }
                        skuValues.Add(skuValueProps);
                    }
                }
                //价格计算。上涨50%
                long price = long.Parse(Math.Ceiling(aliSkuItem.consignPrice * 100 + aliSkuItem.consignPrice * 100 * 0.5).ToString());
                SkuList skuitem = new SkuList()
                {
                    //price = long.Parse((Math.Round(aliSkuItem.price * 100, 2)).ToString()),
                    price = price,
                    sku_no = aliSkuItem.skuId.ToString(),
                    stock_num = aliSkuItem.amountOnSale,
                    sku_props = skuPropsList
                };
                skuLists.Add(skuitem);
            }
            if (!skuValues.IsNull() && skuValues.Count > 0)
            {
                yzPara.sku_value_props = skuValues;
                yzPara.sku_picture_display_config = isImgShow;
            }
            //sku信息
            yzPara.sku_list = skuLists;
 
            ItemPriceParam itemPriceParam = new ItemPriceParam()
            {
                price = long.Parse(Math.Round(aliPro.productSaleInfo.priceRanges[0].price * 100, 2).ToString())
            };
            yzPara.item_price_param = itemPriceParam;
            //处理商品图片
            List<long> imageIds = new List<long>();
            int currentIndex = 0;
            foreach (var img in aliPro.productImage.images)
            {
                currentIndex++;
                long imgId = 0;
                if (currentIndex == 1)
                {
                    //检测第一张主图
                    string imgstr = ImgCheck(filter, aliPro.productImage.images[0]);
                    if (!imgstr.IsNullOrEmpty())
                    {
                        imgError.Append($"主图:[{imgstr}]");
                        imgId = replaceImgId;
                        imageIds.Add(imgId);
                        continue;
                    }
                }
                if (imgDic.ContainsKey(img))
                {
                    imgId = imgDic[img];
                }
                else
                {
                    imgId = UploadImg(yzToken, img);
                    //string imgstr = ImgCheck(filter, img);
                    //if (!imgstr.IsNullOrEmpty())
                    //{
                    //    imgError.Append($"主图:[{imgstr}]");
                    //}
                    imgDic.Add(img, imgId);
                }
                if (imgId == 0)
                {//上传失败
                    continue;
                }
                imageIds.Add(imgId);
            }
            yzPara.image_ids = imageIds;
            return yzPara;
        }
 
 
        #region 更新有赞信息
        private string UpdateYzSku(string yzItemId, string yzToken)
        {
            ////获取有赞商品详情
            YouZanProductDetailGetRequest detailReq = new YouZanProductDetailGetRequest()
            {
                item_id = long.Parse(yzItemId)
            };
            var detailRs = YouZanClient.Execute(detailReq, yzToken);
            if (detailRs.IsNull() || !detailRs.success)
            {
                return null;
            }
            else
            {
                return JSONUtil.ObjectToJson(detailRs.data.sku_list);
            }
        }
 
        #endregion
 
        /// <summary>
        /// 图片上传有赞
        /// </summary>
        /// <param name="urls"></param>
        /// <returns></returns>
        private static long UploadImg(string yzToken, string url)
        {
            if (url.IsNullOrEmpty())
            {
                return 0;
            }
            string[] urlArr = url.Split('.');
            string fileName = "D://Img/" + Guid.NewGuid().ToString() + $".{urlArr[urlArr.Length - 1]}";
            WebClient MyWebClient = new WebClient();
            if (!url.StartsWith("http"))
            {
                url = "https://cbu01.alicdn.com/img/" + url;
            }
            MyWebClient.DownloadFile(url, fileName);
            //上传至有赞
            UploadImageResponse response = YouZanUploadeImg.UploadImage(yzToken, fileName);
 
            if (!response.IsNull() && response.success)
            {
                return response.data.image_id;
            }
            return 0;
        }
 
        /// <summary>
        /// 添加铺货任务
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> AddDistributionTask(ProductDistributionRequest request)
        {
            //判断是否有生成中的
            var history = new DistributionHistoryDAL().ListGet(t => request.ProductId.Contains(t.ProductId) && (t.DisStatus == 0 || t.DisStatus == 1));
            List<DistributionHistory> tasks = new List<DistributionHistory>();
            string taskId = TopUtil.GetId().ToString();
            foreach (var pid in request.ProductId)
            {
                if (history.Any(t => t.ProductId == pid))
                {//正在执行中或未执行的跳过
                    continue;
                }
                DistributionHistory distributionHistory = new DistributionHistory()
                {
                    Id = TopUtil.GetId().ToString(),
                    ProductId = pid,
                    CreateTime = DateTime.Now,
                    TaskId = taskId,
                    DisStatus = 0,
                    ProSource = request.ProSource
                };
                tasks.Add(distributionHistory);
            }
            if (!tasks.IsNull() && tasks.Count > 0)
            {
                //插入记录表
                new DistributionHistoryDAL().InsertRange(tasks);
                //发执行mq
                ProductDistributionMq productDistributionMq = new ProductDistributionMq()
                {
                    TaskId = taskId
                };
                string ret = MQClientFullChannel.SendMessageStatic(0, "product_distribution", JSONUtil.ObjectToJson(productDistributionMq));
                if (ret != "ok")
                {
                    LogUtil.Info($"发MQ失败:{taskId}", "铺货任务mq失败");
                    return false;
                }
                return true;
            }
            return false;
        }
 
        /// <summary>
        /// 解除商品关联
        /// </summary>
        /// <param name="aliProductId"></param>
        /// <param name="aliToken"></param>
        /// <returns></returns>
 
        public bool RemoveRelatProduct(string aliProductId, string aliToken, string yzToken, DistributionHistory history, string yzShopId)
        {
            try
            {
                //取消关注商品
                AlibabaProductUnFollowRequest request = new AlibabaProductUnFollowRequest()
                {
                    productId = long.Parse(aliProductId)
                };
                var response = AliabaClient.Execute(request, aliToken);
                if (response.IsNull() || response.message != "success")
                {
                    return false;
                }
                if (history.ProSource == 1)
                {//代发方案商品,需额外解除分销关系
                    FenXiaoOutproductRelationDeleteRequest deReq = new FenXiaoOutproductRelationDeleteRequest()
                    {
                        channel = "youzan",
                        offerId = long.Parse(history.ProductId),
                        outItemCode = history.YzItemId,
                        outShopCode = yzShopId
                    };
                    var relaRsp = AliabaClient.Execute(deReq, aliToken);
                    if (relaRsp.IsNull() || !relaRsp.Success)
                    {
                        return false;
                    }
                    DaifaProduct daifaProduct = new DaifaProduct()
                    {
                        IsDistribute = 0
                    };
                    new DaifaProductDAL().Update(daifaProduct, i => new { i.IsDistribute }, t => t.Id == history.ProductId);
                }
                //表里关系解除关注
                DistributionRelation distributionRelation = new DistributionRelation()
                {
                    ReStatus = 0
                };
                new DistributionRelationDAL().Update(distributionRelation, i => new { i.ReStatus }, t => t.SourceProduct == aliProductId);
                //删除有赞商品
                YouZanItemDeleteRequest youZanItemDeleteRequest = new YouZanItemDeleteRequest()
                {
                    item_id = long.Parse(history.YzItemId)
                };
                var youZanItemDeleteRsp = YouZanClient.Execute(youZanItemDeleteRequest, yzToken);
                if (youZanItemDeleteRsp.IsNull() || !youZanItemDeleteRsp.success || !youZanItemDeleteRsp.data.is_success)
                {
                    LogUtil.Info($"id:{history.YzItemId}--error:{youZanItemDeleteRsp.message}", "有赞商品删除error");
                }
 
                return true;
 
            }
            catch (Exception e)
            {
                LogUtil.Info("aliProductId:" + aliProductId + "--" + e.ToString(), "解除商品关联error");
                return false;
            }
        }
 
        public static string FilterMsg(List<ProductFilter> filter, string msg)
        {
            try
            {
                foreach (var fi in filter)
                {
                    string replaceStr = fi.Replace.IsNullOrEmpty() ? "" : fi.Replace;
                    msg = msg.Replace(fi.KeyWord, replaceStr);
                }
            }
            catch (Exception e)
            {
                LogUtil.Info(e.ToString(), "过滤关键词error");
            }
            return msg;
        }
 
        public static string ImgCheck(List<ProductFilter> filter, string imgUrl)
        {
            if (!imgUrl.StartsWith("http"))
            {
                imgUrl = "https://cbu01.alicdn.com/img/" + imgUrl;
            }
            string imgMsg = FilterImg(filter, imgUrl);
            if (!imgMsg.IsNullOrEmpty())
            {
                return imgMsg;
            }
            return null;
        }
 
        #region 处理商品详情图片
        public static string FilterDesc(List<ProductFilter> filter, string desc)
        {
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(desc);
            var imgNode = doc.DocumentNode.SelectNodes("//img");
            foreach (var imgItem in imgNode)
            {
                var imgsrc = imgItem.Attributes["src"].Value;
                string imgError = ImgCheck(filter, imgsrc);
                if (!imgError.IsNullOrEmpty())
                {
                    imgItem.Remove();
                }
            }
            return doc.DocumentNode.OuterHtml;
        }
 
        #endregion
 
        #region 图片关键词过滤
        public static string FilterImg(List<ProductFilter> filter, string imgUrl)
        {
            try
            {
                StringBuilder keyError = new StringBuilder();
                //百度ai图片识别
                var res = BaiDuClient.WebImageUrl(imgUrl);
                if (!res.IsSuccess)
                {
                    LogUtil.Info($"百度ai错误:{res.error_msg}--图片:{imgUrl}", "过滤关键词error");
                }
                if (res.words_result_num <= 0)
                {
                    return null;
                }
                var msgList = res.words_result.Select(t => t.words).ToList();
                string msg = string.Join(',', msgList);
                var filterKey = filter.Where(t => msg.Contains(t.KeyWord)).ToList();
                if (!filterKey.IsNull() && filterKey.Count > 0)
                {
                    var filterList = filterKey.Select(t => t.KeyWord).ToList();
                    return string.Join(',', filterList);
                }
            }
            catch (Exception e)
            {
                LogUtil.Info(e.ToString(), "过滤关键词error");
            }
            return null;
        }
        #endregion
 
        #region 处理sku不对应的情况
        private List<SkuList> ResetSkuInfo(List<SkuInfosItem> aliSkuinfo, List<SkuList> youzanSkuInfo)
        {
            try
            {
                Dictionary<string, List<string>> attrbuteDic = new Dictionary<string, List<string>>();
 
            }
            catch (Exception e)
            {
 
            }
            return null;
        }
 
        #endregion
 
        public List<string> GetYzItemIdByTag(ListGetDistributionHistoryRequest request, string yzToken)
        {
            List<string> itemList = new List<string>();
            int pageSize = 50;
            int currentPage = 1;
            int totalPage = 1;
            while (currentPage <= totalPage)
            {
 
                YouZanItemCommonSearchRequest itemReq = new YouZanItemCommonSearchRequest()
                {
                    page_size = pageSize,
                    page_no = currentPage,
                    tag_ids = request.TagIds,
                    is_display = request.IsDisplay
                };
                var itemRsp = YouZanClient.Execute(itemReq, yzToken);
                currentPage++;
                if (itemRsp.IsNull() || !itemRsp.success)
                {
                    continue;
                }
                //计算总页数
                if (totalPage == 1)
                {
                    totalPage = itemRsp.data.paginator.total_count % pageSize == 0 ? itemRsp.data.paginator.total_count / pageSize : (itemRsp.data.paginator.total_count / pageSize) + 1;
                }
                foreach (var yzpro in itemRsp.data.items)
                {
                    if (!itemList.Contains(yzpro.item_id.ToString()))
                    {
                        itemList.Add(yzpro.item_id.ToString());
                    }
                }
            }
            return itemList;
 
        }
 
 
 
        //public void Dispose()
        //{
        //    return base.dis
        //}
    }
}