WYB
2021-03-22 91b8cdad021ab052e4991f3d41834a6f0ddc36b8
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
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
using JiepeiWMS.Common;
using JiepeiWMS.Common.Helper;
using JiepeiWMS.Common.HttpContextUser;
using JiepeiWMS.Common.HttpRestSharp;
using JiepeiWMS.Extends;
using JiepeiWMS.IRepository.UnitOfWork;
using JiepeiWMS.IServices;
using JiepeiWMS.Model;
using JiepeiWMS.Model.BllModels;
using JiepeiWMS.Model.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
 
namespace JiepeiWMS.Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize(Permissions.Name)]
    public class WMSupplierController : ControllerBase
    {
        /// <summary>
        /// 服务器接口,因为是模板生成,所以首字母是大写的,自己可以重构下
        /// </summary>
        private readonly IUnitOfWork _unitOfWork;
        private readonly IWMSupplierServices _wMSupplierServices;
        private readonly IUser _user;
        private readonly ISysUserInfoServices _sysUserInfoServices;
        private readonly IWMSupplierTypeServices _wMSupplierTypeServices;
        private readonly IWMSupplier_TypeServices _wMSupplier_TypeServices;
        private readonly ILogger<WMSupplierController> _logger;
        private readonly ISysOrgServices _SysOrgServices;
        private readonly IUserRoleServices _userRole;
 
        #region 视图
        public WMSupplierController(IWMSupplierServices WMSupplierServices,
            IUser user,
            ISysUserInfoServices SysUserInfoServices,
            IWMSupplierTypeServices WMSupplierTypeServices,
            IWMSupplier_TypeServices WMSupplier_TypeServices,
            ILogger<WMSupplierController> logger,
            IUnitOfWork unitOfWork,
            ISysOrgServices SysOrgServices,
            IUserRoleServices userRole)
        {
            _wMSupplierServices = WMSupplierServices;
            _user = user;
            _sysUserInfoServices = SysUserInfoServices;
            _wMSupplierTypeServices = WMSupplierTypeServices;
            _wMSupplier_TypeServices = WMSupplier_TypeServices;
            _logger = logger;
            _unitOfWork = unitOfWork;
            _SysOrgServices = SysOrgServices;
            _userRole = userRole;
        }
        /// <summary>
        /// 供应商列表
        /// </summary>
        /// <param name="page">默认第几页</param>
        /// <param name="key">供应商名称</param>
        /// <param name="startdate">开始时间</param>
        /// <param name="enddate">结束时间</param>
        /// <param name="intPageSize">一夜多少条数据</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<PageModel<WMSupplier>>> Get(int page = 1, string key = "", DateTime? startdate = null, DateTime? enddate = null, int intPageSize = 20)
        {
            if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            {
                key = "";
            }
            Expression<Func<WMSupplier, bool>> whereExpression = Supplier => Supplier.Id > 0;
            //供应商名称
            if (!string.IsNullOrWhiteSpace(key))
            {
                whereExpression = whereExpression.And(Supplier => Supplier.Name.Contains(key.Trim()));
            }
            //开始时间
            if (startdate != null)
            {
                whereExpression = whereExpression.And(Supplier => Supplier.CreatedTime >= startdate);
            }
            //结束时间
            if (enddate != null)
            {
                whereExpression = whereExpression.And(Supplier => Supplier.CreatedTime <= enddate);
            }
            whereExpression = whereExpression.And(Supplier => Supplier.Status > 0);
            //显示当前操作人的主体ID
            //whereExpression = whereExpression.And(Supplier => Supplier.SysOrgId == _user.SysOrgId);
 
            var PageList = await _wMSupplierServices.QueryTabsPage<WMSupplier, sysUserInfo, WMSupplier>(
             (Supplier, UserInfo) => new object[]
             {
                 JoinType.Left,Supplier.CreatedBy==UserInfo.uID
             },
             (Supplier, UserInfo) => new WMSupplier()
             {
                 Id = Supplier.Id,
                 Sort = Supplier.Sort,
                 Name = Supplier.Name,
                 Address = Supplier.Address,
                 Phone = Supplier.Phone,
                 UnifiedCode = Supplier.UnifiedCode,
                 FileUrl = Supplier.FileUrl,
                 PostalCode = Supplier.PostalCode,
                 ConstactPerson = Supplier.ConstactPerson,
                 IsEnable = Supplier.IsEnable,
                 Status = Supplier.Status,
                 CreatedTime = Supplier.CreatedTime,
                 CreatedBy = Supplier.CreatedBy,
                 UpdatedBy = Supplier.UpdatedBy,
                 UpdatedTime = Supplier.UpdatedTime,
                 CompanyID = Supplier.CompanyID,
                 ShortName = Supplier.ShortName,
                 SysOrgId = Supplier.SysOrgId,
                 CreatedName = UserInfo.uRealName,
                 SupplierAttributes = Supplier.SupplierAttributes,
                 SettlementmMethod = Supplier.SettlementmMethod,
                 BusinessScope = Supplier.BusinessScope,
                 DateofEstablishment = Supplier.DateofEstablishment,
                 Grade = Supplier.Grade,
                 InvoiceType = Supplier.InvoiceType,
                 IsCooperation = Supplier.IsCooperation,
                 LeadTime = Supplier.LeadTime,
                 LegalRepresentative = Supplier.LegalRepresentative,
                 LegalTelephone = Supplier.LegalTelephone,
                 MainProducts = Supplier.MainProducts,
                 PayType = Supplier.PayType,
                 Position = Supplier.Position,
                 RegisteredCapital = Supplier.RegisteredCapital,
                 TaxRate = Supplier.TaxRate,
                 WeChat = Supplier.WeChat,
                 OASupplierId = Supplier.OASupplierId,
             },
             whereExpression,
             page,
             intPageSize,
             " Supplier.Id desc"
             );
            //获取供应商的所有集合
            foreach (var item in PageList.data)
            {
                //获取供应商和供应商类型中间表的所有信息
                var allWMSupplier_Types = await _wMSupplier_TypeServices.Query(d => d.IsDeleted == false);
                //获取所有供应商类型
                var allTypes = await _wMSupplierTypeServices.Query(d => d.IsEnable == true);
 
                var currentWMSupplier_Types = allWMSupplier_Types.Where(d => d.WMSupplierId == item.Id).Select(d => d.WMSupplierTypeId).ToList();
                item.TypeIDs = currentWMSupplier_Types;
                item.TypeNames = allTypes.Where(d => item.TypeIDs.Contains(d.OASupplierTypeId)).Select(d => d.SupTypeName).ToList();
 
                if (!string.IsNullOrEmpty(item.FileUrl))
                {
                    var strs = item.FileUrl.Split(';');
                    int count = strs.Count();
 
                    item.FileUrl1 = strs[0];
                    item.FileUrl2 = count > 1 ? strs[1] : "";
                    item.FileUrl3 = count > 2 ? strs[2] : "";
                    item.FileUrl4 = count > 3 ? strs[3] : "";
                    item.FileUrl5 = count > 4 ? strs[4] : "";
                }
            }
            return new MessageModel<PageModel<WMSupplier>>()
            {
                msg = "获取成功",
                success = PageList.dataCount >= 0,
                response = PageList
            };
 
        }
 
        [HttpGet]
        [AllowAnonymous]
        public async Task<MessageModel<object>> GetList(int id = 0)
        {
            var supplierList = await _wMSupplierServices.Query();
 
            return new MessageModel<object>()
            {
                msg = "获取成功",
                success = true,
                response = new
                {
                    supplierList
                }
            };
        }
        #endregion
 
        #region 操作
        [HttpPost]
        public async Task<MessageModel<string>> Post([FromBody] WMSupplier request)
        {
            var data = new MessageModel<string>();
 
            if (request.TaxRate.ObjToInt() <= 0)
            {
                data.msg = "税率不能小于0";
                return data;
            }
 
            request.CreatedTime = DateTime.Now;
            request.UpdatedTime = DateTime.Now;
            request.CreatedBy = _user.ID;
            request.UpdatedBy = _user.ID;
            request.Status = 1;
            var Supplier = await _wMSupplierServices.GetModel(w => w.Name == request.Name);
            if (Supplier != null)
            {
                data.msg = "供应商名称已存在!";
                return data;
            }
 
            if (!string.IsNullOrEmpty(request.FileUrl1))
            {
                request.FileUrl = request.FileUrl1 + ";";
            }
            if (!string.IsNullOrEmpty(request.FileUrl2))
            {
                request.FileUrl = request.FileUrl + request.FileUrl2 + ";";
            }
            if (!string.IsNullOrEmpty(request.FileUrl3))
            {
                request.FileUrl = request.FileUrl + request.FileUrl3 + ";";
            }
            if (!string.IsNullOrEmpty(request.FileUrl4))
            {
                request.FileUrl = request.FileUrl + request.FileUrl4 + ";";
            }
            if (!string.IsNullOrEmpty(request.FileUrl5))
            {
                request.FileUrl = request.FileUrl + request.FileUrl5 + ";";
            }
            //主体
            request.SysOrgId = _user.SysOrgId;
            var Id = await _wMSupplierServices.AddSupplierInfo(request, _user.ID);
 
            //判断是否添加成功
            if (string.IsNullOrEmpty(Id))
            {
                data.success = true;
            }
            if (data.success)
            {
                data.response = Id.ObjToString();
                data.msg = "添加成功";
            }
 
            return data;
        }
 
        [HttpPut]
        public async Task<MessageModel<string>> Put([FromBody] WMSupplier request)
        {
            var data = new MessageModel<string>();
 
            if (request.TaxRate.ObjToInt() <= 0)
            {
                data.msg = "税率不能小于0";
                return data;
            }
 
            try
            {
                _unitOfWork.BeginTran();
                if (request.Id > 0)
                {
                    request.UpdatedBy = _user.ID;
                    request.UpdatedTime = DateTime.Now;
                    if (request.TypeIDs.Count > 0)
                    {
                        // 无论 Update Or Add , 先删除当前供应商的全部 Supplier_SupplierType 关系
                        var wMSupplier_Types = (await _wMSupplier_TypeServices.Query(d => d.WMSupplierId == request.Id)).Select(d => d.Id.ToString()).ToArray();
                        if (wMSupplier_Types.Count() > 0)
                        {
                            var isAllDeleted = await _wMSupplier_TypeServices.DeleteByIds(wMSupplier_Types);
                        }
 
                        // 然后再执行添加操作
                        var wMSupplierTypesAdd = new List<WMSupplier_Type>();
                        request.TypeIDs.ForEach(tid =>
                        {
                            wMSupplierTypesAdd.Add(new WMSupplier_Type(request.Id, tid));
                        });
 
                        await _wMSupplier_TypeServices.Add(wMSupplierTypesAdd);
 
                    }
                    if (!string.IsNullOrEmpty(request.FileUrl1))
                    {
                        request.FileUrl = request.FileUrl1 + ";";
                    }
                    if (!string.IsNullOrEmpty(request.FileUrl2))
                    {
                        request.FileUrl = request.FileUrl + request.FileUrl2 + ";";
                    }
                    if (!string.IsNullOrEmpty(request.FileUrl3))
                    {
                        request.FileUrl = request.FileUrl + request.FileUrl3 + ";";
                    }
                    if (!string.IsNullOrEmpty(request.FileUrl4))
                    {
                        request.FileUrl = request.FileUrl + request.FileUrl4 + ";";
                    }
                    if (!string.IsNullOrEmpty(request.FileUrl5))
                    {
                        request.FileUrl = request.FileUrl + request.FileUrl5 + ";";
                    }
                    //将分类id转为数组
                    var supid = request.TypeIDs.ToArray();
                    //同步到OA系统
                    var apioahost = Appsettings.app("AppSettings", "ApiOAHost");
                    var result = HttpHelper.PostApi<ApiFinanceResult>(apioahost + "/api/Supplier/SaveOrUpdateSupplier", new
                    {
                        appsecret = "kw3j5k32ur38rnerkKJHk83",
                        timestamp = DateTime.Now._ToTimestamp(),
                        OaSupId = request.OASupplierId,
                        SupName = request.Name,
                        SupShortName = request.ShortName,
                        OrgCode = request.UnifiedCode,
                        SupCharge = request.LegalRepresentative,
                        SupPhone = request.Phone,
                        SupEmail = request.PostalCode,
                        SupAddress = request.Address,
                        SupTypeId = supid
                    });
                    if (result == null || result.Code != 1)
                    {
                        _unitOfWork.RollbackTran();
                        throw new Exception("请求OA供应商接口失败,result值:" + result + ";");
                    }
                    //返回值OA的供应商id
                    request.OASupplierId = Convert.ToInt32(result.Data.OaSupId);
                    request.UnifiedCode = !string.IsNullOrWhiteSpace(result.Data.OaSupCode) ? result.Data.OaSupCode : request.UnifiedCode;
                    request.Name = !string.IsNullOrWhiteSpace(result.Data.OaSupName) ? result.Data.OaSupName : request.Name;
                    //主体
                    request.SysOrgId = _user.SysOrgId;
                    data.success = await _wMSupplierServices.Update(request);
 
                    _unitOfWork.CommitTran();
 
                    if (data.success)
                    {
                        data.msg = "更新成功";
                        data.response = request?.Id.ObjToString();
                    }
                }
 
            }
            catch (Exception e)
            {
 
                _unitOfWork.RollbackTran();
                _logger.LogError(e, e.Message);
            }
 
            return data;
        }
 
        [HttpPut]
        public async Task<MessageModel<string>> UpdateSupplierId()
        {
            var data = new MessageModel<string>();
            try
            {
                var msg = await _wMSupplierServices.EditSupplierInfo();
                //判断是否添加成功
                if (string.IsNullOrEmpty(msg))
                {
                    data.success = true;
                }
                if (data.success)
                {
                    data.response = msg.ObjToString();
                    data.msg = "同步成功!";
                }
            }
            catch (Exception e)
            {
 
                _logger.LogError(e, e.Message);
            }
            return data;
        }
 
        [HttpDelete]
        public async Task<MessageModel<string>> Delete(int Id = 0)
        {
            var data = new MessageModel<string>();
            if (Id > 0)
            {
                var detail = await _wMSupplierServices.QueryById(Id);
 
                detail.Status = -1;
 
                if (detail != null)
                {
                    data.success = await _wMSupplierServices.Update(detail);
                    if (data.success)
                    {
                        data.msg = "删除成功";
                        data.response = detail?.Id.ObjToString();
                    }
                }
            }
 
            return data;
        }
 
 
        /// <summary>
        /// 导出供应商表格
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ExportExcel(string key = "", DateTime? startdate = null, DateTime? enddate = null)
        {
            if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            {
                key = "";
            }
            Expression<Func<WMSupplier, bool>> whereExpression = Supplier => Supplier.Id > 0;
            //供应商名称
            if (!string.IsNullOrWhiteSpace(key))
            {
                whereExpression = whereExpression.And(Supplier => Supplier.Name != null && Supplier.Name.Contains(key.Trim()));
            }
            //开始时间
            if (startdate != null)
            {
                whereExpression = whereExpression.And(Supplier => Supplier.CreatedTime >= startdate);
            }
            //结束时间
            if (enddate != null)
            {
                whereExpression = whereExpression.And(Supplier => Supplier.CreatedTime <= enddate);
            }
            whereExpression = whereExpression.And(Supplier => Supplier.Status > 0);
            var PageList = await _wMSupplierServices.QueryTabsPage<WMSupplier, sysUserInfo, WMSupplier>(
          (Supplier, UserInfo) => new object[]
          {
                 JoinType.Left,Supplier.CreatedBy==UserInfo.uID,
                 JoinType.Left,Supplier.UpdatedBy==UserInfo.uID,
          },
          (Supplier, UserInfo) => new WMSupplier()
          {
              Id = Supplier.Id,
              Sort = Supplier.Sort,
              Name = Supplier.Name,
              Address = Supplier.Address,
              Phone = Supplier.Phone,
              UnifiedCode = Supplier.UnifiedCode,
              FileUrl = Supplier.FileUrl,
              PostalCode = Supplier.PostalCode,
              ConstactPerson = Supplier.ConstactPerson,
              IsEnable = Supplier.IsEnable,
              Status = Supplier.Status,
              CreatedTime = Supplier.CreatedTime,
              CreatedBy = Supplier.CreatedBy,
              UpdatedBy = Supplier.UpdatedBy,
              UpdatedTime = Supplier.UpdatedTime,
              CompanyID = Supplier.CompanyID,
              ShortName = Supplier.ShortName,
              SysOrgId = Supplier.SysOrgId,
              CreatedName = UserInfo.uRealName,
              UpdateName = UserInfo.uRealName,
              SupplierAttributes = Supplier.SupplierAttributes,
              SettlementmMethod = Supplier.SettlementmMethod,
              BusinessScope = Supplier.BusinessScope,
              DateofEstablishment = Supplier.DateofEstablishment,
              Grade = Supplier.Grade,
              InvoiceType = Supplier.InvoiceType,
              IsCooperation = Supplier.IsCooperation,
              LeadTime = Supplier.LeadTime,
              LegalRepresentative = Supplier.LegalRepresentative,
              LegalTelephone = Supplier.LegalTelephone,
              MainProducts = Supplier.MainProducts,
              PayType = Supplier.PayType,
              Position = Supplier.Position,
              RegisteredCapital = Supplier.RegisteredCapital,
              TaxRate = Supplier.TaxRate,
              WeChat = Supplier.WeChat,
 
          },
          whereExpression,
          1,
          100000,
          " Supplier.Id desc"
          );
            //获取供应商和供应商类型中间表的所有信息
            var allWMSupplier_Types = await _wMSupplier_TypeServices.Query(d => d.IsDeleted == false);
            //获取所有供应商类型
            var allTypes = await _wMSupplierTypeServices.Query(d => d.IsEnable == true);
            //获取供应商的所有集合
            var WMSuppliersList = PageList.data;
            foreach (var item in WMSuppliersList)
            {
                var currentWMSupplier_Types = allWMSupplier_Types.Where(d => d.WMSupplierId == item.Id).Select(d => d.WMSupplierTypeId).ToList();
                item.TypeIDs = currentWMSupplier_Types;
                item.TypeNames = allTypes.Where(d => item.TypeIDs.Contains(d.Id)).Select(d => d.SupTypeName).ToList();
                if (item.IsEnable == true)
                {
                    item.IsEnableName = "启用";
                }
                else
                {
                    item.IsEnableName = "禁用";
                }
            }
            if (WMSuppliersList != null && WMSuppliersList.Any())
            {
                var WSPLlist = WMSuppliersList.Select(w => new
                {
                    w.Id,
                    w.Sort,
                    w.TypeNames,
                    w.Name,
                    w.Address,
                    w.Phone,
                    w.UnifiedCode,
                    w.FileUrl,
                    w.PostalCode,
                    w.ConstactPerson,
                    w.IsEnableName,
                    w.Status,
                    w.CreatedTime,
                    w.CreatedName,
                    w.UpdatedTime,
                    w.Type,
                    w.CompanyID,
                    w.ShortName,
                    w.SysOrgId,
                    w.RegisteredCapital,
                    w.BusinessScope,
                    w.DateofEstablishment,
                    w.IsCooperation,
                    w.Grade,
                    w.InvoiceType,
                    w.TaxRate,
                    w.PayType,
                    w.SettlementmMethod,
                    w.LeadTime,
                    w.LegalRepresentative,
                    w.LegalTelephone,
                    w.Position,
                    w.WeChat,
                    w.MainProducts,
                    w.SupplierAttributes
                }).ToList();
                var heads = new List<string>() { "编号","排序","供应商类型名称","供应商名称","地址","手机","统一代码","上传合同地址", "单位邮箱", "联系人",
                    "是否启用 1启用,0禁用","状态:-1=已删除,1是正常","创建时间","创建人","修改时间","无","无","供应商简称","无","注册资本","经营范围",
                    "成立日期","是否合作1是0否","等级","发票类型","税率","支付方式","结算方式","交货周期","法定代表人","法定电话","职位","微信","已合作产品","供应商属性"};
 
 
                var stream = Common.Helper.ExcelHelper.CreateExcelStreamFromList(WSPLlist, heads);
 
 
                return File(stream, "application/octet-stream", "供应商.xlsx");
            }
            return null;
        }
 
 
        /// <summary>
        /// 导入供应商
        /// </summary>
        [HttpPost]
        [AllowAnonymous]
        public async Task<MessageModel<string>> ImportSupplierList([FromForm] IFormCollection files)
        {
            var data = new MessageModel<string>();
            try
            {
                var sysUserInfoModel = await _sysUserInfoServices.QueryById(_user.ID);
                if (sysUserInfoModel == null || sysUserInfoModel.tdIsDelete == true)
                {
                    data.msg = "当前用户已被禁用无法进行导入";
                    data.response = 0.ObjToString();
                    data.status = 500;
                    return data;
                }
                var userRoleList = await _userRole.Query(x => x.UserId == sysUserInfoModel.uID);
                if (userRoleList == null && userRoleList.Count() == 0)
                {
                    data.msg = "当前用户还未配置角色无法进行导入";
                    data.response = 0.ObjToString();
                    data.status = 500;
                    return data;
                }
 
                //创建事务
                _unitOfWork.BeginTran();
                var path = Directory.GetCurrentDirectory();
                var fileFolder = Path.Combine(path, "ImportFile");
                if (!Directory.Exists(fileFolder))
                    Directory.CreateDirectory(fileFolder);
 
                FormFileCollection fileCollection = (FormFileCollection)files.Files;
                foreach (var file in fileCollection)
                {
                    var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetExtension(file.FileName);
                    var filePath = Path.Combine(fileFolder, fileName);
 
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                    }
 
 
                    var dtExcel = ExcelHelper.ImportExcel(filePath);
                    #region 新增编辑供应商以及类型数据
                    foreach (DataRow myRow in dtExcel.Rows)
                    {
                        if (string.IsNullOrWhiteSpace(myRow[1].ToString()))
                        { throw new Exception("供应商名称不能为空!"); }
 
 
                        var ModelSupplier = await _wMSupplierServices.GetModel(s => s.Name == myRow[1].ToString() && s.Status != -1);
                        //判断供应商是否存在,存在就修改不存在就添加
                        if (ModelSupplier == null)
                        {
                            WMSupplier model = new WMSupplier();
                            model.Name = myRow[1].ToString();//供应商名称
                            //判断如果等于空就给默认值
                            if (string.IsNullOrWhiteSpace(myRow[2].ToString()))
                            {
                                model.UnifiedCode = "0";//统一代码
                            }
                            else
                            {
                                model.UnifiedCode = myRow[2].ToString();//统一代码
 
                            }
                            if (string.IsNullOrWhiteSpace(myRow[3].ToString()))
                            {
                                model.SupplierAttributes = "正常供应商";//供应商属性
                            }
                            else
                            {
                                model.SupplierAttributes = myRow[3].ToString();//供应商属性
                            }
 
 
                            if (string.IsNullOrWhiteSpace(myRow[5].ToString()))
                            {
                                model.PayType = "现金";//支付方式
                            }
                            else
                            {
                                model.PayType = myRow[5].ToString();//支付方式
                            }
 
                            if (string.IsNullOrWhiteSpace(myRow[6].ToString()))
                            {
 
                                model.MainProducts = " ";//主营产品(优势产品)
                            }
                            else
                            {
 
                                model.MainProducts = myRow[6].ToString();//主营产品(优势产品)
                            }
 
                            if (string.IsNullOrWhiteSpace(myRow[7].ToString()))
                            {
 
                                model.SettlementmMethod = "现金";//结算方式
                            }
                            else
                            {
 
                                model.SettlementmMethod = myRow[7].ToString();//结算方式
                            }
                            if (string.IsNullOrWhiteSpace(myRow[9].ToString()))
                            {
 
                                model.InvoiceType = "增值税专用发票";//发票类型
                            }
                            else
                            {
 
                                model.InvoiceType = myRow[9].ToString();//发票类型
                            }
                            if (string.IsNullOrWhiteSpace(myRow[10].ToString()))
                            {
 
                                model.TaxRate = "";//税率
                            }
                            else
                            {
 
                                model.TaxRate = (myRow[10].ObjToDecimal() * 100) + "%";//税率
                            }
                            if (string.IsNullOrWhiteSpace(myRow[15].ToString()))
                            {
 
                                model.WeChat = "";//微信
                            }
                            else
                            {
 
                                model.WeChat = myRow[15].ToString();//微信
                            }
 
                            if (string.IsNullOrWhiteSpace(myRow[16].ToString()))
                            {
                                model.Phone = "";//手机
                            }
                            else
                            {
                                model.Phone = myRow[16].ToString();//手机
                            }
                            if (string.IsNullOrWhiteSpace(myRow[17].ToString()))
                            {
 
                                model.PostalCode = "";//单位邮箱
                            }
                            else
                            {
 
                                model.PostalCode = myRow[17].ToString();//单位邮箱
                            }
 
                            if (string.IsNullOrWhiteSpace(myRow[18].ToString()))
                            {
                                model.IsCooperation = true;//是否合作
                            }
                            else
                            {
                                if (myRow[18].ToString().Contains("是"))
                                {
                                    model.IsCooperation = true;//是否合作
                                }
                                else
                                {
                                    model.IsCooperation = false;//是否合作
                                }
                            }
 
                            if (string.IsNullOrWhiteSpace(myRow[19].ToString()))
                            {
                                model.Grade = "";//等级
                            }
                            else
                            {
                                model.Grade = myRow[19].ToString();//等级
                            }
                            if (string.IsNullOrWhiteSpace(myRow[20].ToString()))
                            {
                                model.SysOrgId = _user.SysOrgId;
                            }
                            else
                            {
                                var sysorg = await _SysOrgServices.GetModel(o => o.CompanyName == myRow[20].ToString());
                                if (sysorg != null)
                                {
                                    model.SysOrgId = sysorg.Id;
                                }
                                else
                                {
                                    model.SysOrgId = _user.SysOrgId;
                                }
                            }
 
                            if (string.IsNullOrWhiteSpace(myRow[21].ToString()))
                            {
                                model.Address = "";//经营地址
                            }
                            else
                            {
                                model.Address = myRow[21].ToString();//经营地址
                            }
 
                            if (string.IsNullOrWhiteSpace(myRow[22].ToString()))
                            {
                                model.RegisteredCapital = "";//注册资本
                            }
                            else
                            {
                                model.RegisteredCapital = myRow[22].ToString();//注册资本
                            }
 
                            if (string.IsNullOrWhiteSpace(myRow[23].ToString()))
                            {
                                model.BusinessScope = "";//经营范围
                            }
                            else
                            {
                                model.BusinessScope = myRow[23].ToString();//经营范围
                            }
 
                            if (string.IsNullOrWhiteSpace(myRow[24].ToString()))
                            {
                                model.DateofEstablishment = "";//成立日期
                            }
                            else
                            {
                                model.DateofEstablishment = myRow[24].ToString();//成立日期
                            }
                            model.LeadTime = myRow[8].ObjToInt();//交货周期
                            model.LegalRepresentative = myRow[11].ToString();//法定代表人
                            model.LegalTelephone = myRow[12].ToString();//法人电话
                            model.ConstactPerson = myRow[13].ToString();//联系人
                            model.Position = myRow[14].ToString();//职位
                            model.IsEnable = true;
                            model.CreatedBy = _user.ID;
                            model.Status = 1;
                            model.CreatedTime = DateTime.Now;//创建时间
 
                            var SID = await _wMSupplierServices.Add(model);
                            //myRow[4].ToString();供应商类型
                            if (SID > 0)
                            {
                                if (string.IsNullOrWhiteSpace(myRow[4].ToString()))
                                {
                                    WMSupplier_Type wt = new WMSupplier_Type();
                                    wt.WMSupplierId = SID;
                                    wt.WMSupplierTypeId = 15;
                                    wt.SysOrgId = model.SysOrgId;
                                    wt.IsDeleted = false;
                                    var Tyid = await _wMSupplier_TypeServices.Add(wt);
                                }
                                else
                                {
 
 
                                    var SupplierType = myRow[4].ToString().Split(',');
                                    if (SupplierType.Length > 0)
                                    {
                                        //根据供应商类型循环查出名称插入数据
                                        for (int i = 0; i < SupplierType.Length; i++)
                                        {
                                            var SupTypeName = SupplierType[i].Trim().ToString();
                                            //供应商类型数据
                                            var stype = await _wMSupplierTypeServices.GetModel(t => t.SupTypeName == SupTypeName && t.IsEnable == true);
                                            if (stype != null)
                                            {
                                                WMSupplier_Type wt = new WMSupplier_Type();
                                                wt.WMSupplierId = SID;
                                                wt.WMSupplierTypeId = stype.OASupplierTypeId;
                                                wt.SysOrgId = model.SysOrgId;
                                                wt.IsDeleted = false;
                                                var Tyid = await _wMSupplier_TypeServices.Add(wt);
                                            }
                                            else
                                            {
                                                //供应商类型不存在就插入数据
                                                //WMSupplierType modeltype = new WMSupplierType();
                                                //modeltype.SupTypeName = SupplierType[i].Trim().ToString();
                                                //modeltype.SupTypeShortName = SupplierType[i].Trim().ToString();
                                                //modeltype.IsEnable = true;
                                                //modeltype.SysOrgId = model.SysOrgId;
                                                //modeltype.ParentId = 0;
                                                //modeltype.LevelId = 1;
                                                //var Tid = await _wMSupplierTypeServices.Add(modeltype);
                                                //同时往中间表中插数据
                                                //if (Tid > 0)
                                                //{
                                                //    WMSupplier_Type wt = new WMSupplier_Type();
                                                //    wt.WMSupplierId = SID;
                                                //    wt.WMSupplierTypeId = Tid;
 
                                                //    wt.SysOrgId = model.SysOrgId;
                                                //    var TTyid = await _wMSupplier_TypeServices.Add(wt);
                                                //}
                                            }
                                        }
                                    }
                                }
 
                            }
 
                        }
                        else
                        {
                            ModelSupplier.Name = myRow[1].ToString();//供应商名称
                            ModelSupplier.UnifiedCode = myRow[2].ToString();//统一代码
                            ModelSupplier.SupplierAttributes = myRow[3].ToString();//供应商属性
                            ModelSupplier.PayType = myRow[5].ToString();//支付方式
                            ModelSupplier.MainProducts = myRow[6].ToString();//主营产品(优势产品)
                            ModelSupplier.SettlementmMethod = myRow[7].ToString();//结算方式
                            ModelSupplier.LeadTime = myRow[8].ObjToInt();//交货周期
                            ModelSupplier.InvoiceType = myRow[9].ToString();//发票类型
                            ModelSupplier.TaxRate = (myRow[10].ObjToDecimal() * 100) + "%";//税率
                            ModelSupplier.LegalRepresentative = myRow[11].ToString();//法定代表人
                            ModelSupplier.LegalTelephone = myRow[12].ToString();//法人电话
                            ModelSupplier.ConstactPerson = myRow[13].ToString();//联系人
                            ModelSupplier.Position = myRow[14].ToString();//职位
                            ModelSupplier.WeChat = myRow[15].ToString();//微信
                            ModelSupplier.Phone = myRow[16].ToString();//手机
                            ModelSupplier.PostalCode = myRow[17].ToString();//单位邮箱
                            if (myRow[18].ToString().Contains("是"))
                            {
                                ModelSupplier.IsCooperation = true;//是否合作
                            }
                            else
                            {
                                ModelSupplier.IsCooperation = false;//是否合作
                            }
                            ModelSupplier.Grade = myRow[19].ToString();//等级
                            /*model.SysorgId=myRow[20].ToString();*///主体
                            var sysorg = await _SysOrgServices.GetModel(o => o.CompanyName == myRow[20].ToString());
                            if (sysorg != null)
                            {
                                ModelSupplier.SysOrgId = sysorg.Id;
                            }
                            else
                            {
                                ModelSupplier.SysOrgId = _user.SysOrgId;
                            }
                            ModelSupplier.Address = myRow[21].ToString();//经营地址
                            ModelSupplier.RegisteredCapital = myRow[22].ToString();//注册资本
                            ModelSupplier.BusinessScope = myRow[23].ToString();//经营范围
                            ModelSupplier.DateofEstablishment = myRow[24].ToString();//成立日期
                            ModelSupplier.UpdatedBy = _user.ID;//修改人
                            ModelSupplier.UpdatedTime = DateTime.Now;//修改时间
 
 
                            //获取供应商和供应商类型中间表的所有信息
                            var allWMSupplier_Types = await _wMSupplier_TypeServices.Query(d => d.IsDeleted == false);
                            ModelSupplier.TypeIDs = allWMSupplier_Types.Where(d => d.WMSupplierId == ModelSupplier.Id).Select(d => d.WMSupplierTypeId).ToList();
                            if (ModelSupplier.TypeIDs.Count > 0)
                            {
                                // 无论 Update Or Add , 先删除当前供应商的全部 Supplier_SupplierType 关系
                                var wMSupplier_Types = (await _wMSupplier_TypeServices.Query(d => d.WMSupplierId == ModelSupplier.Id)).Select(d => d.Id.ToString()).ToArray();
                                if (wMSupplier_Types.Count() > 0)
                                {
                                    var isAllDeleted = await _wMSupplier_TypeServices.DeleteByIds(wMSupplier_Types);
                                }
                                // 然后再执行添加操作
                                var SupplierType = myRow[4].ToString().Split(',');
                                if (SupplierType.Length > 0)
                                {
                                    //根据供应商类型循环查出名称插入数据
                                    for (int i = 0; i < SupplierType.Length; i++)
                                    {
                                        var SupTypeName = SupplierType[i].Trim().ToString();
                                        //供应商类型数据
                                        var stype = await _wMSupplierTypeServices.GetModel(t => t.SupTypeName == SupTypeName && t.IsEnable == true);
                                        if (stype != null)
                                        {
                                            WMSupplier_Type wt = new WMSupplier_Type();
                                            wt.WMSupplierId = ModelSupplier.Id;
                                            wt.WMSupplierTypeId = stype.OASupplierTypeId;
                                            wt.SysOrgId = ModelSupplier.SysOrgId;
                                            wt.IsDeleted = false;
                                            var Tyid = await _wMSupplier_TypeServices.Add(wt);
                                        }
                                        else
                                        {
 
                                            //供应商类型不存在就插入数据
                                            //WMSupplierType modeltype = new WMSupplierType();
                                            //modeltype.SupTypeName = SupplierType[i].Trim().ToString();
                                            //modeltype.SupTypeShortName = SupplierType[i].Trim().ToString();
                                            //modeltype.IsEnable = true;
                                            //modeltype.SysOrgId = ModelSupplier.SysOrgId;
                                            //modeltype.ParentId = 0;
                                            //modeltype.LevelId = 1;
                                            //var Tid = await _wMSupplierTypeServices.Add(modeltype);
                                            //同时往中间表中插数据
                                            //if (Tid > 0)
                                            //{
                                            //    WMSupplier_Type wt = new WMSupplier_Type();
                                            //    wt.WMSupplierId = ModelSupplier.Id;
                                            //    wt.WMSupplierTypeId = Tid;
                                            //    wt.SysOrgId = ModelSupplier.SysOrgId;
                                            //    var TTyid = await _wMSupplier_TypeServices.Add(wt);
                                            //}
                                        }
                                    }
                                }
                                var UpID = await _wMSupplierServices.Update(ModelSupplier);
 
                            }
 
 
 
                        }
 
                    }
                    #endregion
                }
                _unitOfWork.CommitTran();
                data.response = 1.ObjToString();
                data.msg = "导入供应商成功";
                data.success = true;
                data.status = 200;
 
 
                return data;
            }
            catch (Exception ex)
            {
                _unitOfWork.RollbackTran();
                _logger.LogError(ex, ex.Message);
                data.msg = ex.Message;
                data.response = 0.ObjToString();
                data.success = false;
                data.status = 500;
                return data;
            }
        }
        #endregion
    }
}