dengjunjie
7 天以前 bc43fe34a67fa68bcfb3a51b79308fad0be11c08
н¨Îļþ¼Ð/WIDESEA_WMSServer/WIDESEA_SquareCabinServices/CabinOrderServices.cs
@@ -1,6 +1,7 @@
using HslCommunication;
using MailKit.Search;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Newtonsoft.Json;
using SqlSugar;
using System;
@@ -13,11 +14,13 @@
using WIDESEA_Common.OrderEnum;
using WIDESEA_Common.StockEnum;
using WIDESEA_Common.TaskEnum;
using WIDESEA_Common.WareHouseEnum;
using WIDESEA_Core;
using WIDESEA_Core.BaseRepository;
using WIDESEA_Core.BaseServices;
using WIDESEA_Core.Enums;
using WIDESEA_Core.Helper;
using WIDESEA_DTO.SquareCabin;
using WIDESEA_IBasicService;
using WIDESEA_ISquareCabinServices;
using WIDESEA_IWMsInfoServices;
@@ -32,29 +35,39 @@
{
    public class CabinOrderServices : ServiceBase<Dt_CabinOrder, IRepository<Dt_CabinOrder>>, ICabinOrderServices
    {
        static string SearchDate = "";
        private readonly IBasicService _basicService;
        private readonly IMedicineGoodsServices _medicineGoodsServices;
        private readonly IUnitOfWorkManage _unitOfWorkManage;
        private readonly IInventory_BatchServices _inventory_BatchServices;
        private readonly IInventoryInfoService _inventoryInfoService;
        private readonly ICabinOrderDetailServices _cabinOrderDetailServices;
        private readonly ISupplyTaskService _supplyTaskService;
        private readonly ISupplyTaskHtyService _supplyTaskHtyService;
        private readonly ILocationInfoService _locationInfoService;
        private readonly IMaterielInfoService _materielInfoService;
        private readonly IMessageInfoService _messageInfoService;
        public IRepository<Dt_CabinOrder> Repository => BaseDal;
        public CabinOrderServices(IRepository<Dt_CabinOrder> BaseDal, IBasicService basicService, IMedicineGoodsServices medicineGoodsServices, IUnitOfWorkManage unitOfWorkManage, IInventory_BatchServices inventory_BatchServices, IInventoryInfoService inventoryInfoService, ICabinOrderDetailServices cabinOrderDetailServices, ICabinOrderHtyServices cabinOrderHtyServices, ICabinOrderDetailHtyServices cabinOrderDetailHtyServices, ISupplyTaskService supplyTaskService) : base(BaseDal)
        public CabinOrderServices(IRepository<Dt_CabinOrder> BaseDal, IMedicineGoodsServices medicineGoodsServices, IUnitOfWorkManage unitOfWorkManage, IInventory_BatchServices inventory_BatchServices, IInventoryInfoService inventoryInfoService, ICabinOrderDetailServices cabinOrderDetailServices, ICabinOrderHtyServices cabinOrderHtyServices, ICabinOrderDetailHtyServices cabinOrderDetailHtyServices, ISupplyTaskService supplyTaskService, ISupplyTaskHtyService supplyTaskHtyService, IMessageInfoService messageInfoService, IMaterielInfoService materielInfoService, ILocationInfoService locationInfoService) : base(BaseDal)
        {
            _basicService = basicService;
            _medicineGoodsServices = medicineGoodsServices;
            _unitOfWorkManage = unitOfWorkManage;
            _inventory_BatchServices = inventory_BatchServices;
            _inventoryInfoService = inventoryInfoService;
            _cabinOrderDetailServices = cabinOrderDetailServices;
            _supplyTaskService = supplyTaskService;
            _supplyTaskHtyService = supplyTaskHtyService;
            _messageInfoService = messageInfoService;
            _materielInfoService = materielInfoService;
            _locationInfoService = locationInfoService;
        }
        /// <summary>
        /// pda查询入库单信息
        /// </summary>
        /// <param name="saveModel"></param>
        /// <returns></returns>
        public WebResponseContent GetCabinOrders(SaveModel saveModel)
        {
            WebResponseContent content = new WebResponseContent();
@@ -82,14 +95,28 @@
            }
            return content;
        }
        /// <summary>
        /// pda查看入库详情表
        /// </summary>
        /// <param name="pageNo"></param>
        /// <param name="orderNo"></param>
        /// <returns></returns>
        public WebResponseContent GetCabinOrderDetail(int pageNo, string orderNo)
        {
            WebResponseContent content = new WebResponseContent();
            Dt_CabinOrder cabinOrder = Db.Queryable<Dt_CabinOrder>().Includes(x => x.Details).First(x => x.Order_no == orderNo);
            List<Dt_CabinOrderDetail> cabinOrderDetails = cabinOrder.Details.Where(x => x.Reservoirarea == pageNo.ToString()).ToList();
            List<Dt_CabinOrderDetail> cabinOrderDetails = cabinOrder.Details.Where(x => x.Status == 2 && x.OrderDetailStatus != "已完成").ToList();
            content.OK(data: cabinOrderDetails);
            return content;
        }
        /// <summary>
        /// Pad入库完成
        /// </summary>
        /// <param name="saveModel"></param>
        /// <returns></returns>
        public WebResponseContent FeedbackIn([FromBody] SaveModel saveModel)
        {
            WebResponseContent content = new WebResponseContent();
@@ -98,13 +125,16 @@
                var LocationCode = saveModel.MainData["LocationCode"].ToString();
                var orderNo = saveModel.MainData["orderNo"].ToString();
                var batchNo = saveModel.MainData["batchNo"].ToString();
                var materielCode = saveModel.MainData["materielCode"].ToString();
                var Inqty = saveModel.MainData["Inqty"].ObjToInt();
                var warehouseCode = saveModel.MainData["warehouseCode"].ToString();
                Dt_CabinOrder cabinOrder = BaseDal.Db.Queryable<Dt_CabinOrder>().Where(x => x.Order_no == orderNo && x.Warehouse_no == warehouseCode).Includes(x => x.Details).First();
                if (cabinOrder == null) return WebResponseContent.Instance.Error($"入库单已完成");
                Dt_CabinOrderDetail 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 (cabinOrder == null || cabinOrder.OdrderStatus == "已完成")
                    return WebResponseContent.Instance.Error($"入库单已完成");
                Dt_CabinOrderDetail cabinOrderDetail = cabinOrder.Details.Where(x => x.Goods_no == materielCode && x.Batch_num == batchNo && x.Status == 2).FirstOrDefault();
                if (cabinOrderDetail == null || cabinOrderDetail.OrderDetailStatus == "已完成")
                    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_Inqty += Inqty;
                if (cabinOrderDetail.Order_Inqty > cabinOrderDetail.Order_qty)
@@ -119,26 +149,24 @@
                if (cabinOrderDetail.Order_Inqty == cabinOrderDetail.Order_qty)
                {
                    cabinOrderDetail.OrderDetailStatus = "已完成";
                    _cabinOrderDetailServices.Repository.DeleteAndMoveIntoHty(cabinOrderDetail, OperateTypeEnum.自动完成);
                }
                else
                {
                    _cabinOrderDetailServices.Repository.UpdateData(cabinOrderDetail);
                }
                var cabinOrder1 = BaseDal.Db.Queryable<Dt_CabinOrder>().Where(x => x.Order_no == cabinOrder.Order_no).Includes(x => x.Details).First();
                if (cabinOrder1.Details == null || cabinOrder1.Details.Count < 1) cabinOrder.OdrderStatus = "已完成";
                _cabinOrderDetailServices.Repository.UpdateData(cabinOrderDetail);
                var cabinOrder1 = BaseDal.Db.Queryable<Dt_CabinOrder>().Where(x => x.Order_no == cabinOrder.Order_no && x.Warehouse_no == warehouseCode).Includes(x => x.Details).First();
                if (!cabinOrder1.Details.Where(x => x.OrderDetailStatus != "已完成").Any()) cabinOrder.OdrderStatus = "已完成";
                Repository.UpdateData(cabinOrder);
                #endregion
                #region è´§ä½
                var location = _basicService.LocationInfoService.Repository.QueryFirst(x => x.LocationCode == LocationCode);
                var location = _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}】已禁用,请恢复正常再使用");
                if (location.LocationStatus != LocationStatusEnum.InStock.ObjToInt())
                if (location.WarehouseCode != cabinOrderDetail.Reservoirarea)
                    return WebResponseContent.Instance.Error($"货位编号【{LocationCode}】所属库房与当前入库单所属库房不匹配");
                if (location.LocationStatus == LocationStatusEnum.Free.ObjToInt())
                {
                    location.LocationStatus = LocationStatusEnum.InStock.ObjToInt();
                    _basicService.LocationInfoService.UpdateData(location);
                    _locationInfoService.UpdateData(location);
                }
                #endregion
@@ -147,6 +175,8 @@
                if (inventoryInfo != null)
                {
                    inventoryInfo.StockQuantity += Inqty;
                    inventoryInfo.AvailableQuantity += Inqty;
                    inventoryInfo.InDate = DateTime.Now;
                    _inventoryInfoService.UpdateData(inventoryInfo);
                }
                else
@@ -159,6 +189,7 @@
                        MaterielSpec = materielInfo.MaterielSpec,
                        OutboundQuantity = 0,
                        StockQuantity = Inqty,
                        AvailableQuantity = Inqty,
                        StockStatus = StockStatusEmun.入库完成.ObjToInt(),
                        ValidityPeriod = cabinOrderDetail.Exp_date,
                        WarehouseCode = cabinOrderDetail.Reservoirarea,
@@ -168,19 +199,59 @@
                        Creater = App.User.UserName,
                        CreateDate = DateTime.Now,
                    };
                    switch (inventoryInfo.WarehouseCode)
                    {
                        case "001":
                            inventoryInfo.Remark = "智能立库";
                            break;
                        case "002":
                            inventoryInfo.Remark = "大件库";
                            break;
                        case "003":
                            inventoryInfo.Remark = "麻精库";
                            break;
                        case "010":
                            inventoryInfo.Remark = "冷冻库";
                            break;
                    }
                    _inventoryInfoService.AddData(inventoryInfo);
                }
                #endregion
                #region ä»»åŠ¡è®°å½•
                Dt_SupplyTask supplyTask = new Dt_SupplyTask()
                #region MyRegion
                //Dt_SupplyTask supplyTask = new Dt_SupplyTask()
                //{
                //    WarehouseCode = cabinOrderDetail.Reservoirarea,
                //    TaskNum = cabinOrderDetail.Id,
                //    TaskStatus = SupplyStatusEnum.InFinish.ObjToInt(),
                //    BatchNo = inventoryInfo.BatchNo,
                //    MaterielName = inventoryInfo.MaterielName,
                //    MaterielCode = inventoryInfo.MaterielCode,
                //    MaterielSpec = inventoryInfo.MaterielSpec,
                //    TaskType = TaskTypeEnum.InPick.ObjToInt(),
                //    CreateDate = DateTime.Now,
                //    Creater = App.User.UserName,
                //    LocationCode = location.LocationCode,
                //    OrderNo = cabinOrder.Order_no,
                //    StockQuantity = Inqty,
                //    SupplyQuantity = 0,
                //    Remark = "入库"
                //};
                //_supplyTaskService.AddData(supplyTask);
                #endregion
                Dt_SupplyTask_Hty supplyTask_Hty = new Dt_SupplyTask_Hty()
                {
                    WarehouseCode = cabinOrderDetail.Reservoirarea,
                    BatchNo=inventoryInfo.BatchNo,
                    MaterielName= inventoryInfo.MaterielName,
                    MaterielCode= inventoryInfo.MaterielCode,
                    MaterielSpec= inventoryInfo.MaterielSpec,
                    TaskType=TaskTypeEnum.InPick.ObjToInt(),
                    TaskNum = cabinOrderDetail.Id,
                    OperateType = OperateTypeEnum.人工完成.ToString(),
                    InsertTime = DateTime.Now,
                    TaskStatus = SupplyStatusEnum.InFinish.ObjToInt(),
                    BatchNo = inventoryInfo.BatchNo,
                    MaterielName = inventoryInfo.MaterielName,
                    MaterielCode = inventoryInfo.MaterielCode,
                    MaterielSpec = inventoryInfo.MaterielSpec,
                    TaskType = cabinOrder.Order_type == "1" ? TaskTypeEnum.In.ObjToInt() : TaskTypeEnum.OutReturn.ObjToInt(),
                    CreateDate = DateTime.Now,
                    Creater = App.User.UserName,
                    LocationCode = location.LocationCode,
@@ -189,7 +260,7 @@
                    SupplyQuantity = 0,
                    Remark = "入库"
                };
                _supplyTaskService.AddData(supplyTask);
                _supplyTaskHtyService.AddData(supplyTask_Hty);
                #endregion
                #region åº“存批次
@@ -197,6 +268,7 @@
                if (inventory_Batch != null)
                {
                    inventory_Batch.StockQuantity += Inqty;
                    inventory_Batch.AvailableQuantity += Inqty;
                    _inventory_BatchServices.UpdateData(inventory_Batch);
                }
                else
@@ -214,7 +286,8 @@
                        ProductionDate = inventoryInfo.ProductionDate,
                        Status = false,
                        StockQuantity = inventoryInfo.StockQuantity,
                        ValidityPeriod = inventoryInfo.ValidityPeriod,
                        AvailableQuantity = inventoryInfo.StockQuantity,
                        ValidityPeriod = inventoryInfo.ValidityPeriod.ObjToDate(),
                        SupplyQuantity = inventoryInfo.SupplyQuantity,
                    };
                    _inventory_BatchServices.AddData(inventory_Batch);
@@ -234,106 +307,155 @@
            return content;
        }
        #region åˆ›å»ºå…¥åº“单
        /// <summary>
        /// èŽ·å–ä¸Šæ¸¸ç³»ç»Ÿçš„å…¥åº“å•
        /// åˆ›å»ºå…¥åº“单,返回一个入库单集合到data
        /// </summary>
        /// <param name="searchDate"></param>
        /// <returns></returns>
        public WebResponseContent GetUpstreamOrder()
        public WebResponseContent CreateInboundOrder(UpstreamOrderInfo order)
        {
            var responseContent = new WebResponseContent();
            WebResponseContent webResponseContent = new WebResponseContent();
            try
            {
                // è¯·æ±‚地址
                var url = "http://121.37.118.63:80/GYZ2/95fck/inOrder";
                //if (string.IsNullOrEmpty(SearchDate)) SearchDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                //// è¯·æ±‚参数
                var requestData = new
                string WareCodeMJ = WarehouseEnum.麻精库.ObjToInt().ToString("000");
                string WareCodeLD = WarehouseEnum.冷冻库.ObjToInt().ToString("000");
                List<Dt_CabinOrder> dt_CabinOrders = new List<Dt_CabinOrder>();
                #region ç‰¹æ®Šè¯å“å…¥ç‰¹æ®Šåº“房
                if (order.warehouse_no == WareCodeMJ || order.warehouse_no == WareCodeLD)
                {
                    //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<UpstreamOrderInfo>>(result);
                if (response.resultCode != "0")
                {
                    // è°ƒç”¨å¼‚常接口
                    SendErrorToUpstream(1, "", response.resultMsg ?? "上游接口返回失败", "");
                    return responseContent.Error(response.resultMsg ?? "上游接口返回失败");
                }
                if (response.data == null || !response.data.Any())
                {
                    return responseContent.OK("无新入库单数据");
                }
                // èŽ·å–æ‰€æœ‰å·²å­˜åœ¨çš„å…¥åº“å•å·
                var existingOrderNos = BaseDal.Db.Queryable<Dt_CabinOrder>()
                    .Select(x => x.Order_no)
                    .ToList();
                // è¿‡æ»¤æŽ‰å·²å­˜åœ¨çš„入库单
                var newOrders = response.data
                    .Where(order => !existingOrderNos.Contains(order.order_no))
                    .ToList();
                if (!newOrders.Any())
                {
                    return responseContent.OK("所有入库单已存在,无需新增");
                }
                Db.Ado.BeginTran();
                try
                {
                    List<Dt_CabinOrder> _CabinOrders = new List<Dt_CabinOrder>();
                    //存储入库单号
                    List<string> orderNos = new List<string>();
                    foreach (var order in newOrders)
                    var entityOrder = new Dt_CabinOrder
                    {
                        var entityOrder = new Dt_CabinOrder
                        Order_no = order.order_no,
                        Order_type = order.order_type,
                        Supplier_no = order.supplier_no,
                        Account_tiem = order.account_time,
                        OdrderStatus = "新建",
                        Supplier_name = order.supplier_name,
                        Warehouse_no = order.warehouse_no,
                        Details = order.details.Select(d => new Dt_CabinOrderDetail
                        {
                            Order_no = order.order_no,
                            //入库单类型
                            Order_type = order.order_type,
                            Supplier_no = order.supplier_no,
                            Account_tiem = order.account_time,
                            OdrderStatus = "新建",
                            Supplier_name = order.supplier_name,
                            Warehouse_no = order.warehouse_no,
                            Details = new List<Dt_CabinOrderDetail>()
                            //Details = order.details.Select(d => new Dt_CabinOrderDetail
                            //{
                            //    //OrderId è¦æ‹¿åˆ°å…¥åº“单表中的id,如何拿不到就将这个字段改了,改成入库单号
                            //    // SqlSugar InsertNav工作原理先插入主表 (Dt_CabinOrder)//获取生成的主键ID//自动设置子表的关联字段 (OrderId)//再插入(Dt_CabinOrderDetail)
                            //    Goods_no = d.goods_no,
                            //    Order_qty = d.order_qty,
                            //    Batch_num = d.batch_num,
                            //    Exp_date = d.exp_date,
                            //    OrderDetailStatus = "新建",
                            //    Status = order.warehouse_no == "001" ? 0 : 2, //如果是001房那么就是未同步状态,如果不是001房那么就是无需同步状态
                            //}).ToList()
                        };
                        foreach (var item in order.details)
                            Reservoirarea = order.warehouse_no,
                            Goods_no = d.goods_no,
                            Order_qty = Math.Abs(d.order_qty),
                            Batch_num = d.batch_num,
                            Exp_date = d.exp_date,
                            OrderDetailStatus = "新建",
                            Status = 2, //如果是001房那么就是未同步状态,如果不是001房那么就是无需同步状态
                        }).ToList()
                    };
                    dt_CabinOrders.Add(entityOrder);
                    webResponseContent.OK(data: dt_CabinOrders);
                }
                #endregion
                else
                {
                    var entityOrder = new Dt_CabinOrder//大件库订单
                    {
                        Order_no = order.order_no,
                        Order_type = order.order_type,
                        Supplier_no = order.supplier_no,
                        Account_tiem = order.account_time,
                        OdrderStatus = "新建",
                        Supplier_name = order.supplier_name,
                        Warehouse_no = WarehouseEnum.大件库.ObjToInt().ToString("000"),
                        Details = new List<Dt_CabinOrderDetail>()
                    };
                    var entityOrderLK = new Dt_CabinOrder//立库订单
                    {
                        Order_no = order.order_no,
                        Order_type = order.order_type,
                        Supplier_no = order.supplier_no,
                        Account_tiem = order.account_time,
                        OdrderStatus = "新建",
                        Supplier_name = order.supplier_name,
                        Warehouse_no = WarehouseEnum.立库.ObjToInt().ToString("000"),
                        Details = new List<Dt_CabinOrderDetail>()
                    };
                    foreach (var item in order.details)
                    {
                        // å°†ä¸Šæ¸¸å…¥åº“数量转为正数
                        item.order_qty = Math.Abs(item.order_qty);
                        #region æ ¹æ®ç‰©æ–™ç¼–码查询物料信息
                        Dt_MaterielInfo materielInfo = _materielInfoService.Repository.QueryFirst(x => x.MaterielCode == item.goods_no);
                        if (materielInfo == null) throw new Exception($"未找到药品编码【{item.goods_no}】的信息");
                        if (!Enum.IsDefined(typeof(MaterielSourceTypeEnum), materielInfo.MaterielSourceType))
                            throw new Exception($"请设置药品编号【{item.goods_no}】的属性分类");
                        #endregion
                        #region å¤§ä»¶
                        if (materielInfo.MaterielSourceType == MaterielSourceTypeEnum.PurchasePart)//如果物料是大件
                        {
                            // å°†ä¸Šæ¸¸å…¥åº“数量转为正数
                            item.order_qty = Math.Abs(item.order_qty);
                            #region æ ¹æ®ç‰©æ–™ç¼–码查询物料信息
                            //Dt_MaterielInfo materielInfo = _basicService.MaterielInfoService.Repository.QueryFirst(x => x.MaterielCode == item.goods_no);
                            Dt_MedicineGoods materielInfo = BaseDal.Db.Queryable<Dt_MedicineGoods>().Where(x => x.Goods_no == item.goods_no).First();
                            ///根据物料信息大小件属性区分是否入立库 //大件入平库
                            if (materielInfo.MaterielSourceType == MaterielSourceTypeEnum.PurchasePart)
                            Dt_CabinOrderDetail orderDetail = new Dt_CabinOrderDetail()
                            {
                                Dt_CabinOrderDetail orderDetail = new Dt_CabinOrderDetail()
                                Reservoirarea = entityOrder.Warehouse_no,
                                Goods_no = item.goods_no,
                                Order_qty = item.order_qty,
                                Batch_num = item.batch_num,
                                Exp_date = item.exp_date,
                                OrderDetailStatus = "新建",
                                Status = 2
                            };
                            entityOrder.Details.Add(orderDetail);
                        }
                        #endregion
                        else
                        {
                            if (materielInfo.BoxQty < 1) throw new Exception($"请设置药品编号【{item.goods_no}】的箱规数量");
                            if (materielInfo.MinQty < 1) throw new Exception($"请设置药品编号【{item.goods_no}】的立库最低库存数");
                            Dt_CabinOrderDetail orderDetail = null;
                            var ys = item.order_qty % materielInfo.BoxQty; //不能整除箱规的散件数
                            var xs = (int)(item.order_qty / materielInfo.BoxQty);//保留整数
                            #region åˆ¤æ–­æ˜¯å¦æœ‰æ•£ä»¶
                            if (ys > 0)
                            {
                                orderDetail = new Dt_CabinOrderDetail()
                                {
                                    Reservoirarea = order.warehouse_no,
                                    Reservoirarea = entityOrderLK.Warehouse_no,
                                    Goods_no = item.goods_no,
                                    Order_qty = item.order_qty,
                                    Order_qty = ys,
                                    Batch_num = item.batch_num,
                                    Exp_date = item.exp_date,
                                    OrderDetailStatus = "新建",
                                    Status = 0
                                };
                                materielInfo.Business_qty += ys;
                            }
                            #endregion
                            #region åˆ¤æ–­ç«‹åº“库存是否大于立库最低库存数
                            while (materielInfo.Business_qty < materielInfo.MinQty && xs > 0) //当业务数量和整箱数都大于0的时候才会停止循环
                            {
                                xs--;
                                if (orderDetail == null)
                                {
                                    orderDetail = new Dt_CabinOrderDetail()
                                    {
                                        Reservoirarea = entityOrderLK.Warehouse_no,
                                        Goods_no = item.goods_no,
                                        Order_qty = materielInfo.BoxQty,
                                        Batch_num = item.batch_num,
                                        Exp_date = item.exp_date,
                                        OrderDetailStatus = "新建",
                                        Status = 0
                                    };
                                    materielInfo.Business_qty += materielInfo.BoxQty;
                                }
                                else
                                {
                                    orderDetail.Order_qty += materielInfo.BoxQty;
                                    materielInfo.Business_qty += materielInfo.BoxQty;
                                }
                            }
                            if (orderDetail != null) entityOrderLK.Details.Add(orderDetail);
                            #endregion
                            #region å‰©ä½™æ•´ä»¶å…¥å¹³åº“
                            if (xs > 0)
                            {
                                orderDetail = new Dt_CabinOrderDetail()
                                {
                                    Reservoirarea = entityOrder.Warehouse_no,
                                    Goods_no = item.goods_no,
                                    Order_qty = materielInfo.BoxQty * xs,
                                    Batch_num = item.batch_num,
                                    Exp_date = item.exp_date,
                                    OrderDetailStatus = "新建",
@@ -341,590 +463,351 @@
                                };
                                entityOrder.Details.Add(orderDetail);
                            }
                            else
                            {
                                Dt_CabinOrderDetail orderDetail = null;
                                var ys = item.order_qty % materielInfo.BoxQty; //不能整除箱规的散件数
                                var xs = item.order_qty / materielInfo.BoxQty;//整箱数量
                                #region ç”Ÿæˆç«‹åº“入库单
                                #region åˆ¤æ–­æ˜¯å¦æœ‰æ•£ä»¶
                                if (ys > 0)
                                {
                                    orderDetail = new Dt_CabinOrderDetail()
                                    {
                                        Reservoirarea = order.warehouse_no,
                                        Goods_no = item.goods_no,
                                        Order_qty = ys,
                                        Batch_num = item.batch_num,
                                        Exp_date = item.exp_date,
                                        OrderDetailStatus = "新建",
                                        Status = 0
                                    };
                                    materielInfo.Business_qty += ys;
                                }
                                #endregion
                                #region åˆ¤æ–­ç«‹åº“库存是否大于立库最低库存数
                                while (materielInfo.Business_qty < materielInfo.MinQty && xs > 0)
                                {
                                    xs--;
                                    if (orderDetail == null)
                                    {
                                        orderDetail = new Dt_CabinOrderDetail()
                                        {
                                            Reservoirarea = order.warehouse_no,
                                            Goods_no = item.goods_no,
                                            Order_qty = materielInfo.BoxQty,
                                            Batch_num = item.batch_num,
                                            Exp_date = item.exp_date,
                                            OrderDetailStatus = "新建",
                                            Status = 0
                                        };
                                        materielInfo.Business_qty += materielInfo.BoxQty;
                                    }
                                    else
                                    {
                                        orderDetail.Order_qty += materielInfo.BoxQty;
                                        materielInfo.Business_qty += materielInfo.BoxQty;
                                    }
                                }
                                #endregion
                                if (orderDetail != null) entityOrder.Details.Add(orderDetail);
                                #endregion
                                #region å‰©ä½™æ•´ä»¶å…¥å¹³åº“
                                if (xs > 0)
                                {
                                    orderDetail = new Dt_CabinOrderDetail()
                                    {
                                        Reservoirarea = order.warehouse_no,
                                        Goods_no = item.goods_no,
                                        Order_qty = materielInfo.BoxQty * xs,
                                        Batch_num = item.batch_num,
                                        Exp_date = item.exp_date,
                                        OrderDetailStatus = "新建",
                                        Status = 2
                                    };
                                    entityOrder.Details.Add(orderDetail);
                                }
                                #endregion
                            }
                            //_basicService.MaterielInfoService.Repository.UpdateData(materielInfo);
                            _medicineGoodsServices.Db.Updateable(materielInfo).ExecuteCommand();
                            #endregion
                        }
                        _CabinOrders.Add(entityOrder);
                        orderNos.Add(order.order_no);
                    };
                    BaseDal.Db.InsertNav(_CabinOrders).Include(x => x.Details).ExecuteCommand();
                    //在下发给wcs
                    //var reslut=  EdiIn(); //发给下游
                    //如果这个方法成功了,那么就调用CompleteOrder接口,然后改变
                    Db.Ado.CommitTran();
                    return responseContent.OK("同步入库单成功");
                }
                catch (Exception ex)
                {
                    Db.Ado.RollbackTran();
                    SendErrorToUpstream(1, "", ex.Message, "");
                    return responseContent.Error("同步失败: " + ex.Message);
                        _materielInfoService.UpdateData(materielInfo);
                    }
                    if (entityOrder.Details.Count > 0) dt_CabinOrders.Add(entityOrder);
                    if (entityOrderLK.Details.Count > 0) dt_CabinOrders.Add(entityOrderLK);
                    webResponseContent.OK(data: dt_CabinOrders);
                }
            }
            catch (Exception ex)
            {
                // å…¨å±€å¼‚常时,也推送异常给上游
                SendErrorToUpstream(1, "", ex.Message, "");
                return responseContent.Error("同步失败: " + ex.Message);
                webResponseContent.Error(ex.Message);
            }
            return webResponseContent;
        }
        #endregion
        /// <summary>
        /// å¯¹æ²¡æœ‰è¿›è¡Œç»´æŠ¤å•†å“ä¿¡æ¯è¡¨çš„入库单进行过滤处理
        /// </summary>
        /// <returns></returns>
        public WebResponseContent GetUpstreamOrder2()
        #region åˆ›å»ºç›˜ç›ˆå…¥åº“单
        public WebResponseContent CreateCheckInOrder(UpstreamOrderInfo order)
        {
            var responseContent = new WebResponseContent();
            WebResponseContent content = new WebResponseContent();
            try
            {
                // è¯·æ±‚地址
                var url = "http://121.37.118.63:80/GYZ2/95fck/inOrder";
                //if (string.IsNullOrEmpty(SearchDate)) SearchDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                //// è¯·æ±‚参数
                var requestData = new
                _unitOfWorkManage.BeginTran();
                string WareCodeMJ = WarehouseEnum.麻精库.ObjToInt().ToString("000");
                string WareCodeLD = WarehouseEnum.冷冻库.ObjToInt().ToString("000");
                #region ç‰¹æ®Šåº“房
                if (order.warehouse_no == WareCodeMJ || order.warehouse_no == WareCodeLD)
                {
                    //searchDate = SearchDate
                    searchDate = "2020-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<UpstreamOrderInfo>>(result);
                if (response.resultCode != "0")
                {
                    SendErrorToUpstream(1, "", response.resultMsg ?? "上游接口返回失败", "");
                    return responseContent.Error(response.resultMsg ?? "上游接口返回失败");
                }
                if (response.data == null || !response.data.Any())
                    return responseContent.OK("无新入库单数据");
                var existingOrderNos = BaseDal.Db.Queryable<Dt_CabinOrder>()
                    .Select(x => x.Order_no)
                    .ToList();
                var newOrders = response.data
                    .Where(order => !existingOrderNos.Contains(order.order_no))
                    .ToList();
                if (!newOrders.Any())
                    return responseContent.OK("所有入库单已存在,无需新增");
                Db.Ado.BeginTran();
                try
                {
                    List<Dt_CabinOrder> _CabinOrders = new();
                    List<string> orderNos = new();
                    foreach (var order in newOrders)
                    #region åº“存、库存批次平账
                    foreach (var item in order.details)
                    {
                        bool skipOrder = false; // æ ‡è®°æ˜¯å¦è·³è¿‡è¯¥å…¥åº“单
                        var entityOrder = new Dt_CabinOrder
                        //找库存批次信息
                        Dt_Inventory_Batch inventory_Batch = _inventory_BatchServices.Repository.QueryFirst(x => x.MaterielCode == item.goods_no && x.BatchNo == item.batch_num);
                        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 = _inventoryInfoService.Repository.QueryData(x => x.MaterielCode == inventory_Batch.MaterielCode && x.BatchNo == inventory_Batch.BatchNo);
                        foreach (var inventoryInfo in inventoryInfos)
                        {
                            Order_no = order.order_no,
                            Order_type = order.order_type,
                            Supplier_no = order.supplier_no,
                            Account_tiem = order.account_time,
                            OdrderStatus = "新建",
                            Supplier_name = order.supplier_name,
                            Warehouse_no = order.warehouse_no,
                            Details = new List<Dt_CabinOrderDetail>()
                        };
                        foreach (var item in order.details)
                        {
                            item.order_qty = Math.Abs(item.order_qty);
                            // æŸ¥è¯¢ç‰©æ–™ä¿¡æ¯
                            var materielInfo = BaseDal.Db.Queryable<Dt_MedicineGoods>()
                                .Where(x => x.Goods_no == item.goods_no)
                                .First();
                            //  è‹¥ç‰©æ–™ä¸å­˜åœ¨æˆ– MaterielSourceType ä¸ºç©ºï¼Œåˆ™è·³è¿‡æ•´ä¸ªå…¥åº“单
                            if (materielInfo == null || !Enum.IsDefined(typeof(MaterielSourceTypeEnum), materielInfo.MaterielSourceType))
                            #region æ·»åŠ ç›˜ç›ˆå…¥åº“ä»»åŠ¡
                            if (inventoryInfo.StockQuantity != inventoryInfo.SupplyQuantity)
                            {
                                skipOrder = true;
                                break;
                            }
                            // åŒºåˆ†å¤§ä»¶/小件
                            if (materielInfo.MaterielSourceType == MaterielSourceTypeEnum.PurchasePart)
                            {
                                var detail = new Dt_CabinOrderDetail
                                Dt_SupplyTask_Hty supplyTask_Hty = new Dt_SupplyTask_Hty()
                                {
                                    Reservoirarea = order.warehouse_no,
                                    Goods_no = item.goods_no,
                                    Order_qty = item.order_qty,
                                    Batch_num = item.batch_num,
                                    Exp_date = item.exp_date,
                                    OrderDetailStatus = "新建",
                                    Status = 2
                                    WarehouseCode = inventoryInfo.WarehouseCode,
                                    OperateType = OperateTypeEnum.自动完成.ToString(),
                                    InsertTime = DateTime.Now,
                                    TaskStatus = SupplyStatusEnum.InFinish.ObjToInt(),
                                    BatchNo = inventoryInfo.BatchNo,
                                    MaterielName = inventoryInfo.MaterielName,
                                    MaterielCode = inventoryInfo.MaterielCode,
                                    MaterielSpec = inventoryInfo.MaterielSpec,
                                    TaskType = TaskTypeEnum.ChenckIn.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 = "盘盈入库"
                                };
                                entityOrder.Details.Add(detail);
                                _supplyTaskHtyService.AddData(supplyTask_Hty);
                            }
                            else
                            {
                                Dt_CabinOrderDetail orderDetail = null;
                                var ys = item.order_qty % materielInfo.BoxQty; // ä¸èƒ½æ•´é™¤çš„æ•£ä»¶
                                var xs = item.order_qty / materielInfo.BoxQty; // æ•´ç®±æ•°é‡
                                // æœ‰æ•£ä»¶
                                if (ys > 0)
                                {
                                    orderDetail = new Dt_CabinOrderDetail
                                    {
                                        Reservoirarea = order.warehouse_no,
                                        Goods_no = item.goods_no,
                                        Order_qty = ys,
                                        Batch_num = item.batch_num,
                                        Exp_date = item.exp_date,
                                        OrderDetailStatus = "新建",
                                        Status = 0
                                    };
                                    materielInfo.Business_qty += ys;
                                }
                                // ä¸è¶³æœ€ä½Žåº“存时补入立库
                                while (materielInfo.Business_qty < materielInfo.MinQty && xs > 0)
                                {
                                    xs--;
                                    if (orderDetail == null)
                                    {
                                        orderDetail = new Dt_CabinOrderDetail
                                        {
                                            Reservoirarea = order.warehouse_no,
                                            Goods_no = item.goods_no,
                                            Order_qty = materielInfo.BoxQty,
                                            Batch_num = item.batch_num,
                                            Exp_date = item.exp_date,
                                            OrderDetailStatus = "新建",
                                            Status = 0
                                        };
                                    }
                                    else
                                    {
                                        orderDetail.Order_qty += materielInfo.BoxQty;
                                    }
                                    materielInfo.Business_qty += materielInfo.BoxQty;
                                }
                                if (orderDetail != null) entityOrder.Details.Add(orderDetail);
                                // å‰©ä½™æ•´ç®±å…¥å¹³åº“
                                if (xs > 0)
                                {
                                    entityOrder.Details.Add(new Dt_CabinOrderDetail
                                    {
                                        Reservoirarea = order.warehouse_no,
                                        Goods_no = item.goods_no,
                                        Order_qty = materielInfo.BoxQty * xs,
                                        Batch_num = item.batch_num,
                                        Exp_date = item.exp_date,
                                        OrderDetailStatus = "新建",
                                        Status = 2
                                    });
                                }
                            }
                            _medicineGoodsServices.Db.Updateable(materielInfo).ExecuteCommand();
                            #endregion
                            inventoryInfo.StockQuantity = inventoryInfo.SupplyQuantity;
                            inventoryInfo.SupplyQuantity = 0;
                            inventoryInfo.StockStatus = StockStatusEmun.入库完成.ObjToInt();
                        }
                        inventory_Batch.StockQuantity = inventory_Batch.SupplyQuantity;
                        inventory_Batch.SupplyQuantity = 0;
                        _inventoryInfoService.UpdateData(inventoryInfos);
                        _inventory_BatchServices.UpdateData(inventory_Batch);
                    }
                    #endregion
                        // â—如果跳过该单,则直接continue,不保存
                        if (skipOrder)
                    #region åˆ›å»ºç›˜ç‚¹å•
                    var entityOrder = new Dt_CabinOrder
                    {
                        Order_no = order.order_no,
                        Order_type = order.order_type,
                        Supplier_no = order.supplier_no,
                        Account_tiem = order.account_time,
                        OdrderStatus = "已完成",
                        Supplier_name = order.supplier_name,
                        Warehouse_no = order.warehouse_no,
                        Details = order.details.Select(d => new Dt_CabinOrderDetail
                        {
                            Console.WriteLine($"跳过入库单 {order.order_no},因为存在未定义物料属性的商品。");
                            continue;
                        }
                        _CabinOrders.Add(entityOrder);
                        orderNos.Add(order.order_no);
                    }
                    if (_CabinOrders.Any())
                    {
                        BaseDal.Db.InsertNav(_CabinOrders).Include(x => x.Details).ExecuteCommand();
                        Db.Ado.CommitTran();
                        return responseContent.OK($"成功同步 {_CabinOrders.Count} æ¡å…¥åº“单");
                    }
                    else
                    {
                        Db.Ado.RollbackTran();
                        return responseContent.OK("无可处理的入库单(商品属性未定义或未找到)");
                    }
                }
                catch (Exception ex)
                {
                    Db.Ado.RollbackTran();
                    SendErrorToUpstream(1, "", ex.Message, "");
                    return responseContent.Error("同步失败: " + ex.Message);
                }
            }
            catch (Exception ex)
            {
                SendErrorToUpstream(1, "", ex.Message, "");
                return responseContent.Error("同步失败: " + ex.Message);
            }
        }
        /// <summary>
        /// ä¼ ç»™wcs
        /// </summary>
        public WebResponseContent EdiIn()
        {
            try
            {
                //2.查询符合条件的订单(表头 = æ–°å»º && åŒ…含有效明细)
                //var orders = BaseDal.Db.Queryable<Dt_CabinOrder>()
                //    .Where(o => o.OdrderStatus == "新建")
                //    .Includes(o => o.Details, d => d.MedicineGoods)
                //    .ToList();
                //查出包含全部的入库单,包含全部明细+一个明细对应一个商品
                var orders = BaseDal.Db.CopyNew()
                .Queryable<Dt_CabinOrder>()
                .Where(o => o.OdrderStatus == "新建")
                .Includes(o => o.Details, d => d.MedicineGoods)
                .ToList();
                // 3. å†è¿‡æ»¤æŽ‰ä¸ç¬¦åˆæ¡ä»¶çš„æ˜Žç»†ï¼ˆåªä¿ç•™ Status=0)
                foreach (var order in orders)
                {
                    order.Details = order.Details.Where(d => d.Status == 0).ToList();
                }
                if (orders == null || !orders.Any())
                {
                    Console.WriteLine("没有符合条件的订单需要推送");
                    return WebResponseContent.Instance.Error("没有符合条件的订单需要推送");
                }
                // 4. éåŽ†è®¢å•ï¼Œç»„è£… DTO å¹¶æŽ¨é€
                foreach (var order in orders)
                {
                    string materialCode = "YY";//默认值
                    //获取当前订单的第一个明细项
                    var firstDetail = order.Details.FirstOrDefault();
                    if (firstDetail?.MedicineGoods != null && !string.IsNullOrEmpty(firstDetail.MedicineGoods.MaterialCode))
                    {
                        //如果条件满足,将物料代码设置为第一个明细项对应的药品物料代码
                        materialCode = firstDetail.MedicineGoods.MaterialCode;
                    }
                    var ediDto = new ToediInInfo
                    {
                        //客户代码
                        customerCode = "905",
                        //物料类型
                        materialCode = materialCode,
                        //入库单号
                        externalOrderNo = order.Order_no,
                        //入库单类型
                        inOrderType = order.Order_type == "1" ? "10" : "20",
                        //优先级
                        priority = 0,
                        //是否取消
                        Is_cancel = 0,
                        details = order.Details.Select(d => new ToediInDetail
                        {
                            //批号
                            batchNo = d.Batch_num,
                            //产品
                            productCode = d.Goods_no,
                            //sku名称
                            productName = d.MedicineGoods?.Goods_spm,
                            //sku规格
                            productSpecifications = d.MedicineGoods?.Model,
                            //数量
                            quantity = (int)d.Order_qty,
                            //效期
                            validityPeriod = d.Exp_date,
                            //生产厂家
                            manufacturer = d.MedicineGoods?.Factory,
                            //房号
                            libraryNo = order.Warehouse_no,
                            //盘盈入库
                            //stocktakingDetails = new List<ToediInStock>()
                            //stocktakingDetails = new List<ToediInStock>()
                            //{
                            //    new ToediInStock
                            //    {
                            //         //料箱号
                            //        palletCode = "PDA001",
                            //        //数量
                            //        quantity = d.Order_qty.ToString()
                            //    }
                            // }
                            Goods_no = d.goods_no,
                            Order_qty = Math.Abs(d.order_qty),
                            Order_Inqty = Math.Abs(d.order_qty),
                            Batch_num = d.batch_num,
                            Exp_date = d.exp_date,
                            Reservoirarea = order.warehouse_no,
                            OrderDetailStatus = "已完成",
                            Status = 2,
                        }).ToList()
                    };
                    var url = "http://172.16.1.2:9357/file-admin/api/in/ediIn";
                    var result = HttpHelper.Post(url, ediDto.ToJsonString());
                    var resp = JsonConvert.DeserializeObject<TowcsResponse<object>>(result);
                    if (resp != null && resp.code == "0")
                    {
                        // æ›´æ–°è¡¨å¤´çŠ¶æ€
                        BaseDal.Db.Updateable<Dt_CabinOrder>()
                           .SetColumns(o => new Dt_CabinOrder { OdrderStatus = "开始" })
                           .Where(o => o.Id == order.Id)
                           .ExecuteCommand();
                        // æ›´æ–°æ˜Žç»†çŠ¶æ€ä¸ºå·²åŒæ­¥
                        BaseDal.Db.Updateable<Dt_CabinOrderDetail>()
                          .SetColumns(d => new Dt_CabinOrderDetail { Status = 1, OrderDetailStatus = "已完成" })
                          .Where(d => d.OrderId == order.Id && d.Status == 0)
                          .ExecuteCommand();
                        Console.WriteLine($"订单 {order.Order_no} æŽ¨é€æˆåŠŸ");
                    }
                    else
                    {
                        SendErrorToUpstream(3, order.Order_no, resp?.msg ?? "WCS æŽ¨é€å¤±è´¥", "");
                        Console.WriteLine($"订单 {order.Order_no} æŽ¨é€å¤±è´¥ï¼š{resp?.msg}");
                        return new WebResponseContent { Status = false, Message = "订单推送失败" };
                    }
                    Db.InsertNav(entityOrder).Include(it => it.Details).ExecuteCommand();
                    //Repository.AddData(entityOrder);
                    #endregion
                }
                return new WebResponseContent { Status = true, Message = "推送成功" };
            }
            catch (Exception ex)
            {
                Console.WriteLine("EdiIn å¼‚常:" + ex.Message);
                return new WebResponseContent { Status = false, Message = ex.Message };
            }
        }
        /// <summary>
        /// å…¥åº“报完成接口
        /// </summary>
        /// <param name="order_no">入库单号</param> //先检查是否所有明细都已完成,如果是,那么更新表头状态为已完成
        /// <returns></returns>
        public WebResponseContent CompleteAllOrders()
        {
            var responseContent = new WebResponseContent();
            try
            {
                // æŸ¥æ‰¾æ‰€æœ‰â€œå¼€å§‹â€çŠ¶æ€çš„å…¥åº“å•
                var orders = BaseDal.Db.Queryable<Dt_CabinOrder>()
                    .Where(o => o.OdrderStatus == "开始")
                    .ToList();
                if (orders == null || !orders.Any())
                #endregion
                else
                {
                    return responseContent.OK("暂无需要处理的入库单");
                }
                    string WareCodeLK = WarehouseEnum.立库.ObjToInt().ToString("000");
                    string WareCodeDJ = WarehouseEnum.大件库.ObjToInt().ToString("000");
                int successCount = 0;
                int failCount = 0;
                foreach (var order in orders)
                {
                    try
                    foreach (var item in order.details)
                    {
                        BaseDal.Db.Ado.BeginTran();
                        // æŸ¥è¯¢è¯¥å•的明细
                        var details = BaseDal.Db.Queryable<Dt_CabinOrderDetail>()
                            .Where(d => d.OrderId == order.Id)
                            .ToList();
                        // åˆ¤æ–­æ˜¯å¦å…¨éƒ¨å®Œæˆ
                        var totalCount = details.Count;
                        var completedCount = details.Count(d => d.OrderDetailStatus == "已完成");
                        if (totalCount > 0 && completedCount == totalCount)
                        //找库存批次信息
                        Dt_Inventory_Batch inventory_Batch = _inventory_BatchServices.Repository.QueryFirst(x => x.MaterielCode == item.goods_no && x.BatchNo == item.batch_num);
                        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 = _inventoryInfoService.Repository.QueryData(x => x.MaterielCode == inventory_Batch.MaterielCode && x.BatchNo == inventory_Batch.BatchNo);
                        //获取立库盘点差异数
                        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)//立库无差异
                        {
                            // æ›´æ–°è¡¨å¤´çŠ¶æ€
                            order.OdrderStatus = "已完成";
                            BaseDal.Db.Updateable(order).ExecuteCommand();
                            // è°ƒç”¨ä¸Šæ¸¸æŽ¥å£
                            var url = "http://121.37.118.63:80/GYZ2/95fck/inOrderOk";
                            var result = HttpHelper.Post(url, new { order_no = order.Order_no }.ToJsonString());
                            var response = JsonConvert.DeserializeObject<UpstreamOrderResponse>(result);
                            if (response.resultCode == "0")
                            #region åº“存、库存批次平账
                            foreach (var inventoryInfo in inventoryInfos)
                            {
                                // === æ­¥éª¤ 1:插入历史表 ===
                                // 1.1 æ’入表头历史
                                var orderHistory = new Dt_CabinOrder_Hty
                                #region æ·»åŠ ç›˜ç›ˆå…¥åº“ä»»åŠ¡
                                if (inventoryInfo.StockQuantity != inventoryInfo.SupplyQuantity)
                                {
                                    Id = order.Id,
                                    Order_no = order.Order_no,
                                    Order_type = order.Order_type,
                                    Supplier_no = order.Supplier_no,
                                    Supplier_name = order.Supplier_name,
                                    Account_tiem = order.Account_tiem,
                                    Warehouse_no = order.Warehouse_no,
                                    OdrderStatus = order.OdrderStatus,
                                };
                                var historyId = BaseDal.Db.Insertable(orderHistory).ExecuteReturnIdentity();
                                // 1.2 æ’入明细历史
                                var detailsHistory = details.Select(d => new Dt_CabinOrderDetail_Hty
                                {
                                    Id = d.Id,
                                    Reservoirarea = d.Reservoirarea,
                                    Goods_no = d.Goods_no,
                                    Order_qty = d.Order_qty,
                                    Order_Inqty = d.Order_Inqty,
                                    Batch_num = d.Batch_num,
                                    Exp_date = d.Exp_date,
                                    OrderDetailStatus = d.OrderDetailStatus,
                                    Status = d.Status,
                                }).ToList();
                                BaseDal.Db.Insertable(detailsHistory).ExecuteCommand();
                                // === æ­¥éª¤ 2:删除原始表 ===
                                BaseDal.Db.Deleteable<Dt_CabinOrderDetail>().Where(d => d.OrderId == order.Id).ExecuteCommand();
                                BaseDal.Db.Deleteable<Dt_CabinOrder>().Where(o => o.Id == order.Id).ExecuteCommand();
                                // æäº¤äº‹åŠ¡
                                BaseDal.Db.Ado.CommitTran();
                                successCount++;
                                    Dt_SupplyTask_Hty supplyTask_Hty = new Dt_SupplyTask_Hty()
                                    {
                                        WarehouseCode = inventoryInfo.WarehouseCode,
                                        OperateType = OperateTypeEnum.自动完成.ToString(),
                                        InsertTime = DateTime.Now,
                                        TaskStatus = SupplyStatusEnum.InFinish.ObjToInt(),
                                        BatchNo = inventoryInfo.BatchNo,
                                        MaterielName = inventoryInfo.MaterielName,
                                        MaterielCode = inventoryInfo.MaterielCode,
                                        MaterielSpec = inventoryInfo.MaterielSpec,
                                        TaskType = TaskTypeEnum.ChenckIn.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);
                                }
                                #endregion
                                inventoryInfo.StockQuantity = inventoryInfo.SupplyQuantity;
                                inventoryInfo.SupplyQuantity = 0;
                                inventoryInfo.StockStatus = StockStatusEmun.入库完成.ObjToInt();
                            }
                            else
                            _inventoryInfoService.UpdateData(inventoryInfos);
                            inventory_Batch.StockQuantity = inventory_Batch.SupplyQuantity;
                            inventory_Batch.SupplyQuantity = 0;
                            _inventory_BatchServices.UpdateData(inventory_Batch);
                            #endregion
                            #region åˆ›å»ºå¤§ä»¶åº“盘点单
                            var entityOrder = new Dt_CabinOrder
                            {
                                BaseDal.Db.Ado.RollbackTran();
                                failCount++;
                                SendErrorToUpstream(2, "", $"上游接口返回失败: {response.resultMsg}", order.Order_no);
                            }
                                Order_no = order.order_no,
                                Order_type = order.order_type,
                                Supplier_no = order.supplier_no,
                                Account_tiem = order.account_time,
                                OdrderStatus = "已完成",
                                Supplier_name = order.supplier_name,
                                Warehouse_no = WareCodeDJ,
                                Details = order.details.Select(d => new Dt_CabinOrderDetail
                                {
                                    Goods_no = d.goods_no,
                                    Order_qty = Math.Abs(d.order_qty),
                                    Order_Inqty = Math.Abs(d.order_qty),
                                    Batch_num = d.batch_num,
                                    Exp_date = d.exp_date,
                                    Reservoirarea = WareCodeDJ,
                                    OrderDetailStatus = "已完成",
                                    Status = 2,
                                }).ToList()
                            };
                            //Repository.AddData(entityOrder);
                            Db.InsertNav(entityOrder).Include(it => it.Details).ExecuteCommand();
                            #endregion
                        }
                        else
                        {
                            BaseDal.Db.Ado.RollbackTran();
                            #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.InFinish.ObjToInt(),
                                        BatchNo = inventoryInfo.BatchNo,
                                        MaterielName = inventoryInfo.MaterielName,
                                        MaterielCode = inventoryInfo.MaterielCode,
                                        MaterielSpec = inventoryInfo.MaterielSpec,
                                        TaskType = TaskTypeEnum.ChenckIn.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);
                                }
                                #endregion
                                inventoryInfo.StockQuantity = inventoryInfo.SupplyQuantity;
                                inventoryInfo.SupplyQuantity = 0;
                                inventoryInfo.StockStatus = StockStatusEmun.入库完成.ObjToInt();
                            }
                            _inventoryInfoService.UpdateData(inventoryInfos);
                            #endregion
                            #region åˆ›å»ºå¤§ä»¶åº“盘点单
                            if (DJQty != 0)
                            {
                                var cabinOrder = new Dt_CabinOrder
                                {
                                    Order_no = order.order_no,
                                    Order_type = order.order_type,
                                    Supplier_no = order.supplier_no,
                                    Account_tiem = order.account_time,
                                    OdrderStatus = "已完成",
                                    Supplier_name = order.supplier_name,
                                    Warehouse_no = WareCodeDJ,
                                    Details = order.details.Select(d => new Dt_CabinOrderDetail
                                    {
                                        Goods_no = d.goods_no,
                                        Order_qty = DJQty,
                                        Order_Inqty = DJQty,
                                        Batch_num = d.batch_num,
                                        Exp_date = d.exp_date,
                                        Reservoirarea = WareCodeDJ,
                                        OrderDetailStatus = "已完成",
                                        Status = 2,
                                    }).ToList()
                                };
                                //Repository.AddData(cabinOrder);
                                Db.InsertNav(cabinOrder).Include(it => it.Details).ExecuteCommand();
                            }
                            #endregion
                            #region åˆ›å»ºç«‹åº“盘点单
                            var entityOrder = new Dt_CabinOrder
                            {
                                Order_no = order.order_no,
                                Order_type = order.order_type,
                                Supplier_no = order.supplier_no,
                                Account_tiem = order.account_time,
                                OdrderStatus = "新建",
                                Supplier_name = order.supplier_name,
                                Warehouse_no = WareCodeLK,
                                Details = order.details.Select(d => new Dt_CabinOrderDetail
                                {
                                    Goods_no = d.goods_no,
                                    Order_qty = LkQty,
                                    Batch_num = d.batch_num,
                                    Exp_date = d.exp_date,
                                    Reservoirarea = WareCodeLK,
                                    OrderDetailStatus = "新建",
                                    Status = 0,
                                }).ToList()
                            };
                            //Repository.AddData(entityOrder);
                            Db.InsertNav(entityOrder).Include(it => it.Details).ExecuteCommand();
                            #endregion
                        }
                    }
                    catch (Exception ex)
                    {
                        BaseDal.Db.Ado.RollbackTran();
                        failCount++;
                        SendErrorToUpstream(1, "", ex.Message, order.Order_no);
                    }
                }
                return responseContent.OK($"批量处理完成:成功 {successCount} å•,失败 {failCount} å•。");
                _unitOfWorkManage.CommitTran();
            }
            catch (Exception ex)
            {
                return responseContent.Error("批量处理失败:" + ex.Message);
                _unitOfWorkManage.RollbackTran();
                //_messageInfoService.AddMessageInfo(MessageGroupByEnum.InOrderAlarm, "创建盘盈入库单", ex.Message);
                content.Error(ex.Message);
            }
            return content;
        }
        #endregion
        /// <summary>
        /// æŽ¨é€å¼‚常信息给上游系统1.入库单接口;2.入库单报完成接口;3.出库单接口;4.出库报完成接口;5.药品基础信息同步接口;6.供应商信息接口;7.客户信息接口;8.库存
        /// äººå·¥å…¥åº“完成
        /// </summary>
        public void SendErrorToUpstream(int type, string code, string message, string remark)
        /// <param name="key"></param>
        /// <returns></returns>
        public WebResponseContent FinishInOrder(int key)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                var url = "http://121.37.118.63:80/GYZ2/95fck/lexceptionLogog";
                Dt_CabinOrder cabinOrder = BaseDal.QueryFirst(x => x.Id == key);
                List<Dt_CabinOrder> cabinOrders = Db.Queryable<Dt_CabinOrder>().Where(x => x.Order_no == cabinOrder.Order_no).Includes(x => x.Details).ToList();//找出所有出库单号相同的出库单
                _unitOfWorkManage.BeginTran();
                var requestData = new
                foreach (var item in cabinOrders)
                {
                    type = type.ToString(),
                    code = code,
                    message = message,
                    remark = remark
                };
                    if (item.Details != null)
                        _cabinOrderDetailServices.Repository.DeleteAndMoveIntoHty(item.Details, OperateTypeEnum.人工完成);
                    item.Modifier = App.User.UserName;
                    item.ModifyDate = DateTime.Now;
                    item.Details = null;
                }
                BaseDal.DeleteAndMoveIntoHty(cabinOrders, OperateTypeEnum.人工完成);
                var result = HttpHelper.Post(url, requestData.ToJsonString());
                // å¯ä»¥ååºåˆ—化检查 resultCode æ˜¯å¦ä¸º0
                if (cabinOrder.Order_type == InOrderTypeEnum.Allocat.ObjToInt().ToString())
                    _unitOfWorkManage.CommitTran();
                else
                {
                    var url = "http://121.37.118.63:80/GYZ2/95fck/outOrderOk";
                    var requestDate = new
                    {
                        order_no = cabinOrder.Order_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") throw new Exception(response.resultMsg);
                    _unitOfWorkManage.CommitTran();
                }
                content.OK();
            }
            catch (Exception e)
            catch (Exception ex)
            {
                // è¿™é‡Œä¸è¦å†æŠ›å¼‚常了,避免死循环
                Console.WriteLine("异常接口推送失败:" + e.Message);
                _unitOfWorkManage.RollbackTran();
                content.Error(ex.Message);
            }
            return content;
        }
    }
}