From 2c7065b9e9bd2a080dbe85f8ed5bc35656d664ff Mon Sep 17 00:00:00 2001
From: kyy <3283105747@qq.com>
Date: 星期二, 25 十一月 2025 13:06:23 +0800
Subject: [PATCH] 1、入库备注

---
 service/Warehouse/MesInvItemInCDetailsManager.cs | 2286 +++++++++++++++++++++++++++++++++++-----------------------
 1 files changed, 1,388 insertions(+), 898 deletions(-)

diff --git a/service/Warehouse/MesInvItemInCDetailsManager.cs b/service/Warehouse/MesInvItemInCDetailsManager.cs
index 0fd977c..591e464 100644
--- a/service/Warehouse/MesInvItemInCDetailsManager.cs
+++ b/service/Warehouse/MesInvItemInCDetailsManager.cs
@@ -1,4 +1,5 @@
-锘縰sing Masuit.Tools.Models;
+using Masuit.Tools.Models;
+using Microsoft.AspNetCore.SignalR.Protocol;
 using NewPdaSqlServer.DB;
 using NewPdaSqlServer.Dto.service;
 using NewPdaSqlServer.entity;
@@ -7,7 +8,11 @@
 using NewPdaSqlServer.util;
 using Newtonsoft.Json;
 using SqlSugar;
+using System;
+using System.Data;
+using System.Data.SqlClient;
 using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
+using DbHelperSQL = NewPdaSqlServer.DB.DbHelperSQL;
 
 namespace NewPdaSqlServer.service.Warehouse;
 
@@ -15,934 +20,1005 @@
 {
     //褰撳墠绫诲凡缁忕户鎵夸簡 Repository 澧炪�佸垹銆佹煡銆佹敼鐨勬柟娉�
 
+
     public ItemInBaseModel SaveBarCodes(WarehouseQuery entity)
     {
+        ItemInBaseModel res = new ItemInBaseModel();
+        string connectionString = DB.DbHelperSQL.strConn;
+
         // 鍙傛暟楠岃瘉
-        if (entity == null)
-            throw new ArgumentNullException(nameof(entity), "鍙傛暟瀵硅薄涓嶈兘涓虹┖");
+        if (string.IsNullOrEmpty(entity.userName)) throw new ArgumentNullException(nameof(entity.userName), "鐢ㄦ埛鍚嶄笉鍏佽涓虹┖");
+        if (string.IsNullOrEmpty(entity.sectionCode)) throw new ArgumentNullException(nameof(entity.sectionCode), "搴撲綅缂栧彿涓嶅厑璁镐负绌�");
+        if (string.IsNullOrEmpty(entity.barcode)) throw new ArgumentNullException(nameof(entity.barcode), "鏉$爜涓嶅厑璁镐负绌�");
 
-        if (string.IsNullOrEmpty(entity.userName))
-            throw new ArgumentException("鐢ㄦ埛鍚嶄笉鑳戒负绌�", nameof(entity.userName));
-
-        if (string.IsNullOrEmpty(entity.barcode))
-            throw new ArgumentException("鏉$爜涓嶈兘涓虹┖", nameof(entity.barcode));
-
-        string functionName = "閲囪喘鍏ュ簱", fieldName = null, inFieldVal = null;
-        string user = entity.userName,
-            sectionCode = entity.sectionCode,
-            itemBarcode = entity.barcode;
-        var transactionNo = "101";
-        int? billTypeId = 100, num = 0, num2 = 0;
-        var freeze = 0;
-        decimal cSyQty = 0;
-
-        if (string.IsNullOrEmpty(sectionCode))
-            throw new Exception("璇锋壂搴撲綅鏉$爜锛�");
-
-        MesInvItemBarcodes itemBarcodeDetails;
-        try
+        using (var conn = new SqlConnection(connectionString))
         {
-            itemBarcodeDetails = Db.Queryable<MesInvItemBarcodes>()
-                .Where(it => it.ItemBarcode == itemBarcode)
-                .First();
-        }
-        catch
-        {
-            throw new Exception("鏉$爜涓嶅瓨鍦紝璇锋牳瀵癸紒");
-        }
-
-        if (string.IsNullOrEmpty(itemBarcodeDetails.Memo) || itemBarcodeDetails.Memo != "閲囪喘鍏ュ簱")
-            throw new Exception("姝ゆ潯鐮佷笉灞炰簬鍒拌揣鏉$爜锛屾棤娉曠敤閲囪喘鍏ュ簱锛�");
-
-        MesInvItemArn inventory;
-        try
-        {
-            inventory = Db.Queryable<MesInvItemArn>()
-                .Where(it => it.BillNo == itemBarcodeDetails.BillNo && it.Fstatus == true )
-                .First();
-        }
-        catch
-        {
-            throw new Exception("姝ゆ潯鐮佹壘涓嶅埌瀵瑰簲鏀惰揣鍗曟垨鏈鏍革紒");
-        }
-
-        // var inventoryDetails = Db.Queryable<MesInvItemArnDetail>()
-        //     .Where(it => it.ParentGuid == inventory.Guid
-        //                  && it.ItemId == itemBarcodeDetails.ItemId
-        //                  && it.EbelnLine == itemBarcodeDetails.WorkLine
-        //                  && it.Ebeln == itemBarcodeDetails.WorkNo)
-        //     .First();
-
-        MesInvItemArnDetail inventoryDetails;
-        try
-        {
-            inventoryDetails = Db.Queryable<MesInvItemArnDetail>()
-                .Where(it => it.Guid == itemBarcodeDetails.AboutGuid)
-                .First();
-        }
-        catch
-        {
-            throw new Exception("姝ゆ潯鐮佹壘涓嶅埌瀵瑰簲鏀惰揣鍗曟槑缁嗭紒");
-        }
-
-        MesRohInData cgddDetails;
-        try
-        {
-            cgddDetails = Db.Queryable<MesRohInData>()
-                .Where(it => it.EbelnK3id == inventoryDetails.LineK3id)
-                .First();
-        }
-        catch
-        {
-            throw new Exception("姝ゆ潯鐮佹壘涓嶅埌瀵瑰簲閲囪喘璁㈠崟鏄庣粏锛�");
-        }
-
-        //鑾峰彇鍒拌揣妫�楠屾槑缁�
-        var sqlParams = new List<SugarParameter> { new("@dhmxGuid", itemBarcodeDetails.AboutGuid) };
-        var sql1 = @"SELECT *FROM v_dhmx WHERE dhmxGuid = @dhmxGuid ";
-        vDhmx dhjymx;
-        try
-        {
-            dhjymx = Db.Ado.SqlQuery<vDhmx>(sql1, sqlParams).First();
-        }
-        catch
-        {
-            throw new Exception("璇ユ潯鐮佹壘涓嶅埌瀵瑰簲鐨勬楠屾槑缁嗭紒");
-        }
-
-        //鍒ゅ畾妫�楠岃兘鍚﹀叆搴�
-        if (dhjymx.CanStore!= 1)
-        {
-            throw new Exception($"璇ユ潯鐮佸搴旂殑鏀舵枡鍗曟楠岀粨鏋�:銆恵dhjymx.InspectionResult}銆�,鍒ゅ畾缁撴灉锛氥�恵dhjymx.JudgmentResult}銆戯紝澶勭悊鎰忚锛氥�恵dhjymx.HandlingSuggestion}銆�,鏃犳硶鍏ュ簱");
-        }
-
-        string depotCode;
-        try
-        {
-            depotCode = Db.Queryable<MesDepotSections>()
-                .Where(it => it.DepotSectionCode == sectionCode)
-                .Select(it => it.DepotGuid)
-                .First();
-        }
-        catch
-        {
-            throw new Exception("搴撲綅缂栫爜 " + sectionCode + " 涓嶅瓨鍦紝璇风‘璁わ紒");
-        }
-
-        MesDepots mesDepost = null;
-
-        var checkGuid = UtilityHelper.CheckGuid(depotCode);
-        if (checkGuid && depotCode != null)
-        {
-            try
+            using (var cmd = new SqlCommand("[prc_pda_inv_cgrk]", conn))
             {
-                mesDepost = Db.Queryable<MesDepots>()
-                    .Where(s => s.Guid == depotCode).First();
-            }
-            catch
-            {
-                throw new Exception("搴撲綅缂栫爜 " + sectionCode + " 瀵瑰簲鐨勪粨搴撲笉瀛樺湪锛岃纭锛�");
-            }
+                //try
+                //{
+                    conn.Open();
+                    cmd.CommandType = CommandType.StoredProcedure;
 
-            // if (depotCode != mesDepost.Guid)
-            //     throw new Exception("鎵弿搴撲綅涓庨噰璐叆搴撳簱浣嶄笉涓�鑷达紒");
-        }
-        else
-        {
-            throw new Exception("搴撲綅缂栫爜 " + sectionCode + " 涓嶅瓨鍦紝璇风‘璁わ紒");
-        }
-
-
-        //num = Db.Queryable<MesInvItemInCDetails>()
-        //    .Where(it => it.ItemBarcode == itemBarcode)
-        //    .Count();
-
-        //if (num > 0)
-        //    throw new Exception("姝ゆ潯鐮佸凡鎵爜鍏ュ簱瀹屾垚锛岃鏍稿锛�");
-
-        //num = Db.Queryable<MesInvItemStocks>()
-        //    .Where(it => it.ItemBarcode == itemBarcode)
-        //    .Count();
-
-        //if (num > 0)
-        //    throw new Exception("姝ゆ潯鐮佸凡鎵爜鍏ュ簱锛岃鏍稿锛�");
-
-        var wmsManager = new WmsBaseMangeer();
-        // 鏂板鍏ュ簱鏍¢獙锛堣皟鐢ㄥ瓨鍌ㄨ繃绋嬶級
-        var checkResult = wmsManager.pdaInvJY(
-            db: Db,
-            edtUserNo: entity.userName,
-            barcode: entity.barcode,
-            sectionCode: sectionCode,
-            stockId: mesDepost.DepotId.ToString(),
-            stockOrgId: mesDepost.FSubsidiary,
-            billNo: "", // 鏍规嵁瀹為檯鍗曟嵁鍙蜂紶鍊�
-            transactionNo: "101" // 浜嬪姟绫诲瀷涓庡瓨鍌ㄨ繃绋嬪尮閰�
-        );
-
-        if (checkResult == null)
-            throw new Exception("鍏ュ簱鏍¢獙澶辫触锛氳繑鍥炵粨鏋滀负绌�");
-
-        if (Convert.ToInt32(checkResult.result) < 1)
-            throw new Exception($"鍏ュ簱鏍¢獙澶辫触锛歿checkResult.strMsg}");
-
-
-
-        //num = Db.Queryable<MesInvItemArn>()
-        //    .Where(a => a.BillNo == itemBarcodeDetails.BillNo)
-        //    .InnerJoin<MesInvItemArnDetail>((a, b) =>
-        //        b.ParentGuid == a.Guid &&
-        //        b.ItemId == itemBarcodeDetails.ItemId && b.Ischeck == 1)
-        //    .Count();
-
-        //num2 = Db.Queryable<MesInvItemArn>()
-        //    .Where(a => a.BillNo == itemBarcodeDetails.BillNo)
-        //    .InnerJoin<MesInvItemArnDetail>((a, b) => b.ParentGuid == a.Guid
-        //        && b.ItemId == itemBarcodeDetails.ItemId
-        //        && (b.CheckRes == "鍚堟牸" || b.CheckStates == "鐗归噰鐩存帴浣跨敤"))
-        //    .Count();
-
-        //switch (num)
-        //{
-        //    case 0 when num2 == 0:
-        //    case > 0 when num2 == 0:
-        //        freeze = 1;
-        //        break;
-        //    case 0 when num2 > 0:
-        //        throw new Exception("鍏ュ簱澶辫触,鍒拌揣鍗曟嵁鏈夐棶棰橈紒");
-        //}
-
-
-        // 鍒ゆ柇璐т富绫诲瀷
-        var owner_type = wmsManager.GetOwnerType(cgddDetails.DemandOrg);
-        // if (Db.Queryable<SysOrganization>().Any(x => x.Fid == cgddDetails.DemandOrg))
-        // {
-        //     owner_type = "BD_OwnerOrg";
-        // }
-        // else
-        // {
-        //     // 绗簩灞傚垽鏂細妫�鏌� MES_CUSTOMER
-        //     if (Db.Queryable<MesCustomer>().Any(x => x.Id == Convert.ToInt32(cgddDetails.DemandOrg)))
-        //     {
-        //         owner_type = "BD_Customer";
-        //     }
-        //     else
-        //     {
-        //         // 绗笁灞傚垽鏂細妫�鏌� MES_SUPPLIER
-        //         if (Db.Queryable<MesSupplier>().Any(x => x.Id == Convert.ToInt32(cgddDetails.DemandOrg)))
-        //         {
-        //             owner_type = "BD_Supplier";
-        //         }
-        //         else
-        //         {
-
-        //             // 绗洓灞傚垽鏂細鍐嶆妫�鏌� SYS_ORGANIZATION
-        //             if (Db.Queryable<SysOrganization>().Any(x => x.Fid == cgddDetails.ReceivingOrg))
-        //             {
-        //                 owner_type = "BD_OwnerOrg";
-        //             }
-        //             else
-        //             {
-        //                 throw new Exception("鍏ュ簱澶辫触,鍒拌揣鍗曟嵁瀵瑰簲鐨勯渶姹傜粍缁囨湁闂锛�");
-        //             }
-        //         }
-        //     }
-        //}
-
-        var result = new ItemInBaseModel();
-
-        UseTransaction(db =>
-        {
-            var existingRecord = db.Queryable<MesInvItemIns>()
-                .Where(it => it.InsDate.Value.ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd")
-                             && it.TaskNo == itemBarcodeDetails.BillNo
-                             && it.Status == 0
-                             && it.TransctionNo == transactionNo
-                             && it.CreateBy == entity.userName
-                             && it.BillTypeId == billTypeId
-                             && it.DepotsId == mesDepost.DepotId)
-                .Select(it => new
-                {
-                    it.Guid,
-                    it.BillNo
-                })
-                .ToList()
-                .FirstOrDefault();
-
-            var cId = Guid.Empty;
-            string cBillNo = null;
-
-            if (existingRecord != null)
-            {
-                // If record exists, assign values
-                cId = existingRecord.Guid;
-                cBillNo = existingRecord.BillNo;
-            }
-            else
-            {
-                cId = Guid.NewGuid();
-                cBillNo = BillNo.GetBillNo("CGRK(閲囪喘鍏ュ簱)");
-
-                MesSupplier suppNo;
-                try
-                {
-                    suppNo = db.Queryable<MesSupplier>()
-                        .Where(s => s.Id.ToString() == inventory.SuppId).First();
-                }
-                catch
-                {
-                    throw new Exception("鎵句笉鍒板搴旂殑渚涘簲鍟嗕俊鎭紒");
-                }
-
-                db.Insertable(new MesInvItemIns
-                {
-                    Guid = cId,
-                    BillNo = cBillNo,
-                    BillTypeId = billTypeId,
-                    InsDate = DateTime.Now,
-                    DepotsId = mesDepost.DepotId,
-                    DepotsCode = mesDepost.DepotCode,
-                    TransctionNo = transactionNo,
-                    SuppId = suppNo.Id.ToString(),
-                    SuppNo = suppNo.SuppNo,
-                    CreateBy = user,
-                    CreateDate = DateTime.Now,
-                    LastupdateBy = user,
-                    LastupdateDate = DateTime.Now,
-                    UrgentFlag = itemBarcodeDetails.UrgentFlag.GetValueOrDefault() ? "1" : "0",
-                    CbillNo = itemBarcodeDetails.BillNo,
-                    Fstatus = 0,
-                    Status = 0,
-                    ReceiveOrgId = inventory.ReceiveOrgId,
-                    InType = "閲囪喘鍏ュ簱",
-                    TaskNo = itemBarcodeDetails.BillNo
-                    //WorkNo = itemBarcodeDetails.WorkNo
-                }).IgnoreColumns(true).ExecuteCommand();
-            }
-
-            cSyQty = itemBarcodeDetails.Quantity ?? 0;
-
-            if (cSyQty <= 0)
-                throw new Exception("鏉$爜鏁伴噺鏃犳晥锛岃妫�鏌ユ潯鐮佷俊鎭紒");
-
-            entity.id = cId.ToString();
-            entity.PageIndex = 1;
-            entity.Limit = 1;
-
-            itemBarcodeDetails.Hbdy ??= 0;
-            if (itemBarcodeDetails.Hbdy == 1)
-            {
-                var details = db.Queryable<MesInvItemArnDetail>()
-                    .Where(d =>
-                        d.CbillNo == itemBarcodeDetails.BillNo &&
-                        d.Quantity != d.OkRkqty &&
-                        d.ItemId == itemBarcodeDetails.ItemId)
-                    .ToList();
-
-
-                foreach (var detail in details)
-                {
-                    if (cSyQty == 0) break;
-
-                    var remainingQty = detail.Quantity - (detail.OkRkqty ?? 0);
-                    if (remainingQty <= cSyQty)
+                    // 璁剧疆瀛樺偍杩囩▼鍙傛暟
+                    SqlParameter[] parameters =
                     {
-                        // Update detail
-                        db.Updateable<MesInvItemArnDetail>()
-                            .SetColumns(d => new MesInvItemArnDetail
-                            {
-                                OkRkqty = (int)d.Quantity,
-                                IsdepsIn = true
-                            })
-                            .Where(d => d.Guid == detail.Guid)
-                            .IgnoreColumns(true)
-                            .ExecuteCommand();
+                        new SqlParameter("@pi_user", SqlDbType.NVarChar, 100) { Value = entity.userName },
+                        new SqlParameter("@pi_barcode", SqlDbType.NVarChar, 100) { Value =  entity.barcode.Trim().ToLower() },
+                        new SqlParameter("@pi_sectionCode", SqlDbType.NVarChar, 30) { Value = entity.sectionCode },
+                        new SqlParameter("@pi_remark", SqlDbType.NVarChar, 30) { Value = entity.remark },
+                        new SqlParameter("@pi_cgrkType", SqlDbType.NVarChar, 30) { Value = "姝e父鍏ュ簱" },
+                        new SqlParameter("@pi_weight", SqlDbType.Decimal) { Value = entity.weight },
+                        new SqlParameter("@po_outMsg", SqlDbType.NVarChar, 300) { Direction = ParameterDirection.Output },
+                        new SqlParameter("@po_outSum", SqlDbType.NVarChar, 300) { Direction = ParameterDirection.Output }
+                    };
 
-                        // Check if already inserted
-                        var count = db.Queryable<MesInvItemInCItems>()
-                            .Where(it =>
-                                it.ItemInId == cId &&
-                                    it.ItemId == detail.ItemId &&
-                                    it.DepotId == mesDepost.DepotId.ToString() &&
-                                    it.EbelnK3id == detail.EbelnK3id &&
-                                    it.LineK3id == detail.LineK3id)
-                            .Count();
+                    cmd.Parameters.AddRange(parameters);
+                    cmd.ExecuteNonQuery();
 
-                        cSyQty -= remainingQty.Value;
+                    // 鑾峰彇杈撳嚭鍙傛暟
+                    string? outMessage = parameters[5].Value?.ToString();
+                    string? outSum = parameters[6].Value?.ToString();
 
-                        if (count == 0)
-                            // Insert new item into MES_INV_ITEM_IN_C_ITEMS
-                            db.Insertable(new MesInvItemInCItems
-                            {
-                                ItemInId = cId,
-                                Quantity = remainingQty,
-                                CreateBy = user,
-                                CreateDate = DateTime.Now,
-                                ItemId = detail.ItemId,
-                                DepotCode = mesDepost.DepotCode,
-                                ItemSname = itemBarcodeDetails.ItemSname,
-                                Unit = itemBarcodeDetails.Unit,
-                                Ebeln = detail.Ebeln,
-                                BillNo = cBillNo,
-                                WorkNo = detail.WorkNo,
-                                CbillNo = detail.CbillNo,
-                                WorkLine = detail.WorkLine,
-                                SuppId = itemBarcodeDetails.SuppId,
-                                SuppNo = itemBarcodeDetails.SuppNo,
-                                Remark = itemBarcodeDetails.Memo,
-                                EbelnK3id = detail.EbelnK3id,
-                                LineK3id = detail.LineK3id,
-                                DepotId = mesDepost.DepotId.ToString(),
-                                itemDabid = itemBarcodeDetails.AboutGuid.ToString()
-                            }).IgnoreColumns(true).ExecuteCommand();
-                        else
-                            db.Updateable<MesInvItemInCItems>()
-                                .SetColumns(it =>
-                                    it.Quantity == it.Quantity + remainingQty)
-                                .Where(it =>
-                                    it.ItemInId == cId &&
-                                    it.ItemId == detail.ItemId &&
-                                    it.DepotId == mesDepost.DepotId.ToString() &&
-                                    it.EbelnK3id == detail.EbelnK3id &&
-                                    it.LineK3id == detail.LineK3id)
-                                .IgnoreColumns(true)
-                                .ExecuteCommand();
 
-                        // Insert new detail into MES_INV_ITEM_IN_C_DETAILS
-                        db.Insertable(new MesInvItemInCDetails
-                        {
-                            ItemInId = cId,
-                            BillNo = cBillNo,
-                            ItemBarcode = itemBarcode,
-                            Quantity = remainingQty,
-                            BarcodeFlag = true,
-                            EpFlag = true,
-                            WorkType = 1,
-                            ItemNo = detail.ItemNo,
-                            SuppId = itemBarcodeDetails.SuppId,
-                            SuppNo = itemBarcodeDetails.SuppNo,
-                            DepotCode = mesDepost.DepotCode,
-                            DepotSectionCode = sectionCode,
-                            ItemSname = itemBarcodeDetails.ItemSname,
-                            Unit = itemBarcodeDetails.Unit,
-                            CreateBy = user,
-                            CreateDate = DateTime.Now,
-                            LastupdateBy = user,
-                            LastupdateDate = DateTime.Now,
-                            Remark = itemBarcodeDetails.Memo,
-                            Ebeln = detail.WorkNo,
-                            WorkNo = detail.WorkNo,
-                            WorkLine = detail.WorkLine,
-                            CbillNo = itemBarcodeDetails.BillNo,
-                            UrgentFlag = detail.UrgentFlag,
-                            BoardStyle = detail.BoardStyle,
-                            TaskNo = detail.WorkNo,
-                            EbelnK3id = detail.EbelnK3id,
-                            LineK3id = detail.LineK3id,
-                            ItemId = detail.ItemId,
-                            ReceiveOrgId = inventory.ReceiveOrgId,
-                            LotNo = cgddDetails.BatchNumber
-                        }).IgnoreColumns(true).ExecuteCommand();
+                    // 妫�鏌ュ弬鏁版槸鍚︿负绌猴紝骞跺湪寮傚父涓樉绀哄疄闄呭��
+                    if (string.IsNullOrEmpty(outMessage) || string.IsNullOrEmpty(outSum))
+                    {
+                        // 鎷兼帴鍙傛暟瀹為檯鍊硷紙澶勭悊 null 鐨勬儏鍐碉級
+                        string messageValue = outMessage ?? "null";
+                        string sumValue = outSum ?? "null";
+                        throw new InvalidOperationException(
+                            $"瀛樺偍杩囩▼杩斿洖鍙傛暟寮傚父锛氳緭鍑烘秷鎭负銆恵messageValue}銆戯紝杈撳嚭鏁伴噺涓恒�恵sumValue}銆�"
+                        );
                     }
-                    else
-                    {
-                        // Partially fulfill remaining quantity
-                        db.Updateable<MesInvItemArnDetail>()
-                            .SetColumns(d => new MesInvItemArnDetail
-                            {
-                                OkRkqty = (int)((d.OkRkqty ?? 0) + cSyQty)
-                            })
-                            .Where(d => d.Guid == detail.Guid)
-                            .IgnoreColumns(true)
-                            .ExecuteCommand();
 
-                        var count = db.Queryable<MesInvItemInCItems>()
-                            .Where(it =>
-                                it.ItemInId == cId &&
-                                    it.ItemId == detail.ItemId &&
-                                    it.DepotId == mesDepost.DepotId.ToString() &&
-                                    it.EbelnK3id == detail.EbelnK3id &&
-                                    it.LineK3id == detail.LineK3id)
-                            .Count();
+                    // 楠岃瘉缁撴灉
+                    if (!int.TryParse(outSum, out int result) || result <= 0)
+                        throw new InvalidOperationException(outMessage);
 
-                        if (count == 0)
-                            db.Insertable(new MesInvItemInCItems
-                            {
-                                ItemInId = cId,
-                                Quantity = cSyQty,
-                                CreateBy = user,
-                                CreateDate = DateTime.Now,
-                                ItemNo = detail.ItemNo,
-                                DepotCode = mesDepost.DepotCode,
-                                ItemSname = itemBarcodeDetails.ItemSname,
-                                Unit = itemBarcodeDetails.Unit,
-                                Ebeln = detail.WorkNo,
-                                BillNo = cBillNo,
-                                WorkNo = detail.WorkNo,
-                                EbelnLineNo = detail.EbelnLine,
-                                CbillNo = detail.CbillNo,
-                                WorkLine = detail.WorkLine,
-                                SuppId = itemBarcodeDetails.SuppId,
-                                SuppNo = itemBarcodeDetails.SuppNo,
-                                Remark = itemBarcodeDetails.Memo,
-                                EbelnK3id = detail.EbelnK3id,
-                                LineK3id = detail.LineK3id,
-                                ItemId = detail.ItemId,
-                                DepotId = mesDepost.DepotId.ToString()
-                            }).IgnoreColumns(true).ExecuteCommand();
-                        else
-                            db.Updateable<MesInvItemInCItems>()
-                                .SetColumns(it =>
-                                    it.Quantity == it.Quantity + cSyQty)
-                                .Where(it =>
-                                    it.ItemInId == cId &&
-                                    it.ItemId == detail.ItemId &&
-                                    it.DepotId == mesDepost.DepotId.ToString() &&
-                                    it.EbelnK3id == detail.EbelnK3id &&
-                                    it.LineK3id == detail.LineK3id)
-                                .IgnoreColumns(true)
-                                .ExecuteCommand();
+                    // 璋冭瘯杈撳嚭
+                    Console.WriteLine($"鏌ヨ鐨勬潯鐮佸��: '{entity.barcode}' (闀垮害: {entity.barcode.Length})");
 
-                        db.Insertable(new MesInvItemInCDetails
-                        {
-                            ItemInId = cId,
-                            BillNo = cBillNo,
-                            ItemBarcode = itemBarcode,
-                            Quantity = cSyQty,
-                            BarcodeFlag = true,
-                            EpFlag = true,
-                            WorkType = 1,
-                            ItemNo = detail.ItemNo,
-                            SuppId = itemBarcodeDetails.SuppId,
-                            SuppNo = itemBarcodeDetails.SuppNo,
-                            DepotCode = mesDepost.DepotCode,
-                            DepotSectionCode = sectionCode,
-                            ItemSname = itemBarcodeDetails.ItemSname,
-                            Unit = itemBarcodeDetails.Unit,
-                            CreateBy = user,
-                            CreateDate = DateTime.Now,
-                            LastupdateBy = user,
-                            LastupdateDate = DateTime.Now,
-                            Remark = itemBarcodeDetails.Memo,
-                            Ebeln = detail.WorkNo,
-                            EbelnLineNo = detail.EbelnLine,
-                            WorkNo = detail.WorkNo,
-                            WorkLine = detail.WorkLine,
-                            CbillNo = itemBarcodeDetails.BillNo,
-                            UrgentFlag = detail.UrgentFlag,
-                            BoardStyle = detail.BoardStyle,
-                            TaskNo = detail.WorkNo,
-                            EbelnK3id = detail.EbelnK3id,
-                            LineK3id = detail.LineK3id,
-                            ItemId = detail.ItemId,
-                            ReceiveOrgId = inventory.ReceiveOrgId,
-                            LotNo = cgddDetails.BatchNumber
-                        }).IgnoreColumns(true).ExecuteCommand();
+                    // 浣跨敤鍙傛暟鍖栨煡璇㈠苟蹇界暐澶у皬鍐欙紙閫傜敤浜庢敮鎸佺殑鏁版嵁搴擄級
+                    var itemBarcodeDetails = Db.Queryable<MesInvItemBarcodes>()
+                        .Where(it => it.ItemBarcode.Trim().ToLower() == entity.barcode.Trim().ToLower())
+                        .First() ?? throw new InvalidOperationException($"鏈壘鍒版潯鐮� '{entity.barcode}' 鐨勫尮閰嶄俊鎭�");
 
-                        cSyQty = 0; // Remaining quantity fulfilled
-                    }
-                }
+                    // 璋冭瘯杈撳嚭锛堟鏌ュ�煎拰闀垮害锛�
+                    Console.WriteLine($"鏌ヨ鐨勬潯鐮佸��: '{entity.barcode}' (闀垮害: {entity.barcode.Length})");
 
-                db.Insertable(new MesInvBusiness2
-                {
-                    Status = 1,
-                    BillTypeId = billTypeId,
-                    TransactionCode = transactionNo,
-                    BusinessType = 1,
-                    ItemBarcode = itemBarcode,
-                    ItemNo = itemBarcodeDetails.ItemNo,
-                    LotNo = cgddDetails.BatchNumber,
-                    EpFlag = true,
-                    Quantity = itemBarcodeDetails.Quantity,
-                    ToInvDepotsCode = mesDepost.DepotCode,
-                    ToInvDepotSectionsCode = sectionCode,
-                    Description = "閲囪喘鍏ュ簱",
-                    CreateBy = user,
-                    CreateDate = DateTime.Now,
-                    LastupdateBy = user,
-                    LastupdateDate = DateTime.Now,
-                    TaskNo = itemBarcodeDetails.BillNo,
-                    BillNo = cBillNo,
-                    WorkNo = itemBarcodeDetails.WorkNo,
-                    WorkLine = itemBarcodeDetails.WorkLine,
-                    SuppId = itemBarcodeDetails.SuppId,
-                    SuppNo = itemBarcodeDetails.SuppNo,
-                    EbelnK3id = itemBarcodeDetails.EbelnK3id,
-                    LineK3id = itemBarcodeDetails.LineK3id,
-                    ItemId = itemBarcodeDetails.ItemId
-                }).IgnoreColumns(true).ExecuteCommand();
+                    // 浼樺寲鏌ヨ锛堝幓闄ょ┖鏍煎苟蹇界暐澶у皬鍐欙級
+                    var MesInvItemInCDetails = Db.Queryable<MesInvItemInCDetails>()
+                        .Where(it => it.ItemBarcode.Trim().ToLower() == entity.barcode.Trim().ToLower())
+                        .First() ?? throw new InvalidOperationException($"鏈壘鍒版潯鐮� '{entity.barcode}' 鐨勫尮閰嶇殑鍏ュ簱淇℃伅");
 
-                // Insert into mes_inv_item_stocks
-            }
-            else
-            {
-                var detailone = db.Queryable<MesInvItemArnDetail>()
-                    .Where(d =>
-                        d.Guid == itemBarcodeDetails.AboutGuid)
-                    .First();
+                    // 浠庡叆搴撴潯鐮佷腑鑾峰彇鏈夋晥鐨処temInId
+                    var cId = MesInvItemInCDetails.ItemInId; // 鍋囪瀛樺湪ItemInId灞炴��
 
-                // 妫�鏌ユ槸鍚﹀瓨鍦ㄤ簬 MES_INV_ITEM_IN_C_ITEMS 琛�
-                var existingCount = db.Queryable<MesInvItemInCItems>()
-                    .Where(it =>
-                    it.ItemInId == cId &&
-                                    it.ItemId == detailone.ItemId &&
-                                    it.DepotId == mesDepost.DepotId.ToString() &&
-                                    it.itemDabid == itemBarcodeDetails.AboutGuid.ToString())
-                    .Count();
+                    // 鏌ヨ鐗╂枡姹囨�绘槑缁�
+                    var sql = string.Format(@"
+                    SELECT 
+                        b.Item_No AS ItemNo,
+                        b.Item_Name AS ItemName,
+                        b.Item_Model AS ItemModel,
+                        a.Quantity AS FQty,
+                        b.Item_Id AS FMaterialId,
+                        CONVERT(VARCHAR(36), b.Guid) AS Id
+                    FROM MES_INV_ITEM_IN_C_ITEMS a
+                    LEFT JOIN  Mes_Items b ON a.Item_Id = b.Item_Id
+                   WHERE a.Item_In_Id = '{0}' AND a.Item_Id = '{1}'", cId, itemBarcodeDetails.ItemId);
 
-                if (existingCount == 0)
-                    // 涓嶅瓨鍦ㄦ椂鎻掑叆鏂拌褰�
-                    db.Insertable(new MesInvItemInCItems
-                    {
-                        ItemInId = cId,
-                        Quantity = itemBarcodeDetails.Quantity,
-                        CreateBy = user,
-                        CreateDate = DateTime.Now,
-                        ItemNo = itemBarcodeDetails.ItemNo,
-                        DepotCode = mesDepost.DepotCode,
-                        ItemSname = itemBarcodeDetails.ItemSname,
-                        Unit = itemBarcodeDetails.Unit,
-                        Ebeln = itemBarcodeDetails.WorkNo,
-                        BillNo = cBillNo,
-                        WorkNo = itemBarcodeDetails.WorkNo,
-                        EbelnLineNo = itemBarcodeDetails.WorkLine,
-                        CbillNo = itemBarcodeDetails.BillNo,
-                        WorkLine = itemBarcodeDetails.WorkLine,
-                        SuppId = itemBarcodeDetails.SuppId,
-                        SuppNo = itemBarcodeDetails.SuppNo,
-                        Remark = itemBarcodeDetails.Memo,
-                        EbelnK3id = itemBarcodeDetails.EbelnK3id,
-                        LineK3id = itemBarcodeDetails.LineK3id,
-                        ItemId = itemBarcodeDetails.ItemId,
-                        DepotId = mesDepost.DepotId.ToString(),
-                        itemDabid = itemBarcodeDetails.AboutGuid.ToString()
-                    }).IgnoreColumns(true).ExecuteCommand();
-                else
-                    // 瀛樺湪鏃舵洿鏂版暟閲�
-                    db.Updateable<MesInvItemInCItems>()
-                        .SetColumns(it => new MesInvItemInCItems
-                        {
-                            Quantity = SqlFunc.IsNull(it.Quantity, 0) + itemBarcodeDetails.Quantity // 纭繚 Quantity 涓嶄负 null
-                        })
-                        .Where(it =>
-                                    it.ItemInId == cId &&
-                                    it.ItemId == detailone.ItemId &&
-                                    it.DepotId == mesDepost.DepotId.ToString() &&
-                                    it.itemDabid == itemBarcodeDetails.AboutGuid.ToString())
-                        //.IgnoreColumns(true) // 淇濈暀 IgnoreColumns
-                        .ExecuteCommand();
+                    res.ItemInDetails = Db.Ado.SqlQuery<dynamic>(sql);
 
-                // 鎻掑叆 mes_inv_item_in_c_details 琛�
-                db.Insertable(new MesInvItemInCDetails
-                {
-                    ItemInId = cId,
-                    BillNo = cBillNo,
-                    ItemBarcode = itemBarcode,
-                    Quantity = itemBarcodeDetails.Quantity,
-                    BarcodeFlag = true,
-                    EpFlag = true,
-                    WorkType = 1,
-                    ItemNo = itemBarcodeDetails.ItemNo,
-                    LotNo = cgddDetails.BatchNumber,
-                    SuppId = itemBarcodeDetails.SuppId,
-                    SuppNo = itemBarcodeDetails.SuppNo,
-                    DepotCode = mesDepost.DepotCode,
-                    DepotSectionCode = sectionCode,
-                    ItemSname = itemBarcodeDetails.ItemSname,
-                    Unit = itemBarcodeDetails.Unit,
-                    CreateBy = user,
-                    CreateDate = DateTime.Now,
-                    LastupdateBy = user,
-                    LastupdateDate = DateTime.Now,
-                    Remark = itemBarcodeDetails.Memo,
-                    Ebeln = itemBarcodeDetails.Mblnr,
-                    EbelnLineNo = itemBarcodeDetails.Zeile,
-                    WorkNo = itemBarcodeDetails.WorkNo,
-                    WorkLine = itemBarcodeDetails.WorkLine,
-                    CbillNo = itemBarcodeDetails.BillNo,
-                    UrgentFlag = itemBarcodeDetails.UrgentFlag,
-                    BoardStyle = itemBarcodeDetails.BoardStyle,
-                    TaskNo = itemBarcodeDetails.TaskNo,
-                    EbelnK3id = itemBarcodeDetails.EbelnK3id,
-                    LineK3id = itemBarcodeDetails.LineK3id,
-                    ItemId = itemBarcodeDetails.ItemId,
-                    Ischeck = true,
-                    CheckDate = inventoryDetails.CheckDate,
-                    CheckRes = inventoryDetails.CheckRes,
-                    CheckStates = inventoryDetails.CheckStates,
-                    ReceiveOrgId = inventory.ReceiveOrgId,
-                    DepotId = Convert.ToInt64(mesDepost.DepotId.ToString())
-                }).IgnoreColumns(true).ExecuteCommand();
+                    // 鏌ヨ鍏ュ簱鏉$爜鏄庣粏
+                    var sql2 = string.Format(@"
+                    SELECT 
+                        b.Item_No AS ItemNo,
+                        b.Item_Name AS ItemName,
+                        b.Item_Model AS ItemModel,
+                        a.Quantity AS FQty,
+                        b.Item_Id AS FMaterialId,
+                        CONVERT(VARCHAR(36), a.Guid) AS Id,
+                        a.Depot_Section_Code AS kw,
+                        a.Item_Barcode AS barcode
+                    FROM   Mes_Inv_Item_In_C_Details a
+                    LEFT JOIN  Mes_Items b ON a.Item_Id = b.Item_Id
+                    WHERE  a.Item_In_Id = '{0}' AND a.Item_Id = '{1}'", cId, itemBarcodeDetails.ItemId);
 
-                // 鎻掑叆 mes_inv_business2 琛�
-                db.Insertable(new MesInvBusiness2
-                {
-                    Status = 1,
-                    BillTypeId = billTypeId,
-                    TransactionCode = transactionNo,
-                    BusinessType = 1,
-                    ItemBarcode = itemBarcode,
-                    ItemNo = itemBarcodeDetails.ItemNo,
-                    LotNo = itemBarcodeDetails.LotNo,
-                    EpFlag = true,
-                    Quantity = itemBarcodeDetails.Quantity,
-                    FromInvDepotsCode = null,
-                    FromInvDepotSectionsCode = null,
-                    ToInvDepotsCode = mesDepost.DepotCode,
-                    ToInvDepotSectionsCode = sectionCode,
-                    Description = "閲囪喘鍏ュ簱",
-                    CreateBy = user,
-                    CreateDate = DateTime.Now,
-                    LastupdateBy = user,
-                    LastupdateDate = DateTime.Now,
-                    TaskNo = itemBarcodeDetails.TaskNo,
-                    BillNo = cBillNo,
-                    WorkNo = itemBarcodeDetails.WorkNo,
-                    WorkLine = itemBarcodeDetails.WorkLine,
-                    SuppId = itemBarcodeDetails.SuppId,
-                    SuppNo = itemBarcodeDetails.SuppNo,
-                    EbelnK3id = itemBarcodeDetails.EbelnK3id,
-                    LineK3id = itemBarcodeDetails.LineK3id,
-                    ItemId = itemBarcodeDetails.ItemId
-                }).IgnoreColumns(true).ExecuteCommand();
-
-                // 鎻掑叆 mes_inv_item_stocks 琛�
-            }
-
-
-
-            db.Insertable(new MesInvItemStocks
-            {
-                TaskNo = itemBarcodeDetails.TaskNo,
-                ItemBarcode = itemBarcode,
-                ItemNo = cgddDetails.BatchNumber,
-                LotNo = itemBarcodeDetails.LotNo,
-                Quantity = itemBarcodeDetails.Quantity,
-                DepotsCode = mesDepost.DepotCode,
-                DepotSectionsCode = sectionCode,
-                CheckDate = inventoryDetails.CheckDate,
-                IndepDate = DateTime.Now,
-                IqcStatus = inventoryDetails.CheckStates,
-                BoardStyle = itemBarcodeDetails.BoardStyle,
-                WorkNo = itemBarcodeDetails.WorkNo,
-                WorkLine = itemBarcodeDetails.WorkLine,
-                SuppId = itemBarcodeDetails.SuppId,
-                SuppNo = itemBarcodeDetails.SuppNo,
-                EbelnK3id = itemBarcodeDetails.EbelnK3id,
-                LineK3id = itemBarcodeDetails.LineK3id,
-                ItemId = itemBarcodeDetails.ItemId,
-                BillNo = itemBarcodeDetails.BillNo,
-                DepotId = Convert.ToInt32(mesDepost.DepotId),
-                OwnerId = cgddDetails.DemandOrg,
-                OwnerType = owner_type,
-                StockOrgId = mesDepost.FSubsidiary,
-                IndepUserCode = user
-            }).IgnoreColumns(true).ExecuteCommand();
-
-            itemBarcodeDetails.Hbdy ??= 0;
-
-            if (itemBarcodeDetails.Hbdy != 1)
-            {
-                //鏇存柊鏀舵枡鍗曟槑缁�
-                db.Updateable<MesInvItemArnDetail>()
-                    .SetColumns(d => new MesInvItemArnDetail
-                    {
-                        OkRkqty = (int)((d.OkRkqty ?? 0) + cSyQty)
-                    })
-                    .Where(d => d.Guid == itemBarcodeDetails.AboutGuid)
-                    .ExecuteCommand();
-
-                var first = db
-                    .Queryable<MesInvItemArnDetail>()
-                    .Where(b =>
-                        b.Guid == itemBarcodeDetails.AboutGuid)
-                    .Select(b => new
-                    {
-                        TotalQuantity =
-                            SqlFunc.AggregateSum(b.Quantity),
-                        TotalOkRkQty = SqlFunc.AggregateSum(b.OkRkqty)
-                    })
-                    .First();
-
-                var TotalQuantity = first.TotalQuantity ?? 0;
-                var TotalOkRkQty = first.TotalOkRkQty ?? 0;
-
-                if (TotalQuantity == TotalOkRkQty)
-                    db.Updateable<MesInvItemArnDetail>()
-                        .SetColumns(s => s.IsdepsIn == true)
-                        .Where(s => s.Guid == itemBarcodeDetails.AboutGuid)
-                        .ExecuteCommand();
-
-
-                var totalSummary = db.Queryable<MesInvItemArnDetail>()
-                    .InnerJoin<MesInvItemArn>((b, a) => a.Guid == b.ParentGuid)
-                    .Where((b, a) =>
-                        a.BillNo == inventory.BillNo && b.ReturnFlag == 0)
-                    .Select((b, a) => new
-                    {
-                        TotalQuantity = SqlFunc.AggregateSum(b.Quantity),
-                        TotalOkRkQty = SqlFunc.AggregateSum(b.OkRkqty)
-                    })
-                    .First();
-
-                if ((totalSummary.TotalQuantity ?? 0) ==
-                    (totalSummary.TotalOkRkQty ?? 0))
-                    db.Updateable<MesInvItemArn>()
-                        .SetColumns(it => it.Status == 1)
-                        .Where(it => it.BillNo == itemBarcodeDetails.BillNo)
-                        .ExecuteCommand();
-
-                var totalCDetailsQuantity = db.Queryable<MesInvItemInCDetails>()
-                    .Where(it => it.ItemId == itemBarcodeDetails.ItemId &&
-                                 it.WorkNo == itemBarcodeDetails.WorkNo &&
-                                 it.ItemInId == cId)
+                    res.ItemBarCDetails = Db.Ado.SqlQuery<dynamic>(sql2);
+                    //鏌ヨ宸插叆搴撴�绘暟
+                    var totalCDetailsQuantity = Db.Queryable<MesInvItemInCDetails>()
+                    .Where(it => it.ItemInId == cId)
                     .Sum(it => it.Quantity);
+                  
+                    res.SumQuantity = Convert.ToDecimal(totalCDetailsQuantity);
 
-                var detailSummary = db.Queryable<MesInvItemArnDetail>()
-                    .Where(it => it.Guid == inventoryDetails.Guid)
-                    .Select(it => new
-                    {
-                        TotalComeQty = SqlFunc.AggregateSum(it.Quantity),
-                        TotalInvQty = SqlFunc.AggregateSum(it.OkRkqty)
-                    })
-                    .First();
+                    // 璁剧疆杩斿洖淇℃伅
+                    res.Message = outMessage;
+                    
 
-                var comeQty = detailSummary.TotalComeQty ?? 0;
-                var invQty = detailSummary.TotalInvQty ?? 0;
-                var diffQty = comeQty - invQty;
-
-                if (detailSummary == null)
-                    throw new Exception("姝ゆ潯鐮佹壘涓嶅埌瀵瑰簲鏀惰揣鍗曟槑缁嗭紒");
-
-                var mesItems = db.Queryable<MesItems>()
-                    .Where(s => s.Id == itemBarcodeDetails.ItemId).First();
-
-                //result.Message =
-                //    $"鏉$爜鏁伴噺 {itemBarcodeDetails.Quantity},閲囪喘璁㈠崟 {itemBarcodeDetails.WorkNo} 椤规 {itemBarcodeDetails.WorkLine} 鐗╂枡 {mesItems.ItemNo} 鏈鍏ュ簱鎬绘暟锛歿totalCDetailsQuantity} 鎬诲埌 {comeQty} 宸插叆 {invQty} 娆� {diffQty}";
-                result.Message = $"鐗╂枡{mesItems.ItemNo}鍏ュ簱鎴愬姛鏁伴噺{itemBarcodeDetails.Quantity.ToString()}";
-
-                result.itemDetail = mesItems;
-
-                result.ItemInDetails = db.Queryable<MesInvItemInCItems,MesItems>(
-                    (a, b) => new JoinQueryInfos(
-                    JoinType.Left,
-                    a.ItemId == b.ItemId)
-                    )
-                    .Where(a => a.ItemInId == cId && a.ItemId == itemBarcodeDetails.ItemId)
-                    .Select<dynamic>((a, b) => new 
-                    {
-                        ItemNo = b.ItemNo,
-                        ItemName = b.ItemName,
-                        ItemModel = b.ItemModel,
-                        FQty = a.Quantity, // 鐢宠鏁伴噺
-                        FMaterialId = b.ItemId,
-                        Id = b.Guid.ToString()
-                    })
-                    .ToList();
-
-                result.ItemBarCDetails = db.Queryable<MesInvItemInCDetails, MesItems>(
-                    (a, b) => new JoinQueryInfos(
-                    JoinType.Left,
-                    a.ItemId == b.ItemId)
-                    )
-                    .Where(a => a.ItemInId == cId && a.ItemId == itemBarcodeDetails.ItemId)
-                    .Select<dynamic>((a, b) => new
-                    {
-                        ItemNo = b.ItemNo,
-                        ItemName = b.ItemName,
-                        ItemModel = b.ItemModel,
-                        FQty = a.Quantity, // 鐢宠鏁伴噺
-                        FMaterialId = b.ItemId,
-                        Id = a.Guid.ToString(),
-                        kw = a.DepotSectionCode,
-                        barcode = a.ItemBarcode
-                    })
-                    .ToList();
+                    return res;
+                //}
+                //catch (Exception ex)
+                //{
 
 
-                //result.ItemNo = mesItems.ItemNo;
-                result.SumQuantity = Convert.ToDecimal(invQty);
-
-                return 1;
+                //    // 璁板綍寮傚父鏃ュ織锛堝缓璁坊鍔犳棩蹇楄褰曪級
+                //    res.Message = $"鎿嶄綔澶辫触: {ex.Message}";
+                //    res.SumQuantity = -1;
+                //    return res;
+                //}
             }
-            else
-            {
-                // Step 1: Check if bill needs to be closed (status update)
-                var totalSummary = db.Queryable<MesInvItemArnDetail>()
-                    .LeftJoin<MesInvItemArn>((b, a) => a.Guid == b.ParentGuid)
-                    .Where((b, a) =>
-                        a.BillNo == inventory.BillNo && b.ReturnFlag == 0)
-                    .Select((b, a) => new
-                    {
-                        TotalQuantity = SqlFunc.AggregateSum(b.Quantity),
-                        TotalOkRkQty = SqlFunc.AggregateSum(b.OkRkqty)
-                    })
-                    .First();
-
-                if ((totalSummary.TotalQuantity ?? 0) ==
-                    (totalSummary.TotalOkRkQty ?? 0))
-                    db.Updateable<MesInvItemArn>()
-                        .SetColumns(it => it.Status == 1)
-                        .Where(it => it.BillNo == itemBarcodeDetails.BillNo)
-                        .ExecuteCommand();
-
-                // Step 2: Calculate total sum from `mes_inv_item_in_c_details`
-                var totalCDetailsQuantity = db.Queryable<MesInvItemInCDetails>()
-                    .Where(it => it.Guid == itemBarcodeDetails.AboutGuid)
-                    .Sum(it => it.Quantity);
-
-                // Step 3: Calculate comeQty and invQty from `mes_inv_item_arn_detail`
-                var detailSummary = db.Queryable<MesInvItemArnDetail>()
-                    .Where(it => it.Guid == itemBarcodeDetails.AboutGuid)
-                    .Select(it => new
-                    {
-                        TotalComeQty = SqlFunc.AggregateSum(it.Quantity),
-                        TotalInvQty = SqlFunc.AggregateSum(it.OkRkqty)
-                    })
-                    .First();
-
-                if (detailSummary == null)
-                    throw new Exception("姝ゆ潯鐮佹壘涓嶅埌瀵瑰簲鏀惰揣鍗曟槑缁嗭紒");
-
-                var comeQty = detailSummary.TotalComeQty ?? 0;
-                var invQty = detailSummary.TotalInvQty ?? 0;
-                var diffQty = comeQty - invQty;
-
-                var mesItems = db.Queryable<MesItems>()
-                    .Where(s => s.Id == itemBarcodeDetails.ItemId).First();
-
-                // Step 5: Combine final result
-                result.Message =
-                    $" 鏉$爜鏁伴噺:{itemBarcodeDetails.Quantity},鐗╂枡 {mesItems.ItemNo} 鏈鍏ュ簱鎬绘暟锛歿totalCDetailsQuantity} 鎬诲埌 {comeQty} 宸插叆 {invQty} 娆� {diffQty}";
-
-
-                //result.ItemNo = mesItems.ItemNo;
-                result.SumQuantity = Convert.ToDecimal(totalCDetailsQuantity);
-            }
-
-            var mesInvItemInCDetails =
-                base.GetSingle(it => it.ItemBarcode == entity.barcode);
-
-            if (mesInvItemInCDetails == null)
-                throw new Exception("鐗╂枡鍏ュ簱鏉$爜鏄庣粏涓嶅瓨鍦�"); // 鎶涘嚭寮傚父浠ヤ緵鍓嶅彴澶勭悊
-
-            // 鍒涘缓 鎻掑叆鏃ュ織
-            var logService = new LogService();
-            var LogMsg = "銆怭DA銆戦噰璐叆搴撱�傛潯鐮併��" + entity.barcode + "銆� 鍏ュ簱鍗曞彿銆�" + cBillNo + "銆�";
-            logService.CreateLog(db, entity.userName, inventory.Guid.ToString(), "MES_INV_ITEM_ARN", LogMsg, inventory.BillNo);
-
-            return 1;
-        });
-
-        var purchaseInventory = getPurchaseInventory(entity);
-
-        
-        //result.ItemInDetails = purchaseInventory.ItemInDetails;
-        //result.InvItemInCDetails = purchaseInventory.InvItemInCDetails;
-
-        return result;
+        }
     }
 
+
+
+
+    /*  public ItemInBaseModel SaveBarCodes(WarehouseQuery entity)
+      {
+          string functionName = "閲囪喘鍏ュ簱", fieldName = null, inFieldVal = null;
+          string user = entity.userName,
+              sectionCode = entity.sectionCode,
+              itemBarcode = entity.barcode;
+          var transactionNo = "101";
+          int? billTypeId = 100, num = 0, num2 = 0;
+          var freeze = 0;
+          decimal cSyQty = 0;
+
+          if (string.IsNullOrEmpty(sectionCode))
+              throw new Exception("璇锋壂搴撲綅鏉$爜锛�");
+
+          var itemBarcodeDetails = Db.Queryable<MesInvItemBarcodes>()
+              .Where(it => it.ItemBarcode == itemBarcode)
+              .First();
+
+          if (itemBarcodeDetails == null)
+              throw new Exception("鏉$爜涓嶅瓨鍦紝璇锋牳瀵癸紒");
+
+          if (string.IsNullOrEmpty(itemBarcodeDetails.Memo) || itemBarcodeDetails.Memo != "閲囪喘鍏ュ簱")
+              throw new Exception("姝ゆ潯鐮佷笉灞炰簬鍒拌揣鏉$爜锛屾棤娉曠敤閲囪喘鍏ュ簱锛�");
+
+          var inventory = Db.Queryable<MesInvItemArn>()
+              .Where(it => it.BillNo == itemBarcodeDetails.BillNo && it.Fstatus == true )
+              .First();
+
+          if (inventory == null)
+              throw new Exception("姝ゆ潯鐮佹壘涓嶅埌瀵瑰簲鏀惰揣鍗曟垨鏈鏍革紒");
+
+          // var inventoryDetails = Db.Queryable<MesInvItemArnDetail>()
+          //     .Where(it => it.ParentGuid == inventory.Guid
+          //                  && it.ItemId == itemBarcodeDetails.ItemId
+          //                  && it.EbelnLine == itemBarcodeDetails.WorkLine
+          //                  && it.Ebeln == itemBarcodeDetails.WorkNo)
+          //     .First();
+
+          var inventoryDetails = Db.Queryable<MesInvItemArnDetail>()
+              .Where(it => it.Guid == itemBarcodeDetails.AboutGuid)
+              .First();
+
+          var cgddDetails = Db.Queryable<MesRohInData>()
+              .Where(it => it.EbelnK3id == inventoryDetails.LineK3id)
+              .First();
+
+          if (cgddDetails == null)
+              throw new Exception("姝ゆ潯鐮佹壘涓嶅埌瀵瑰簲閲囪喘璁㈠崟鏄庣粏锛�");
+
+          if (inventoryDetails == null)
+              throw new Exception("姝ゆ潯鐮佹壘涓嶅埌瀵瑰簲鏀惰揣鍗曟槑缁嗭紒");
+
+          //鑾峰彇鍒拌揣妫�楠屾槑缁�
+          var sqlParams = new List<SugarParameter> { new("@dhmxGuid", itemBarcodeDetails.AboutGuid) };
+          var sql1 = @"SELECT *FROM v_dhmx WHERE dhmxGuid = @dhmxGuid ";
+          var dhjymx = Db.Ado.SqlQuery<vDhmx>(sql1, sqlParams).First();
+          //鍒ゅ畾妫�楠岃兘鍚﹀叆搴�
+          if (dhjymx.CanStore!= 1)
+          {
+              throw new Exception($"璇ユ潯鐮佸搴旂殑鏀舵枡鍗曟楠岀粨鏋�:銆恵dhjymx.InspectionResult}銆�,鍒ゅ畾缁撴灉锛氥�恵dhjymx.JudgmentResult}銆戯紝澶勭悊鎰忚锛氥�恵dhjymx.HandlingSuggestion}銆�,鏃犳硶鍏ュ簱");
+          }
+
+          var depotCode = Db.Queryable<MesDepotSections>()
+              .Where(it => it.DepotSectionCode == sectionCode)
+              .Select(it => it.DepotGuid)
+              .First();
+
+          var depotCode2 = Db.Queryable<MesInvItemArn>()
+              .Where(it => it.BillNo == itemBarcodeDetails.BillNo)
+              .Select(it => it.DepotsId)
+              .First();
+
+          MesDepots mesDepost = null;
+
+          var checkGuid = UtilityHelper.CheckGuid(depotCode);
+          if (checkGuid && depotCode != null)
+          {
+              mesDepost = Db.Queryable<MesDepots>()
+                  .Where(s => s.DepotId.ToString() == depotCode).First();
+
+              // if (depotCode != mesDepost.Guid)
+              //     throw new Exception("鎵弿搴撲綅涓庨噰璐叆搴撳簱浣嶄笉涓�鑷达紒");
+          }
+          else
+          {
+              throw new Exception("搴撲綅缂栫爜 " + sectionCode + " 涓嶅瓨鍦紝璇风‘璁わ紒");
+          }
+
+
+          //num = Db.Queryable<MesInvItemInCDetails>()
+          //    .Where(it => it.ItemBarcode == itemBarcode)
+          //    .Count();
+
+          //if (num > 0)
+          //    throw new Exception("姝ゆ潯鐮佸凡鎵爜鍏ュ簱瀹屾垚锛岃鏍稿锛�");
+
+          //num = Db.Queryable<MesInvItemStocks>()
+          //    .Where(it => it.ItemBarcode == itemBarcode)
+          //    .Count();
+
+          //if (num > 0)
+          //    throw new Exception("姝ゆ潯鐮佸凡鎵爜鍏ュ簱锛岃鏍稿锛�");
+
+          var wmsManager = new WmsBaseMangeer();
+          // 鏂板鍏ュ簱鏍¢獙锛堣皟鐢ㄥ瓨鍌ㄨ繃绋嬶級
+          var checkResult = wmsManager.pdaInvJY(
+              db: Db,
+              edtUserNo: entity.userName,
+              barcode: entity.barcode,
+              sectionCode: sectionCode,
+              stockId: mesDepost.DepotId.ToString(),
+              stockOrgId: mesDepost.FSubsidiary,
+              billNo: "", // 鏍规嵁瀹為檯鍗曟嵁鍙蜂紶鍊�
+              transactionNo: "101" // 浜嬪姟绫诲瀷涓庡瓨鍌ㄨ繃绋嬪尮閰�
+          );
+
+          if (Convert.ToInt32(checkResult.result) < 1)
+              throw new Exception($"鍏ュ簱鏍¢獙澶辫触锛歿checkResult.strMsg}");
+
+
+
+          //num = Db.Queryable<MesInvItemArn>()
+          //    .Where(a => a.BillNo == itemBarcodeDetails.BillNo)
+          //    .InnerJoin<MesInvItemArnDetail>((a, b) =>
+          //        b.ParentGuid == a.Guid &&
+          //        b.ItemId == itemBarcodeDetails.ItemId && b.Ischeck == 1)
+          //    .Count();
+
+          //num2 = Db.Queryable<MesInvItemArn>()
+          //    .Where(a => a.BillNo == itemBarcodeDetails.BillNo)
+          //    .InnerJoin<MesInvItemArnDetail>((a, b) => b.ParentGuid == a.Guid
+          //        && b.ItemId == itemBarcodeDetails.ItemId
+          //        && (b.CheckRes == "鍚堟牸" || b.CheckStates == "鐗归噰鐩存帴浣跨敤"))
+          //    .Count();
+
+          //switch (num)
+          //{
+          //    case 0 when num2 == 0:
+          //    case > 0 when num2 == 0:
+          //        freeze = 1;
+          //        break;
+          //    case 0 when num2 > 0:
+          //        throw new Exception("鍏ュ簱澶辫触,鍒拌揣鍗曟嵁鏈夐棶棰橈紒");
+          //}
+
+
+          // 鍒ゆ柇璐т富绫诲瀷
+          var owner_type = wmsManager.GetOwnerType(cgddDetails.DemandOrg);
+          // if (Db.Queryable<SysOrganization>().Any(x => x.Fid == cgddDetails.DemandOrg))
+          // {
+          //     owner_type = "BD_OwnerOrg";
+          // }
+          // else
+          // {
+          //     // 绗簩灞傚垽鏂細妫�鏌� MES_CUSTOMER
+          //     if (Db.Queryable<MesCustomer>().Any(x => x.Id == Convert.ToInt32(cgddDetails.DemandOrg)))
+          //     {
+          //         owner_type = "BD_Customer";
+          //     }
+          //     else
+          //     {
+          //         // 绗笁灞傚垽鏂細妫�鏌� MES_SUPPLIER
+          //         if (Db.Queryable<MesSupplier>().Any(x => x.Id == Convert.ToInt32(cgddDetails.DemandOrg)))
+          //         {
+          //             owner_type = "BD_Supplier";
+          //         }
+          //         else
+          //         {
+
+          //             // 绗洓灞傚垽鏂細鍐嶆妫�鏌� SYS_ORGANIZATION
+          //             if (Db.Queryable<SysOrganization>().Any(x => x.Fid == cgddDetails.ReceivingOrg))
+          //             {
+          //                 owner_type = "BD_OwnerOrg";
+          //             }
+          //             else
+          //             {
+          //                 throw new Exception("鍏ュ簱澶辫触,鍒拌揣鍗曟嵁瀵瑰簲鐨勯渶姹傜粍缁囨湁闂锛�");
+          //             }
+          //         }
+          //     }
+          //}
+
+          var result = new ItemInBaseModel();
+
+          UseTransaction(db =>
+          {
+              var existingRecord = db.Queryable<MesInvItemIns>()
+                  .Where(it => it.InsDate.Value.ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd")
+                               && it.TaskNo == itemBarcodeDetails.BillNo
+                               && it.Status == 0
+                               && it.TransctionNo == transactionNo
+                               && it.CreateBy == entity.userName
+                               && it.BillTypeId == billTypeId
+                               && it.DepotsId == mesDepost.DepotId)
+                  .Select(it => new
+                  {
+                      it.Guid,
+                      it.BillNo
+                  })
+                  .First();
+
+              var cId = Guid.Empty;
+              string cBillNo = null;
+
+              if (existingRecord != null)
+              {
+                  // If record exists, assign values
+                  cId = existingRecord.Guid;
+                  cBillNo = existingRecord.BillNo;
+              }
+              else
+              {
+                  cId = Guid.NewGuid();
+                  cBillNo = BillNo.GetBillNo("CGRK(閲囪喘鍏ュ簱)");
+
+                  var suppNo = db.Queryable<MesSupplier>()
+                      .Where(s => s.Id.ToString() == inventory.SuppId).First();
+
+                  db.Insertable(new MesInvItemIns
+                  {
+                      Guid = cId,
+                      BillNo = cBillNo,
+                      BillTypeId = billTypeId,
+                      InsDate = DateTime.Now,
+                      DepotsId = mesDepost.DepotId,
+                      DepotsCode = mesDepost.DepotCode,
+                      TransctionNo = transactionNo,
+                      SuppId = suppNo.Id.ToString(),
+                      SuppNo = suppNo.SuppNo,
+                      CreateBy = user,
+                      CreateDate = DateTime.Now,
+                      LastupdateBy = user,
+                      LastupdateDate = DateTime.Now,
+                      UrgentFlag = itemBarcodeDetails.UrgentFlag.GetValueOrDefault() ? "1" : "0",
+                      CbillNo = itemBarcodeDetails.BillNo,
+                      Fstatus = 0,
+                      Status = 0,
+                      ReceiveOrgId = inventory.ReceiveOrgId,
+                      InType = "閲囪喘鍏ュ簱",
+                      TaskNo = itemBarcodeDetails.BillNo
+                      //WorkNo = itemBarcodeDetails.WorkNo
+                  }).IgnoreColumns(true).ExecuteCommand();
+              }
+
+              cSyQty = itemBarcodeDetails.Quantity.Value;
+
+              entity.id = cId.ToString();
+              entity.PageIndex = 1;
+              entity.Limit = 1;
+
+              itemBarcodeDetails.Hbdy ??= 0;
+              if (itemBarcodeDetails.Hbdy == 1)
+              {
+                  var details = db.Queryable<MesInvItemArnDetail>()
+                      .Where(d =>
+                          d.CbillNo == itemBarcodeDetails.BillNo &&
+                          d.Quantity != d.OkRkqty &&
+                          d.ItemId == itemBarcodeDetails.ItemId)
+                      .ToList();
+
+
+                  foreach (var detail in details)
+                  {
+                      if (cSyQty == 0) break;
+
+                      var remainingQty = detail.Quantity - (detail.OkRkqty ?? 0);
+                      if (remainingQty <= cSyQty)
+                      {
+                          // Update detail
+                          db.Updateable<MesInvItemArnDetail>()
+                              .SetColumns(d => new MesInvItemArnDetail
+                              {
+                                  OkRkqty = (int)d.Quantity,
+                                  IsdepsIn = true
+                              })
+                              .Where(d => d.Guid == detail.Guid)
+                              .IgnoreColumns(true)
+                              .ExecuteCommand();
+
+                          // Check if already inserted
+                          var count = db.Queryable<MesInvItemInCItems>()
+                              .Where(it =>
+                                  it.ItemInId == cId &&
+                                      it.ItemId == detail.ItemId &&
+                                      it.DepotId == mesDepost.DepotId.ToString() &&
+                                      it.EbelnK3id == detail.EbelnK3id &&
+                                      it.LineK3id == detail.LineK3id)
+                              .Count();
+
+                          cSyQty -= remainingQty.Value;
+
+                          if (count == 0)
+                              // Insert new item into MES_INV_ITEM_IN_C_ITEMS
+                              db.Insertable(new MesInvItemInCItems
+                              {
+                                  ItemInId = cId,
+                                  Quantity = remainingQty,
+                                  CreateBy = user,
+                                  CreateDate = DateTime.Now,
+                                  ItemId = detail.ItemId,
+                                  DepotCode = mesDepost.DepotCode,
+                                  ItemSname = itemBarcodeDetails.ItemSname,
+                                  Unit = itemBarcodeDetails.Unit,
+                                  Ebeln = detail.Ebeln,
+                                  BillNo = cBillNo,
+                                  WorkNo = detail.WorkNo,
+                                  CbillNo = detail.CbillNo,
+                                  WorkLine = detail.WorkLine,
+                                  SuppId = itemBarcodeDetails.SuppId,
+                                  SuppNo = itemBarcodeDetails.SuppNo,
+                                  Remark = itemBarcodeDetails.Memo,
+                                  EbelnK3id = detail.EbelnK3id,
+                                  LineK3id = detail.LineK3id,
+                                  DepotId = mesDepost.DepotId.ToString(),
+                                  itemDabid = itemBarcodeDetails.AboutGuid.ToString()
+                              }).IgnoreColumns(true).ExecuteCommand();
+                          else
+                              db.Updateable<MesInvItemInCItems>()
+                                  .SetColumns(it =>
+                                      it.Quantity == it.Quantity + remainingQty)
+                                  .Where(it =>
+                                      it.ItemInId == cId &&
+                                      it.ItemId == detail.ItemId &&
+                                      it.DepotId == mesDepost.DepotId.ToString() &&
+                                      it.EbelnK3id == detail.EbelnK3id &&
+                                      it.LineK3id == detail.LineK3id)
+                                  .IgnoreColumns(true)
+                                  .ExecuteCommand();
+
+                          // Insert new detail into MES_INV_ITEM_IN_C_DETAILS
+                          db.Insertable(new MesInvItemInCDetails
+                          {
+                              ItemInId = cId,
+                              BillNo = cBillNo,
+                              ItemBarcode = itemBarcode,
+                              Quantity = remainingQty,
+                              BarcodeFlag = true,
+                              EpFlag = true,
+                              WorkType = 1,
+                              ItemNo = detail.ItemNo,
+                              SuppId = itemBarcodeDetails.SuppId,
+                              SuppNo = itemBarcodeDetails.SuppNo,
+                              DepotCode = mesDepost.DepotCode,
+                              DepotSectionCode = sectionCode,
+                              ItemSname = itemBarcodeDetails.ItemSname,
+                              Unit = itemBarcodeDetails.Unit,
+                              CreateBy = user,
+                              CreateDate = DateTime.Now,
+                              LastupdateBy = user,
+                              LastupdateDate = DateTime.Now,
+                              Remark = itemBarcodeDetails.Memo,
+                              Ebeln = detail.WorkNo,
+                              WorkNo = detail.WorkNo,
+                              WorkLine = detail.WorkLine,
+                              CbillNo = itemBarcodeDetails.BillNo,
+                              UrgentFlag = detail.UrgentFlag,
+                              BoardStyle = detail.BoardStyle,
+                              TaskNo = detail.WorkNo,
+                              EbelnK3id = detail.EbelnK3id,
+                              LineK3id = detail.LineK3id,
+                              ItemId = detail.ItemId,
+                              ReceiveOrgId = inventory.ReceiveOrgId,
+                              LotNo = cgddDetails.BatchNumber
+                          }).IgnoreColumns(true).ExecuteCommand();
+                      }
+                      else
+                      {
+                          // Partially fulfill remaining quantity
+                          db.Updateable<MesInvItemArnDetail>()
+                              .SetColumns(d => new MesInvItemArnDetail
+                              {
+                                  OkRkqty = (int)((d.OkRkqty ?? 0) + cSyQty)
+                              })
+                              .Where(d => d.Guid == detail.Guid)
+                              .IgnoreColumns(true)
+                              .ExecuteCommand();
+
+                          var count = db.Queryable<MesInvItemInCItems>()
+                              .Where(it =>
+                                  it.ItemInId == cId &&
+                                      it.ItemId == detail.ItemId &&
+                                      it.DepotId == mesDepost.DepotId.ToString() &&
+                                      it.EbelnK3id == detail.EbelnK3id &&
+                                      it.LineK3id == detail.LineK3id)
+                              .Count();
+
+                          if (count == 0)
+                              db.Insertable(new MesInvItemInCItems
+                              {
+                                  ItemInId = cId,
+                                  Quantity = cSyQty,
+                                  CreateBy = user,
+                                  CreateDate = DateTime.Now,
+                                  ItemNo = detail.ItemNo,
+                                  DepotCode = mesDepost.DepotCode,
+                                  ItemSname = itemBarcodeDetails.ItemSname,
+                                  Unit = itemBarcodeDetails.Unit,
+                                  Ebeln = detail.WorkNo,
+                                  BillNo = cBillNo,
+                                  WorkNo = detail.WorkNo,
+                                  EbelnLineNo = detail.EbelnLine,
+                                  CbillNo = detail.CbillNo,
+                                  WorkLine = detail.WorkLine,
+                                  SuppId = itemBarcodeDetails.SuppId,
+                                  SuppNo = itemBarcodeDetails.SuppNo,
+                                  Remark = itemBarcodeDetails.Memo,
+                                  EbelnK3id = detail.EbelnK3id,
+                                  LineK3id = detail.LineK3id,
+                                  ItemId = detail.ItemId,
+                                  DepotId = mesDepost.DepotId.ToString()
+                              }).IgnoreColumns(true).ExecuteCommand();
+                          else
+                              db.Updateable<MesInvItemInCItems>()
+                                  .SetColumns(it =>
+                                      it.Quantity == it.Quantity + cSyQty)
+                                  .Where(it =>
+                                      it.ItemInId == cId &&
+                                      it.ItemId == detail.ItemId &&
+                                      it.DepotId == mesDepost.DepotId.ToString() &&
+                                      it.EbelnK3id == detail.EbelnK3id &&
+                                      it.LineK3id == detail.LineK3id)
+                                  .IgnoreColumns(true)
+                                  .ExecuteCommand();
+
+                          db.Insertable(new MesInvItemInCDetails
+                          {
+                              ItemInId = cId,
+                              BillNo = cBillNo,
+                              ItemBarcode = itemBarcode,
+                              Quantity = cSyQty,
+                              BarcodeFlag = true,
+                              EpFlag = true,
+                              WorkType = 1,
+                              ItemNo = detail.ItemNo,
+                              SuppId = itemBarcodeDetails.SuppId,
+                              SuppNo = itemBarcodeDetails.SuppNo,
+                              DepotCode = mesDepost.DepotCode,
+                              DepotSectionCode = sectionCode,
+                              ItemSname = itemBarcodeDetails.ItemSname,
+                              Unit = itemBarcodeDetails.Unit,
+                              CreateBy = user,
+                              CreateDate = DateTime.Now,
+                              LastupdateBy = user,
+                              LastupdateDate = DateTime.Now,
+                              Remark = itemBarcodeDetails.Memo,
+                              Ebeln = detail.WorkNo,
+                              EbelnLineNo = detail.EbelnLine,
+                              WorkNo = detail.WorkNo,
+                              WorkLine = detail.WorkLine,
+                              CbillNo = itemBarcodeDetails.BillNo,
+                              UrgentFlag = detail.UrgentFlag,
+                              BoardStyle = detail.BoardStyle,
+                              TaskNo = detail.WorkNo,
+                              EbelnK3id = detail.EbelnK3id,
+                              LineK3id = detail.LineK3id,
+                              ItemId = detail.ItemId,
+                              ReceiveOrgId = inventory.ReceiveOrgId,
+                              LotNo = cgddDetails.BatchNumber
+                          }).IgnoreColumns(true).ExecuteCommand();
+
+                          cSyQty = 0; // Remaining quantity fulfilled
+                      }
+                  }
+
+                  db.Insertable(new MesInvBusiness2
+                  {
+                      Status = 1,
+                      BillTypeId = billTypeId,
+                      TransactionCode = transactionNo,
+                      BusinessType = 1,
+                      ItemBarcode = itemBarcode,
+                      ItemNo = itemBarcodeDetails.ItemNo,
+                      LotNo = cgddDetails.BatchNumber,
+                      EpFlag = true,
+                      Quantity = itemBarcodeDetails.Quantity,
+                      ToInvDepotsCode = mesDepost.DepotCode,
+                      ToInvDepotSectionsCode = sectionCode,
+                      Description = "閲囪喘鍏ュ簱",
+                      CreateBy = user,
+                      CreateDate = DateTime.Now,
+                      LastupdateBy = user,
+                      LastupdateDate = DateTime.Now,
+                      TaskNo = itemBarcodeDetails.BillNo,
+                      BillNo = cBillNo,
+                      WorkNo = itemBarcodeDetails.WorkNo,
+                      WorkLine = itemBarcodeDetails.WorkLine,
+                      SuppId = itemBarcodeDetails.SuppId,
+                      SuppNo = itemBarcodeDetails.SuppNo,
+                      EbelnK3id = itemBarcodeDetails.EbelnK3id,
+                      LineK3id = itemBarcodeDetails.LineK3id,
+                      ItemId = itemBarcodeDetails.ItemId
+                  }).IgnoreColumns(true).ExecuteCommand();
+
+                  // Insert into mes_inv_item_stocks
+              }
+              else
+              {
+                  var detailone = db.Queryable<MesInvItemArnDetail>()
+                      .Where(d =>
+                          d.Guid == itemBarcodeDetails.AboutGuid)
+                      .First();
+
+                  // 妫�鏌ユ槸鍚﹀瓨鍦ㄤ簬 MES_INV_ITEM_IN_C_ITEMS 琛�
+                  var existingCount = db.Queryable<MesInvItemInCItems>()
+                      .Where(it =>
+                      it.ItemInId == cId &&
+                                      it.ItemId == detailone.ItemId &&
+                                      it.DepotId == mesDepost.DepotId.ToString() &&
+                                      it.itemDabid == itemBarcodeDetails.AboutGuid.ToString())
+                      .Count();
+
+                  if (existingCount == 0)
+                      // 涓嶅瓨鍦ㄦ椂鎻掑叆鏂拌褰�
+                      db.Insertable(new MesInvItemInCItems
+                      {
+                          ItemInId = cId,
+                          Quantity = itemBarcodeDetails.Quantity,
+                          CreateBy = user,
+                          CreateDate = DateTime.Now,
+                          ItemNo = itemBarcodeDetails.ItemNo,
+                          DepotCode = mesDepost.DepotCode,
+                          ItemSname = itemBarcodeDetails.ItemSname,
+                          Unit = itemBarcodeDetails.Unit,
+                          Ebeln = itemBarcodeDetails.WorkNo,
+                          BillNo = cBillNo,
+                          WorkNo = itemBarcodeDetails.WorkNo,
+                          EbelnLineNo = itemBarcodeDetails.WorkLine,
+                          CbillNo = itemBarcodeDetails.BillNo,
+                          WorkLine = itemBarcodeDetails.WorkLine,
+                          SuppId = itemBarcodeDetails.SuppId,
+                          SuppNo = itemBarcodeDetails.SuppNo,
+                          Remark = itemBarcodeDetails.Memo,
+                          EbelnK3id = itemBarcodeDetails.EbelnK3id,
+                          LineK3id = itemBarcodeDetails.LineK3id,
+                          ItemId = itemBarcodeDetails.ItemId,
+                          DepotId = mesDepost.DepotId.ToString(),
+                          itemDabid = itemBarcodeDetails.AboutGuid.ToString()
+                      }).IgnoreColumns(true).ExecuteCommand();
+                  else
+                      // 瀛樺湪鏃舵洿鏂版暟閲�
+                      db.Updateable<MesInvItemInCItems>()
+                          .SetColumns(it => new MesInvItemInCItems
+                          {
+                              Quantity = SqlFunc.IsNull(it.Quantity, 0) + itemBarcodeDetails.Quantity // 纭繚 Quantity 涓嶄负 null
+                          })
+                          .Where(it =>
+                                      it.ItemInId == cId &&
+                                      it.ItemId == detailone.ItemId &&
+                                      it.DepotId == mesDepost.DepotId.ToString() &&
+                                      it.itemDabid == itemBarcodeDetails.AboutGuid.ToString())
+                          //.IgnoreColumns(true) // 淇濈暀 IgnoreColumns
+                          .ExecuteCommand();
+
+                  // 鎻掑叆 mes_inv_item_in_c_details 琛�
+                  db.Insertable(new MesInvItemInCDetails
+                  {
+                      ItemInId = cId,
+                      BillNo = cBillNo,
+                      ItemBarcode = itemBarcode,
+                      Quantity = itemBarcodeDetails.Quantity,
+                      BarcodeFlag = true,
+                      EpFlag = true,
+                      WorkType = 1,
+                      ItemNo = itemBarcodeDetails.ItemNo,
+                      LotNo = cgddDetails.BatchNumber,
+                      SuppId = itemBarcodeDetails.SuppId,
+                      SuppNo = itemBarcodeDetails.SuppNo,
+                      DepotCode = mesDepost.DepotCode,
+                      DepotSectionCode = sectionCode,
+                      ItemSname = itemBarcodeDetails.ItemSname,
+                      Unit = itemBarcodeDetails.Unit,
+                      CreateBy = user,
+                      CreateDate = DateTime.Now,
+                      LastupdateBy = user,
+                      LastupdateDate = DateTime.Now,
+                      Remark = itemBarcodeDetails.Memo,
+                      Ebeln = itemBarcodeDetails.Mblnr,
+                      EbelnLineNo = itemBarcodeDetails.Zeile,
+                      WorkNo = itemBarcodeDetails.WorkNo,
+                      WorkLine = itemBarcodeDetails.WorkLine,
+                      CbillNo = itemBarcodeDetails.BillNo,
+                      UrgentFlag = itemBarcodeDetails.UrgentFlag,
+                      BoardStyle = itemBarcodeDetails.BoardStyle,
+                      TaskNo = itemBarcodeDetails.TaskNo,
+                      EbelnK3id = itemBarcodeDetails.EbelnK3id,
+                      LineK3id = itemBarcodeDetails.LineK3id,
+                      ItemId = itemBarcodeDetails.ItemId,
+                      Ischeck = true,
+                      CheckDate = inventoryDetails.CheckDate,
+                      CheckRes = inventoryDetails.CheckRes,
+                      CheckStates = inventoryDetails.CheckStates,
+                      ReceiveOrgId = inventory.ReceiveOrgId,
+                      DepotId = Convert.ToInt64(mesDepost.DepotId.ToString())
+                  }).IgnoreColumns(true).ExecuteCommand();
+
+                  // 鎻掑叆 mes_inv_business2 琛�
+                  db.Insertable(new MesInvBusiness2
+                  {
+                      Status = 1,
+                      BillTypeId = billTypeId,
+                      TransactionCode = transactionNo,
+                      BusinessType = 1,
+                      ItemBarcode = itemBarcode,
+                      ItemNo = itemBarcodeDetails.ItemNo,
+                      LotNo = itemBarcodeDetails.LotNo,
+                      EpFlag = true,
+                      Quantity = itemBarcodeDetails.Quantity,
+                      FromInvDepotsCode = null,
+                      FromInvDepotSectionsCode = null,
+                      ToInvDepotsCode = mesDepost.DepotCode,
+                      ToInvDepotSectionsCode = sectionCode,
+                      Description = "閲囪喘鍏ュ簱",
+                      CreateBy = user,
+                      CreateDate = DateTime.Now,
+                      LastupdateBy = user,
+                      LastupdateDate = DateTime.Now,
+                      TaskNo = itemBarcodeDetails.TaskNo,
+                      BillNo = cBillNo,
+                      WorkNo = itemBarcodeDetails.WorkNo,
+                      WorkLine = itemBarcodeDetails.WorkLine,
+                      SuppId = itemBarcodeDetails.SuppId,
+                      SuppNo = itemBarcodeDetails.SuppNo,
+                      EbelnK3id = itemBarcodeDetails.EbelnK3id,
+                      LineK3id = itemBarcodeDetails.LineK3id,
+                      ItemId = itemBarcodeDetails.ItemId
+                  }).IgnoreColumns(true).ExecuteCommand();
+
+                  // 鎻掑叆 mes_inv_item_stocks 琛�
+              }
+
+
+
+              db.Insertable(new MesInvItemStocks
+              {
+                  TaskNo = itemBarcodeDetails.TaskNo,
+                  ItemBarcode = itemBarcode,
+                  ItemNo = cgddDetails.BatchNumber,
+                  LotNo = itemBarcodeDetails.LotNo,
+                  Quantity = itemBarcodeDetails.Quantity,
+                  DepotsCode = mesDepost.DepotCode,
+                  DepotSectionsCode = sectionCode,
+                  CheckDate = inventoryDetails.CheckDate,
+                  IndepDate = DateTime.Now,
+                  IqcStatus = inventoryDetails.CheckStates,
+                  BoardStyle = itemBarcodeDetails.BoardStyle,
+                  WorkNo = itemBarcodeDetails.WorkNo,
+                  WorkLine = itemBarcodeDetails.WorkLine,
+                  SuppId = itemBarcodeDetails.SuppId,
+                  SuppNo = itemBarcodeDetails.SuppNo,
+                  EbelnK3id = itemBarcodeDetails.EbelnK3id,
+                  LineK3id = itemBarcodeDetails.LineK3id,
+                  ItemId = itemBarcodeDetails.ItemId,
+                  BillNo = itemBarcodeDetails.BillNo,
+                  DepotId = Convert.ToInt32(mesDepost.DepotId),
+                  OwnerId = cgddDetails.DemandOrg,
+                  OwnerType = owner_type,
+                  StockOrgId = mesDepost.FSubsidiary,
+                  IndepUserCode = user
+              }).IgnoreColumns(true).ExecuteCommand();
+
+              itemBarcodeDetails.Hbdy ??= 0;
+
+              if (itemBarcodeDetails.Hbdy != 1)
+              {
+                  //鏇存柊鏀舵枡鍗曟槑缁�
+                  db.Updateable<MesInvItemArnDetail>()
+                      .SetColumns(d => new MesInvItemArnDetail
+                      {
+                          OkRkqty = (int)((d.OkRkqty ?? 0) + cSyQty)
+                      })
+                      .Where(d => d.Guid == itemBarcodeDetails.AboutGuid)
+                      .ExecuteCommand();
+
+                  var first = db
+                      .Queryable<MesInvItemArnDetail>()
+                      .Where(b =>
+                          b.Guid == itemBarcodeDetails.AboutGuid)
+                      .Select(b => new
+                      {
+                          TotalQuantity =
+                              SqlFunc.AggregateSum(b.Quantity),
+                          TotalOkRkQty = SqlFunc.AggregateSum(b.OkRkqty)
+                      })
+                      .First();
+
+                  var TotalQuantity = first.TotalQuantity ?? 0;
+                  var TotalOkRkQty = first.TotalOkRkQty ?? 0;
+
+                  if (TotalQuantity == TotalOkRkQty)
+                      db.Updateable<MesInvItemArnDetail>()
+                          .SetColumns(s => s.IsdepsIn == true)
+                          .Where(s => s.Guid == itemBarcodeDetails.AboutGuid)
+                          .ExecuteCommand();
+
+
+                  var totalSummary = db.Queryable<MesInvItemArnDetail>()
+                      .InnerJoin<MesInvItemArn>((b, a) => a.Guid == b.ParentGuid)
+                      .Where((b, a) =>
+                          a.BillNo == inventory.BillNo && b.ReturnFlag == 0)
+                      .Select((b, a) => new
+                      {
+                          TotalQuantity = SqlFunc.AggregateSum(b.Quantity),
+                          TotalOkRkQty = SqlFunc.AggregateSum(b.OkRkqty)
+                      })
+                      .First();
+
+                  if ((totalSummary.TotalQuantity ?? 0) ==
+                      (totalSummary.TotalOkRkQty ?? 0))
+                      db.Updateable<MesInvItemArn>()
+                          .SetColumns(it => it.Status == 1)
+                          .Where(it => it.BillNo == itemBarcodeDetails.BillNo)
+                          .ExecuteCommand();
+
+                  var totalCDetailsQuantity = db.Queryable<MesInvItemInCDetails>()
+                      .Where(it => it.ItemId == itemBarcodeDetails.ItemId &&
+                                   it.WorkNo == itemBarcodeDetails.WorkNo &&
+                                   it.ItemInId == cId)
+                      .Sum(it => it.Quantity);
+
+                  var detailSummary = db.Queryable<MesInvItemArnDetail>()
+                      .Where(it => it.Guid == inventoryDetails.Guid)
+                      .Select(it => new
+                      {
+                          TotalComeQty = SqlFunc.AggregateSum(it.Quantity),
+                          TotalInvQty = SqlFunc.AggregateSum(it.OkRkqty)
+                      })
+                      .First();
+
+                  var comeQty = detailSummary.TotalComeQty ?? 0;
+                  var invQty = detailSummary.TotalInvQty ?? 0;
+                  var diffQty = comeQty - invQty;
+
+                  if (detailSummary == null)
+                      throw new Exception("姝ゆ潯鐮佹壘涓嶅埌瀵瑰簲鏀惰揣鍗曟槑缁嗭紒");
+
+                  var mesItems = db.Queryable<MesItems>()
+                      .Where(s => s.Id == itemBarcodeDetails.ItemId).First();
+
+                  //result.Message =
+                  //    $"鏉$爜鏁伴噺 {itemBarcodeDetails.Quantity},閲囪喘璁㈠崟 {itemBarcodeDetails.WorkNo} 椤规 {itemBarcodeDetails.WorkLine} 鐗╂枡 {mesItems.ItemNo} 鏈鍏ュ簱鎬绘暟锛歿totalCDetailsQuantity} 鎬诲埌 {comeQty} 宸插叆 {invQty} 娆� {diffQty}";
+                  result.Message = $"鐗╂枡{mesItems.ItemNo}鍏ュ簱鎴愬姛鏁伴噺{itemBarcodeDetails.Quantity.ToString()}";
+
+                  result.itemDetail = mesItems;
+
+                  result.ItemInDetails = db.Queryable<MesInvItemInCItems,MesItems>(
+                      (a, b) => new JoinQueryInfos(
+                      JoinType.Left,
+                      a.ItemId == b.ItemId)
+                      )
+                      .Where(a => a.ItemInId == cId && a.ItemId == itemBarcodeDetails.ItemId)
+                      .Select<dynamic>((a, b) => new 
+                      {
+                          ItemNo = b.ItemNo,
+                          ItemName = b.ItemName,
+                          ItemModel = b.ItemModel,
+                          FQty = a.Quantity, // 鐢宠鏁伴噺
+                          FMaterialId = b.ItemId,
+                          Id = b.Guid.ToString()
+                      })
+                      .ToList();
+
+                  result.ItemBarCDetails = db.Queryable<MesInvItemInCDetails, MesItems>(
+                      (a, b) => new JoinQueryInfos(
+                      JoinType.Left,
+                      a.ItemId == b.ItemId)
+                      )
+                      .Where(a => a.ItemInId == cId && a.ItemId == itemBarcodeDetails.ItemId)
+                      .Select<dynamic>((a, b) => new
+                      {
+                          ItemNo = b.ItemNo,
+                          ItemName = b.ItemName,
+                          ItemModel = b.ItemModel,
+                          FQty = a.Quantity, // 鐢宠鏁伴噺
+                          FMaterialId = b.ItemId,
+                          Id = a.Guid.ToString(),
+                          kw = a.DepotSectionCode,
+                          barcode = a.ItemBarcode
+                      })
+                      .ToList();
+
+
+                  //result.ItemNo = mesItems.ItemNo;
+                  result.SumQuantity = Convert.ToDecimal(invQty);
+
+                  return 1;
+              }
+              else
+              {
+                  // Step 1: Check if bill needs to be closed (status update)
+                  var totalSummary = db.Queryable<MesInvItemArnDetail>()
+                      .LeftJoin<MesInvItemArn>((b, a) => a.Guid == b.ParentGuid)
+                      .Where((b, a) =>
+                          a.BillNo == inventory.BillNo && b.ReturnFlag == 0)
+                      .Select((b, a) => new
+                      {
+                          TotalQuantity = SqlFunc.AggregateSum(b.Quantity),
+                          TotalOkRkQty = SqlFunc.AggregateSum(b.OkRkqty)
+                      })
+                      .First();
+
+                  if ((totalSummary.TotalQuantity ?? 0) ==
+                      (totalSummary.TotalOkRkQty ?? 0))
+                      db.Updateable<MesInvItemArn>()
+                          .SetColumns(it => it.Status == 1)
+                          .Where(it => it.BillNo == itemBarcodeDetails.BillNo)
+                          .ExecuteCommand();
+
+                  // Step 2: Calculate total sum from `mes_inv_item_in_c_details`
+                  var totalCDetailsQuantity = db.Queryable<MesInvItemInCDetails>()
+                      .Where(it => it.Guid == itemBarcodeDetails.AboutGuid)
+                      .Sum(it => it.Quantity);
+
+                  // Step 3: Calculate comeQty and invQty from `mes_inv_item_arn_detail`
+                  var detailSummary = db.Queryable<MesInvItemArnDetail>()
+                      .Where(it => it.Guid == itemBarcodeDetails.AboutGuid)
+                      .Select(it => new
+                      {
+                          TotalComeQty = SqlFunc.AggregateSum(it.Quantity),
+                          TotalInvQty = SqlFunc.AggregateSum(it.OkRkqty)
+                      })
+                      .First();
+
+                  if (detailSummary == null)
+                      throw new Exception("姝ゆ潯鐮佹壘涓嶅埌瀵瑰簲鏀惰揣鍗曟槑缁嗭紒");
+
+                  var comeQty = detailSummary.TotalComeQty ?? 0;
+                  var invQty = detailSummary.TotalInvQty ?? 0;
+                  var diffQty = comeQty - invQty;
+
+                  var mesItems = db.Queryable<MesItems>()
+                      .Where(s => s.Id == itemBarcodeDetails.ItemId).First();
+
+                  // Step 5: Combine final result
+                  result.Message =
+                      $" 鏉$爜鏁伴噺:{itemBarcodeDetails.Quantity},鐗╂枡 {mesItems.ItemNo} 鏈鍏ュ簱鎬绘暟锛歿totalCDetailsQuantity} 鎬诲埌 {comeQty} 宸插叆 {invQty} 娆� {diffQty}";
+
+
+                  //result.ItemNo = mesItems.ItemNo;
+                  result.SumQuantity = Convert.ToDecimal(totalCDetailsQuantity);
+              }
+
+              var mesInvItemInCDetails =
+                  base.GetSingle(it => it.ItemBarcode == entity.barcode);
+
+              if (mesInvItemInCDetails == null)
+                  throw new Exception("鐗╂枡鍏ュ簱鏉$爜鏄庣粏涓嶅瓨鍦�"); // 鎶涘嚭寮傚父浠ヤ緵鍓嶅彴澶勭悊
+
+              // 鍒涘缓 鎻掑叆鏃ュ織
+              var logService = new LogService();
+              var LogMsg = "銆怭DA銆戦噰璐叆搴撱�傛潯鐮併��" + entity.barcode + "銆� 鍏ュ簱鍗曞彿銆�" + cBillNo + "銆�";
+              logService.CreateLog(db, entity.userName, inventory.Guid.ToString(), "MES_INV_ITEM_ARN", LogMsg, inventory.BillNo);
+
+              return 1;
+          });
+
+          var purchaseInventory = getPurchaseInventory(entity);
+
+
+          //result.ItemInDetails = purchaseInventory.ItemInDetails;
+          //result.InvItemInCDetails = purchaseInventory.InvItemInCDetails;
+
+          return result;
+      }
+  */
     public ItemInBaseModel getPurchaseInventory(WarehouseQuery query)
     {
         return new ItemInBaseModel
@@ -950,6 +1026,126 @@
             //ItemIns = GetInvItemInsList(query).Items[0],
             //ItemInDetails = GetItemInDetails(query.id),
             //InvItemInCDetails = GetInvItemInCDetails(query.id)
+        };
+    }
+
+    public dynamic WcsmBar(WarehouseQuery entity)
+    {
+        if (entity == null) throw new ArgumentNullException(nameof(entity), "鍙傛暟瀵硅薄涓嶈兘涓� null");
+
+        // 鍙傛暟鏍¢獙
+        if (string.IsNullOrEmpty(entity.userName?.ToString()))
+            throw new ArgumentException("鎿嶄綔浜哄憳涓嶅厑璁镐负绌�", nameof(entity.userName));
+
+        if (string.IsNullOrEmpty(entity.barcode?.ToString()))
+            throw new ArgumentException("鏉$爜涓嶅厑璁镐负绌�", nameof(entity.barcode));
+
+        var _strMsg = "";
+        var _status = -1;
+        using (var conn = new SqlConnection(DbHelperSQL.strConn))
+        {
+            using (var cmd = new SqlCommand("prc_pda_wcsm", conn))
+            {
+                try
+                {
+                    conn.Open();
+                    cmd.CommandType = CommandType.StoredProcedure;
+                    // 鏍规嵁瀛樺偍杩囩▼璁剧疆鍙傛暟
+                    SqlParameter[] parameters = 
+                    {
+                        new SqlParameter("@pi_user", SqlDbType.NVarChar, 100) { Value = entity.userName },
+                        new SqlParameter("@pi_barcode", SqlDbType.NVarChar, 100) { Value = entity.barcode },
+                        new SqlParameter("@pi_sectionCode", SqlDbType.NVarChar, 100) { Value = entity.sectionCode == null ? DBNull.Value : (object)entity.sectionCode },
+                        new SqlParameter("@pi_IN1", SqlDbType.NVarChar, 30) { Value = DBNull.Value }, // 澶囩敤瀛楁1
+                        new SqlParameter("@pi_IN2", SqlDbType.NVarChar, 30) { Value = DBNull.Value }, // 澶囩敤瀛楁2
+                        new SqlParameter("@po_outMsg", SqlDbType.NVarChar, 2000) { Direction = ParameterDirection.Output },
+                        new SqlParameter("@po_outSum", SqlDbType.Int) { Direction = ParameterDirection.Output }
+                    };
+
+                    foreach (var parameter in parameters)
+                        cmd.Parameters.Add(parameter);
+
+                    cmd.ExecuteNonQuery();
+
+                    _strMsg = parameters[5].Value?.ToString() ?? "";
+                    _status = Convert.ToInt32(parameters[6].Value ?? -1);
+
+                    if (_status <= 0) throw new Exception(_strMsg);
+
+                    return new
+                    {
+                        message = _strMsg,
+                        status = _status,
+                        userName = entity.userName,
+                        barcode = entity.barcode,
+                        sectionCode = entity.sectionCode
+                    };
+                }
+                catch (Exception ex)
+                {
+                    throw new Exception($"澶栦粨鎵爜鍏ュ簱澶辫触锛歿ex.Message}");
+                }
+                finally
+                {
+                    conn.Close();
+                }
+            }
+        }
+    }
+
+    public dynamic WcsmDetail(WarehouseQuery entity)
+    {
+        if (entity == null) throw new ArgumentNullException(nameof(entity), "鍙傛暟瀵硅薄涓嶈兘涓� null");
+
+        // 鍙傛暟鏍¢獙
+        if (string.IsNullOrEmpty(entity.barcode?.ToString()))
+            throw new ArgumentException("鏉$爜涓嶅厑璁镐负绌�", nameof(entity.barcode));
+
+        // 浣跨敤ADO.NET鐩存帴璋冪敤瀛樺偍杩囩▼
+        var ds = new DataSet();
+
+        // 鍋囪鎮ㄤ娇鐢ㄧ殑鏄疭QL Server锛屽垱寤篠qlConnection
+        using (var conn = new SqlConnection(DbHelperSQL.strConn))
+        {
+            conn.Open();
+
+            using (var cmd = new SqlCommand("prc_pda_wcsm_detailList", conn))
+            {
+                cmd.CommandType = CommandType.StoredProcedure;
+
+                // 娣诲姞鍙傛暟
+                cmd.Parameters.Add(new SqlParameter("@daa001", entity.barcode));
+                cmd.Parameters.Add(new SqlParameter("@pi_orgId", DBNull.Value));
+                cmd.Parameters.Add(new SqlParameter("@inP1", DBNull.Value));
+                cmd.Parameters.Add(new SqlParameter("@inP2", DBNull.Value));
+                cmd.Parameters.Add(new SqlParameter("@inP3", DBNull.Value));
+                cmd.Parameters.Add(new SqlParameter("@inP4", DBNull.Value));
+
+                using (var adapter = new System.Data.SqlClient.SqlDataAdapter(cmd))
+                {
+                    adapter.Fill(ds);
+                }
+            }
+        }
+
+        // 楠岃瘉缁撴灉闆嗘暟閲�
+        if (ds.Tables.Count < 4)
+        {
+            throw new ApplicationException($"瀛樺偍杩囩▼杩斿洖鐨勭粨鏋滈泦鏁伴噺涓嶈冻锛屾湡鏈�4涓紝瀹為檯{ds.Tables.Count}涓�");
+        }
+
+        // 杞崲缁撴灉锛堢粺涓�浣跨敤ds锛�
+        var unscannedList = Db.Utilities.DataTableToDynamic(ds.Tables[0]);
+        var otherUnscannedList = Db.Utilities.DataTableToDynamic(ds.Tables[1]);
+        var scanProgressList = Db.Utilities.DataTableToDynamic(ds.Tables[2]);
+        var daaInfo = Db.Utilities.DataTableToDynamic(ds.Tables[3]);
+        
+        return new
+        {
+            unscannedList,
+            otherUnscannedList,
+            scanProgressList,
+            daaInfo
         };
     }
 
@@ -1204,4 +1400,298 @@
 
         return encodedUrl;
     }
+
+    // 楠岄��鎵爜
+    public ItemInBaseModel GetReturnBarcodeInfo(WarehouseQuery entity)
+    {
+        ItemInBaseModel res = new ItemInBaseModel();
+
+        // 鍙傛暟楠岃瘉
+        if (string.IsNullOrEmpty(entity.userName)) throw new ArgumentNullException(nameof(entity.userName), "鐢ㄦ埛鍚嶄笉鍏佽涓虹┖");
+        if (string.IsNullOrEmpty(entity.sectionCode)) throw new ArgumentNullException(nameof(entity.sectionCode), "搴撲綅缂栧彿涓嶅厑璁镐负绌�");
+        if (string.IsNullOrEmpty(entity.returnBarcode)) throw new ArgumentNullException(nameof(entity.returnBarcode), "鏉$爜涓嶅厑璁镐负绌�");
+
+        //try
+        //{
+            // 妫�鏌ユ潯鐮佹槸鍚﹀凡鍏ュ簱
+            var isInStock = Db.Queryable<MesInvItemInCDetails>()
+                .Where(it => it.ItemBarcode == entity.returnBarcode)
+                .Any();
+
+            if (isInStock)
+                throw new Exception($"璇ユ潯鐮佺墿鏂橻{entity.returnBarcode}]宸插叆搴擄紝涓嶈兘鍐嶆鎵弿锛�");
+
+            // 妫�鏌ユ潯鐮佹槸鍚﹀凡鎵弿楠岄��
+            var sqlParams = new List<SugarParameter> { new("@barcode", entity.returnBarcode) };
+            var isReturnScanned = Db.Ado.SqlQuery<dynamic>(
+                "SELECT 1 FROM MES_INV_ITEM_CGYT_C_DETAILS WHERE ITEM_BARCODE = @barcode",
+                sqlParams);
+
+
+            if (isReturnScanned.Count > 0)
+                throw new Exception($"璇ユ潯鐮佺墿鏂橻{entity.returnBarcode}]宸叉壂鎻忛獙閫�锛岃鏍稿锛�");
+            // 浣跨敤鍙傛暟鍖栨煡璇㈠苟蹇界暐澶у皬鍐欙紙閫傜敤浜庢敮鎸佺殑鏁版嵁搴擄級
+            var itemBarcode = Db.Queryable<MesInvItemBarcodes>()
+                .Where(it => it.ItemBarcode.Trim().ToLower() == entity.returnBarcode.Trim().ToLower())
+                .First() ?? throw new InvalidOperationException($"鏈壘鍒版潯鐮� '{entity.returnBarcode}' 鐨勫尮閰嶄俊鎭�");
+
+            // 鑾峰彇鍒拌揣鏄庣粏ID锛堝亣璁句粠鏉$爜淇℃伅涓彲浠ヨ幏鍙栧埌dhmxGuid锛�
+            var dhmxGuid = itemBarcode.AboutGuid; 
+
+            // 鏌ヨ妫�楠屼俊鎭紙瀵瑰簲SQL涓殑瑙嗗浘鏌ヨ閫昏緫锛�
+            var checkParams = new List<SugarParameter>
+        {
+            new("@dHdMx", dhmxGuid),
+            new("@JYZT", null, true),  // 杈撳嚭鍙傛暟锛氭楠岀姸鎬�
+            new("@JYJG", null, true),  // 杈撳嚭鍙傛暟锛氭楠岀粨鏋�
+            new("@PDJG", null, true),  // 杈撳嚭鍙傛暟锛氬垽瀹氱粨鏋�
+            new("@ISRK", null, true),  // 杈撳嚭鍙傛暟锛氭槸鍚﹁兘鍏ュ簱
+            new("@CLYS", null, true)   // 杈撳嚭鍙傛暟锛氬鐞嗘剰瑙�
+        };
+
+            // 鎵ц鏌ヨ鑾峰彇妫�楠屼俊鎭�
+            Db.Ado.ExecuteCommand(@"
+            SELECT @JYZT = ISNULL(妫�楠岀姸鎬�, '鏈煡'),
+                   @JYJG = ISNULL(妫�楠岀粨鏋�, '鏈煡'),
+                   @PDJG = ISNULL(鍒ゅ畾缁撴灉, '鏈煡'),
+                   @ISRK = ISNULL(鏄惁鑳藉叆搴�, 0),
+                   @CLYS = ISNULL(澶勭悊鎰忚, '鏃�')
+            FROM v_dhmx
+            WHERE dhmxGuid = @dHdMx", checkParams);
+
+            // 瑙f瀽杈撳嚭鍙傛暟
+            var jyzt = checkParams[1].Value?.ToString() ?? "鏈煡";
+            var jyjg = checkParams[2].Value?.ToString() ?? "鏈煡";
+            var pdjg = checkParams[3].Value?.ToString() ?? "鏈煡";
+            var isRk = checkParams[4].Value != DBNull.Value ? Convert.ToInt32(checkParams[4].Value) : 0;
+            var clys = checkParams[5].Value?.ToString() ?? "鏃�";
+
+            // 妫�鏌ユ槸鍚︽煡璇㈠埌妫�楠岃褰�
+            if (string.IsNullOrEmpty(jyzt) && string.IsNullOrEmpty(jyjg))
+                throw new Exception($"鏈壘鍒板埌璐ф槑缁唅d涓篬{dhmxGuid}]鐨勬楠岃褰�");
+            // 妫�鏌ユ槸鍚﹀厑璁搁獙閫�锛堝紓甯哥洿鎺ユ姏鍑猴級
+            if (isRk != 1)
+                throw new Exception($"璇ユ潯鐮佸搴旂殑鏀舵枡鍗曟楠岀粨鏋�:[{jyjg}]锛屽垽瀹氱粨鏋�:[{pdjg}]锛屽鐞嗘剰瑙�:[{clys}]锛屼笉鑳借繘琛岄獙閫�鎿嶄綔");
+
+
+
+
+            // 灏嗘煡璇㈠埌鐨勬潯鐮佷俊鎭祴鍊肩粰杩斿洖妯″瀷
+            res.itemBarcodeDetails = itemBarcode;
+            res.Message = "鏌ヨ鎴愬姛";
+            return res;
+        //}
+        //catch (Exception ex)
+        //{
+        //    // 璁板綍寮傚父鏃ュ織锛堝缓璁ˉ鍏呭叿浣撴棩蹇楄褰曚唬鐮侊級
+        //    res.Message = $"鎿嶄綔澶辫触: {ex.Message}";
+        //    res.SumQuantity = -1;
+        //    return res;
+        //}
+    }
+
+    // 楠岄��
+    public ItemInBaseModel ConfirmReturn(WarehouseQuery entity)
+    {
+        ItemInBaseModel res = new ItemInBaseModel();
+
+        // 鍙傛暟楠岃瘉
+        if (string.IsNullOrEmpty(entity.userName)) throw new ArgumentNullException(nameof(entity.userName), "鐢ㄦ埛鍚嶄笉鍏佽涓虹┖");
+        if (string.IsNullOrEmpty(entity.sectionCode)) throw new ArgumentNullException(nameof(entity.sectionCode), "搴撲綅缂栧彿涓嶅厑璁镐负绌�");
+        if (string.IsNullOrEmpty(entity.returnBarcode)) throw new ArgumentNullException(nameof(entity.returnBarcode), "鏉$爜涓嶅厑璁镐负绌�");
+        if (entity.returnQuantity <= 0) throw new ArgumentException("楠岄��鏁伴噺蹇呴』澶т簬0", nameof(entity.returnQuantity));
+
+        //try
+        //{
+            // 妫�鏌ユ潯鐮佹槸鍚﹀凡鍏ュ簱
+            var isInStock = Db.Queryable<MesInvItemInCDetails>()
+                .Where(it => it.ItemBarcode == entity.returnBarcode)
+                .Any();
+
+            if (isInStock)
+                throw new Exception($"璇ユ潯鐮佺墿鏂橻{entity.returnBarcode}]宸插叆搴擄紝涓嶈兘鍐嶆鎵弿锛�");
+
+            // 妫�鏌ユ潯鐮佹槸鍚﹀凡鎵弿楠岄��
+            var sqlParams = new List<SugarParameter> { new("@barcode", entity.returnBarcode) };
+            var isReturnScanned = Db.Ado.SqlQuery<dynamic>(
+                "SELECT 1 FROM MES_INV_ITEM_CGYT_C_DETAILS WHERE ITEM_BARCODE = @barcode",
+                sqlParams);
+
+            // 浣跨敤鍙傛暟鍖栨煡璇㈠苟蹇界暐澶у皬鍐欙紙閫傜敤浜庢敮鎸佺殑鏁版嵁搴擄級
+            var itemBarcode = Db.Queryable<MesInvItemBarcodes>()
+                .Where(it => it.ItemBarcode.Trim().ToLower() == entity.returnBarcode.Trim().ToLower())
+                .First() ?? throw new InvalidOperationException($"鏈壘鍒版潯鐮� '{entity.returnBarcode}' 鐨勫尮閰嶄俊鎭�");
+
+            // 鍒ゆ柇楠岄��鏁伴噺鏄惁澶т簬鏉$爜鐨勬暟閲忥紙鍋囪鏉$爜鏁伴噺瀛楁涓篞uantity锛�
+            if (entity.returnQuantity > itemBarcode.Quantity)
+            {
+                throw new ArgumentException($"楠岄��鏁伴噺涓嶈兘澶т簬鏉$爜鐨勬暟閲忥紝褰撳墠鏉$爜鏁伴噺涓�: {itemBarcode.Quantity}", nameof(entity.returnQuantity));
+            }
+            // 灏嗘煡璇㈠埌鐨勬潯鐮佷俊鎭祴鍊肩粰杩斿洖妯″瀷
+            res.itemBarcodeDetails = itemBarcode;
+
+            // 璋冪敤瀛樺偍杩囩▼ prc_pda_bar_cf_before
+            string strMsg = "";
+            string intSum = "";
+            string cfBar = "";
+
+            using (var conn = new SqlConnection(DB.DbHelperSQL.strConn))
+            {
+                using (var cmd = new SqlCommand("[prc_pda_bar_cf_before]", conn))
+                {
+                    conn.Open();
+                    cmd.CommandType = CommandType.StoredProcedure;
+                    SqlParameter[] parameters =
+                    {
+                        new("@outMsg", SqlDbType.NVarChar, 300),
+                        new("@outSum", SqlDbType.NVarChar, 300),
+                        new("@barcode_new", SqlDbType.NVarChar, 300),
+                        new("@c_user", entity.userName),
+                        new("@p_old_barcode", entity.returnBarcode),
+                        new("@p_qty", entity.returnQuantity),
+                    };
+                    parameters[0].Direction = ParameterDirection.Output;
+                    parameters[1].Direction = ParameterDirection.Output;
+                    parameters[2].Direction = ParameterDirection.Output;
+
+                    foreach (var parameter in parameters)
+                        cmd.Parameters.Add(parameter);
+                    cmd.ExecuteNonQuery();
+                    strMsg = parameters[0].Value.ToString();
+                    intSum = parameters[1].Value.ToString();
+                    cfBar = parameters[2].Value.ToString();
+
+                    var result = Convert.ToInt32(intSum);
+                    if (result <= 0) throw new Exception(strMsg);
+                }
+            }
+
+            // 璋冪敤楠岄��瀛樺偍杩囩▼ prc_pda_scan_CGYT锛屼娇鐢ㄦ媶鍒嗗悗鐨勬柊鏉$爜
+            string ytMsg = "";
+            string ytSum = "";
+            string ytdh = "";
+
+            using (var conn = new SqlConnection(DB.DbHelperSQL.strConn))
+            {
+                using (var cmd = new SqlCommand("prc_pda_scan_CGYT", conn))
+                {
+                    conn.Open();
+                    cmd.CommandType = CommandType.StoredProcedure;
+                    SqlParameter[] ytParameters =
+                    {
+                        new("@pi_user", SqlDbType.NVarChar, 100) { Value = entity.userName },
+                        new("@pi_barcode", SqlDbType.NVarChar, 100) { Value = cfBar }, // 浣跨敤鎷嗗垎鍚庣殑鏂版潯鐮�
+                        new("@po_outMsg", SqlDbType.NVarChar, 2000) { Direction = ParameterDirection.Output },
+                        new("@po_outSum", SqlDbType.Int) { Direction = ParameterDirection.Output },
+                        new("@po_ygdh", SqlDbType.NVarChar, 200) { Direction = ParameterDirection.Output }
+                    };
+
+                    cmd.Parameters.AddRange(ytParameters);
+                    cmd.ExecuteNonQuery();
+
+                    ytMsg = ytParameters[2].Value.ToString();
+                    ytSum = ytParameters[3].Value.ToString();
+                    ytdh = ytParameters[4].Value.ToString();
+
+                    if (ytSum == "-1") throw new Exception(ytMsg);
+                }
+            }
+
+            // 璋冪敤鍏ュ簱瀛樺偍杩囩▼ prc_pda_inv_cgrk锛屼娇鐢ㄥ師濮嬫潯鐮�
+            string rkMsg = "";
+            string rkSum = "";
+
+            using (var conn = new SqlConnection(DB.DbHelperSQL.strConn))
+            {
+                using (var cmd = new SqlCommand("prc_pda_inv_cgrk", conn))
+                {
+                    conn.Open();
+                    cmd.CommandType = CommandType.StoredProcedure;
+                    SqlParameter[] rkParameters =
+                    {
+                        new("@pi_user", SqlDbType.NVarChar, 100) { Value = entity.userName },
+                        new("@pi_barcode", SqlDbType.NVarChar, 100) { Value = entity.returnBarcode }, // 浣跨敤鍘熷鏉$爜
+                        new("@pi_sectionCode", SqlDbType.NVarChar, 100) { Value = entity.sectionCode },
+                        new("@pi_remark", SqlDbType.NVarChar, 30) { Value = entity.remark },
+                        new("@pi_cgrkType", SqlDbType.NVarChar, 30) { Value = "姝e父鍏ュ簱" },
+                        new("@pi_weight", SqlDbType.Decimal) { Value = entity.weight },
+                        new("@po_outMsg", SqlDbType.NVarChar, 2000) { Direction = ParameterDirection.Output },
+                        new("@po_outSum", SqlDbType.Int) { Direction = ParameterDirection.Output }
+                    };
+
+                    cmd.Parameters.AddRange(rkParameters);
+                    cmd.ExecuteNonQuery();
+
+                    rkMsg = rkParameters[5].Value.ToString();
+                    rkSum = rkParameters[6].Value.ToString();
+
+                    if (rkSum == "-1") throw new Exception(rkMsg);
+                }
+            }
+
+
+
+            // 浼樺寲鏌ヨ锛堝幓闄ょ┖鏍煎苟蹇界暐澶у皬鍐欙級
+            var mesInvItemInCDetails = Db.Queryable<MesInvItemInCDetails>()
+                .Where(it => it.ItemBarcode.Trim().ToLower() == entity.returnBarcode.Trim().ToLower())
+                .First() ?? throw new InvalidOperationException($"鏈壘鍒版潯鐮� '{entity.returnBarcode}' 鐨勫尮閰嶇殑鍏ュ簱淇℃伅");
+
+            // 浠庡叆搴撴潯鐮佷腑鑾峰彇鏈夋晥鐨処temInId
+            var cId = mesInvItemInCDetails.ItemInId; // 鍋囪瀛樺湪ItemInId灞炴��
+
+            // 鏌ヨ鐗╂枡姹囨�绘槑缁嗭紙浣跨敤鍙傛暟鍖栨煡璇㈤槻姝QL娉ㄥ叆锛�
+            var sql = @"
+            SELECT 
+                b.Item_No AS ItemNo,
+                b.Item_Name AS ItemName,
+                b.Item_Model AS ItemModel,
+                a.Quantity AS FQty,
+                b.Item_Id AS FMaterialId,
+                CONVERT(VARCHAR(36), b.Guid) AS Id
+            FROM MES_INV_ITEM_IN_C_ITEMS a
+            LEFT JOIN Mes_Items b ON a.Item_Id = b.Item_Id
+            WHERE a.Item_In_Id = @cId AND a.Item_Id = @itemId";
+
+            res.ItemInDetails = Db.Ado.SqlQuery<dynamic>(sql, new { cId, itemId = itemBarcode.ItemId });
+
+            // 鏌ヨ鍏ュ簱鏉$爜鏄庣粏锛堜娇鐢ㄥ弬鏁板寲鏌ヨ闃叉SQL娉ㄥ叆锛�
+            var sql2 = @"
+            SELECT 
+                b.Item_No AS ItemNo,
+                b.Item_Name AS ItemName,
+                b.Item_Model AS ItemModel,
+                a.Quantity AS FQty,
+                b.Item_Id AS FMaterialId,
+                CONVERT(VARCHAR(36), a.Guid) AS Id,
+                a.Depot_Section_Code AS kw,
+                a.Item_Barcode AS barcode
+            FROM Mes_Inv_Item_In_C_Details a
+            LEFT JOIN Mes_Items b ON a.Item_Id = b.Item_Id
+            WHERE a.Item_In_Id = @cId AND a.Item_Id = @itemId";
+
+            res.ItemBarCDetails = Db.Ado.SqlQuery<dynamic>(sql2, new { cId, itemId = itemBarcode.ItemId });
+
+
+            //鏌ヨ宸插叆搴撴�绘暟
+            var totalCDetailsQuantity = Db.Queryable<MesInvItemInCDetails>()
+            .Where(it => it.ItemInId == cId)
+            .Sum(it => it.Quantity);
+
+            res.SumQuantity = Convert.ToDecimal(totalCDetailsQuantity);
+
+
+            res.Message = $"楠岄��鎿嶄綔鎴愬姛锛屾媶鍒嗗悗鏉$爜锛歿cfBar}锛岄獙閫�鍗曞彿锛歿ytdh}";
+            // res.SumQuantity = res.ItemBarCDetails?.Count ?? 0;
+            res.SumQuantity = Convert.ToDecimal(totalCDetailsQuantity);
+            return res;
+        //}
+        //catch (Exception ex)
+        //{
+        //    // 璁板綍寮傚父鏃ュ織锛堝缓璁ˉ鍏呭叿浣撴棩蹇楄褰曚唬鐮侊級
+        //    res.Message = $"鎿嶄綔澶辫触: {ex.Message}";
+        //    res.SumQuantity = -1;
+        //    return res;
+        //}
+    }
+
 }
\ No newline at end of file

--
Gitblit v1.9.3