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
using JiepeiWMS.Common;
using JiepeiWMS.Common.Config;
using JiepeiWMS.Common.Enums;
using JiepeiWMS.Common.Helper;
using JiepeiWMS.Common.HttpContextUser;
using JiepeiWMS.Extends;
using JiepeiWMS.IRepository.UnitOfWork;
using JiepeiWMS.IServices;
using JiepeiWMS.Model;
using JiepeiWMS.Model.Models;
using JiepeiWMS.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
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 WMSaleInfoController : ControllerBase
    {
        /// <summary>
        /// 领料申请
        /// </summary>
        private readonly IWMSaleInfoServices _wMSaleInfoServices;
        private readonly IWMSaleDetailServices _wMSaleDetailServices;
        private readonly IWMProductListServices _wMProductListServices;
        private readonly IWMWareHouseServices _wMWareHouseServices;
        private readonly IWMProductInfoServices _wMProductInfoServices;
        private readonly IWMStockLogServices _wMStockLogServices;
        private readonly IWMCheckInfoServices _wMCheckInfoServices;
        private readonly IWMSaleInfoLogServices _wMSaleInfoLogServices;
        private readonly IDepartmentServices _departmentServices;
        private readonly ISysUserInfoServices _sysUserInfoServices;
        private readonly IUser _user;
        private readonly ILogger<WMPurchaseInfoController> _logger;
        private readonly IUnitOfWork _unitOfWork;
        private readonly IRoleServices _roleServices;
        private readonly IUserRoleServices _userRoleServices;
 
        public WMSaleInfoController(
            IWMSaleInfoServices WMSaleInfoServices,
            IWMSaleDetailServices WMSaleDetailServices,
            IWMProductListServices WMProductListServices,
            IWMWareHouseServices WMWareHouseServices,
            IWMProductInfoServices WMProductInfoServices,
            IWMStockLogServices WMStockLogServices,
            IWMCheckInfoServices WMCheckInfoServices,
            IWMSaleInfoLogServices WMSaleInfoLogServices,
            IDepartmentServices DepartmentServices,
            ISysUserInfoServices SysUserInfoServices,
            IUser user,
            ILogger<WMPurchaseInfoController> logger,
            IUnitOfWork unitOfWork,
            IRoleServices RoleServices,
            IUserRoleServices UserRoleServices)
        {
            _wMSaleInfoServices = WMSaleInfoServices;
            _wMSaleDetailServices = WMSaleDetailServices;
            _wMProductListServices = WMProductListServices;
            _wMWareHouseServices = WMWareHouseServices;
            _wMProductInfoServices = WMProductInfoServices;
            _wMStockLogServices = WMStockLogServices;
            _wMCheckInfoServices = WMCheckInfoServices;
            _wMSaleInfoLogServices = WMSaleInfoLogServices;
            _departmentServices = DepartmentServices;
            _sysUserInfoServices = SysUserInfoServices;
            _user = user;
            _logger = logger;
            _unitOfWork = unitOfWork;
            _roleServices = RoleServices;
            _userRoleServices = UserRoleServices;
        }
 
        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="key">关键字</param>
        /// <param name="options">仓库筛选</param>
        /// <param name="typeoptions">类型筛选</param>
        /// <param name="startdate">开始时间筛选</param>
        /// <param name="enddate">结束时间筛选</param>
        /// <param name="statusoptions">审核状态筛选</param>
        /// <param name="page">页数</param>
        /// <param name="intPageSize">条数</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<PageModel<WMSaleInfo>>> Get(string key = "", string options = "", string typeoptions = "", DateTime? startdate = null, DateTime? enddate = null, string statusoptions = "", int page = 1, int intPageSize = 20)
        {
            if (string.IsNullOrWhiteSpace(key))
                key = "";
            if (string.IsNullOrWhiteSpace(options))
                options = "";
            if (string.IsNullOrWhiteSpace(typeoptions))
                typeoptions = "";
            if (string.IsNullOrWhiteSpace(statusoptions))
                statusoptions = "";
 
            var PageList = await _wMSaleInfoServices.GetWMSaleInfoPage(page, intPageSize, key, options, typeoptions, startdate, enddate, statusoptions);
 
            //测试接口
            //var dsdfss = await _wMSaleInfoServices.QueryById(1073);
            //var sdd = await _wMSaleDetailServices.Query(x => x.SaleId == dsdfss.Id);
            //foreach (var item in sdd)
            //{
            //    item.GiveNum = 2;
            //}
            //var s = await _wMSaleInfoServices.BeginMaterialOutInNC(dsdfss, sdd);
 
            return new MessageModel<PageModel<WMSaleInfo>>()
            {
                msg = "获取成功",
                success = PageList.dataCount >= 0,
                response = PageList
            };
        }
 
        /// <summary>
        /// 获取参数
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<MessageModel<object>> GetParams()
        {
            var dicStatus = typeof(EnumWMSaleStatus)._GetValueDescriptionDicFromEnumType<EnumWMSaleStatus>().Select(t => new { Key = t.Key.GetHashCode(), t.Value });
 
            return new MessageModel<object>()
            {
                msg = "获取成功",
                success = true,
                response = new
                {
                    dicStatus
                }
            };
        }
 
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<string>> Post([FromBody] WMSaleInfo request)
        {
            var msg = string.Empty;
            var data = new MessageModel<string>();
            try
            {
                if (request.WareHouseId <= 0)
                {
                    data.msg = "请选择仓库!";
                    return data;
                }
 
                //创建事务
                _unitOfWork.BeginTran();
                int SaleId = 0;
                //根据当前操作人查出用户的model
                var UserModel = await _sysUserInfoServices.GetModel(u => u.uID == _user.ID);
                //查出审批流
                var checkModel = await _wMCheckInfoServices.GetModel(w => w.SysOrgId == _user.SysOrgId && w.Key == "LL");
                if (checkModel != null)
                {
                    request.CheckKey = checkModel.Key;
                }
                else
                {
                    data.msg = "无法获取审批流,请联系管理员!";
                    return data;
                }
 
                var rankList = JsonHelper.DeserializeObject<CheckRankList>(checkModel.Json);
                if (rankList.checkRankList.Where(w => w.CheckRank == 1).FirstOrDefault() == null)
                {
                    data.msg = "请先配置审批人!";
                    return data;
                }
                if (request.noMatchData.Count <= 0)
                {
                    data.msg = "请选择商品信息!";
                    return data;
                }
 
                var code = await _wMSaleInfoServices.GetSaleInfoMaxId();
                request.SaleCode = "SUOI000" + (code + 1);
                request.EmployeeId = _user.ID;
                request.CreateTime = DateTime.Now;
 
                if (request.PayType == 1)
                {
                    request.CheckRank = 1;
                    request.CheckAdminId = rankList.checkRankList.Where(w => w.CheckRank == 1).FirstOrDefault().AdminId;
                    request.Status = EnumWMSaleStatus.WaitCheck.GetHashCode();
                }
                else
                {
                    request.Status = EnumWMSaleStatus.OutWareHouse.GetHashCode();
                }
 
                request.SysOrgId = _user.SysOrgId;
 
                //获取所有商品
                foreach (var item in request.noMatchData)
                {
                    if (item.WNum <= 0)
                    {
                        _unitOfWork.RollbackTran();
                        data.msg = "商品数量不能小于0!";
                        return data;
                    }
                    if (item.Quantity < 1)
                    {
                        _unitOfWork.RollbackTran();
                        data.msg = "其中有库存数量不足的商品将无法出库!";
                        return data;
                    }
                    if (item.WNum > item.Quantity)
                    {
                        _unitOfWork.RollbackTran();
                        data.msg = "输入的商品数量不能超过库存数量!";
                        return data;
                    }
 
 
                    WMSaleDetail SaleDetail = new WMSaleDetail
                    {
                        CheckNum = item.WNum,
                        Price = 0,
                        Amount = 0,
                        Quantity = item.WNum,
                        ApprovalNum = item.WNum,
                        //ActualNum = item.WNum,
                        CreateTime = DateTime.Now,
                        SaleId = code + 1,
                        ProductId = item.Id,
                        SysOrgId = request.SysOrgId
                    };
 
                    if (request.PayType == 1)
                    {
                        SaleDetail.Status = EnumWMSaleStatus.WaitCheck.GetHashCode();
                    }
                    else
                    {
                        SaleDetail.Status = EnumWMSaleStatus.OutWareHouse.GetHashCode();
 
                        //出库的库存为0默认不做出库操作
                        decimal oldStorageNum = 0, newStorageNum = 0;//旧库存  新库存
                        decimal oldTotalPrice = 0, newTotalPrice, AvgPrice = 0;//旧总价  新总价  平均单价
                        var ProductInfo = await _wMProductInfoServices.GetModel(w => w.ProductListId == item.Id && w.WareHouseId == request.WareHouseId);
                        var ProductListInfo = await _wMProductListServices.QueryById(ProductInfo.ProductListId);
 
                        //期初 旧库存  *  旧单价  =  旧总额
                        //库存商品新增库存数量
                        oldStorageNum = ProductInfo.Quantity.Value;//旧库存
                        oldTotalPrice = oldStorageNum * ProductListInfo.Price;//旧总额
 
                        //新台账总额  = 领料出库库存  *  领料出库新单价
                        newTotalPrice = item.WNum * ProductListInfo.Price;
 
                        //新库存总额  = 新库存  *  单价
                        ProductInfo.Quantity = ProductInfo.Quantity - item.WNum;
                        newStorageNum = ProductInfo.Quantity.Value;//新库存
 
                        //库存总额 = 老得库存总额  -  新得台账总额
                        var TotalPrice = oldTotalPrice - newTotalPrice;
                        if (newStorageNum <= 0)
                            AvgPrice = ProductListInfo.Price;
                        else
                            AvgPrice = TotalPrice / newStorageNum;//现有库存平均单价
 
                        ProductListInfo.Price = AvgPrice;//平均单价赋值
                        await _wMProductInfoServices.Update(ProductInfo);
                        await _wMProductListServices.Update(ProductListInfo);
 
                        //增加库存流水日志
                        //WMStockLog StockLog = new WMStockLog
                        //{
                        //    Id = 0,
                        //    ProductId = ProductInfo.Id,
                        //    Type = EnumWMStockType.SaleStock.GetHashCode(),
                        //    Operation = 1,
                        //    Quantity = item.WNum,
                        //    Price = item.Price,
                        //    TotalPrice = newTotalPrice,
                        //    RemainQuantity = ProductInfo.Quantity,
                        //    RemainPrice = AvgPrice,
                        //    TotalRemainPrice = oldTotalPrice,
                        //    AdminId = _user.ID,
                        //    CreateTime = DateTime.Now,
                        //    ProductListId = ProductInfo.ProductListId,
                        //    ProductSpecId = ProductInfo.ProductSpecId,
                        //    WareHouseId = request.WareHouseId,
                        //    Remark = "【商品出库】减少库存:" + item.WNum + " -> 出库商品单价:" + item.Price,
                        //    OrderId = SaleId,
                        //    DepId = UserModel.DepartmentId
                        //};
                        //await _wMStockLogServices.Add(StockLog);
                    }
                    var pid = await _wMSaleDetailServices.Add(SaleDetail);
                }
 
                var result = await _wMSaleInfoServices.Add(request);
                if (result > 0)
                {
                    var id = await _wMSaleInfoLogServices.Add(new WMSaleInfoLog
                    {
                        AdminId = _user.ID,
                        OrderId = result,
                        Type = 1,
                        Content = "【领料审批】设置状态为" + ((EnumWMSaleStatus)request.Status)._GetDescriptionByEnumValue(),
                        CreateTime = DateTime.Now
                    });
                    data.success = id > 0;
                }
                _unitOfWork.CommitTran();
                if (data.success)
                {
                    data.response = result.ObjToString();
                    data.msg = "领料单添加成功!";
                }
 
                return data;
            }
            catch (Exception e)
            {
                _unitOfWork.RollbackTran();
                _logger.LogError(e, e.Message);
                return data;
            }
        }
 
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<MessageModel<string>> Put([FromBody] WMSaleInfo request)
        {
            var data = new MessageModel<string>();
            if (request.Id > 0)
            {
                data.success = await _wMSaleInfoServices.Update(request);
                if (data.success)
                {
                    data.msg = "更新成功";
                    data.response = request?.Id.ObjToString();
                }
            }
 
            return data;
        }
 
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<MessageModel<string>> Delete(int id = 0)
        {
            var data = new MessageModel<string>();
            if (id > 0)
            {
                var detail = await _wMSaleInfoServices.QueryById(id);
                if (detail != null)
                {
                    data.success = await _wMSaleInfoServices.Update(detail);
                    if (data.success)
                    {
                        data.msg = "删除成功";
                        data.response = detail?.Id.ObjToString();
                    }
                }
            }
 
            return data;
        }
 
        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<WMSaleInfo>> Detail(int Id = 0)
        {
            var model = await _wMSaleInfoServices.GetWMSaleInfo(Id);
 
            foreach (var item in model.SaleDetailList)
            {
                var ProductInfoModel = await _wMProductInfoServices.GetProductInfoByListId(item.ProductId, model.WareHouseId);
                if (ProductInfoModel != null)
                {
                    item.StockNum = ProductInfoModel.Quantity;
                    item.WeekNum = await _wMStockLogServices.GetStockNumByDateDay(item.ProductId, ProductInfoModel.Id, 7, 2);
                    item.MonthNum = await _wMStockLogServices.GetStockNumByDateDay(item.ProductId, ProductInfoModel.Id, 30, 2);
                }
            }
 
            return new MessageModel<WMSaleInfo>()
            {
                msg = "获取成功",
                success = true,
                response = model
            };
        }
 
        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<MessageModel<string>> SaleCheck([FromBody] WMSaleInfo request)
        {
            bool flag = false;
            var data = new MessageModel<string>();
            var NEWSaleDetailList = new List<WMSaleDetail>();
            var content = "";
            try
            {
                var model = await _wMSaleInfoServices.QueryById(request.Id);
                if (model != null)
                {
                    if (model.Status == EnumWMSaleStatus.CheckedNoPass.GetHashCode())
                    {
                        data.msg = "当前订单已审核为不通过!";
                        return data;
                    }
                    var checkModel = await _wMCheckInfoServices.GetModel(x => x.SysOrgId == _user.SysOrgId && x.Key == model.CheckKey);
                    if (checkModel == null)
                    {
                        data.msg = "暂无该部门审批流,请先申请配置!";
                        return data;
                    }
                    if (_user.ID != model.CheckAdminId)
                    {
                        data.msg = "非审批人,审批失败!";
                        return data;
                    }
 
                    //创建事务
                    _unitOfWork.BeginTran();
                    var rankList = JsonHelper.DeserializeObject<CheckRankList>(checkModel.Json);
                    foreach (var item in rankList.checkRankList)
                    {    //审批人跟审批级别是否一一对应
                        if (!flag)
                        {
                            if (model.CheckRank == item.CheckRank)
                            {
                                flag = true;
                                //设置下次审批
                                int index = rankList.checkRankList.IndexOf(item) + 1; //index为索引值
                                if (rankList.checkRankList.Count > 1 && rankList.checkRankList.Count > index)
                                {
                                    model.CheckRank = rankList.checkRankList[index].CheckRank;
                                    model.CheckAdminId = rankList.checkRankList[index].AdminId;
                                }
 
                                //获取所有商品
                                if (request.SaleDetailList.Count <= 0)
                                {
                                    data.msg = "暂无待审核得商品";
                                    return data;
                                }
                                foreach (var tableItem in request.SaleDetailList)
                                {
                                    if (tableItem.Checked == 0)
                                    {
                                        _unitOfWork.RollbackTran();
                                        data.msg = "请选择审核状态!";
                                        return data;
                                    }
                                    if (tableItem.CheckNum <= 0)
                                    {
                                        _unitOfWork.RollbackTran();
                                        data.msg = "审批数量不能小于0!";
                                        return data;
                                    }
                                    //if (tableItem.StockNum < 1)
                                    //{
                                    //    _unitOfWork.RollbackTran();
                                    //    data.msg = "其中有库存数量不足的商品将无法出库!";
                                    //    return data;
                                    //}
                                    //if (tableItem.CheckNum > tableItem.StockNum)
                                    //{
                                    //    _unitOfWork.RollbackTran();
                                    //    data.msg = "输入的审批数量不能超过库存数量!";
                                    //    return data;
                                    //}
 
                                    var SaleDetailModel = await _wMSaleDetailServices.QueryById(tableItem.Id);
                                    if (SaleDetailModel == null || SaleDetailModel.Status == EnumWMSaleStatus.CheckedNoPass.GetHashCode())
                                        continue;
 
                                    var ProductListMdoel = await _wMProductListServices.QueryById(tableItem.ProductId);
                                    var ProductInfoModel = await _wMProductInfoServices.GetModel(x => x.ProductListId == tableItem.ProductId && x.WareHouseId == model.WareHouseId);
                                    #region 领料数量审批
                                    if (tableItem.Checked == 2 || ProductInfoModel.Quantity < 1 || tableItem.CheckNum > ProductInfoModel.Quantity || ProductListMdoel == null || ProductListMdoel.IsUse == false)
                                    {
                                        SaleDetailModel.Status = EnumWMSaleStatus.CheckedNoPass.GetHashCode();
                                    }
                                    else
                                    {
                                        if (rankList.checkRankList.Count > 1 && rankList.checkRankList.Count > index)
                                            SaleDetailModel.Status = EnumWMSaleStatus.Checking.GetHashCode();
                                        else
                                            SaleDetailModel.Status = EnumWMSaleStatus.CheckedPass.GetHashCode();
                                    }
                                    #endregion
 
                                    //审核数量有变动则写进操作日志里
                                    if (tableItem.CheckNum != SaleDetailModel.Quantity)
                                    {
                                        content += ",商品名称:" + ProductListMdoel.Name + ",审核数量:" + SaleDetailModel.Quantity.ObjToInt() + "->" + tableItem.CheckNum;
                                    }
                                    SaleDetailModel.Quantity = tableItem.CheckNum;
                                    //SaleDetailModel.ActualNum = tableItem.CheckNum;
                                    SaleDetailModel.ApprovalNum = tableItem.CheckNum;
                                    SaleDetailModel.Remark = tableItem.SaleDetailRemark;
                                    SaleDetailModel.UpdateTime = DateTime.Now;
 
                                    NEWSaleDetailList.Add(SaleDetailModel);
                                    await _wMSaleDetailServices.Update(SaleDetailModel);
                                }
 
                                #region 修改审批订单状态
                                //审核中
                                var CheckingList = NEWSaleDetailList.Where(p => p.Status == EnumWMSaleStatus.Checking.GetHashCode()).ToList();
                                //审核不通过
                                var CheckedNoPassList = NEWSaleDetailList.Where(p => p.Status == EnumWMSaleStatus.CheckedNoPass.GetHashCode()).ToList();
                                //审核通过
                                var CheckedPassList = NEWSaleDetailList.Where(p => p.Status == EnumWMSaleStatus.CheckedPass.GetHashCode()).ToList();
                                var listCount = CheckingList.Count + CheckedNoPassList.Count + CheckedPassList.Count;
                                if (CheckingList.Count > 0)
                                    model.Status = EnumWMSaleStatus.Checking.GetHashCode();
                                else
                                {
                                    if ((listCount == NEWSaleDetailList.Count) && CheckedPassList.Count > 0)
                                    {
                                        model.Status = EnumWMSaleStatus.CheckedPass.GetHashCode();
                                        model.CheckAdminId = 0;
                                        model.CheckRank = 0;
                                    }
                                    else
                                    {
                                        if (listCount == NEWSaleDetailList.Count || CheckedNoPassList.Count > 0)
                                        {
                                            model.Status = EnumWMSaleStatus.CheckedNoPass.GetHashCode();
                                            model.CheckAdminId = 0;
                                        }
                                    }
                                }
                                #endregion
                            }
                        }
                    }
 
                    var id = await _wMSaleInfoLogServices.Add(new WMSaleInfoLog
                    {
                        AdminId = _user.ID,
                        OrderId = model.Id,
                        Type = 1,
                        Content = "【领料审批】设置状态为" + ((EnumWMSaleStatus)model.Status)._GetDescriptionByEnumValue() + content,
                        CreateTime = DateTime.Now
                    });
                    model.UpdateTime = DateTime.Now;
                    data.success = await _wMSaleInfoServices.Update(model);
                    _unitOfWork.CommitTran();
                    if (data.success)
                    {
                        data.response = model.Id.ObjToString();
                        data.msg = "审核成功!";
                    }
                }
                return data;
            }
            catch (Exception e)
            {
                _unitOfWork.RollbackTran();
                _logger.LogError(e, e.Message);
                return data;
            }
        }
 
        /// <summary>
        /// 出库详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<WMSaleInfo>> OutDetail(int Id = 0)
        {
            var model = await _wMSaleInfoServices.GetWMSaleInfo(Id);
            model.SaleDetailList = model.SaleDetailList.Where(x => x.Status != EnumWMSaleStatus.CheckedNoPass.GetHashCode()).ToList();
 
            foreach (var item in model.SaleDetailList)
            {
                var ProductInfoModel = await _wMProductInfoServices.GetProductInfoByListId(item.ProductId, model.WareHouseId);
                if (ProductInfoModel != null)
                {
                    item.StockNum = ProductInfoModel.Quantity;
                    //item.WeekNum = await _wMStockLogServices.GetStockNumByDateDay(item.ProductId, ProductInfoModel.Id, 7, 2);
                    //item.MonthNum = await _wMStockLogServices.GetStockNumByDateDay(item.ProductId, ProductInfoModel.Id, 30, 2);
                }
            }
 
            var userrolemodel = await _userRoleServices.GetModel(r => r.UserId == _user.ID);
            if (userrolemodel != null)
            {
                var rolemodel = await _roleServices.QueryById(userrolemodel.RoleId);
                if (rolemodel != null && rolemodel.Name == RoleConfig.SaleCangKuStaff)
                {
                    model.MayOut = true;//显示出库按钮
                }
            }
 
            return new MessageModel<WMSaleInfo>()
            {
                msg = "获取成功",
                success = true,
                response = model
            };
        }
 
        /// <summary>
        /// 出库
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<MessageModel<string>> SaleOut([FromBody] WMSaleInfo request)
        {
            var msg = string.Empty;
            var data = new MessageModel<string>();
            try
            {
                decimal oldStorageNum = 0, newStorageNum = 0;//旧库存  新库存
                decimal oldTotalPrice = 0, newTotalPrice, AvgPrice = 0;//旧总价  新总价  平均单价
 
                if (request.Status < EnumWMSaleStatus.CheckedPass.GetHashCode())
                {
                    data.msg = "审核通过才能出库!";
                    return data;
                }
                var userrolemodel = await _userRoleServices.GetModel(r => r.UserId == _user.ID);
                if (userrolemodel != null)
                {
                    var rolemodel = await _roleServices.QueryById(userrolemodel.RoleId);
                    if (rolemodel != null && rolemodel.Name != RoleConfig.SaleCangKuStaff)
                    {
                        data.msg = "只有仓库管理员才能出库!";
                        return data;
                    }
                }
                else
                {
                    data.msg = "未获取到可出库的用户!";
                    return data;
                }
 
                request.Status = EnumWMSaleStatus.Finish.GetHashCode();
 
                //创建事务
                _unitOfWork.BeginTran();
 
                var MaterialOutResult = new Tuple<string, bool>("", true);
                //根据配置是否调用NC接口
                var NCInterfaceSecret = Appsettings.app("AppSettings", "NCInterfaceSecret").ToString();
                if (NCInterfaceSecret == "True")
                    //调NC物料出库接口
                    MaterialOutResult = await _wMSaleInfoServices.BeginMaterialOutInNC(request, request.SaleDetailList);
                if (!MaterialOutResult.Item2 && !string.IsNullOrWhiteSpace(MaterialOutResult.Item1))
                {
                    _unitOfWork.RollbackTran();
                    data.msg = MaterialOutResult.Item1;
                    return data;
                }
 
                //获取所有商品
                foreach (var item in request.SaleDetailList)
                {
                    var SaleDetailModel = await _wMSaleDetailServices.QueryById(item.Id);
                    if (SaleDetailModel.Status == EnumWMSaleStatus.CheckedNoPass.GetHashCode())
                        continue;
 
                    if (item.GiveNum < 0)
                    {
                        _unitOfWork.RollbackTran();
                        data.msg = "输入的实发数量不能小于0!";
                        return data;
                    }
                    if (item.GiveNum > item.StockNum)
                    {
                        _unitOfWork.RollbackTran();
                        data.msg = "输入的实发数量不能超过库存数量!";
                        return data;
                    }
                    //if (item.GiveNum > item.ActualNum)
                    //{
                    //    _unitOfWork.RollbackTran();
                    //    data.msg = "输入的实发数量不能超过出库数量!";
                    //    return data;
                    //}
                    //库存商品减少库存数量
                    var ProductInfoModel = await _wMProductInfoServices.GetProductInfoByListId(SaleDetailModel.ProductId, request.WareHouseId);
                    if (ProductInfoModel == null)
                    {
                        _unitOfWork.RollbackTran();
                        data.msg = "未获取到商品库存!";
                        return data;
                    }
                    if (ProductInfoModel.Quantity < item.GiveNum)
                    {
                        _unitOfWork.RollbackTran();
                        data.msg = "库存不足将无法出库!";
                        return data;
                    }
 
                    //期初 旧库存  *  旧单价  =  旧总额
                    var ProductListModel = await _wMProductListServices.QueryById(ProductInfoModel.ProductListId);
                    oldStorageNum = ProductInfoModel.Quantity.Value;//旧库存
                    oldTotalPrice = oldStorageNum * ProductListModel.Price;//旧总额
 
                    //新台账总额    =  领料出库库存  * 领料出库新单价
                    newTotalPrice = item.GiveNum.Value * ProductListModel.Price;
 
                    //新库存总额     = 新库存   *   单价
                    ProductInfoModel.Quantity = ProductInfoModel.Quantity - item.GiveNum.Value;
                    newStorageNum = ProductInfoModel.Quantity.Value;//新库存
 
                    //库存总额 = 老得库存总额 - 新得台账总额
                    var TotalPrice = oldTotalPrice - newTotalPrice;
 
                    if (newStorageNum <= 0)
                        AvgPrice = ProductListModel.Price;
                    else
                        AvgPrice = TotalPrice / newStorageNum;//现有库存平均单价
 
                    SaleDetailModel.Status = EnumWMSaleStatus.Finish.GetHashCode();
                    SaleDetailModel.ActualNum = item.GiveNum;
 
                    //增加库存流水日志
                    WMStockLog StockLog = new WMStockLog();
                    StockLog.Id = 0;
                    StockLog.ProductId = ProductInfoModel.Id;
                    StockLog.Type = EnumWMStockType.SaleStock.GetHashCode();
                    StockLog.Operation = 2;
                    StockLog.Quantity = item.GiveNum;
                    StockLog.Price = ProductListModel.Price;
                    StockLog.TotalPrice = newTotalPrice;
                    StockLog.RemainQuantity = ProductInfoModel.Quantity != null ? ProductInfoModel.Quantity.Value : 0;
                    StockLog.RemainPrice = AvgPrice;
                    StockLog.TotalRemainPrice = TotalPrice;
                    StockLog.AdminId = _user.ID;
                    StockLog.CreateTime = DateTime.Now;
                    StockLog.ProductListId = ProductInfoModel.ProductListId;
                    StockLog.ProductSpecId = ProductInfoModel.ProductSpecId;
                    StockLog.WareHouseId = request.WareHouseId;
                    StockLog.OrderId = request.Id;
                    StockLog.Remark = "【商品出库】减少库存:" + item.GiveNum.Value;
                    var DepartmentModel = await _departmentServices.QueryById(request.DepartmentId.Value);
                    if (DepartmentModel != null)
                        StockLog.DepId = DepartmentModel.Id;
 
                    ProductListModel.Price = AvgPrice;
                    await _wMStockLogServices.Add(StockLog);
                    await _wMProductInfoServices.Update(ProductInfoModel);
                    await _wMProductListServices.Update(ProductListModel);
                    await _wMSaleDetailServices.Update(SaleDetailModel);
                }
                await _wMSaleInfoServices.Update(request);
 
                var id = await _wMSaleInfoLogServices.Add(new WMSaleInfoLog
                {
                    AdminId = _user.ID,
                    OrderId = request.Id,
                    Type = 1,
                    Content = "【领料出库】设置状态为" + ((EnumWMSaleStatus)request.Status)._GetDescriptionByEnumValue(),
                    CreateTime = DateTime.Now
                });
                data.success = id > 0;
                _unitOfWork.CommitTran();
 
                if (data.success)
                {
                    data.msg = "领料单出库成功!";
                    data.response = id.ObjToString();
                }
 
                return data;
            }
            catch (Exception e)
            {
                _unitOfWork.RollbackTran();
                _logger.LogError(e, e.Message);
                return data;
            }
        }
 
        /// <summary>
        /// 设置交易完成
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<MessageModel<string>> SaleSetFinish([FromBody] WMSaleInfo request)
        {
            var msg = string.Empty;
            var data = new MessageModel<string>();
            try
            {
                if (request == null)
                {
                    data.msg = "当前订单不存在!";
                    return data;
                }
                if (request.Status == EnumWMSaleStatus.CheckedNoPass.GetHashCode())
                {
                    data.msg = "当前订单已审核,为审核不通过!";
                    return data;
                }
                //获取审批流
                var checkModel = await _wMCheckInfoServices.GetModel(x => x.SysOrgId == _user.SysOrgId && x.Key == request.CheckKey);
                if (checkModel == null)
                {
                    data.msg = "暂无该部门审批流,请先申请配置!";
                    return data;
                }
 
                #region 状态判断
                //获取所有商品
                var SaleDetailList = await _wMSaleDetailServices.Query(x => x.SaleId == request.Id);
                foreach (var item in SaleDetailList)
                {
                    if (item.Status != EnumWMSaleStatus.CheckedNoPass.GetHashCode())
                        item.Status = EnumWMSaleStatus.Finish.GetHashCode();
                }
                #endregion
 
                #region 修改报价订单状态为(交易成功)
                //采购订单中的商品——》审核不通过
                var CheckedNoPassList = SaleDetailList.Where(p => p.Status == EnumWMSaleStatus.CheckedNoPass.GetHashCode()).ToList<WMSaleDetail>();
                //采购订单中的商品——》交易成功
                var FinishList = SaleDetailList.Where(p => p.Status == EnumWMSaleStatus.Finish.GetHashCode()).ToList<WMSaleDetail>();
 
                #region 修改状态(交易成功)
                //交易成功 = 审核不通过 + 交易成功
                var FinishListCount = CheckedNoPassList.Count + FinishList.Count;
                if (FinishListCount == SaleDetailList.Count)
                    request.Status = EnumWMSaleStatus.Finish.GetHashCode();//交易成功
                #endregion
                #endregion
 
                var result = await _wMSaleInfoServices.Update(request);
                var result1 = await _wMSaleDetailServices.Update(SaleDetailList);
                if (result == true && result1 == true)
                {
                    var id = await _wMSaleInfoLogServices.Add(new WMSaleInfoLog
                    {
                        AdminId = _user.ID,
                        OrderId = request.Id,
                        Type = 1,
                        Content = "【交易成功】设置状态为" + ((EnumWMSaleStatus)request.Status)._GetDescriptionByEnumValue(),
                        CreateTime = DateTime.Now
                    });
                    data.success = id > 0;
                    _unitOfWork.CommitTran();
 
                    if (data.success)
                    {
                        data.response = id.ObjToString();
                        data.msg = "设置交易完成成功!";
                    }
                }
 
                return data;
            }
            catch (Exception e)
            {
                _unitOfWork.RollbackTran();
                _logger.LogError(e, e.Message);
                return data;
            }
        }
 
        /// <summary>
        /// 操作日志
        /// </summary>
        /// <param name="page"></param>
        /// <param name="intPageSize"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<PageModel<WMSaleInfoLog>>> SaleLog(int page = 1, int intPageSize = 10, int id = 0)
        {
            Expression<Func<WMSaleInfoLog, bool>> whereExpression = SaleInfoLog => SaleInfoLog.OrderId == id;
 
            var PageList = await _wMSaleInfoLogServices.QueryTabsPage<WMSaleInfoLog, sysUserInfo, WMSaleInfo, WMSaleInfoLog>
                (
                (SaleInfoLog, UserInfo, SaleInfo) => new object[]
                {
                    JoinType.Left,SaleInfoLog.AdminId==UserInfo.uID,
                    JoinType.Left,SaleInfoLog.OrderId==SaleInfo.Id,
                },
                (SaleInfoLog, UserInfo, SaleInfo) => new WMSaleInfoLog
                {
                    AdminId = SaleInfoLog.AdminId,
                    Content = SaleInfoLog.Content,
                    CreateTime = SaleInfoLog.CreateTime,
                    OrderId = SaleInfoLog.OrderId,
                    Type = SaleInfoLog.Type,
                    UserName = UserInfo.uRealName,
                },
                whereExpression,
                page,
                intPageSize,
                " SaleInfoLog.Id desc"
                );
            return new MessageModel<PageModel<WMSaleInfoLog>>()
            {
                msg = "获取成功",
                success = PageList.dataCount > 0,
                response = PageList
            };
        }
 
        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        [AllowAnonymous]
        public async Task<MessageModel<string>> DeleteProductList(int id = 0)
        {
            var data = new MessageModel<string>();
            if (id > 0)
            {
                var SaleDetailModel = await _wMSaleDetailServices.QueryById(id);
                if (SaleDetailModel == null)
                {
                    data.msg = "未获取到该出库商品";
                    return data;
                }
 
                data.success = await _wMSaleDetailServices.DeleteById(id);
                if (data.success)
                {
                    var SaleInfoModel = await _wMSaleInfoServices.QueryById(SaleDetailModel.SaleId);
                    if (SaleInfoModel.EmployeeId != _user.ID)
                    {
                        data.msg = "不是当前领料人将无法删除商品";
                        return data;
                    }
 
                    var SaleDetailList = await _wMSaleDetailServices.Query(x => x.SaleId == SaleInfoModel.Id);
                    if (SaleDetailList.Count() == 0)
                    {
                        SaleInfoModel.Status = EnumWMSaleStatus.Cancellation.GetHashCode();
                        await _wMSaleInfoServices.Update(SaleInfoModel);
                    }
 
                    data.msg = "删除商品成功";
                    data.response = SaleDetailModel?.Id.ObjToString();
                }
            }
            return data;
        }
 
    }
}