yanjinhui
6 天以前 5b8bf171b9afda52fa366a72e54eedbd9e6d4d17
н¨Îļþ¼Ð/WIDESEA_WMSServer/WIDESEA_SquareCabinServices/DeliveryOrderServices.cs
@@ -34,19 +34,20 @@
{
    public partial class DeliveryOrderServices : ServiceBase<Dt_DeliveryOrder, IRepository<Dt_DeliveryOrder>>, IDeliveryOrderServices
    {
        static string SearchDate = "";
        private readonly IBasicService _basicService;
        private readonly ICabinOrderServices _cabinOrderServices;
        private readonly IUnitOfWorkManage _unitOfWorkManage;
        private readonly IInventory_BatchServices _inventory_BatchServices;
        private readonly ILocationInfoService _locationInfoService;
        private readonly IInventoryInfoService _inventoryInfoService;
        private readonly IDeliveryOrderDetailServices _deliveryOrderDetailServices;
        private readonly ISupplyTaskService _supplyTaskService;
        private readonly ICabinOrderServices _cabinOrderServices;
        private readonly ISupplyTaskHtyService _supplyTaskHtyService;
        private readonly ITacticsService _tacticsService;
        private readonly IMaterielInfoService _materielInfoService;
        private readonly IMessageInfoService _messageInfoService;
        public IRepository<Dt_DeliveryOrder> Repository => BaseDal;
        public DeliveryOrderServices(IRepository<Dt_DeliveryOrder> BaseDal, IBasicService basicService, IUnitOfWorkManage unitOfWorkManage, IInventory_BatchServices inventory_BatchServices, IInventoryInfoService inventoryInfoService, IDeliveryOrderDetailServices deliveryOrderDetailServices, ISupplyTaskService supplyTaskService, ICabinOrderServices cabinOrderServices, ITacticsService tacticsService) : base(BaseDal)
        public DeliveryOrderServices(IRepository<Dt_DeliveryOrder> BaseDal, IUnitOfWorkManage unitOfWorkManage, IInventory_BatchServices inventory_BatchServices, IInventoryInfoService inventoryInfoService, IDeliveryOrderDetailServices deliveryOrderDetailServices, ISupplyTaskService supplyTaskService, ICabinOrderServices cabinOrderServices, ITacticsService tacticsService, ISupplyTaskHtyService supplyTaskHtyService, IMessageInfoService messageInfoService, IMaterielInfoService materielInfoService, ILocationInfoService locationInfoService) : base(BaseDal)
        {
            _basicService = basicService;
            _unitOfWorkManage = unitOfWorkManage;
            _deliveryOrderDetailServices = deliveryOrderDetailServices;
            _supplyTaskService = supplyTaskService;
@@ -54,106 +55,12 @@
            _inventoryInfoService = inventoryInfoService;
            _cabinOrderServices = cabinOrderServices;
            _tacticsService = tacticsService;
            _supplyTaskHtyService = supplyTaskHtyService;
            _messageInfoService = messageInfoService;
            _materielInfoService = materielInfoService;
            _locationInfoService = locationInfoService;
        }
        public WebResponseContent GetUpstreamOutOrder()
        {
            var responseContent = new WebResponseContent();
            try
            {
                var url = "http://121.37.118.63:80/GYZ2/95fck/outOrder";
                //var url = "http://127.0.0.1:4523/m1/5660322-5340849-default/GYZ2/95fck/outOrder";
                if (string.IsNullOrEmpty(SearchDate)) SearchDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                //// è¯·æ±‚参数
                var requestData = new
                {
                    searchDate = SearchDate
                    //searchDate = "2022-10-10 20:45:16"  // æ­£ç¡®çš„æ ¼å¼
                };
                SearchDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss");
                var result = HttpHelper.Post(url, requestData.ToJsonString());
                var response = JsonConvert.DeserializeObject<UpstreamResponse<UpstramOutOrderInfo>>(result);
                if (response.resultCode != "0")
                {
                    SendErrorToUpstream(3, "", response.resultMsg ?? "上游接口返回失败", "");
                    return responseContent.Error(response.resultMsg ?? "上游接口返回失败");
                }
                if (response.data == null || !response.data.Any())
                {
                    return responseContent.OK("无新出库单数据");
                }
                // å·²å­˜åœ¨å‡ºåº“单号
                var existingOutOrderNos = BaseDal.Db.Queryable<Dt_DeliveryOrder>()
                    .Select(x => x.Out_no)
                    .ToList();
                // æ–°å‡ºåº“单
                var newOutOrders = response.data
                    .Where(outorder => !existingOutOrderNos.Contains(outorder.order_no))
                    .ToList();
                List<string> order_no = newOutOrders.Select(x => x.order_no).ToList();
                if (!newOutOrders.Any())
                {
                    return responseContent.OK("所有出库单已存在,无需新增");
                }
                Db.Ado.BeginTran();
                try
                {
                    List<Dt_DeliveryOrder> _DeliveryOrders = new List<Dt_DeliveryOrder>();
                    List<string> orderNos = new List<string>();
                    foreach (var outorder in newOutOrders)
                    {
                        bool skipOrder = false; // æ ‡è®°æ˜¯å¦è·³è¿‡è¯¥å‡ºåº“单
                        // å¦‚果这个出库单类型不等于1,属于出库退货(要入货上游传过来的数量为负数)
                        if (outorder.order_type != "1")
                        {
                            // åˆ›å»ºå‡ºåº“退货单 - è¿™é‡Œéœ€è¦æ ¹æ®ä¸šåŠ¡é€»è¾‘å®žçŽ°
                            // æš‚时跳过或实现退货逻辑
                            continue;
                        }
                        else if (outorder.order_type == "1") // æ­£å¸¸å‡ºåº“单
                        {
                            CreateOutboundOrder(outorder);//创建出库单、处理库存、添加出库任务
                        }
                    }
                    // æ‰¹é‡æ’入出库单和明细
                    if (_DeliveryOrders.Any())
                    {
                        BaseDal.Db.InsertNav(_DeliveryOrders).Include(x => x.Details).ExecuteCommand();
                    }
                    //下发出库单任务给wcs
                    Db.Ado.CommitTran();
                    var tex = CreateSupplyTask(order_no);
                    if (!tex)
                    {
                        return responseContent.Error("创建供应任务失败");
                    }
                    return responseContent.OK($"同步出库单成功,共{_DeliveryOrders.Count}条");
                }
                catch (Exception ex)
                {
                    Db.Ado.RollbackTran();
                    SendErrorToUpstream(3, "", ex.Message, "");
                    return responseContent.Error("同步失败: " + ex.Message);
                }
            }
            catch (Exception ex)
            {
                SendErrorToUpstream(3, "", ex.Message, "");
                return responseContent.Error("同步失败: " + ex.Message);
            }
        }
        #region åˆ›å»ºå‡ºåº“单
        /// <summary>
        /// åˆ›å»ºå‡ºåº“单
        /// </summary>
@@ -165,7 +72,10 @@
            try
            {
                Dt_Tactics tactics = _tacticsService.Repository.QueryFirst(x => x.TacticeName == "出库策略");
                if (outorder.warehouse_no == WarehouseEnum.麻精库.ObjToInt().ToString("000") || outorder.warehouse_no == WarehouseEnum.冷冻库.ObjToInt().ToString("000"))
                #region ç‰¹æ®Šåº“房出库
                string WareCodeMJ = WarehouseEnum.麻精库.ObjToInt().ToString("000");
                string WareCodeLD = WarehouseEnum.冷冻库.ObjToInt().ToString("000");
                if (outorder.warehouse_no == WareCodeMJ || outorder.warehouse_no == WareCodeLD)
                {
                    #region æ·»åŠ å‡ºåº“å•
                    var entityOrder = new Dt_DeliveryOrder
@@ -188,17 +98,22 @@
                            Status = 2, // pad平库,无需同步
                        }).ToList()
                    };
                    BaseDal.Db.InsertNav(entityOrder).Include(x => x.Details).ExecuteCommand();
                    #endregion
                    #region å¤„理库存、库存批次、添加出库任务
                    List<Dt_SupplyTask> supplyTasks = new List<Dt_SupplyTask>();
                    List<Dt_Inventory_Batch> batchesUp = new List<Dt_Inventory_Batch>();
                    List<Dt_InventoryInfo> inventoryInfosUp = new List<Dt_InventoryInfo>();
                    var inventory_Batchs = _inventory_BatchServices.Repository.QueryData(x => entityOrder.Details.Select(e => e.Goods_no).Contains(x.MaterielCode));
                    var InventoryInfos = _inventoryInfoService.Repository.QueryData(x => entityOrder.Details.Select(e => e.Goods_no).Contains(x.MaterielCode) && x.StockStatus == StockStatusEmun.入库完成.ObjToInt() && x.AvailableQuantity > 0 && x.WarehouseCode == outorder.warehouse_no);
                    foreach (var item in entityOrder.Details)
                    {
                        Dt_Inventory_Batch inventory_Batch = _inventory_BatchServices.Repository.QueryFirst(x => x.MaterielCode == item.Goods_no && x.BatchNo == item.Batch_num);
                        Dt_Inventory_Batch? inventory_Batch = inventory_Batchs.Where(x => x.MaterielCode == item.Goods_no && x.BatchNo == item.Batch_num).FirstOrDefault();
                        if (inventory_Batch == null) throw new Exception($"未找到出库单号【{entityOrder.Out_no}】中物料编号【{item.Goods_no}】物料批次【{item.Batch_num}】的库存批次信息");
                        if (inventory_Batch.AvailableQuantity < item.Order_qty) throw new Exception($"出库单号【{entityOrder.Out_no}】中物料编号【{item.Goods_no}】物料批次【{item.Batch_num}】的库存批次信息可用数量不足");
                        inventory_Batch.AvailableQuantity -= item.Order_qty;
                        inventory_Batch.OutboundQuantity += item.Order_qty;
                        List<Dt_InventoryInfo> dt_InventoryInfos = _inventoryInfoService.Repository.QueryData(x => x.MaterielCode == item.Goods_no && x.BatchNo == item.Batch_num && x.StockStatus == StockStatusEmun.入库完成.ObjToInt() && x.StockQuantity > x.OutboundQuantity && x.WarehouseCode == item.Reservoirarea);
                        List<Dt_InventoryInfo> dt_InventoryInfos = InventoryInfos.Where(x => x.MaterielCode == item.Goods_no && x.BatchNo == item.Batch_num).ToList();
                        if (dt_InventoryInfos.Count < 1) throw new Exception($"出库单号【{entityOrder.Out_no}】中物料编号【{item.Goods_no}】物料批次【{item.Batch_num}】的可用库存不足");
                        #region æŒ‰å‡ºåº“策略查找库存
                        if (tactics.SelectTactice == TacticsEnum.ComeOutonFirstTime.ObjToInt())
                            dt_InventoryInfos = dt_InventoryInfos.OrderBy(x => x.ValidityPeriod).ToList();
@@ -209,52 +124,71 @@
                        foreach (var InventoryInfo in dt_InventoryInfos)
                        {
                            if (Order_qty <= 0) break;
                            if (InventoryInfo.AvailableQuantity < Order_qty)
                            if (InventoryInfo.AvailableQuantity <= Order_qty)
                            {
                                InventoryInfo.AvailableQuantity = 0;
                                Order_qty -= InventoryInfo.AvailableQuantity;
                                InventoryInfo.OutboundQuantity += InventoryInfo.AvailableQuantity;
                                InventoryInfo.StockStatus = StockStatusEmun.出库锁定.ObjToInt();
                                Dt_SupplyTask supplyTask = new Dt_SupplyTask()
                                {
                                    WarehouseCode = InventoryInfo.WarehouseCode,
                                    BatchNo = InventoryInfo.BatchNo,
                                    MaterielName = InventoryInfo.MaterielName,
                                    MaterielCode = InventoryInfo.MaterielCode,
                                    MaterielSpec = InventoryInfo.MaterielSpec,
                                    TaskStatus = SupplyStatusEnum.NewOut.ObjToInt(),
                                    TaskType = outorder.order_type == "1" ? TaskTypeEnum.Out.ObjToInt() : TaskTypeEnum.InReturn.ObjToInt(),
                                    CreateDate = DateTime.Now,
                                    Creater = App.User.UserName ?? "System",
                                    LocationCode = InventoryInfo.LocationCode,
                                    OrderNo = entityOrder.Out_no,
                                    StockQuantity = InventoryInfo.AvailableQuantity,
                                    SupplyQuantity = 0,
                                    Remark = "出库"
                                };
                                supplyTasks.Add(supplyTask);
                                InventoryInfo.AvailableQuantity = 0;
                            }
                            else
                            {
                                InventoryInfo.AvailableQuantity -= Order_qty;
                                Order_qty = 0;
                                InventoryInfo.OutboundQuantity += Order_qty;
                                InventoryInfo.StockStatus = StockStatusEmun.出库锁定.ObjToInt();
                                Dt_SupplyTask supplyTask = new Dt_SupplyTask()
                                {
                                    WarehouseCode = InventoryInfo.WarehouseCode,
                                    BatchNo = InventoryInfo.BatchNo,
                                    MaterielName = InventoryInfo.MaterielName,
                                    MaterielCode = InventoryInfo.MaterielCode,
                                    MaterielSpec = InventoryInfo.MaterielSpec,
                                    TaskStatus = SupplyStatusEnum.NewOut.ObjToInt(),
                                    TaskType = outorder.order_type == "1" ? TaskTypeEnum.Out.ObjToInt() : TaskTypeEnum.InReturn.ObjToInt(),
                                    CreateDate = DateTime.Now,
                                    Creater = App.User.UserName ?? "System",
                                    LocationCode = InventoryInfo.LocationCode,
                                    OrderNo = entityOrder.Out_no,
                                    StockQuantity = Order_qty,
                                    SupplyQuantity = 0,
                                    Remark = "出库"
                                };
                                supplyTasks.Add(supplyTask);
                                Order_qty = 0;
                            }
                            inventoryInfosUp.Add(InventoryInfo);
                        }
                        dt_InventoryInfos = dt_InventoryInfos.Where(X => X.StockStatus == StockStatusEmun.出库锁定.ObjToInt()).ToList();
                        List<Dt_SupplyTask> supplyTasks = new List<Dt_SupplyTask>();
                        foreach (var inventoryInfo in dt_InventoryInfos)
                        {
                            Dt_SupplyTask supplyTask = new Dt_SupplyTask()
                            {
                                WarehouseCode = inventoryInfo.WarehouseCode,
                                BatchNo = inventoryInfo.BatchNo,
                                MaterielName = inventoryInfo.MaterielName,
                                MaterielCode = inventoryInfo.MaterielCode,
                                MaterielSpec = inventoryInfo.MaterielSpec,
                                TaskStatus = SupplyStatusEnum.NewOut.ObjToInt(),
                                TaskType = TaskTypeEnum.OutPick.ObjToInt(),
                                CreateDate = DateTime.Now,
                                Creater = App.User.UserName ?? "System",
                                LocationCode = inventoryInfo.LocationCode,
                                OrderNo = entityOrder.Out_no,
                                StockQuantity = inventoryInfo.OutboundQuantity,
                                SupplyQuantity = 0,
                                Remark = "出库"
                            };
                            supplyTasks.Add(supplyTask);
                        }
                        _inventory_BatchServices.Repository.UpdateData(inventory_Batch);
                        _inventoryInfoService.Repository.UpdateData(dt_InventoryInfos);
                        _supplyTaskService.AddData(supplyTasks);
                        batchesUp.Add(inventory_Batch);
                    }
                    _unitOfWorkManage.BeginTran();
                    _supplyTaskService.AddData(supplyTasks);
                    _inventory_BatchServices.UpdateData(batchesUp);
                    _inventoryInfoService.UpdateData(inventoryInfosUp);
                    BaseDal.Db.CopyNew().InsertNav(entityOrder).Include(x => x.Details).ExecuteCommand();
                    _unitOfWorkManage.CommitTran();
                    #endregion
                }
                #endregion
                else
                {
                    string WareCodeDJ = WarehouseEnum.大件库.ObjToInt().ToString("000");
                    string WareCodeLK = WarehouseEnum.立库.ObjToInt().ToString("000");
                    #region åˆ›å»ºå¤§ä»¶åº“、立库出库头表
                    var entityOrder = new Dt_DeliveryOrder
                    {
@@ -264,7 +198,7 @@
                        Client_name = outorder.client_name,
                        Account_time = outorder.account_time,
                        Client_no = outorder.client_no,
                        Warehouse_no = WarehouseEnum.大件库.ObjToInt().ToString("000"),
                        Warehouse_no = WareCodeDJ,
                        Details = new List<Dt_DeliveryOrderDetail>()
                    };
                    var entityOrderLK = new Dt_DeliveryOrder
@@ -275,20 +209,27 @@
                        Client_name = outorder.client_name,
                        Account_time = outorder.account_time,
                        Client_no = outorder.client_no,
                        Warehouse_no = WarehouseEnum.立库.ObjToInt().ToString("000"),
                        Warehouse_no = WareCodeLK,
                        Details = new List<Dt_DeliveryOrderDetail>()
                    };
                    #endregion
                    #region æŸ¥æ‰¾åº“å­˜
                    List<Dt_Inventory_Batch> batchesUp = new List<Dt_Inventory_Batch>();
                    List<Dt_InventoryInfo> inventoryInfosUp = new List<Dt_InventoryInfo>();
                    List<Dt_SupplyTask> supplyTasks = new List<Dt_SupplyTask>();
                    List<Dt_MaterielInfo> materielInfos = _materielInfoService.Repository.QueryData(x => outorder.details.Select(e => e.goods_no).Contains(x.MaterielCode));
                    var inventory_Batchs = _inventory_BatchServices.Repository.QueryData(x => outorder.details.Select(e => e.goods_no).Contains(x.MaterielCode));
                    var InventoryInfos = _inventoryInfoService.Repository.QueryData(x => outorder.details.Select(e => e.goods_no).Contains(x.MaterielCode) && x.StockStatus == StockStatusEmun.入库完成.ObjToInt() && x.AvailableQuantity > 0 && (x.WarehouseCode == WareCodeDJ || x.WarehouseCode == WareCodeLK));
                    foreach (var detail in outorder.details)
                    {
                        #region æŸ¥è¯¢åº“存批次和库存
                        Dt_Inventory_Batch inventory_Batch = _inventory_BatchServices.Repository.QueryFirst(x => x.MaterielCode == detail.goods_no && x.BatchNo == detail.batch_num);
                        Dt_Inventory_Batch? inventory_Batch = inventory_Batchs.Where(x => x.MaterielCode == detail.goods_no && x.BatchNo == detail.batch_num).FirstOrDefault();
                        if (inventory_Batch == null) throw new Exception($"未找到出库单号【{outorder.order_no}】中物料编号【{detail.goods_no}】物料批次【{detail.batch_num}】的库存批次信息");
                        if (inventory_Batch.AvailableQuantity < detail.order_qty) throw new Exception($"出库单号【{outorder.order_no}】中物料编号【{detail.goods_no}】物料批次【{detail.batch_num}】的库存批次信息可用数量不足");
                        inventory_Batch.AvailableQuantity -= detail.order_qty;
                        inventory_Batch.OutboundQuantity += detail.order_qty;
                        List<Dt_InventoryInfo> dt_InventoryInfos = _inventoryInfoService.Repository.QueryData(x => x.MaterielCode == inventory_Batch.MaterielCode && x.BatchNo == inventory_Batch.BatchNo && x.StockStatus == StockStatusEmun.入库完成.ObjToInt() && x.StockQuantity > x.OutboundQuantity && (x.WarehouseCode == WarehouseEnum.大件库.ObjToInt().ToString("000") || x.WarehouseCode == WarehouseEnum.立库.ObjToInt().ToString("000")));
                        List<Dt_InventoryInfo> dt_InventoryInfos = InventoryInfos.Where(x => x.MaterielCode == inventory_Batch.MaterielCode && x.BatchNo == inventory_Batch.BatchNo).ToList();
                        if (dt_InventoryInfos.Count < 1) throw new Exception($"出库单号【{outorder.order_no}】中物料编号【{detail.goods_no}】物料批次【{detail.batch_num}】的可用库存不足");
                        #endregion
                        #region æŒ‰å‡ºåº“策略查找库存
                        if (tactics.SelectTactice == TacticsEnum.ComeOutonFirstTime.ObjToInt())
@@ -298,11 +239,10 @@
                        #endregion
                        var Order_qty = Math.Abs(detail.order_qty);//出库单数量
                        #region æ ¹æ®ç‰©æ–™ç¼–码查询物料信息
                        Dt_MaterielInfo materielInfo = _basicService.MaterielInfoService.Repository.QueryFirst(x => x.MaterielCode == detail.goods_no);
                        Dt_MaterielInfo? materielInfo = materielInfos.Where(x => x.MaterielCode == detail.goods_no).FirstOrDefault();
                        if (materielInfo == null) throw new Exception($"未找到药品编码【{detail.goods_no}】的信息");
                        if (!Enum.IsDefined(typeof(MaterielSourceTypeEnum), materielInfo.MaterielSourceType))
                            throw new Exception($"请设置药品编号【{detail.goods_no}】的属性分类");
                        if (materielInfo.BoxQty < 1) throw new Exception($"请设置药品编号【{detail.goods_no}】的箱规数量");
                        #endregion
                        #region å¤§ä»¶
                        if (materielInfo.MaterielSourceType == MaterielSourceTypeEnum.PurchasePart)//如果物料是大件
@@ -322,59 +262,70 @@
                            entityOrder.Details.Add(orderDetail);
                            #endregion
                            #region è®¡ç®—库存
                            #region è®¡ç®—库存、添加出库任务
                            foreach (var InventoryInfo in dt_InventoryInfos)
                            {
                                if (Order_qty <= 0) break;
                                if (InventoryInfo.AvailableQuantity < Order_qty)
                                {
                                    InventoryInfo.AvailableQuantity = 0;
                                    Order_qty -= InventoryInfo.AvailableQuantity;
                                    InventoryInfo.OutboundQuantity += InventoryInfo.AvailableQuantity;
                                    InventoryInfo.StockStatus = StockStatusEmun.出库锁定.ObjToInt();
                                    Dt_SupplyTask supplyTask = new Dt_SupplyTask()
                                    {
                                        WarehouseCode = InventoryInfo.WarehouseCode,
                                        BatchNo = InventoryInfo.BatchNo,
                                        MaterielName = InventoryInfo.MaterielName,
                                        MaterielCode = InventoryInfo.MaterielCode,
                                        MaterielSpec = InventoryInfo.MaterielSpec,
                                        TaskStatus = SupplyStatusEnum.NewOut.ObjToInt(),
                                        TaskType = outorder.order_type == "1" ? TaskTypeEnum.Out.ObjToInt() : TaskTypeEnum.InReturn.ObjToInt(),
                                        CreateDate = DateTime.Now,
                                        Creater = App.User.UserName ?? "System",
                                        LocationCode = InventoryInfo.LocationCode,
                                        OrderNo = entityOrder.Out_no,
                                        StockQuantity = InventoryInfo.AvailableQuantity,
                                        SupplyQuantity = 0,
                                        Remark = "出库"
                                    };
                                    supplyTasks.Add(supplyTask);
                                    InventoryInfo.AvailableQuantity = 0;
                                }
                                else
                                {
                                    InventoryInfo.AvailableQuantity -= Order_qty;
                                    Order_qty = 0;
                                    InventoryInfo.OutboundQuantity += Order_qty;
                                    InventoryInfo.StockStatus = StockStatusEmun.出库锁定.ObjToInt();
                                    Dt_SupplyTask supplyTask = new Dt_SupplyTask()
                                    {
                                        WarehouseCode = InventoryInfo.WarehouseCode,
                                        BatchNo = InventoryInfo.BatchNo,
                                        MaterielName = InventoryInfo.MaterielName,
                                        MaterielCode = InventoryInfo.MaterielCode,
                                        MaterielSpec = InventoryInfo.MaterielSpec,
                                        TaskStatus = SupplyStatusEnum.NewOut.ObjToInt(),
                                        TaskType = outorder.order_type == "1" ? TaskTypeEnum.Out.ObjToInt() : TaskTypeEnum.InReturn.ObjToInt(),
                                        CreateDate = DateTime.Now,
                                        Creater = App.User.UserName ?? "System",
                                        LocationCode = InventoryInfo.LocationCode,
                                        OrderNo = entityOrder.Out_no,
                                        StockQuantity = Order_qty,
                                        SupplyQuantity = 0,
                                        Remark = "出库"
                                    };
                                    supplyTasks.Add(supplyTask);
                                    Order_qty = 0;
                                }
                            }
                            #endregion
                            #region ç”Ÿæˆå‡ºåº“任务
                            dt_InventoryInfos = dt_InventoryInfos.Where(X => X.StockStatus == StockStatusEmun.出库锁定.ObjToInt()).ToList();
                            List<Dt_SupplyTask> supplyTasks = new List<Dt_SupplyTask>();
                            foreach (var inventoryInfo in dt_InventoryInfos)
                            {
                                Dt_SupplyTask supplyTask = new Dt_SupplyTask()
                                {
                                    WarehouseCode = inventoryInfo.WarehouseCode,
                                    BatchNo = inventoryInfo.BatchNo,
                                    MaterielName = inventoryInfo.MaterielName,
                                    MaterielCode = inventoryInfo.MaterielCode,
                                    MaterielSpec = inventoryInfo.MaterielSpec,
                                    TaskStatus = SupplyStatusEnum.NewOut.ObjToInt(),
                                    TaskType = TaskTypeEnum.OutPick.ObjToInt(),
                                    CreateDate = DateTime.Now,
                                    Creater = App.User.UserName ?? "System",
                                    LocationCode = inventoryInfo.LocationCode,
                                    OrderNo = entityOrder.Out_no,
                                    StockQuantity = inventoryInfo.OutboundQuantity,
                                    SupplyQuantity = 0,
                                    Remark = "出库"
                                };
                                supplyTasks.Add(supplyTask);
                            }
                            #endregion
                            _inventory_BatchServices.Repository.UpdateData(inventory_Batch);
                            _inventoryInfoService.Repository.UpdateData(dt_InventoryInfos);
                            _supplyTaskService.AddData(supplyTasks);
                            inventoryInfosUp.AddRange(dt_InventoryInfos);
                            batchesUp.Add(inventory_Batch);
                            //_inventory_BatchServices.Repository.UpdateData(inventory_Batch);
                            //_inventoryInfoService.Repository.UpdateData(dt_InventoryInfos);
                            //_supplyTaskService.AddData(supplyTasks);
                        }
                        #endregion
                        else
                        {
                            if (materielInfo.BoxQty < 1) throw new Exception($"请设置药品编号【{detail.goods_no}】的箱规数量");
                            Dt_DeliveryOrderDetail orderDetail = null;
                            Dt_DeliveryOrderDetail orderDetailLK = null;
                            var ys = Order_qty % materielInfo.BoxQty; //不能整除箱规的散件数 
@@ -396,11 +347,11 @@
                            }
                            #endregion
                            #region æ•´ä»¶ä¼˜å…ˆåˆ†é…å¤§ä»¶åº“
                            foreach (var item in dt_InventoryInfos.Where(x => x.WarehouseCode == WarehouseEnum.大件库.ObjToInt().ToString("000")))
                            #region æ•´ä»¶ä¼˜å…ˆåˆ†é…å¤§ä»¶åº“,计划库存,添加出库任务
                            foreach (var item in dt_InventoryInfos.Where(x => x.WarehouseCode == WareCodeDJ))
                            {
                                if (xs <= 0) break;
                                item.StockStatus = StockStatusEmun.出库锁定.ObjToInt();
                                decimal outqty = 0;
                                while (item.AvailableQuantity > 0 && xs > 0)
                                {
                                    xs--;
@@ -415,50 +366,74 @@
                                            Exp_date = detail.exp_date,
                                            OotDetailStatus = "新建",
                                            Order_Outqty = 0,
                                            Status = 0
                                            Status = 2
                                        };
                                        item.AvailableQuantity -= materielInfo.BoxQty;
                                        item.OutboundQuantity += materielInfo.BoxQty;
                                        outqty += materielInfo.BoxQty;
                                    }
                                    else
                                    {
                                        orderDetail.Order_qty += materielInfo.BoxQty;
                                        item.AvailableQuantity -= materielInfo.BoxQty;
                                        item.OutboundQuantity += materielInfo.BoxQty;
                                        outqty += materielInfo.BoxQty;
                                    }
                                }
                                Dt_SupplyTask supplyTask = new Dt_SupplyTask()
                                {
                                    WarehouseCode = item.WarehouseCode,
                                    BatchNo = item.BatchNo,
                                    MaterielName = item.MaterielName,
                                    MaterielCode = item.MaterielCode,
                                    MaterielSpec = item.MaterielSpec,
                                    TaskStatus = SupplyStatusEnum.NewOut.ObjToInt(),
                                    TaskType = outorder.order_type == "1" ? TaskTypeEnum.Out.ObjToInt() : TaskTypeEnum.InReturn.ObjToInt(),
                                    CreateDate = DateTime.Now,
                                    Creater = App.User.UserName ?? "System",
                                    LocationCode = item.LocationCode,
                                    OrderNo = entityOrder.Out_no,
                                    StockQuantity = outqty,
                                    SupplyQuantity = 0,
                                    Remark = "出库"
                                };
                                supplyTasks.Add(supplyTask);
                                inventoryInfosUp.Add(item);
                                //_inventoryInfoService.Repository.UpdateData(item);
                            }
                            #endregion
                            #region åˆ†é…å®Œå¤§ä»¶åº“如果还有箱数,再选择分配立库
                            if (orderDetailLK == null)
                            if (xs > 0)
                            {
                                orderDetailLK = new Dt_DeliveryOrderDetail()
                                if (orderDetailLK == null)
                                {
                                    Reservoirarea = entityOrderLK.Warehouse_no,
                                    Goods_no = detail.goods_no,
                                    Order_qty = xs * materielInfo.BoxQty,
                                    Batch_num = detail.batch_num,
                                    Exp_date = detail.exp_date,
                                    OotDetailStatus = "新建",
                                    Order_Outqty = 0,
                                    Status = 0
                                };
                            }
                            else
                            {
                                orderDetailLK.Order_qty += xs * materielInfo.BoxQty;
                                    orderDetailLK = new Dt_DeliveryOrderDetail()
                                    {
                                        Reservoirarea = entityOrderLK.Warehouse_no,
                                        Goods_no = detail.goods_no,
                                        Order_qty = xs * materielInfo.BoxQty,
                                        Batch_num = detail.batch_num,
                                        Exp_date = detail.exp_date,
                                        OotDetailStatus = "新建",
                                        Order_Outqty = 0,
                                        Status = 0
                                    };
                                }
                                else
                                {
                                    orderDetailLK.Order_qty += xs * materielInfo.BoxQty;
                                }
                            }
                            #endregion
                            List<Dt_SupplyTask> supplyTasks = new List<Dt_SupplyTask>();
                            #region ç«‹åº“出库单,修改立库库存,添加立库出库任务
                            if (orderDetailLK != null)
                            {
                                #region æ·»åŠ å‡ºåº“ä»»åŠ¡ã€ä¿®æ”¹åº“å­˜ä¿¡æ¯
                                Dt_InventoryInfo inventoryInfo = dt_InventoryInfos.Where(x => x.WarehouseCode == WarehouseEnum.立库.ObjToInt().ToString("000")).First();
                                Dt_InventoryInfo inventoryInfo = dt_InventoryInfos.Where(x => x.WarehouseCode == WareCodeLK).First();
                                inventoryInfo.AvailableQuantity -= orderDetailLK.Order_qty;
                                inventoryInfo.OutboundQuantity += orderDetailLK.Order_qty;
                                inventoryInfo.StockStatus = StockStatusEmun.出库锁定.ObjToInt();
                                _inventoryInfoService.Repository.UpdateData(inventoryInfo);
                                Dt_SupplyTask supplyTask = new Dt_SupplyTask()
                                {
                                    WarehouseCode = inventoryInfo.WarehouseCode,
@@ -467,280 +442,362 @@
                                    MaterielCode = inventoryInfo.MaterielCode,
                                    MaterielSpec = inventoryInfo.MaterielSpec,
                                    TaskStatus = SupplyStatusEnum.NewOut.ObjToInt(),
                                    TaskType = TaskTypeEnum.OutPick.ObjToInt(),
                                    TaskType = outorder.order_type == "1" ? TaskTypeEnum.Out.ObjToInt() : TaskTypeEnum.InReturn.ObjToInt(),
                                    CreateDate = DateTime.Now,
                                    Creater = App.User.UserName ?? "System",
                                    LocationCode = inventoryInfo.LocationCode,
                                    OrderNo = entityOrder.Out_no,
                                    StockQuantity = inventoryInfo.OutboundQuantity,
                                    StockQuantity = orderDetailLK.Order_qty,
                                    SupplyQuantity = 0,
                                    Remark = "出库"
                                };
                                supplyTasks.Add(supplyTask);
                                #endregion
                                //_inventoryInfoService.Repository.UpdateData(inventoryInfo);
                                inventoryInfosUp.Add(inventoryInfo);
                                entityOrderLK.Details.Add(orderDetailLK);
                            }
                            if (orderDetail != null)
                            {
                                #region æ·»åŠ å‡ºåº“ä»»åŠ¡ã€ä¿®æ”¹åº“å­˜ä¿¡æ¯
                                dt_InventoryInfos = dt_InventoryInfos.Where(X => X.StockStatus == StockStatusEmun.出库锁定.ObjToInt()).ToList();
                                foreach (var inventoryInfo in dt_InventoryInfos)
                                {
                                    Dt_SupplyTask supplyTask = new Dt_SupplyTask()
                                    {
                                        WarehouseCode = inventoryInfo.WarehouseCode,
                                        BatchNo = inventoryInfo.BatchNo,
                                        MaterielName = inventoryInfo.MaterielName,
                                        MaterielCode = inventoryInfo.MaterielCode,
                                        MaterielSpec = inventoryInfo.MaterielSpec,
                                        TaskStatus = SupplyStatusEnum.NewOut.ObjToInt(),
                                        TaskType = TaskTypeEnum.OutPick.ObjToInt(),
                                        CreateDate = DateTime.Now,
                                        Creater = App.User.UserName ?? "System",
                                        LocationCode = inventoryInfo.LocationCode,
                                        OrderNo = entityOrder.Out_no,
                                        StockQuantity = inventoryInfo.OutboundQuantity,
                                        SupplyQuantity = 0,
                                        Remark = "出库"
                                    };
                                    supplyTasks.Add(supplyTask);
                                }
                                #endregion
                                entityOrder.Details.Add(orderDetail);
                            }
                            _inventory_BatchServices.Repository.UpdateData(inventory_Batch);
                            _inventoryInfoService.Repository.UpdateData(dt_InventoryInfos);
                            _supplyTaskService.AddData(supplyTasks);
                            #endregion
                            if (orderDetail != null) entityOrder.Details.Add(orderDetail);
                            batchesUp.Add(inventory_Batch);
                            //_inventory_BatchServices.Repository.UpdateData(inventory_Batch);
                            //_supplyTaskService.AddData(supplyTasks);
                        }
                    }
                    if (entityOrder.Details.Count > 0)
                        BaseDal.Db.InsertNav(entityOrder).Include(x => x.Details).ExecuteCommand();
                    if (entityOrderLK.Details.Count > 0)
                        BaseDal.Db.InsertNav(entityOrderLK).Include(x => x.Details).ExecuteCommand();
                    try
                    {
                        _unitOfWorkManage.BeginTran();
                        _supplyTaskService.AddData(supplyTasks);
                        _inventory_BatchServices.UpdateData(batchesUp);
                        _inventoryInfoService.UpdateData(inventoryInfosUp);
                        if (entityOrder.Details.Count > 0)
                            BaseDal.Db.CopyNew().InsertNav(entityOrder).Include(x => x.Details).ExecuteCommand();
                        if (entityOrderLK.Details.Count > 0)
                            BaseDal.Db.CopyNew().InsertNav(entityOrderLK).Include(x => x.Details).ExecuteCommand();
                        _unitOfWorkManage.CommitTran();
                    }
                    catch (Exception ex)
                    {
                        _unitOfWorkManage.RollbackTran();
                    }
                    #endregion
                }
                webResponseContent.OK();
            }
            catch (Exception ex)
            {
                _messageInfoService.AddMessageInfo(MessageGroupByEnum.OutOrderAlarm, (outorder.order_type == "3" ? "入库退货" : "正常出库") + $":单号【{outorder.order_no}】", ex.Message);
                webResponseContent.Error(ex.Message);
            }
            return webResponseContent;
        }
        /// <summary>
        /// ç”Ÿæˆå‡ºåº“单任务
        /// </summary>
        /// <param name="order_no">出库单号</param>
        /// <returns></returns>
        private bool CreateSupplyTask(List<string> order_no)
        #endregion
        #region åˆ›å»ºç›˜äºå‡ºåº“单
        public WebResponseContent CreateCheckOutOrder(UpstramOutOrderInfo order)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                // å…ˆèŽ·å–ç¬¦åˆæ¡ä»¶çš„ä¸»è¡¨æ•°æ®
                var mainOrders = BaseDal.Db.Queryable<Dt_DeliveryOrder>()
                    .Where(x => order_no.Contains(x.Out_no))
                    .ToList();
                // èŽ·å–æ‰€æœ‰ä¸»è¡¨ID
                var mainOrderIds = mainOrders.Select(x => x.Id).ToList();
                // ç›´æŽ¥æŸ¥è¯¢å­è¡¨æ•°æ®
                List<Dt_DeliveryOrderDetail> filteredDetails = BaseDal.Db.Queryable<Dt_DeliveryOrderDetail>()
                    .Where(d => mainOrderIds.Contains(d.DeliveryOrderId) && d.OotDetailStatus == "新建")
                    .ToList();
                // èŽ·å–æ‰€æœ‰éœ€è¦æŸ¥è¯¢çš„ç‰©æ–™ç¼–ç 
                var materielCodes = filteredDetails.Select(x => x.Goods_no).Distinct().ToList();
                // æ‰¹é‡æŸ¥è¯¢ç‰©æ–™ä¿¡æ¯
                var materielList = BaseDal.Db.Queryable<Dt_MaterielInfo>()
                    .Where(x => materielCodes.Contains(x.MaterielCode))
                    .ToList();
                List<Dt_SupplyTask> supplyTasks = new List<Dt_SupplyTask>();
                foreach (var item in filteredDetails)
                string WareCodeMJ = WarehouseEnum.麻精库.ObjToInt().ToString("000");
                string WareCodeLD = WarehouseEnum.冷冻库.ObjToInt().ToString("000");
                List<Dt_SupplyTask_Hty> supplyTask_Hties = new List<Dt_SupplyTask_Hty>();
                List<Dt_Inventory_Batch> batchesUp = new List<Dt_Inventory_Batch>();
                List<Dt_InventoryInfo> infosUp = new List<Dt_InventoryInfo>();
                var codes = order.details.Select(x => x.goods_no).ToList();
                #region ç‰¹æ®Šåº“房
                if (order.warehouse_no == WareCodeMJ || order.warehouse_no == WareCodeLD)
                {
                    // æ ¹æ®å­è¡¨ç‰©æ–™ç¼–码查询物料信息
                    var medication = materielList.FirstOrDefault(x => x.MaterielCode == item.Goods_no);
                    // æŸ¥æ‰¾å¯¹åº”的主表信息
                    var mainOrder = mainOrders.FirstOrDefault(x => x.Id == item.DeliveryOrderId);
                    //随机生成任务编号加时间戳
                    if (mainOrder == null) continue;
                    var location = Db.Queryable<Dt_InventoryInfo>()
                    .Where(x => x.MaterielCode == ""//materielCode
                             && x.BatchNo == ""//batchNo
                             && x.StockQuantity > 0)
                    .OrderBy(x => x.InDate) // æŒ‰å…¥åº“时间排序
                    .First();
                    var supplyTask = new Dt_SupplyTask
                    List<Dt_Inventory_Batch> inventory_Batchs = _inventory_BatchServices.Repository.QueryData(x => codes.Contains(x.MaterielCode));
                    List<Dt_InventoryInfo> _InventoryInfos = _inventoryInfoService.Repository.QueryData(x => codes.Contains(x.MaterielCode));
                    #region åº“存、库存批次平账
                    foreach (var item in order.details)
                    {
                        TaskNum = GenerateTaskNumber(),
                        PalletCode = "0",
                        BatchNo = item.Batch_num,
                        MaterielCode = item.Goods_no,
                        MaterielName = medication?.MaterielName, // å¦‚果物料信息不存在,使用子表的物料名称
                        MaterielSpec = medication?.MaterielSpec, // å¦‚果物料信息不存在,使用子表的物料规格
                        TaskType = 0,
                        TaskStatus = item.Status == 0 ? 0 : 1,
                        WarehouseCode = mainOrder.Warehouse_no,
                        LocationCode = item.Status == 0 ? "立库" : "平库",
                        StockQuantity = item.Order_qty, // å‡è®¾å­è¡¨æœ‰Quantity字段
                        SupplyQuantity = 0,
                        OrderNo = mainOrder.Out_no,
                        Dispatchertime = DateTime.Now,
                        Remark = ""
                    };
                    supplyTasks.Add(supplyTask);
                }
                // æ‰¹é‡æ’入供应任务
                if (supplyTasks.Any())
                {
                    return BaseDal.Db.Insertable(supplyTasks).ExecuteCommand() > 0;
                }
                return false;
            }
            catch (Exception ex)
            {
                // è®°å½•日志
                Console.WriteLine($"创建供应任务失败:{ex.Message}");
                return false;
            }
        }
        /// <summary>
        /// ç”Ÿæˆéšæœºä»»åŠ¡ç¼–å·ï¼ˆéšæœºæ•° + æ—¶é—´æˆ³ï¼‰
        /// </summary>
        /// <returns>任务编号</returns>
        private int GenerateTaskNumber()
        {
            // ç”Ÿæˆ4位随机数
            Random random = new Random(Guid.NewGuid().GetHashCode());
            int randomNum = random.Next(1000, 9999); // 1000-9999之间的随机数
            // ç»„合成任务编号:TASK + æ—¶é—´æˆ³ + éšæœºæ•°
            return randomNum;
        }
        /// <summary>
        /// å‡ºåº“单推送给 WCS
        /// </summary>
        /// <returns></returns>
        public WebResponseContent EdiOut()
        {
            var responseContent = new WebResponseContent();
            try
            {
                // 1. æŸ¥è¯¢ç¬¦åˆæ¡ä»¶çš„订单(表头=新建 && åŒ…含有效明细)
                var outOrders = BaseDal.Db.CopyNew().Queryable<Dt_DeliveryOrder>()
                    .Where(o => o.OutStatus == "新建" && o.Warehouse_no == WarehouseEnum.立库.ObjToInt().ToString("000"))
                    .Includes(o => o.Details, d => d.MedicineGoods)
                    .ToList();
                // 2. å†è¿‡æ»¤æŽ‰ä¸ç¬¦åˆæ¡ä»¶çš„æ˜Žç»†ï¼ˆåªä¿ç•™ Status=0 ï¼‰
                foreach (var order in outOrders)
                {
                    order.Details = order.Details.Where(d => d.Status == 0).ToList();
                }
                if (outOrders == null || !outOrders.Any())
                {
                    Console.WriteLine("没有符合条件的订单需要推送");
                    return responseContent.Error("没有符合条件的订单需要推送");
                }
                foreach (var order in outOrders)
                {
                    try
                    {
                        string materialCode = "YY";//默认值
                                                   //获取当前订单的第一个明细项
                        var firstDetail = order.Details.FirstOrDefault();
                        if (firstDetail?.MedicineGoods != null && !string.IsNullOrEmpty(firstDetail.MedicineGoods.MaterielErpType))
                        //找库存批次信息
                        Dt_Inventory_Batch inventory_Batch = inventory_Batchs.Where(x => x.MaterielCode == item.goods_no && x.BatchNo == item.batch_num).First();
                        var Qty = Math.Abs(inventory_Batch.StockQuantity - inventory_Batch.SupplyQuantity);
                        if (Qty != item.order_qty) throw new Exception($"盘亏出库单【{order.order_no}】物料编号【{item.goods_no}】物料批次【{item.batch_num}】的盘亏数量有误");
                        //找所有库存
                        List<Dt_InventoryInfo> inventoryInfos = _InventoryInfos.Where(x => x.MaterielCode == inventory_Batch.MaterielCode && x.BatchNo == inventory_Batch.BatchNo).ToList();
                        foreach (var inventoryInfo in inventoryInfos)
                        {
                            //如果条件满足,将物料代码设置为第一个明细项对应的药品物料代码
                            materialCode = firstDetail.MedicineGoods.MaterielErpType;
                        }
                        // 3. ç»„装 DTO
                        var ediDto = new TowcsDto.ToediOutInfo
                        {
                            customerCode = "905",
                            materialCode = materialCode,
                            externalOrderNo = order.Out_no,
                            outOrderType = order.Out_type == "1" ? "10" : order.Out_type == "3" ? "20" : "30",//出库单类型是1就是正常的,3就是盘点
                            priority = 1,
                            Is_cancel = 0,
                            details = order.Details.Select(d => new TowcsDto.ToeOutdiInDetail
                            #region æ·»åŠ ç›˜äºå‡ºåº“ä»»åŠ¡
                            if (inventoryInfo.StockQuantity != inventoryInfo.SupplyQuantity)
                            {
                                batchNo = d.Batch_num,
                                productCode = d.Goods_no,
                                productName = d.MedicineGoods?.MaterielName,
                                productSpecifications = d.MedicineGoods?.MaterielModel,
                                quantity = (int)d.Order_qty,
                                //stocktakingDetails = order.Out_type == "3"
                                //    ? new List<ToOutediInStock>
                                //      {
                                //  new ToOutediInStock { palletCode = "FC00001", quantity = d.Order_qty.ToString() }
                                //      }
                                //    : null
                            }).ToList()
                        };
                                Dt_SupplyTask_Hty supplyTask_Hty = new Dt_SupplyTask_Hty()
                                {
                                    WarehouseCode = inventoryInfo.WarehouseCode,
                                    OperateType = OperateTypeEnum.自动完成.ToString(),
                                    InsertTime = DateTime.Now,
                                    TaskStatus = SupplyStatusEnum.OutFinish.ObjToInt(),
                                    BatchNo = inventoryInfo.BatchNo,
                                    MaterielName = inventoryInfo.MaterielName,
                                    MaterielCode = inventoryInfo.MaterielCode,
                                    MaterielSpec = inventoryInfo.MaterielSpec,
                                    TaskType = TaskTypeEnum.ChenckOut.ObjToInt(),
                                    CreateDate = DateTime.Now,
                                    Creater = App.User.UserName,
                                    LocationCode = inventoryInfo.LocationCode,
                                    OrderNo = order.order_no,
                                    StockQuantity = Math.Abs(inventoryInfo.StockQuantity - inventoryInfo.SupplyQuantity),
                                    SupplyQuantity = 0,
                                    Remark = "盘亏入库"
                                };
                                //_supplyTaskHtyService.AddData(supplyTask_Hty);
                                supplyTask_Hties.Add(supplyTask_Hty);
                            }
                            #endregion
                            inventoryInfo.StockQuantity = inventoryInfo.SupplyQuantity;
                            inventoryInfo.SupplyQuantity = 0;
                            inventoryInfo.StockStatus = StockStatusEmun.入库完成.ObjToInt();
                        }
                        inventory_Batch.StockQuantity = inventory_Batch.SupplyQuantity;
                        inventory_Batch.SupplyQuantity = 0;
                        infosUp.AddRange(inventoryInfos);
                        batchesUp.Add(inventory_Batch);
                        //_inventoryInfoService.UpdateData(inventoryInfos);
                        //_inventory_BatchServices.UpdateData(inventory_Batch);
                    }
                    #endregion
                        // 4. è°ƒç”¨æŽ¥å£
                        var url = "http://172.16.1.2:9357/file-admin/api/out/ediOut";
                        //var url = "http://127.0.0.1:4523/m2/5660322-5340849-default/363076920";
                        var result = HttpHelper.Post(url, ediDto.ToJsonString());
                        var resp = JsonConvert.DeserializeObject<TowcsDto.TowcsResponse<object>>(result);
                        if (resp != null && resp.code == "0")
                    #region åˆ›å»ºç›˜ç‚¹å•
                    var entityOrder = new Dt_DeliveryOrder
                    {
                        Out_no = order.order_no,
                        Out_type = order.order_type,
                        Client_no = order.client_no,
                        Client_name = order.client_name,
                        OutStatus = "已完成",
                        Account_time = order.account_time,
                        Warehouse_no = order.warehouse_no,
                        Details = order.details.Select(d => new Dt_DeliveryOrderDetail
                        {
                            // æ›´æ–°è¡¨å¤´çŠ¶æ€
                            BaseDal.Db.Updateable<Dt_DeliveryOrder>()
                              .SetColumns(o => new Dt_DeliveryOrder { OutStatus = "开始" })
                              .Where(o => o.Id == order.Id)
                              .ExecuteCommand();
                            Goods_no = d.goods_no,
                            Order_qty = Math.Abs(d.order_qty),
                            Order_Outqty = Math.Abs(d.order_qty),
                            Batch_num = d.batch_num,
                            Exp_date = d.exp_date,
                            Reservoirarea = order.warehouse_no,
                            OotDetailStatus = "已完成",
                            Status = 2,
                        }).ToList()
                    };
                    _unitOfWorkManage.BeginTran();
                    _supplyTaskHtyService.AddData(supplyTask_Hties);
                    _inventoryInfoService.UpdateData(infosUp);
                    _inventory_BatchServices.UpdateData(batchesUp);
                    BaseDal.Db.InsertNav(entityOrder).Include(it => it.Details).ExecuteCommand();
                    _unitOfWorkManage.CommitTran();
                    #endregion
                }
                #endregion
                else
                {
                    List<Dt_DeliveryOrder> deliveryOrdersAdd = new List<Dt_DeliveryOrder>();
                    string WareCodeLK = WarehouseEnum.立库.ObjToInt().ToString("000");
                    string WareCodeDJ = WarehouseEnum.大件库.ObjToInt().ToString("000");
                    List<Dt_Inventory_Batch> inventory_Batchs = _inventory_BatchServices.Repository.QueryData(x => codes.Contains(x.MaterielCode));
                    List<Dt_InventoryInfo> _InventoryInfos = _inventoryInfoService.Repository.QueryData(x => codes.Contains(x.MaterielCode));
                    foreach (var item in order.details)
                    {
                        //找库存批次信息
                        Dt_Inventory_Batch inventory_Batch = inventory_Batchs.Where(x => x.MaterielCode == item.goods_no && x.BatchNo == item.batch_num).First();
                        var Qty = Math.Abs(inventory_Batch.StockQuantity - inventory_Batch.SupplyQuantity);
                        if (Qty != item.order_qty) throw new Exception($"盘亏出库单【{order.order_no}】物料编号【{item.goods_no}】物料批次【{item.batch_num}】的盘亏数量有误");
                        //找所有库存
                        List<Dt_InventoryInfo> inventoryInfos = _InventoryInfos.Where(x => x.MaterielCode == inventory_Batch.MaterielCode && x.BatchNo == inventory_Batch.BatchNo).ToList();
                        //获取立库盘点差异数.。。。。。。。。。。。。
                        var inventoryLK = inventoryInfos.Where(x => x.WarehouseCode == WareCodeLK).First();
                        var LkQty = Math.Abs(inventoryLK.StockQuantity - inventoryLK.SupplyQuantity);
                        //获取大件库盘点差异数
                        var inventoryDJ = inventoryInfos.Where(x => x.WarehouseCode == WareCodeDJ).ToList();
                        var DJQty = Math.Abs(inventoryDJ.Sum(x => x.StockQuantity) - inventoryDJ.Sum(x => x.SupplyQuantity));
                        if (LkQty + DJQty != Qty) throw new Exception($"【{order.order_no}】物料编号【{item.goods_no}】物料批次【{item.batch_num}】的物料信息与物料批次信息盘盈数量不符");
                        if (LkQty == 0)//立库无差异
                        {
                            #region åº“存、库存批次平账
                            foreach (var inventoryInfo in inventoryInfos)
                            {
                                #region æ·»åŠ ç›˜äºå‡ºåº“ä»»åŠ¡
                                if (inventoryInfo.StockQuantity != inventoryInfo.SupplyQuantity)
                                {
                                    Dt_SupplyTask_Hty supplyTask_Hty = new Dt_SupplyTask_Hty()
                                    {
                                        WarehouseCode = inventoryInfo.WarehouseCode,
                                        OperateType = OperateTypeEnum.自动完成.ToString(),
                                        InsertTime = DateTime.Now,
                                        TaskStatus = SupplyStatusEnum.OutFinish.ObjToInt(),
                                        BatchNo = inventoryInfo.BatchNo,
                                        MaterielName = inventoryInfo.MaterielName,
                                        MaterielCode = inventoryInfo.MaterielCode,
                                        MaterielSpec = inventoryInfo.MaterielSpec,
                                        TaskType = TaskTypeEnum.ChenckOut.ObjToInt(),
                                        CreateDate = DateTime.Now,
                                        Creater = App.User.UserName,
                                        LocationCode = inventoryInfo.LocationCode,
                                        OrderNo = order.order_no,
                                        StockQuantity = Math.Abs(inventoryInfo.StockQuantity - inventoryInfo.SupplyQuantity),
                                        SupplyQuantity = 0,
                                        Remark = "盘亏入库"
                                    };
                                    //_supplyTaskHtyService.AddData(supplyTask_Hty);
                                    supplyTask_Hties.Add(supplyTask_Hty);
                                }
                                #endregion
                                inventoryInfo.StockQuantity = inventoryInfo.SupplyQuantity;
                                inventoryInfo.SupplyQuantity = 0;
                                inventoryInfo.StockStatus = StockStatusEmun.入库完成.ObjToInt();
                            }
                            //_inventoryInfoService.UpdateData(inventoryInfos);
                            inventory_Batch.StockQuantity = inventory_Batch.SupplyQuantity;
                            inventory_Batch.SupplyQuantity = 0;
                            //_inventory_BatchServices.UpdateData(inventory_Batch);
                            infosUp.AddRange(inventoryInfos);
                            batchesUp.Add(inventory_Batch);
                            #endregion
                            // æ›´æ–°æ˜Žç»†çŠ¶æ€
                            BaseDal.Db.Updateable<Dt_DeliveryOrderDetail>()
                              .SetColumns(d => new Dt_DeliveryOrderDetail { Status = 1, OotDetailStatus = "开始" })
                              .Where(d => d.DeliveryOrderId == order.Id && d.Status == 0)
                              .ExecuteCommand();
                            Console.WriteLine($"订单 {order.Out_no} æŽ¨é€æˆåŠŸ");
                            #region åˆ›å»ºå¤§ä»¶åº“盘点单
                            var entityOrder = new Dt_DeliveryOrder
                            {
                                Out_no = order.order_no,
                                Out_type = order.order_type,
                                Client_no = order.client_no,
                                Account_time = order.account_time,
                                OutStatus = "已完成",
                                Client_name = order.client_name,
                                Warehouse_no = WareCodeDJ,
                                Details = order.details.Select(d => new Dt_DeliveryOrderDetail
                                {
                                    Goods_no = d.goods_no,
                                    Order_qty = Math.Abs(d.order_qty),
                                    Order_Outqty = Math.Abs(d.order_qty),
                                    Batch_num = d.batch_num,
                                    Exp_date = d.exp_date,
                                    Reservoirarea = WareCodeDJ,
                                    OotDetailStatus = "已完成",
                                    Status = 2,
                                }).ToList()
                            };
                            //Db.InsertNav(entityOrder).Include(it => it.Details).ExecuteCommand();
                            //Repository.AddData(entityOrder);
                            deliveryOrdersAdd.Add(entityOrder);
                            #endregion
                        }
                        else
                        {
                            SendErrorToUpstream(3, order.Out_no, resp?.msg ?? "WCS æŽ¨é€å¤±è´¥", "");
                            Console.WriteLine($"订单 {order.Out_no} æŽ¨é€å¤±è´¥ï¼š{resp?.msg}");
                        }
                        //删除全部状为已完成的明细和表头,移入历史表
                    }
                    catch (Exception ex)
                    {
                        SendErrorToUpstream(3, order.Out_no, ex.Message, "");
                        Console.WriteLine($"订单 {order.Out_no} æŽ¨é€å¼‚常:{ex.Message}");
                    }
                }
                            #region å¤§ä»¶åº“库存平账
                            inventoryInfos = inventoryInfos.Where(x => x.WarehouseCode == WareCodeDJ).ToList();
                            foreach (var inventoryInfo in inventoryInfos)
                            {
                                #region æ·»åŠ ç›˜äºå‡ºåº“ä»»åŠ¡
                                if (inventoryInfo.StockQuantity != inventoryInfo.SupplyQuantity)
                                {
                                    Dt_SupplyTask_Hty supplyTask_Hty = new Dt_SupplyTask_Hty()
                                    {
                                        WarehouseCode = inventoryInfo.WarehouseCode,
                                        OperateType = OperateTypeEnum.自动完成.ToString(),
                                        InsertTime = DateTime.Now,
                                        TaskStatus = SupplyStatusEnum.OutFinish.ObjToInt(),
                                        BatchNo = inventoryInfo.BatchNo,
                                        MaterielName = inventoryInfo.MaterielName,
                                        MaterielCode = inventoryInfo.MaterielCode,
                                        MaterielSpec = inventoryInfo.MaterielSpec,
                                        TaskType = TaskTypeEnum.ChenckOut.ObjToInt(),
                                        CreateDate = DateTime.Now,
                                        Creater = App.User.UserName,
                                        LocationCode = inventoryInfo.LocationCode,
                                        OrderNo = order.order_no,
                                        StockQuantity = Math.Abs(inventoryInfo.StockQuantity - inventoryInfo.SupplyQuantity),
                                        SupplyQuantity = 0,
                                        Remark = "盘亏出库"
                                    };
                                    //_supplyTaskHtyService.AddData(supplyTask_Hty);
                                    supplyTask_Hties.Add(supplyTask_Hty);
                                }
                                #endregion
                                inventoryInfo.StockQuantity = inventoryInfo.SupplyQuantity;
                                inventoryInfo.SupplyQuantity = 0;
                                inventoryInfo.StockStatus = StockStatusEmun.入库完成.ObjToInt();
                            }
                            //_inventoryInfoService.UpdateData(inventoryInfos);
                            infosUp.AddRange(inventoryInfos);
                            #endregion
                return responseContent.OK("出库订单推送完成");
                            #region åˆ›å»ºå¤§ä»¶åº“盘点单
                            if (DJQty != 0)
                            {
                                var cabinOrder = new Dt_DeliveryOrder
                                {
                                    Out_no = order.order_no,
                                    Out_type = order.order_type,
                                    Client_name = order.client_name,
                                    Account_time = order.account_time,
                                    OutStatus = "已完成",
                                    Client_no = order.client_no,
                                    Warehouse_no = WareCodeDJ,
                                    Details = order.details.Select(d => new Dt_DeliveryOrderDetail
                                    {
                                        Goods_no = d.goods_no,
                                        Order_qty = DJQty,
                                        Order_Outqty = DJQty,
                                        Batch_num = d.batch_num,
                                        Exp_date = d.exp_date,
                                        Reservoirarea = WareCodeDJ,
                                        OotDetailStatus = "已完成",
                                        Status = 2,
                                    }).ToList()
                                };
                                //Repository.AddData(cabinOrder);
                                //Db.InsertNav(cabinOrder).Include(it => it.Details).ExecuteCommand();
                                deliveryOrdersAdd.Add(cabinOrder);
                            }
                            #endregion
                            #region åˆ›å»ºç«‹åº“盘点单
                            var entityOrder = new Dt_DeliveryOrder
                            {
                                Out_no = order.order_no,
                                Out_type = order.order_type,
                                Client_no = order.client_no,
                                Account_time = order.account_time,
                                OutStatus = "新建",
                                Client_name = order.client_name,
                                Warehouse_no = WareCodeLK,
                                Details = order.details.Select(d => new Dt_DeliveryOrderDetail
                                {
                                    Goods_no = d.goods_no,
                                    Order_qty = LkQty,
                                    Batch_num = d.batch_num,
                                    Exp_date = d.exp_date,
                                    Reservoirarea = WareCodeLK,
                                    OotDetailStatus = "新建",
                                    Status = 0,
                                }).ToList()
                            };
                            //Db.InsertNav(entityOrder).Include(it => it.Details).ExecuteCommand();
                            //Repository.AddData(entityOrder);
                            deliveryOrdersAdd.Add(entityOrder);
                            #endregion
                        }
                        //return WebResponseContent.Instance.OK("成功");
                    }
                    _unitOfWorkManage.BeginTran();
                    _supplyTaskHtyService.AddData(supplyTask_Hties);
                    _inventoryInfoService.UpdateData(infosUp);
                    _inventory_BatchServices.UpdateData(batchesUp);
                    BaseDal.Db.InsertNav(deliveryOrdersAdd).Include(it => it.Details).ExecuteCommand();
                    _unitOfWorkManage.CommitTran();
                }
                return WebResponseContent.Instance.OK("成功");
            }
            catch (Exception ex)
            {
                Console.WriteLine("EdiOut å¼‚常:" + ex.Message);
                return responseContent.Error("出库订单推送失败:" + ex.Message);
                _unitOfWorkManage.RollbackTran();
                content.Error(ex.Message);
            }
            return content;
        }
        #endregion
        //盘点 æ‹¿æ•´ä¸ªæ‰¹æ¬¡ä¿¡æ¯è¡¨çš„商品批号和商品编号来进行盘点
@@ -750,7 +807,7 @@
            try
            {
                // 1️⃣ æŸ¥æ‰¾æŒ‡å®šæ‰¹æ¬¡ä¸Žç‰©æ–™çš„库存信息
                var batchInfo = BaseDal.Db.Queryable<Dt_Inventory_Batch>()
                var batchInfo = BaseDal.Db.CopyNew().Queryable<Dt_Inventory_Batch>()
                    .Where(x => x.BatchNo == batchNo && x.MaterielCode == goodsNo)
                    .First();
@@ -808,88 +865,6 @@
        }
        /// <summary>
        /// å‡ºåº“报完成接口
        /// </summary>
        /// <param name="out_no">出库单号</param>
        /// <returns></returns>
        public WebResponseContent CompleteAllOutOrders()
        {
            var responseContent = new WebResponseContent();
            try
            {
                #region æŸ¥æ‰¾æ‰€æœ‰å·²å®Œæˆå‡ºåº“单
                var outorders = BaseDal.QueryData(x => x.OutStatus == "已完成").Select(x => x.Out_no).Distinct().ToList();
                foreach (var outorder in outorders)
                {
                    var Orders = BaseDal.Db.Queryable<Dt_DeliveryOrder>().Where(x => x.Out_no == outorder).Includes(x => x.Details).ToList();
                    if (!Orders.Where(x => x.OutStatus != "已完成").Any())
                    {
                        BaseDal.Db.Ado.BeginTran();
                        BaseDal.DeleteAndMoveIntoHty(Orders, OperateTypeEnum.自动完成);
                        foreach (var item in Orders)
                        {
                            _deliveryOrderDetailServices.Repository.DeleteAndMoveIntoHty(item.Details, OperateTypeEnum.自动完成);
                        }
                        var url = "http://121.37.118.63:80/GYZ2/95fck/outOrderOk";
                        var requestDate = new
                        {
                            order_no = outorder
                        };
                        var result = HttpHelper.Post(url, requestDate.ToJsonString());
                        var response = JsonConvert.DeserializeObject<UpstreamOrderResponse>(result);
                        if (response.resultCode == "0") BaseDal.Db.Ado.CommitTran();
                        else
                        {
                            BaseDal.Db.Ado.RollbackTran();
                            SendErrorToUpstream(4, "", $"上游接口返回失败: {response.resultMsg}", outorder);
                        }
                    }
                }
                #endregion
                return responseContent.OK();
            }
            catch (Exception ex)
            {
                BaseDal.Db.Ado.RollbackTran();
                return responseContent.Error("批量处理失败:" + ex.Message);
            }
        }
        /// <summary>
        /// æŽ¨é€å¼‚常信息给上游系统 1.入库单接口;2.入库单报完成接口;3.出库单接口;4.出库报完成接口;5.药品基础信息同步接口;6.供应商信息接口;7.客户信息接口;8.库存查询接口
        /// </summary>
        public void SendErrorToUpstream(int type, string code, string message, string remark)
        {
            try
            {
                var url = "http://121.37.118.63:80/GYZ2/95fck/exceptionLog";
                var requestData = new
                {
                    type = type.ToString(),
                    code = code,
                    message = message,
                    remark = remark
                };
                var result = HttpHelper.Post(url, requestData.ToJsonString());
                // å¯ä»¥ååºåˆ—化检查 resultCode æ˜¯å¦ä¸º0
            }
            catch (Exception e)
            {
                // è¿™é‡Œä¸è¦å†æŠ›å¼‚常了,避免死循环
                Console.WriteLine("异常接口推送失败:" + e.Message);
            }
        }
        /// <summary>
        /// æŸ¥è¯¢å‡ºåº“单列表
        /// </summary>
@@ -906,11 +881,11 @@
                List<Dt_DeliveryOrder> dt_ReceiveOrders = new List<Dt_DeliveryOrder>();
                if (string.IsNullOrEmpty(orderNo))
                {
                    dt_ReceiveOrders = Db.Queryable<Dt_DeliveryOrder>().Where(x => (x.OutStatus == "新建" || x.OutStatus == "开始") && x.Warehouse_no == warehouseCode && x.Out_type != "3").Includes(x => x.Details).OrderByDescending(x => x.CreateDate).ToPageList(pageNo, 5);
                    dt_ReceiveOrders = Db.Queryable<Dt_DeliveryOrder>().Where(x => (x.OutStatus == "新建" || x.OutStatus == "开始") && x.Warehouse_no == warehouseCode && x.Out_type != "20").Includes(x => x.Details).OrderByDescending(x => x.CreateDate).ToPageList(pageNo, 5);
                }
                else
                {
                    dt_ReceiveOrders = Db.Queryable<Dt_DeliveryOrder>().Where(x => (x.Out_no.Contains(orderNo) || x.Client_no.Contains(orderNo)) && (x.OutStatus == "新建" || x.OutStatus == "开始") && x.Out_type != "3" && x.Warehouse_no == warehouseCode).OrderByDescending(x => x.CreateDate).Includes(x => x.Details).ToPageList(pageNo, 5);
                    dt_ReceiveOrders = Db.Queryable<Dt_DeliveryOrder>().Where(x => (x.Out_no.Contains(orderNo) || x.Client_no.Contains(orderNo)) && (x.OutStatus == "新建" || x.OutStatus == "开始") && x.Out_type != "20" && x.Warehouse_no == warehouseCode).OrderByDescending(x => x.CreateDate).Includes(x => x.Details).ToPageList(pageNo, 5);
                }
                content.OK(data: dt_ReceiveOrders);
@@ -935,15 +910,21 @@
            WebResponseContent content = new WebResponseContent();
            Dt_DeliveryOrder cabinOrder = new Dt_DeliveryOrder();
            if (isPick)
                cabinOrder = Db.Queryable<Dt_DeliveryOrder>().Includes(x => x.Details).First(x => x.Out_no == orderNo && x.Out_type == "3");
                cabinOrder = Db.Queryable<Dt_DeliveryOrder>().Includes(x => x.Details).First(x => x.Out_no == orderNo && x.Out_type == "20");
            else
                cabinOrder = Db.Queryable<Dt_DeliveryOrder>().Includes(x => x.Details).First(x => x.Out_no == orderNo && x.Out_type != "3");
                cabinOrder = Db.Queryable<Dt_DeliveryOrder>().Includes(x => x.Details).First(x => x.Out_no == orderNo && x.Out_type != "20");
            //List<Dt_DeliveryOrderDetail>? cabinOrderDetails = cabinOrder.Details?.Where(x => x.Reservoirarea == pageNo.ToString()).ToList(); 
            List<Dt_DeliveryOrderDetail>? cabinOrderDetails = cabinOrder.Details?.Where(x => x.Status == 2).ToList();
            content.OK(data: cabinOrderDetails);
            return content;
        }
        /// <summary>
        /// pad出库完成
        /// </summary>
        /// <param name="saveModel"></param>
        /// <returns></returns>
        public WebResponseContent OutFinish(SaveModel saveModel)
        {
            WebResponseContent content = new WebResponseContent();
@@ -954,7 +935,9 @@
                Dt_SupplyTask supplyTask = _supplyTaskService.Repository.QueryFirst(x => x.TaskId == TaskId && x.TaskStatus == SupplyStatusEnum.NewOut.ObjToInt());
                if (supplyTask == null) throw new Exception("当前出库任务已完成");
                if (supplyTask.LocationCode != LocationCode) throw new Exception($"当前出库货位【{LocationCode}】与任务分配货位不匹配");
                OutTaskFinish(supplyTask);
                Dt_DeliveryOrder deliveryOrder = BaseDal.Db.Queryable<Dt_DeliveryOrder>().Where(x => x.Out_no == supplyTask.OrderNo && x.Warehouse_no == supplyTask.WarehouseCode).Includes(x => x.Details).First();
                if (deliveryOrder == null) return WebResponseContent.Instance.OK($"出库单已完成");
                content = OutTaskFinish(supplyTask, deliveryOrder);
            }
            catch (Exception ex)
            {
@@ -962,19 +945,96 @@
            }
            return content;
        }
        public WebResponseContent OutTaskFinish(Dt_SupplyTask supplyTask, Dt_DeliveryOrder deliveryOrder)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                Dt_DeliveryOrderDetail? cabinOrderDetail = deliveryOrder.Details.FirstOrDefault(x => x.Batch_num == supplyTask.BatchNo && x.Goods_no == supplyTask.MaterielCode);
                if (cabinOrderDetail == null) throw new Exception($"出库单明细未找到");
                Dt_MaterielInfo materielInfo = _materielInfoService.Repository.QueryFirst(x => x.MaterielCode == supplyTask.MaterielCode);
                if (materielInfo == null) throw new Exception($"请维护物料编号【{supplyTask.MaterielCode}】的物料信息");
                cabinOrderDetail.Order_Outqty += supplyTask.StockQuantity;
                if (cabinOrderDetail.Order_Outqty > cabinOrderDetail.Order_qty) throw new Exception($"出库数量不可超出单据数量");
                deliveryOrder.OutStatus = "开始";
                cabinOrderDetail.OotDetailStatus = "开始";
                if (cabinOrderDetail.Order_Outqty == cabinOrderDetail.Order_qty) cabinOrderDetail.OotDetailStatus = "已完成";
                #region åº“å­˜
                Dt_InventoryInfo inventoryInfo = _inventoryInfoService.Repository.QueryFirst(x => x.BatchNo == cabinOrderDetail.Batch_num && x.MaterielCode == cabinOrderDetail.Goods_no && x.LocationCode == supplyTask.LocationCode);
                if (inventoryInfo == null) throw new Exception($"未找到货位【{supplyTask.LocationCode}】的库存信息");
                inventoryInfo.StockQuantity -= supplyTask.StockQuantity;
                inventoryInfo.OutboundQuantity -= supplyTask.StockQuantity;
                #endregion
                Dt_LocationInfo location = _locationInfoService.Repository.QueryFirst(x => x.LocationCode == supplyTask.LocationCode);
                #region è´§ä½
                if (supplyTask.WarehouseCode != WarehouseEnum.立库.ObjToInt().ToString("000"))
                {
                    if (location == null)
                        return WebResponseContent.Instance.Error($"请维护货位编号【{supplyTask.LocationCode}】的货位信息");
                    Dt_InventoryInfo inventoryInfo1 = _inventoryInfoService.Repository.QueryFirst(x => x.LocationCode == supplyTask.LocationCode);
                    if (inventoryInfo1 == null) location.LocationStatus = LocationStatusEnum.Free.ObjToInt();
                }
                #endregion
                #region åº“存批次 å¦‚果任务类型是调拨出库任务(8)就不修改批次库存
                Dt_Inventory_Batch inventory_Batch = _inventory_BatchServices.Repository.QueryFirst(x => x.BatchNo == inventoryInfo.BatchNo && x.MaterielCode ==
                    inventoryInfo.MaterielCode);
                if (supplyTask.TaskType != TaskTypeEnum.AllocatOut.ObjToInt())
                {
                    inventory_Batch.StockQuantity -= supplyTask.StockQuantity;
                    inventory_Batch.OutboundQuantity -= supplyTask.StockQuantity;
                }
                #endregion
                supplyTask.TaskStatus = SupplyStatusEnum.OutFinish.ObjToInt();
                _unitOfWorkManage.BeginTran();
                if (inventory_Batch.StockQuantity <= 0)
                    _inventory_BatchServices.DeleteData(inventory_Batch);
                else
                    _inventory_BatchServices.UpdateData(inventory_Batch);
                _materielInfoService.UpdateData(materielInfo);
                if (inventoryInfo.StockQuantity <= 0)
                    _inventoryInfoService.DeleteData(inventoryInfo);
                else
                    _inventoryInfoService.UpdateData(inventoryInfo);
                if (location != null) _locationInfoService.UpdateData(location);
                _deliveryOrderDetailServices.UpdateData(cabinOrderDetail);
                _supplyTaskService.Repository.DeleteAndMoveIntoHty(supplyTask, OperateTypeEnum.人工完成);
                #region åˆ¤æ–­è¯¦æƒ…是否全部完成
                if (!_deliveryOrderDetailServices.Repository.QueryData(x => x.DeliveryOrderId == deliveryOrder.Id && x.OotDetailStatus != "已完成").Any())
                    deliveryOrder.OutStatus = "已完成";
                BaseDal.UpdateData(deliveryOrder);
                if (supplyTask.WarehouseCode == WarehouseEnum.立库.ObjToInt().ToString("000"))
                {
                    materielInfo.Business_qty -= supplyTask.StockQuantity;
                    if (materielInfo.Business_qty < materielInfo.MinQty)
                        CreateAllocatInOut(materielInfo);//创建调拨任务
                }
                #endregion
                _unitOfWorkManage.CommitTran();
                content.OK();
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                content.Error(ex.Message);
            }
            return content;
        }
        public WebResponseContent OutTaskFinish(Dt_SupplyTask supplyTask)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                Dt_DeliveryOrder? cabinOrder = BaseDal.Db.CopyNew().Queryable<Dt_DeliveryOrder>().Where(x => x.Out_no == supplyTask.OrderNo && x.Warehouse_no == supplyTask.WarehouseCode).Includes(x => x.Details).First();
                if (cabinOrder == null) return WebResponseContent.Instance.OK($"出库单已完成");
                Dt_DeliveryOrder cabinOrder = BaseDal.Db.Queryable<Dt_DeliveryOrder>().Where(x => x.Out_no == supplyTask.OrderNo && x.Warehouse_no == supplyTask.WarehouseCode).Includes(x => x.Details).First();
                if (cabinOrder == null) return WebResponseContent.Instance.Error($"出库单已完成");
                Dt_DeliveryOrderDetail cabinOrderDetail = cabinOrder.Details.Where(x => x.Batch_num == supplyTask.BatchNo && x.Reservoirarea == supplyTask.WarehouseCode && x.Goods_no == supplyTask.MaterielCode).First();
                if (cabinOrderDetail == null) return WebResponseContent.Instance.Error($"出库单明细已完成");
                Dt_MaterielInfo materielInfo = _basicService.MaterielInfoService.Repository.QueryFirst(x => x.MaterielCode == cabinOrderDetail.Goods_no);
                Dt_DeliveryOrderDetail? cabinOrderDetail = cabinOrder.Details.Where(x => x.Batch_num == supplyTask.BatchNo && x.Reservoirarea == supplyTask.WarehouseCode && x.Goods_no == supplyTask.MaterielCode).FirstOrDefault();
                if (cabinOrderDetail == null) return WebResponseContent.Instance.Error($"出库单明细未找到");
                Dt_MaterielInfo materielInfo = _materielInfoService.Repository.QueryFirst(x => x.MaterielCode == cabinOrderDetail.Goods_no);
                if (materielInfo == null) return WebResponseContent.Instance.Error($"请维护物料编号【{cabinOrderDetail.Goods_no}】的物料信息");
                cabinOrderDetail.Order_Outqty += supplyTask.StockQuantity;
                if (cabinOrderDetail.Order_Outqty > cabinOrderDetail.Order_qty)
@@ -982,7 +1042,7 @@
                #region å¤„理出库单,货位,库存,库存批次信息,出库任务
                _unitOfWorkManage.BeginTran();
                //_unitOfWorkManage.BeginTran();
                #region å‡ºåº“单
                cabinOrder.OutStatus = "开始";
@@ -993,7 +1053,7 @@
                    //_deliveryOrderDetailServices.Repository.DeleteAndMoveIntoHty(cabinOrderDetail, OperateTypeEnum.自动完成);
                }
                _deliveryOrderDetailServices.Repository.UpdateData(cabinOrderDetail);
                var cabinOrder1 = BaseDal.Db.Queryable<Dt_DeliveryOrder>().Where(x => x.Out_no == cabinOrder.Out_no && x.Warehouse_no == supplyTask.WarehouseCode && x.Out_type != "3").Includes(x => x.Details).First();
                var cabinOrder1 = BaseDal.Db.CopyNew().Queryable<Dt_DeliveryOrder>().Where(x => x.Out_no == cabinOrder.Out_no && x.Warehouse_no == supplyTask.WarehouseCode && x.Out_type != "20").Includes(x => x.Details).First();
                if (!cabinOrder1.Details.Where(x => x.OotDetailStatus != "已完成").Any())
                    cabinOrder.OutStatus = "已完成";
                Repository.UpdateData(cabinOrder);
@@ -1013,7 +1073,7 @@
                #region è´§ä½
                if (supplyTask.WarehouseCode != WarehouseEnum.立库.ObjToInt().ToString("000"))
                {
                    var location = _basicService.LocationInfoService.Repository.QueryFirst(x => x.LocationCode == supplyTask.LocationCode);
                    var location = _locationInfoService.Repository.QueryFirst(x => x.LocationCode == supplyTask.LocationCode);
                    if (location == null)
                        return WebResponseContent.Instance.Error($"请维护货位编号【{supplyTask.LocationCode}】的货位信息");
                    //if (location.EnableStatus == EnableStatusEnum.Disable.ObjToInt())
@@ -1022,7 +1082,7 @@
                    if (inventoryInfo1 == null)
                    {
                        location.LocationStatus = LocationStatusEnum.Free.ObjToInt();
                        _basicService.LocationInfoService.UpdateData(location);
                        _locationInfoService.UpdateData(location);
                    }
                }
                #endregion
@@ -1032,21 +1092,29 @@
                supplyTask.TaskStatus = SupplyStatusEnum.OutFinish.ObjToInt();
                _supplyTaskService.Repository.DeleteAndMoveIntoHty(supplyTask, OperateTypeEnum.人工完成);
                #region åº“存批次
                Dt_Inventory_Batch inventory_Batch = _inventory_BatchServices.Repository.QueryFirst(x => x.BatchNo == inventoryInfo.BatchNo && x.MaterielCode == inventoryInfo.MaterielCode);
                if (inventory_Batch != null)
                #region åº“存批次 å¦‚果任务类型是调拨出库任务(8)就不修改批次库存
                if (supplyTask.TaskType != TaskTypeEnum.AllocatOut.ObjToInt())
                {
                    inventory_Batch.StockQuantity -= supplyTask.StockQuantity;
                    inventory_Batch.OutboundQuantity -= supplyTask.StockQuantity;
                    if (inventory_Batch.StockQuantity <= 0)
                        _inventory_BatchServices.DeleteData(inventory_Batch);
                    else
                        _inventory_BatchServices.UpdateData(inventory_Batch);
                    Dt_Inventory_Batch inventory_Batch = _inventory_BatchServices.Repository.QueryFirst(x => x.BatchNo == inventoryInfo.BatchNo && x.MaterielCode == inventoryInfo.MaterielCode);
                    if (inventory_Batch != null)
                    {
                        inventory_Batch.StockQuantity -= supplyTask.StockQuantity;
                        inventory_Batch.OutboundQuantity -= supplyTask.StockQuantity;
                        if (inventory_Batch.StockQuantity <= 0)
                            _inventory_BatchServices.DeleteData(inventory_Batch);
                        else
                            _inventory_BatchServices.UpdateData(inventory_Batch);
                    }
                }
                #endregion
                if (supplyTask.WarehouseCode == WarehouseEnum.立库.ObjToInt().ToString("000"))
                    CreateAllocatInOut(materielInfo);//创建调拨任务
                _unitOfWorkManage.CommitTran();
                {
                    materielInfo.Business_qty -= supplyTask.StockQuantity;
                    _materielInfoService.UpdateData(materielInfo);
                    if (materielInfo.Business_qty < materielInfo.MinQty)
                        CreateAllocatInOut(materielInfo);//创建调拨任务
                }
                //_unitOfWorkManage.CommitTran();
                #endregion
                content.OK();
            }
@@ -1057,116 +1125,50 @@
            return content;
        }
        /// <summary>
        /// å¹³åº“人工拣料出库处理(即人工扫码出库时调用)
        /// äººå·¥åœ¨å‡ºåº“单中点击完成按钮实现上报
        /// </summary>
        /// <param name="saveModel"></param>
        /// <param name="key">id</param>
        /// <returns></returns>
        public WebResponseContent MatPicking(SaveModel saveModel)
        public WebResponseContent FinishOutOrder(int key)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                var LocationCode = saveModel.MainData["LocationCode"].ToString();
                var orderNo = saveModel.MainData["orderNo"].ToString();
                var batchNo = saveModel.MainData["batchNo"].ToString();
                var Inqty = saveModel.MainData["Inqty"].ObjToInt();
                var warehouseCode = saveModel.MainData["warehouseCode"].ToString();
                Dt_DeliveryOrder cabinOrder = BaseDal.Db.Queryable<Dt_DeliveryOrder>().Where(x => x.Out_no == orderNo && x.Warehouse_no == warehouseCode && x.Out_type != "3").Includes(x => x.Details).First();
                if (cabinOrder == null) return WebResponseContent.Instance.Error($"出库单已完成");
                Dt_DeliveryOrderDetail cabinOrderDetail = cabinOrder.Details.Where(x => x.Batch_num == batchNo && x.Reservoirarea == warehouseCode).First();
                if (cabinOrderDetail == null) return WebResponseContent.Instance.Error($"出库单明细已完成");
                Dt_MaterielInfo materielInfo = _basicService.MaterielInfoService.Repository.QueryFirst(x => x.MaterielCode == cabinOrderDetail.Goods_no);
                if (materielInfo == null) return WebResponseContent.Instance.Error($"请维护物料编号【{cabinOrderDetail.Goods_no}】的物料信息");
                cabinOrderDetail.Order_Outqty += Inqty;
                if (cabinOrderDetail.Order_Outqty > cabinOrderDetail.Order_qty)
                    return WebResponseContent.Instance.Error($"出库数量不可超出单据数量");
                #region å¤„理出库单,货位,库存,库存批次信息
                _unitOfWorkManage.BeginTran();
                #region å‡ºåº“单
                cabinOrder.OutStatus = "开始";
                cabinOrderDetail.OotDetailStatus = "开始";
                if (cabinOrderDetail.Order_Outqty == cabinOrderDetail.Order_qty)
                Dt_DeliveryOrder deliveryOrder = BaseDal.QueryFirst(x => x.Id == key);
                List<Dt_DeliveryOrder> deliveryOrders = Db.Queryable<Dt_DeliveryOrder>().Where(x => x.Out_no == deliveryOrder.Out_no).Includes(x => x.Details).ToList();//找出所有出库单号相同的出库单
                List<Dt_DeliveryOrderDetail> deliveryOrderDetails = new List<Dt_DeliveryOrderDetail>();
                foreach (var item in deliveryOrders)
                {
                    cabinOrderDetail.OotDetailStatus = "已完成";
                    _deliveryOrderDetailServices.Repository.DeleteAndMoveIntoHty(cabinOrderDetail, OperateTypeEnum.自动完成);
                    if (item.Details != null) deliveryOrderDetails.AddRange(item.Details);
                    item.Modifier = App.User.UserName;
                    item.ModifyDate = DateTime.Now;
                    item.Details = null;
                }
                if (deliveryOrder.Out_type == OutOrderTypeEnum.Allocate.ObjToInt().ToString())
                {
                    _deliveryOrderDetailServices.Repository.DeleteAndMoveIntoHty(deliveryOrderDetails, OperateTypeEnum.人工完成);
                    BaseDal.DeleteAndMoveIntoHty(deliveryOrders, OperateTypeEnum.人工完成);
                }
                else
                {
                    _deliveryOrderDetailServices.Repository.UpdateData(cabinOrderDetail);
                    var url = "http://121.37.118.63:80/GYZ2/95fck/outOrderOk";
                    if (deliveryOrder.Out_type == "3") url = "http://121.37.118.63:80/GYZ2/95fck/inOrderOk";
                    var requestDate = new
                    {
                        order_no = deliveryOrder.Out_no
                    };
                    var result = HttpHelper.Post(url, requestDate.ToJsonString());
                    var response = JsonConvert.DeserializeObject<UpstreamOrderResponse>(result);
                    if (response == null) throw new Exception("上报ERP出库单完成失败!");
                    if (response.resultCode != "0" && response.resultMsg != "未找到合法单据") throw new Exception(response.resultMsg);
                    _deliveryOrderDetailServices.Repository.DeleteAndMoveIntoHty(deliveryOrderDetails, OperateTypeEnum.人工完成);
                    BaseDal.DeleteAndMoveIntoHty(deliveryOrders, OperateTypeEnum.人工完成);
                }
                var cabinOrder1 = BaseDal.Db.Queryable<Dt_DeliveryOrder>().Where(x => x.Out_no == cabinOrder.Out_no && x.Out_type != "3").Includes(x => x.Details).First();
                if (cabinOrder1.Details == null || cabinOrder1.Details.Count < 1) cabinOrder.OutStatus = "已完成";
                Repository.UpdateData(cabinOrder);
                #endregion
                #region åº“å­˜
                Dt_InventoryInfo inventoryInfo = _inventoryInfoService.Repository.QueryFirst(x => x.BatchNo == cabinOrderDetail.Batch_num && x.MaterielCode == cabinOrderDetail.Goods_no && x.LocationCode == LocationCode);
                if (inventoryInfo == null) return WebResponseContent.Instance.Error($"未找到货位【{LocationCode}】的库存信息");
                inventoryInfo.StockQuantity -= Inqty;
                if (inventoryInfo.StockQuantity <= 0)
                    _inventoryInfoService.DeleteData(inventoryInfo);
                else
                    _inventoryInfoService.UpdateData(inventoryInfo);
                #endregion
                #region è´§ä½
                var location = _basicService.LocationInfoService.Repository.QueryFirst(x => x.LocationCode == LocationCode);
                if (location == null) return WebResponseContent.Instance.Error($"请维护货位编号【{LocationCode}】的货位信息");
                if (location.EnableStatus == EnableStatusEnum.Disable.ObjToInt())
                    return WebResponseContent.Instance.Error($"货位编号【{LocationCode}】已禁用,请恢复正常再使用");
                Dt_InventoryInfo inventoryInfo1 = _inventoryInfoService.Repository.QueryFirst(x => x.LocationCode == LocationCode);
                if (inventoryInfo1 == null)
                {
                    location.LocationStatus = LocationStatusEnum.Free.ObjToInt();
                    _basicService.LocationInfoService.UpdateData(location);
                }
                #endregion
                #region ä»»åŠ¡è®°å½•
                Dt_SupplyTask supplyTask = new Dt_SupplyTask()
                {
                    WarehouseCode = cabinOrderDetail.Reservoirarea,
                    BatchNo = inventoryInfo.BatchNo,
                    MaterielName = inventoryInfo.MaterielName,
                    MaterielCode = inventoryInfo.MaterielCode,
                    MaterielSpec = inventoryInfo.MaterielSpec,
                    TaskStatus = SupplyStatusEnum.OutFinish.ObjToInt(),
                    TaskType = TaskTypeEnum.OutPick.ObjToInt(),
                    CreateDate = DateTime.Now,
                    Creater = App.User.UserName,
                    LocationCode = location.LocationCode,
                    OrderNo = cabinOrder.Out_no,
                    StockQuantity = Inqty,
                    SupplyQuantity = 0,
                    Remark = "出库"
                };
                _supplyTaskService.AddData(supplyTask);
                #endregion
                #region åº“存批次
                Dt_Inventory_Batch inventory_Batch = _inventory_BatchServices.Repository.QueryFirst(x => x.BatchNo == inventoryInfo.BatchNo && x.MaterielCode == inventoryInfo.MaterielCode);
                if (inventory_Batch != null)
                {
                    inventory_Batch.StockQuantity -= Inqty;
                    if (inventory_Batch.StockQuantity <= 0)
                        _inventory_BatchServices.DeleteData(inventory_Batch);
                    else
                        _inventory_BatchServices.UpdateData(inventory_Batch);
                }
                #endregion
                _unitOfWorkManage.CommitTran();
                #endregion
                content.OK(cabinOrderDetail.Order_Outqty.ToString());
                content.OK();
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                content.Error(ex.Message);
            }
            return content;