From cad9f911a2f0c7a14d62f1503aadd279423caccc Mon Sep 17 00:00:00 2001
From: zjh <2207896513@qq.com>
Date: 星期二, 22 七月 2025 16:40:32 +0800
Subject: [PATCH] 退料单接口BUG修复

---
 StandardPda/MES.Service/service/Warehouse/MesInvItemOutsManager.cs | 1244 +++++++++++++++-------------------------------------------
 1 files changed, 323 insertions(+), 921 deletions(-)

diff --git a/StandardPda/MES.Service/service/Warehouse/MesInvItemOutsManager.cs b/StandardPda/MES.Service/service/Warehouse/MesInvItemOutsManager.cs
index 95cc7b2..6c5d183 100644
--- a/StandardPda/MES.Service/service/Warehouse/MesInvItemOutsManager.cs
+++ b/StandardPda/MES.Service/service/Warehouse/MesInvItemOutsManager.cs
@@ -1,973 +1,375 @@
-锘縰sing System.Data;
-using MES.Service.DB;
+锘縰sing MES.Service.DB;
 using MES.Service.Dto.service;
 using MES.Service.Modes;
-using MES.Service.util;
-using Newtonsoft.Json;
-using SqlSugar;
-using DbType = System.Data.DbType;
 
 namespace MES.Service.service.Warehouse;
 
 public class MesInvItemOutsManager : Repository<MesInvItemOuts>
 {
-    //褰撳墠绫诲凡缁忕户鎵夸簡 Repository 澧炪�佸垹銆佹煡銆佹敼鐨勬柟娉�
-    //杩欓噷闈㈠啓鐨勪唬鐮佷笉浼氱粰瑕嗙洊,濡傛灉瑕侀噸鏂扮敓鎴愯鍒犻櫎 MesInvItemOutsManager.cs
+    private readonly int BILL_TYPE_ID = 200;
+    private readonly int TRANSACTION_NO = 203;
 
-    public List<MesInvItemOuts> GetProductionPickPage(WarehouseQuery query)
+    public bool ReturnRequest(ItemOut oItemOut)
     {
-        return Db.Queryable<MesInvItemOuts, MesDepots>((a, o) =>
-                new JoinQueryInfos(
-                    JoinType.Left,
-                    o.DepotCode == a.DepotCode && a.Company == o.Company &&
-                    a.Factory == o.Factory
-                ))
-            .Where((a, o) => a.BillTypeId == 200 &&
-                             a.TransactionNo == 201 &&
-                             a.Factory == "1000" &&
-                             a.Company == "1000" &&
-                             a.IsVisual == 1)
-            .WhereIF(query.status != null, (a, o) => a.Status == query.status)
-            .WhereIF(query.id != null, (a, o) => a.Id == query.id)
-            .Select((a, o) => new MesInvItemOuts
-            {
-                Id = a.Id,
-                Sapstatus = a.Sapstatus,
-                OutDate = a.OutDate,
-                CheckDate = a.CheckDate,
-                BoardItem = a.BoardItem,
-                WorkNo = a.WorkNo,
-                OutPart = a.OutPart,
-                PbillNo = a.PbillNo,
-                OutType = a.OutType,
-                CreateBy = a.CreateBy,
-                Status = a.Status,
-                CheckUser = a.CheckUser,
-                ItemOutNo = a.ItemOutNo,
-                DepotName = o.DepotName // 闇�瑕佸姩鎬佹坊鍔犵殑瀛楁
-            })
-            .ToPageList(query.PageIndex, query.Limit);
-    }
+        var itemOutFrom = oItemOut.from;
+        var itemOutLists = oItemOut.items;
 
-    public MaterialReceipt GetProductionPick(WarehouseQuery query)
-    {
-        var form = new MaterialReceipt();
-        if (query.id != null)
+        return UseTransaction(db =>
         {
-            var mesInvItemOutsList = GetProductionPickPage(query);
-            if (mesInvItemOutsList.Count <= 0) return form;
+            // 鏍规嵁AsnNo鍜孧esNo瀵规槑缁嗚繘琛屽垎缁�
+            var groupedItems = itemOutLists
+                .GroupBy(item => new {  item.MesNo, item.SqNo })
+                .ToList();
 
-            form.ItemOuts = mesInvItemOutsList[0];
-            form.ItemsList = getProductionItemsList(query);
-            form.InvItemoutCDetails = GetProductionDetails(query);
-        }
-
-        return form;
-    }
-
-    private List<MesInvItemOutItems> getProductionItemsList(
-        WarehouseQuery query)
-    {
-        return Db.Queryable<MesInvItemOutItems, MesItems, MesDepTaskInfo>(
-                (c, s, f) => new JoinQueryInfos(
-                    JoinType.Inner, c.ItemNo == s.ItemNo,
-                    JoinType.Left, f.TaskNo == c.TaskNo && f.ItemNo == c.ItemNo
-                ))
-            .Where((c, s, f) => c.ItemOutId == query.id)
-            .OrderBy(c => c.Id)
-            .Select((c, s, f) => new MesInvItemOutItems
+            int result = 1;
+            int count = 1;
+            foreach (var group in groupedItems)
             {
-                Id = c.Id,
-                ItemNo = c.ItemNo,
-                Quantity = c.Quantity,
-                TaskNo = c.TaskNo,
-                Remark = c.Remark,
-                ItemName = s.ItemName, // 鍔ㄦ�佸瓧娈�
-                ItemModel = s.ItemModel, // 鍔ㄦ�佸瓧娈�
-                ItemUnit = SqlFunc.Subqueryable<MesItems>()
-                    .Where(si => si.ItemUnit == s.ItemUnit)
-                    .Select(si =>
-                        SqlFunc.MappingColumn<string>(
-                            "F_GETUNITNAME(si.Item_Unit)")) // 鍔ㄦ�佸瓧娈�
-            })
-            .ToList();
-    }
+                //if (group.Key.AsnNo == null)
+                //{
+                //    throw new NotImplementedException("AsnNo涓嶈兘涓虹┖");
+                //}
 
-    private List<MesInvItemOutCDetails> GetProductionDetails(
-        WarehouseQuery query)
-    {
-        return Db
-            .Queryable<MesInvItemOutCDetails, MesItems, MesDepots>(
-                (b, c, d) => new JoinQueryInfos(
-                    JoinType.Left,
-                    b.ItemNo == c.ItemNo && b.Company == c.Company &&
-                    b.Factory == c.Factory,
-                    JoinType.Left,
-                    d.DepotCode == b.DepotCode && b.Company == d.Company &&
-                    b.Factory == d.Factory
-                ))
-            .Where((b, c, d) => b.ItemOutId == query.id)
-            .Select((b, c, d) => new MesInvItemOutCDetails
-            {
-                ForceOutFlag = b.ForceOutFlag,
-                DepotSectionCode = b.DepotSectionCode,
-                ItemNo = b.ItemNo,
-                Quantity = b.Quantity,
-                ItemBarcode = b.ItemBarcode,
-                ItemName = c.ItemName,
-                ItemModel = c.ItemModel,
-                DepotName = d.DepotName,
-                DepotCode = b.DepotCode
-            })
-            .ToList();
-    }
-
-    public bool ScanCode(WarehouseQuery query)
-    {
-        decimal billTypeId = 200;
-        decimal transactionNo = 203;
-
-        var count = Db.Queryable<MesInvItemOutCDetails>()
-            .Where(a =>
-                a.ItemBarcode == query.barcode && a.TaskNo == query.billNo)
-            .Count();
-
-        if (count > 0) throw new Exception("鏉$爜閲嶅鎵弿锛岃鏍稿锛�");
-
-        //楠岃瘉鏉$爜
-        var mesInvItemStocks = Db.Queryable<MesInvItemStocks>()
-            .Where(a => a.ItemBarcode == query.barcode
-                        && a.Quantity > 0).Single();
-
-        if (mesInvItemStocks == null)
-            throw new Exception(query.barcode + "搴撳瓨涓棤姝ゆ潯鐮侊紝璇锋牳瀵癸紒");
-
-        //楠岃瘉鍑哄簱鍗昺es_inv_item_outs
-        var mesInvItemOuts = Db.Queryable<MesInvItemOuts>()
-            .Where(d => d.ItemOutNo == query.billNo
-                        && d.BillTypeId == billTypeId &&
-                        d.TransactionNo == transactionNo).Single();
-
-        //鍑哄簱鍗曠殑鏍¢獙
-        if (mesInvItemOuts == null)
-            throw new Exception("鍑哄簱鍗�  " + query.billNo + " 涓嶅瓨鍦紝璇风‘璁わ紒");
-
-        //鏈鏍哥殑涓嶅厑璁哥户缁�
-        if (mesInvItemOuts.Status == null || mesInvItemOuts.Status == 0)
-            throw new Exception("鍑哄簱鍗�  " + query.billNo + "鏈鏍�");
-
-        //宸叉帹閫佺殑涓嶅厑璁哥户缁�
-        if (mesInvItemOuts.Nflag == 1)
-            throw new Exception("鍑哄簱鍗�  " + query.billNo + "宸茬粡鎺ㄩ�侊紝鏃犳硶閲嶅鎺ㄩ��");
-
-        var depotCodeOut = mesInvItemOuts.DepotCode ?? "0";
-        var depotsCodeStock = mesInvItemStocks.DepotsCode ?? "0";
-
-        if (!depotCodeOut.Equals(depotsCodeStock))
-        {
-            // 鍒涘缓閿欒娑堟伅
-            var errorMessage =
-                $"002[鏉$爜浠撳簱{depotsCodeStock}涓庣敵璇蜂粨搴搟depotCodeOut}涓嶄竴鑷达紝璇锋牳瀵癸紒";
-
-            throw new Exception(errorMessage);
-        }
-
-        var StocksNum = mesInvItemStocks.Quantity;
-
-        var sql = string.Format(
-            @"select nvl(SUM(S.QUANTITY),0) - nvl(SUM(S.TL_QTY),0)
-                  from MES_INV_ITEM_OUT_ITEMS S
-                  LEFT JOIN mes_inv_item_outs d
-                    ON S.ITEM_OUT_ID = D.ID
-                 where d.item_out_no = '{0}'
-                   and d.bill_type_id = {1}
-                   and d.transaction_no = {2}
-                   AND S.item_no = '{3}'
-                   and nvl(d.status, 0) = 1
-                   and nvl(d.nflag, 0) = 0", query.billNo, billTypeId,
-            transactionNo,
-            mesInvItemStocks.ItemNo);
-
-        var cqty = Db.Ado.SqlQuerySingle<decimal>(sql);
-
-        if (cqty == null)
-            throw new Exception("鐗╂枡" + mesInvItemStocks.ItemNo +
-                                "鐨勮緟鍔╁睘鎬т笌鏉$爜涓嶄竴鑷达紒璇锋鏌�");
-
-        if (cqty < StocksNum) throw new Exception("璇风‘璁ゅ彂鏂欐暟閲�");
-
-        //璋冪敤瀛樺偍杩囩▼
-        try
-        {
-            // 瀹氫箟杈撳嚭鍙傛暟
-            var outputResult = new SugarParameter("C_RESULT", null,
-                DbType.Int32, ParameterDirection.Output,
-                4000);
-
-            var outputMessage = new SugarParameter("MSG", null, DbType.String,
-                ParameterDirection.Output, 4000);
-
-            // 瀹氫箟杈撳叆鍙傛暟
-            var parameters = new List<SugarParameter>
-            {
-                new("p_item_barcode", query.barcode,
-                    DbType.String, ParameterDirection.Input),
-                new("p_bill_no", query.billNo, DbType.String,
-                    ParameterDirection.Input),
-                new("pi_factory", "1000", DbType.String,
-                    ParameterDirection.Input),
-                new("pi_company", "1000", DbType.String,
-                    ParameterDirection.Input),
-                new("c_user", query.userName, DbType.String,
-                    ParameterDirection.Input),
-                outputResult,
-                outputMessage
-            };
-
-            // 浣跨敤 SqlSugar 鎵ц瀛樺偍杩囩▼
-            Db.Ado.ExecuteCommand(
-                "BEGIN MES_CG_UPDATE_BARCODES(:p_item_barcode, :p_bill_no, :pi_factory, :pi_company, :c_user, :C_RESULT, :MSG); END;",
-                parameters.ToArray());
-
-            // 鑾峰彇杈撳嚭鍙傛暟鐨勫��
-            var resultValue = outputResult.Value?.ToString();
-            var messageValue = outputMessage.Value?.ToString();
-
-            if ("1".Equals(resultValue)) throw new Exception("鏉$爜鎵i櫎澶辫触");
-        }
-        catch (Exception ex)
-        {
-            throw new Exception(ex.Message);
-        }
-
-        // 鍙橀噺鐢ㄤ簬淇濆瓨鏌ヨ缁撴灉
-        decimal? C_SQ_QTY = 0;
-        decimal? C_OK_QTY = 0;
-        var c_result = string.Empty;
-        var C_COUNT = 0;
-
-
-        sql = string.Format(@"
-                SELECT SUM(C.QUANTITY) AS SQ_QTY, SUM(D.QUANTITY_OK) AS OK_QTY
-                FROM MES_INV_ITEM_OUT_ITEMS C
-                LEFT JOIN (
-                    SELECT ITEM_OUT_ID, ITEM_NO, PBILL_NO, RK_NO, SUM(QUANTITY) AS QUANTITY_OK
-                    FROM MES_INV_ITEM_OUT_C_DETAILS
-                    GROUP BY ITEM_OUT_ID, ITEM_NO, PBILL_NO, RK_NO
-                ) D
-                ON D.ITEM_OUT_ID = C.ITEM_OUT_ID
-                AND D.ITEM_NO = C.ITEM_NO
-                AND D.RK_NO = C.RK_NO
-                AND NVL(C.PBILL_NO, '0') = NVL(D.PBILL_NO, '0')
-                WHERE C.ITEM_OUT_ID = {0}", mesInvItemOuts.Id);
-
-        var queryResult = Db.Ado.SqlQuerySingle<dynamic>(sql);
-
-        C_SQ_QTY = queryResult?.SQ_QTY;
-        C_OK_QTY = queryResult?.OK_QTY;
-
-        // 鍒ゆ柇閫昏緫
-        if (C_SQ_QTY < C_OK_QTY) throw new Exception("鎵弿鏁伴噺瓒呰繃鐢宠鏁伴噺,璇烽噸鏂版壂鎻忥紒");
-
-        if (C_SQ_QTY == C_OK_QTY) return true;
-
-        return false;
-    }
-
-
-    public bool Audit(WarehouseQuery query)
-    {
-        // 瀹℃牳鍓嶆牎楠�
-        Validate(query);
-        query.status = 1;
-        //瀹℃牳
-        return Update(query);
-    }
-
-    public bool SetNFlag(WarehouseQuery query)
-    {
-        return Db.Updateable<MesInvItemOuts>()
-            .SetColumns(s => s.Nflag == 1)
-            .Where(s => s.ItemOutNo == query.billNo)
-            .ExecuteCommand() > 0;
-    }
-
-    public bool DeApprove(WarehouseQuery query)
-    {
-        query.date = null;
-        query.status = 0;
-        return Update(query);
-    }
-
-    private bool Update(WarehouseQuery entity)
-    {
-        var userName = entity.userName ?? "system";
-        return Db.Updateable<MesInvItemOuts>()
-            .SetColumns(s => s.Status == entity.status)
-            .SetColumns(s => s.CheckUser == userName)
-            .SetColumns(s => s.CheckDate == DateTime.Now)
-            .Where(s => s.Id == entity.id).ExecuteCommand() > 0;
-    }
-
-
-    public void Validate(WarehouseQuery query)
-    {
-        // 鏍¢獙鍗曞彿鏄惁姝g‘
-        var mesInvItemOuts = Db.Queryable<MesInvItemOuts>()
-            .Where(o => o.ItemOutNo == query.billNo)
-            .Single();
-
-        if (mesInvItemOuts == null)
-            throw new Exception("娌℃壘鍒�" + query.billNo + " 瀵瑰簲鐨勯噰璐��璐у崟锛岃妫�鏌�");
-
-        // 鏍¢獙瀛愯〃鏁版嵁
-        var itemOutItems = Db.Queryable<MesInvItemOutItems>()
-            .Where(o => o.ItemOutId == mesInvItemOuts.Id)
-            .ToList();
-
-        var sql = string.Empty;
-        var P_Msg = string.Empty;
-
-        foreach (var item in itemOutItems)
-        {
-            // 鍒ゆ柇鐢宠鏁伴噺鏄惁澶т簬鍓╀綑鍙��鏁伴噺
-            sql = string.Format(
-                @"SELECT NVL(s1.RK_QTY, 0) - NVL(KT_QTY, 0) KT_QTY --鍓╀綑鍙��
-            FROM MES_INV_ITEM_OUT_ITEMS C
-            LEFT JOIN (SELECT SUM(QUANTITY) KT_QTY,
-                              ITEM_NO,
-                              PBILL_NO,
-                              RK_NO,
-                              WORK_LINE
-                         FROM MES_INV_ITEM_OUT_ITEMS
-                        GROUP BY ITEM_NO, PBILL_NO, WORK_LINE,RK_NO) U
-              ON U.ITEM_NO = C.ITEM_NO
-             AND U.WORK_LINE = C.WORK_LINE
-             AND U.PBILL_NO = C.PBILL_NO
-             AND U.RK_NO = C.RK_NO
-            LEFT JOIN (SELECT SUM(QUANTITY) RK_QTY,
-                              ITEM_NO,
-                              EBELN,
-                              WORK_LINE,BILL_NO
-                         FROM MES_INV_ITEM_IN_C_ITEMS
-                        GROUP BY ITEM_NO, EBELN, WORK_LINE,BILL_NO) s1
-              ON S1.ITEM_NO = C.ITEM_NO
-             AND S1.WORK_LINE = C.WORK_LINE
-             AND S1.EBELN = C.PBILL_NO
-                AND S1.BILL_NO = C.RK_NO
-           WHERE C.ID = {0}", item.Id);
-            var sy_Qty = Db.Ado.SqlQuery<decimal>(sql);
-
-            if (sy_Qty != null && sy_Qty[0] < 0)
-            {
-                P_Msg =
-                    $"閲囪喘璁㈠崟锛歿item.PbillNo}锛岃锛歿item.WorkLine}锛岀墿鏂欙細{item.ItemNo} 鐢宠鏁伴噺澶т簬鍓╀綑鍙敹鏁伴噺";
-                throw new Exception(P_Msg);
-            }
-
-            // 鍒ゆ柇琛屾槸鍚﹂噸澶�
-            var cf_Num = Db.Queryable<MesInvItemOutItems>()
-                .Where(s1 => s1.ItemNo == item.ItemNo &&
-                             s1.WorkLine == item.WorkLine &&
-                             s1.PbillNo == item.PbillNo &&
-                             s1.ItemOutId == mesInvItemOuts.Id &&
-                             s1.RkNo == item.RkNo)
-                .Count();
-
-            if (cf_Num > 1)
-            {
-                P_Msg =
-                    $"閲囪喘璁㈠崟锛歿item.PbillNo}锛岃锛歿item.WorkLine}锛岀墿鏂欙細{item.ItemNo}閲嶅璇峰垹闄ゅ叾涓竴鏉℃暟鎹�";
-                throw new Exception(P_Msg);
-            }
-        }
-
-        // 鏍¢獙涓昏〃鍐呭鏄惁琚垹鎺�
-        // 涓昏〃浠撳簱缂栫爜
-        if (string.IsNullOrEmpty(mesInvItemOuts.DepotCode))
-        {
-            P_Msg = "浠撳簱缂栫爜涓虹┖锛岃妫�鏌�";
-            throw new Exception(P_Msg);
-        }
-
-        var supplierExists = Db.Queryable<MesSupplier>()
-            .Any(supplier => supplier.SuppNo == mesInvItemOuts.SuppNo);
-
-        if (!supplierExists)
-        {
-            P_Msg = $"渚涘簲鍟嗙紪鐮� {mesInvItemOuts.SuppNo} 鍦ㄧ郴缁熶腑涓嶅瓨鍦紝璇锋鏌�";
-            throw new Exception(P_Msg);
-        }
-
-        // 瀛愯〃琛屼笌涓昏〃绗﹀悎鎬ф牎楠�
-        foreach (var j in itemOutItems)
-        {
-            // 鏍¢獙瀛愯〃瀵瑰簲閲囪喘璁㈠崟鐨勪緵搴斿晢缂栫爜
-            var c_SuppNo = Db.Queryable<MesRohIn, MesSupplier>(
-                    (roh, supp) => new JoinQueryInfos(
-                        JoinType.Left,
-                        roh.Supplier == supp.Id.ToString()
-                    ))
-                .Where(roh => roh.BillNo == j.PbillNo)
-                .Select((roh, supp) => supp.SuppNo)
-                .Single();
-
-            if (c_SuppNo == null)
-            {
-                P_Msg = $"瀛愯〃琛屼緵搴斿晢缂栫爜 {c_SuppNo} 鍦ㄧ郴缁熶腑鏈壘鍒�";
-                throw new Exception(P_Msg);
-            }
-
-            if (mesInvItemOuts.SuppNo != c_SuppNo)
-            {
-                P_Msg =
-                    $"瀛愯〃閲囪喘璁㈠崟琛岀殑渚涘簲鍟嗙紪鐮� {c_SuppNo} 涓庝富琛ㄤ緵搴斿晢缂栫爜 {mesInvItemOuts.SuppNo} 涓嶄竴鑷达紝璇锋鏌�";
-                throw new Exception(P_Msg);
-            }
-
-            // 鏍¢獙瀛愯〃濮斿閲囪喘绫诲瀷鍜屼富琛ㄧ被鍨嬫槸鍚︿竴鑷�
-            if (j.FType != mesInvItemOuts.FType)
-            {
-                P_Msg =
-                    $"瀛愯〃濮斿绫诲瀷锛歿j.FType}锛屼笌涓昏〃濮斿绫诲瀷锛歿mesInvItemOuts.FType}锛屼笉涓�鑷达紝璇锋鏌�";
-                throw new Exception(P_Msg);
-            }
-
-            // 妫�鏌ュ瓙琛ㄤ粨搴撴槸鍚﹀拰涓昏〃浠撳簱涓�鑷�
-            if (j.DepotCode != mesInvItemOuts.DepotCode)
-            {
-                P_Msg =
-                    $"瀛愯〃浠撳簱缂栫爜锛歿j.DepotCode} 涓庝富琛ㄤ粨搴撶紪鐮侊細{mesInvItemOuts.DepotCode}锛屼笉涓�鑷达紝璇锋鏌�";
-                throw new Exception(P_Msg);
-            }
-        }
-    }
-
-    public OutItemDto SaveCombination(OutItemDto dto)
-    {
-        var mesInvItemOuts = dto.Form;
-        mesInvItemOuts.Status = 0;
-        mesInvItemOuts.BoardFlag = 0;
-        mesInvItemOuts.Sapstatus = 0;
-        mesInvItemOuts.OutStatus = 0;
-        mesInvItemOuts.ItemFlag = 0;
-        mesInvItemOuts.IsVisual = 1;
-        mesInvItemOuts.TransactionNo = 203;
-        mesInvItemOuts.Factory = "1000";
-        mesInvItemOuts.Company = "1000";
-
-        //杩斿洖ID
-        var id = Db.Insertable(mesInvItemOuts)
-            .ExecuteReturnIdentity();
-
-        if (id <= 0) throw new Exception("鎻掑叆閿欒");
-
-        mesInvItemOuts.Id = id;
-        dto.SaveItems.ForEach(s =>
-        {
-            s.ItemOutId = id;
-            s.Factory = "1000";
-            s.Company = "1000";
-            s.Status = 0;
-            s.DepotCode = mesInvItemOuts.DepotCode;
-            s.FType = mesInvItemOuts.FType;
-            s.CreateBy = mesInvItemOuts.CreateBy;
-            s.CreateDate = mesInvItemOuts.CreateDate;
-        });
-
-        var insertable = Db.Insertable(dto.SaveItems)
-            .ExecuteCommand();
-
-        if (insertable < 0) throw new Exception("鎻掑叆閿欒");
-
-        var query = new WarehouseQuery();
-        query.id = id;
-        dto.SelectItems = GetItems(query);
-
-        return dto;
-    }
-
-    public List<MesInvItemOuts> GetPage(WarehouseQuery query)
-    {
-        return
-            Db.Queryable<MesInvItemOuts, MesDepots, MesSupplier, SysUser,
-                    SysUser>((a, e, i, u1, u3) =>
-                    new JoinQueryInfos(
-                        JoinType.Left,
-                        a.DepotCode == e.DepotCode
-                        && e.Factory == a.Factory
-                        && e.Company == a.Company,
-                        JoinType.Left,
-                        a.SuppNo == i.SuppNo,
-                        JoinType.Left,
-                        a.CreateBy == u1.Fcode,
-                        JoinType.Left,
-                        a.CheckUser == u3.Fcode))
-                .WhereIF(query.id > 0,
-                    (a, e, i, u1, u3) => a.Id == query.id)
-                .WhereIF(!string.IsNullOrEmpty(query.billNo),
-                    (a, e, i, u1, u3) => a.ItemOutNo == query.billNo)
-                .Select((a, e, i, u1, u3) => new MesInvItemOuts
+                if (group.Key.MesNo == null)
                 {
-                    Id = a.Id,
-                    DepotCode = a.DepotCode,
-                    Fmrmode = a.Fmrmode,
-                    CheckDate = a.CheckDate,
-                    CheckUser = a.CheckUser,
-                    States = a.States,
-                    Reason = a.Reason,
-                    Remark = a.Remark,
-                    Nflag = a.Nflag,
-                    FType = a.FType,
-                    SuppNo = a.SuppNo,
-                    DepotName = e.DepotName,
-                    SuppName = i.SuppName,
-                    CreateByFname = u1.Fname,
-                    CheckUserFname = u3.Fname,
-                    CreateDate = a.CreateDate,
-                    CreateBy = a.CreateBy,
-                    Status = a.Status,
-                    ItemOutNo = a.ItemOutNo
-                }).ToPageList(query.PageIndex, query.Limit);
+                    throw new NotImplementedException("鍏ュ簱鍗曞崟鍙蜂笉鑳戒负绌�");
+                }
+
+                if (group.Key.SqNo == null)
+                {
+                    throw new NotImplementedException("閫�璐х敵璇峰崟琛屽彿涓嶈兘涓虹┖");
+                }
+
+                // 鍒涘缓涓�涓复鏃剁殑itemOutFrom瀵硅薄锛屼娇鐢ㄥ垎缁勭殑Key浣滀负涓昏灞炴��
+                var tempItemOutFrom = new ItemOutFrom
+                {
+                    //AsnNo = group.Key.AsnNo,
+                    MesNo = group.Key.MesNo,
+                    SqNo = group.Key.SqNo,
+                    // 缁ф壙鍘熷itemOutFrom鐨勫叾浠栧睘鎬�
+                    RtnNo = itemOutFrom.RtnNo+ "-"+count.ToString(),
+                    Type = itemOutFrom.Type,
+                    CreateBy = itemOutFrom.CreateBy,
+                    FMRMODE = itemOutFrom.FMRMODE,
+                    DepotId = itemOutFrom.DepotId,
+                    SupperId = itemOutFrom.SupperId
+                };
+                count++;
+                // 鏍规嵁Type鎵ц涓嶅悓鐨勯�昏緫
+                switch (tempItemOutFrom.Type)
+                {
+                    case "1":
+                        {
+                            var mesInvItemOuts = Db.Queryable<MesInvItemOuts>()
+                                .Where(s => s.BillTypeId == BILL_TYPE_ID
+                                            && s.TransactionNo == TRANSACTION_NO
+                                            && s.ItemOutNo == tempItemOutFrom.RtnNo
+                                            && s.Sapno == tempItemOutFrom.SqNo
+                                )
+                                .Count();
+
+                            if (mesInvItemOuts > 0)
+                            {
+                                throw new NotImplementedException(
+                                    tempItemOutFrom.RtnNo +
+                                    "鐨勯��鏂欑敵璇峰崟宸茬粡瀛樺湪");
+                            }
+
+                            // 涓哄綋鍓嶅垎缁勪繚瀛樻暟鎹�
+                            var groupResult = Save(tempItemOutFrom, group.ToList());
+                            if (!groupResult)
+                            {
+                                result = 0;
+                            }
+
+                            break;
+                        }
+                    case "4":
+                        var removeResult = Remove(tempItemOutFrom);
+                        if (!removeResult)
+                        {
+                            result = 0;
+                        }
+
+                        break;
+                    default:
+                        result = 0;
+                        break;
+                }
+            }
+
+            return result;
+        }) > 0;
+
+
     }
 
-    public List<MesInvItemOutCDetails> GetScanBarcode(WarehouseQuery query)
+    private bool Save(ItemOutFrom from, List<ItemOutList> items)
     {
-        return Db.Queryable<MesInvItemOutCDetails, MesInvItemBarcodes, MesItems,
-                MesDepots>(
-                (b, bar, c, d) => new
-                    JoinQueryInfos(
-                        JoinType.Left, b.ItemBarcode == bar.ItemBarcode,
-                        JoinType.Left, b.ItemNo == c.ItemNo &&
-                                       b.Company == c.Company &&
-                                       b.Factory == c.Factory,
-                        JoinType.Left, b.DepotCode == d.DepotCode &&
-                                       b.Company == d.Company &&
-                                       b.Factory == d.Factory
-                    ))
-            .Where((b, bar, c, d) => b.ItemOutId == query.id)
-            .Select((b, bar, c, d) => new MesInvItemOutCDetails
-            {
-                Quantity = b.Quantity,
-                DepotSectionCode = b.DepotSectionCode,
-                DepotCode = b.DepotCode,
-                ItemNo = b.ItemNo,
-                ItemBarcode = b.ItemBarcode,
-                ItemName = c.ItemName,
-                ItemModel = c.ItemModel,
-                DepotName = d.DepotName,
-                Unit = bar.Unit
-            }).ToList();
-    }
+        var mesInvItemIns = Db.Queryable<MesInvItemIns>()
+            .Where(s => s.BillTypeId == 100
+                        && s.TransctionNo == "101"
+                        && s.Id == Convert.ToInt32(from.MesNo)
+            ).First();
 
-    //MESInvItemOutItems
-    public List<MESInvItemOutItems> GetItems(WarehouseQuery query)
-    {
-        var where = "and 1=1";
-        if (query.id != null) where = "and ITEM_OUT_ID = '" + query.id + "'";
-
-        var sql = string.Format(@"select * from (
-        SELECT C.REMARK, C.PBILL_NO, C.ITEM_OUT_ID, C.RK_QTY,
-               C.TL_QTY, C.WORK_LINE, C.QUANTITY, C.ITEM_NO,
-               NVL(s1.RK_QTY, 0) - NVL(KT_QTY, 0) KT_QTY,
-               R.DEPOT_SECTION_CODE, S.ITEM_MODEL, S.ITEM_NAME,
-               K.CGB014, Q.STAFF_NAME, R.DEPOT_CODE
-        FROM MES_INV_ITEM_OUT_ITEMS C JOIN MES_ITEMS S ON C.ITEM_NO = S.ITEM_NO
-                 LEFT JOIN (SELECT SUM(QUANTITY) KT_QTY, ITEM_NO, PBILL_NO, WORK_LINE, RK_NO
-                            FROM MES_INV_ITEM_OUT_ITEMS
-                            GROUP BY ITEM_NO, PBILL_NO, WORK_LINE, RK_NO) U
-                           ON U.ITEM_NO = C.ITEM_NO AND U.WORK_LINE = C.WORK_LINE
-                               AND U.PBILL_NO = C.PBILL_NO AND U.RK_NO = C.RK_NO
-                 LEFT JOIN (SELECT SUM(QUANTITY) RK_QTY, ITEM_NO, EBELN, WORK_LINE, BILL_NO
-                            FROM mes_inv_item_in_c_details
-                            GROUP BY ITEM_NO, EBELN, WORK_LINE, BILL_NO) s1
-                           ON S1.ITEM_NO = C.ITEM_NO AND S1.WORK_LINE = C.WORK_LINE
-                               AND S1.EBELN = C.PBILL_NO AND S1.BILL_NO = C.RK_NO
-                 LEFT JOIN MES_ROH_IN_DATA K
-                           ON K.BILL_NO = C.PBILL_NO AND C.WORK_LINE = K.PURCHASE_ORDER_LINE_NUMBER
-                 left join MES_ROH_IN H on H.BILL_NO = K.BILL_NO
-                 left join MES_STAFF Q on H.PURCHASER = Q.STAFF_NAME
-                 LEFT JOIN MES_SUPPLIER T ON H.SUPPLIER = T.ID
-                 LEFT JOIN (select *
-                            from (SELECT row_number() over (partition by DEPOT_CODE, ITEM_NO, EBELN order by CREATE_DATE) rn, DEPOT_CODE, DEPOT_SECTION_CODE, ITEM_NO,
-                                         EBELN FROM mes_inv_item_in_c_details
-                                  where EBELN is not null)
-                            where rn = 1 and ROWNUM = 1) R ON R.ITEM_NO = C.ITEM_NO) where 1=1 {0}",
-            where);
-        var results = Db.Ado.SqlQuery<MESInvItemOutItems>(sql);
-        return results;
-    }
-
-    public OutItemDto GetSumItem(WarehouseQuery query)
-    {
-        var mesInvItemOuts = base.GetSingle(it => it.ItemOutNo == query.billNo);
-        if (mesInvItemOuts == null) throw new Exception("閲囪喘閫�璐у崟涓嶅瓨鍦�");
-
-        var sql = string.Format(@"SELECT DEPOT ,ITEM_NO,ITEM_MODEL,
-           ITEM_NAME,QTY FROM (SELECT SUM(QTY) QTY, DEPOT, ITEM_NO, ITEM_MODEL, ITEM_NAME
-              FROM (SELECT f_get_section_code2('1000', '1000', b.ITEM_NO,'{0}') DEPOT,
-                           B.ITEM_NO, A.ITEM_MODEL,A.ITEM_NAME,to_char(nvl(b.QUANTITY, 0) - nvl(D.QUANTITY_OK, 0),'FM9999999990.00') QTY
-                      FROM MES_INV_ITEM_OUT_ITEMS B LEFT JOIN mes_ITEMS A
-                        ON B.ITEM_NO = A.ITEM_NO LEFT JOIN (SELECT ITEM_OUT_ID,
-                                       ITEM_NO,PBILL_NO,SUM(QUANTITY) QUANTITY_OK,RK_NO
-                                  FROM MES_INV_ITEM_OUT_C_DETAILS
-                                 WHERE ITEM_OUT_ID = {1}
-                                 GROUP BY ITEM_OUT_ID,ITEM_NO,PBILL_NO,RK_NO) D
-                        ON D.ITEM_OUT_ID = B.ITEM_OUT_ID
-                       AND D.ITEM_NO = B.ITEM_NO
-                       AND D.PBILL_NO = B.PBILL_NO
-                       AND D.RK_NO = B.RK_NO
-                     WHERE B.ITEM_OUT_ID = {1}
-                       AND nvl(b.QUANTITY, 0) - nvl(D.QUANTITY_OK, 0) > 0
-                     ORDER BY f_get_section_code2('1000','1000',b.ITEM_NO,'{0}'),
-                              A.ITEM_MODEL,A.ITEM_NAME)
-             GROUP BY DEPOT, ITEM_NO, ITEM_MODEL, ITEM_NAME)",
-            mesInvItemOuts.DepotCode,
-            mesInvItemOuts.Id);
-
-        var results = Db.Ado.SqlQuery<InventoryItem>(sql);
-
-        var mesInvItemStocks = Db.Queryable<MesInvItemStocks>()
-            .Where(a => a.ItemBarcode == query.barcode).Single();
-
-        var dto = new OutItemDto();
-        dto.SumItem = results;
-
-        if (mesInvItemStocks != null)
+        if (mesInvItemIns == null)
         {
-            dto.ItemNo = mesInvItemStocks.ItemNo;
-            dto.Quantity = mesInvItemStocks.Quantity;
+            throw new NotImplementedException("閲囪喘鍏ュ簱涓嶅瓨鍦�");
         }
 
-        return dto;
-    }
+        var mesDepots = Db.Queryable<MesDepots>()
+            .Where(s => s.DepotId == Decimal.Parse(from.DepotId)).First();
 
-    public List<InventoryItemDetail> SelectMaterials(WarehouseQuery query)
-    {
-        var sql = string.Format(@"select B.WORK_NO, b.work_line,
-                               b.item_no, s2.item_name, s2.item_model,
-                               sum(b.quantity)                         sum_Quantity,
-                               b.unit, b.supp_no,
-                               nvl(s1.quantity, 0)                     quantity,
-                               sum(b.quantity) - nvl(U.KT_QTY, 0)      Refundable_Quantity,
-                               B.cbill_no, B.task_no, A.BILL_NO,
-                               to_char(b.CREATE_DATE, 'yyyy-mm-dd') as CREATE_DATE
-                        from mes_inv_item_in_c_details b
-                                 left join mes_inv_item_ins a on b.item_in_id = a.id
-                                 LEFT JOIN (select s.item_no, s.work_line, s.Work_no,
-                                                   sum(s.quantity) quantity, S.RK_NO
-                                            from mes_inv_item_out_c_details s
-                                            group by s.item_no, s.work_line, s.work_no, S.RK_NO) s1
-                                           ON NVL(B.work_LINE, '0') = NVL(s1.work_LINE, '0')
-                                               and B.work_no = s1.work_no
-                                               and B.item_no = s1.item_no
-                                               AND B.BILL_NO = S1.RK_NO
-                                 LEFT JOIN (SELECT SUM(QUANTITY) KT_QTY, ITEM_NO, PBILL_NO, WORK_LINE, RK_NO
-                                            FROM MES_INV_ITEM_OUT_ITEMS
-                                            GROUP BY ITEM_NO, PBILL_NO, WORK_LINE, RK_NO) U
-                                           ON U.ITEM_NO = B.ITEM_NO
-                                               AND U.WORK_LINE = B.WORK_LINE
-                                               AND U.PBILL_NO = B.WORK_NO AND U.RK_NO = B.BILL_NO
-                                 left join mes_items s2 on b.item_no = s2.item_no
-                                 left join purdha da on da.dha001 = b.cbill_no
-                        WHERE A.BILL_NO LIKE 'Q%'
-                          AND A.CBILL_NO like 'L%'
-                        group by b.item_no, b.work_line, b.supp_no, b.remark, s1.quantity, b.unit,
-                                 s2.item_name, s2.item_model, da.dha003, B.WORK_NO, B.cbill_no, B.task_no,
-                                 to_char(b.CREATE_DATE, 'yyyy-mm-dd'), A.BILL_NO, U.KT_QTY, A.CBILL_NO
-                        having b.remark = '閲囪喘鍏ュ簱'
-                           and sum(b.quantity) - nvl(U.KT_QTY, 0) > 0
-                           and b.supp_no = '{0}'
-                        order by to_char(b.CREATE_DATE, 'yyyy-mm-dd')",
-            query.SuppNo);
+        var mesLinkU9 = Db.Queryable<MesLinkU9>()
+            .Where(s => s.TableType == "MES_SUPPLIER"
+                        && s.U9Id == from.SupperId).First();
 
-        var results = Db.Ado.SqlQuery<InventoryItemDetail>(sql);
-        return results;
-    }
-
-    public string GetMaxItemOutNo()
-    {
-        var date = DateTime.Now.ToString("yyyyMMdd");
-        var par = "NTL" + date;
-        var sql =
-            $"select max(ITEM_OUT_NO) from MES_INV_ITEM_OUTS where ITEM_OUT_NO like '{par}%'";
-        var maxBillNo = Db.Ado.SqlQuerySingle<string>(sql);
-
-        var number = "0001";
-        if (maxBillNo != null)
+        if (mesLinkU9 == null)
         {
-            maxBillNo = maxBillNo.Substring(11);
-            var no = Convert.ToInt32(maxBillNo);
-            no++;
-            number = no.ToString().PadLeft(4, '0');
+            throw new NotImplementedException("渚涘簲鍟咺D涓嶅瓨鍦ㄦ垨鏈悓姝ヤ簬U9");
         }
 
-        return "NTL" + date + number;
-    }
+        var mesSupplier = Db.Queryable<MesSupplier>()
+            .Where(s => s.Id == Decimal.Parse(mesLinkU9.MesId))
+            .First();
 
-    public MessageCenter SaveMessageCenter(WarehouseQuery query)
-    {
-        var message = MesToErpParam(query);
-
-        var executeReturnIdentity =
-            Db.Insertable(message).ExecuteReturnIdentity();
-        if (executeReturnIdentity > 0)
+        if (mesDepots == null)
         {
-            message.Id = executeReturnIdentity;
-            message.Pid = executeReturnIdentity;
-            return message;
+            throw new NotImplementedException("[" + from.DepotId +
+                                              "]浠撳簱涓嶅瓨鍦紝璇峰悓姝ョ粰MES");
         }
 
-        throw new Exception("鑾峰彇鏁版嵁澶辫触");
-    }
-
-
-    public MessageCenter MesToErpParam(WarehouseQuery query)
-    {
-        var erpParameters = "";
-        var title = "";
-        var tableName = "MES_INV_ITEM_OUTS_" + query.Type;
-        if ("A".Equals(query.Type))
+        if (mesSupplier == null)
         {
-            erpParameters = GetErpParameters(query.billNo);
-            title = "閲囪喘閫�璐у崟" + query.billNo + "瀹℃牳";
-        }
-        else if ("B".Equals(query.Type))
-        {
-            erpParameters = GetDeApprovePam(query.id);
-            title = "閲囪喘閫�璐у崟" + query.billNo + "鍙嶅鏍�";
+            throw new NotImplementedException("[" + from.SupperId +
+                                              "]渚涘簲鍟嗕笉瀛樺湪锛岃鍚屾缁橫ES");
         }
 
-        var ErpUrl = AppsettingsUtility.Settings.ProductionErpUrl;
-        var message = new MessageCenter
+        var nextSequenceValue =
+            Db.Ado.SqlQuery<decimal>("SELECT SEQ_OUT_ID.NEXTVAL FROM DUAL")
+                .First();
+
+        // var billCode =
+        //     Db.Ado.SqlQuery<string>(
+        //             "SELECT GETBILLCODE1('1000', '1000', 'TLSQ') FROM DUAL")
+        //         .First();
+        var billCode = from.RtnNo;
+
+        // 鍒涘缓閲囪喘閫�鏂欏崟璁板綍
+        var mesInvItemOuts = new MesInvItemOuts
         {
-            TableName = tableName,
-            Url = ErpUrl,
-            Status = 1,
-            CreateBy = query.userName,
-            Route = query.billNo,
-            Title = title,
-            PageName = "Warehouse/PurchaseReturn/Add?id=" + query.id +
-                       "&itemOutNo=" + query.billNo,
-            CreateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
-            Method = "POST",
-            Seq = 1,
-            Data = erpParameters,
-            IsMessage = 0,
-            ContentType = "application/x-www-form-urlencoded"
+            Id = nextSequenceValue,
+            ItemOutNo = billCode,
+            Status = 0,
+            CreateBy = "PL017",
+            CreateDate = DateTime.Now,
+            BillTypeId = 200,
+            TransactionNo = 203,
+            DepotCode = mesDepots.DepotCode,
+            FType = 0,
+            OutStatus = 0,
+            IsVisual = 1,
+            Factory = "1000",
+            Company = "1000",
+            SuppNo = mesSupplier.SuppNo,
+            ItemFlag = 0,
+            BoardFlag = 0,
+            OutType = "閲囪喘閫�鏂�",
+            Nflag = 0,
+            Fmrmode = from.FMRMODE,
+            Sapno = from.SqNo,
+            Organizeid = "1002503270000079",
         };
-        return message;
-    }
 
-    public bool DeApproveBefore(WarehouseQuery query)
-    {
-        var mesInvItemOuts = base.GetById(query.id);
-        if (mesInvItemOuts == null) throw new Exception("鍑哄簱鍗曚笉瀛樺湪");
+        // 鍒涘缓閲囪喘閫�鏂欏崟璁板綍
+        var mesInvItemOutItems = new List<MesInvItemOutItems>();
 
-        var nflag = mesInvItemOuts.Nflag ?? 0;
-
-        if (nflag != 0) return true;
-
-        return false;
-    }
-
-    private string GetDeApprovePam(decimal? id)
-    {
-        var sid = (int)id;
-        var encodedUrl = "taskname=CGTL&mesid=" + sid +
-                         "&optype=delete&datajson={}";
-
-        return encodedUrl;
-    }
-
-    private string GetErpParameters(string? billNo)
-    {
-        var invItemIns = Db.Queryable<MesInvItemOuts>()
-            .Single(x => x.ItemOutNo == billNo);
-
-        //璋冪敤function鍑芥暟
-        var sql =
-            $"SELECT F_GENERATE_DATA_INSERTED('{billNo}') FROM DUAL;";
-        var jsonString = Db.Ado.SqlQuerySingle<string>(sql);
-
-        var encodedUrl = "taskname=CGTL&mesid=" + invItemIns.Id +
-                         "&optype=create&datajson=" + jsonString;
-
-        return encodedUrl;
-    }
-
-    public List<string> GetItemOutNo()
-    {
-        var data5 = Db.Queryable<MesInvItemOuts>().Where(it =>
-                it.BillTypeId == 200 && it.TransactionNo == 203 &&
-                it.Status == 1)
-            .OrderBy(it => it.Id, OrderByType.Desc)
-            .ToPageList(1, 20);
-
-        var ItemOutNos = data5.FindAll(a => a.Nflag == null || a.Nflag == 0)
-            .Select(s => s.ItemOutNo).ToList();
-        //
-        // var ItemOutNos = data5
-        //     .Select(s => s.ItemOutNo).ToList();
-
-        return ItemOutNos;
-    }
-    //鐢熶骇棰嗘枡鍗曞鏍稿墠鏍¢獙
-
-
-    public MessageCenter SaveProductionMessageCenter(WarehouseQuery entity)
-    {
-        var message = ProductionMesToErpParam(entity);
-
-        var executeReturnIdentity =
-            Db.Insertable(message).ExecuteReturnIdentity();
-        if (executeReturnIdentity > 0)
+        foreach (var itemOutList in items)
         {
-            message.Id = executeReturnIdentity;
-            message.Pid = executeReturnIdentity;
-            return message;
-        }
-
-        throw new Exception("鑾峰彇鏁版嵁澶辫触");
-    }
-
-    public MessageCenter ProductionMesToErpParam(WarehouseQuery query)
-    {
-        var erpParameters = "";
-        var title = "";
-        var tableName = "INV_ITEM_OUTS_" + query.Type;
-        if ("A".Equals(query.Type))
-        {
-            erpParameters =
-                GetProductionErpParameters(query.billNo, query.userName);
-            title = "鐢熶骇棰嗘枡鍗�" + query.billNo + "瀹℃牳";
-        }
-
-        var ErpUrl = AppsettingsUtility.Settings.ProductionErpUrl;
-        var message = new MessageCenter
-        {
-            TableName = tableName,
-            Url = ErpUrl,
-            Status = 1,
-            CreateBy = query.userName,
-            Route = query.billNo,
-            Title = title,
-            PageName = "Warehouse/ProductionPick/Add?id=" + query.id +
-                       "&itemOutNo=" + query.billNo,
-            CreateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
-            Method = "POST",
-            Seq = 1,
-            Data = erpParameters,
-            IsMessage = 0,
-            ContentType = "application/x-www-form-urlencoded"
-        };
-        return message;
-    }
-
-    private string GetProductionErpParameters(string? queryBillNo,
-        string? userName)
-    {
-        userName ??= "system";
-        var mesInvItemOuts = Db.Queryable<MesInvItemOuts>()
-            .Where(it => it.ItemOutNo == queryBillNo)
-            .First();
-
-        if (mesInvItemOuts == null) throw new Exception("棰嗘枡鍗曞彿涓嶅瓨鍦�");
-
-        var womcaa = Db.Queryable<Womcaa>()
-            .Where(it => it.Caa020 == mesInvItemOuts.WorkNo)
-            .First();
-
-        if (womcaa == null) throw new Exception("浠诲姟鍗曞彿涓嶅瓨鍦�");
-
-        var Departmentcode = Db.Queryable<SysDepartment, MesInvItemOuts>(
-                (a, b) =>
-                    new JoinQueryInfos(JoinType.Left,
-                        a.Departmentname == b.OutPart
-                    )).Where((a, b) =>
-                b.OutPart == mesInvItemOuts.OutPart &&
-                b.ItemOutNo == queryBillNo).Select(a => a.Departmentcode)
-            .First();
-
-        if (string.IsNullOrEmpty(Departmentcode))
-            throw new Exception("閮ㄩ棬淇℃伅涓嶅瓨鍦�");
-
-        // 妫�鏌ラ鏂欏崟鐘舵��
-        if (mesInvItemOuts.Status == 1) throw new Exception("棰嗘枡鍗曞凡瀹℃牳锛屼笉鑳介噸澶嶆帹閫�");
-
-        var C_OUT_ITEMS = Db
-            .Queryable<MesInvItemOutItems, Womdab, Womdaa, Womcaa, Womcab>(
-                (c, b, d, e, f) =>
-                    new JoinQueryInfos(
-                        JoinType.Left, b.Id == c.ItemDabid,
-                        JoinType.Left, d.Id == b.Pid,
-                        JoinType.Left, e.Caa001 == d.Daa021,
-                        JoinType.Left, f.Eid == e.Erpid
-                    ))
-            .Where((c, b, d, e, f) => c.ItemOutId == mesInvItemOuts.Id)
-            .Select((c, b, d, e, f) => new
+            // 妫�鏌ュ繀瑕佸瓧娈垫槸鍚︿负绌�
+            if (string.IsNullOrEmpty(itemOutList.SrcDocNo))
             {
-                c.Id,
-                c.ItemNo,
-                c.Quantity,
-                c.DepotCode,
-                c.DepotSectionCode,
-                c.ItemId,
-                erpId = b.ErpId,
-                e.Caa015,
-                f.PositionNo
-            }).ToList();
+                throw new NotImplementedException("閲囪喘璁㈠崟鍙蜂笉鑳戒负绌�");
+            }
 
-        var scllentryList = new List<dynamic>();
-
-        foreach (var item in C_OUT_ITEMS)
-        {
-            var sql =
-                "SELECT FNAME FROM MES_UNIT WHERE ID = (SELECT ITEM_UNIT FROM MES_ITEMS WHERE ID = '" +
-                item.ItemId + "')";
-            var C_ITEM_UNIT = Db.Ado.SqlQuerySingle<string>(sql);
-
-            var xsddh = item.Caa015 ?? "";
-            var wzh = item.PositionNo ?? "";
-            var qty = ((int)item.Quantity).ToString();
-            var erpid = ((int)item.erpId).ToString();
-            var id = ((int)item.Id).ToString();
-            scllentryList.Add(new
+            if (string.IsNullOrEmpty(itemOutList.SrcDocLineNo))
             {
-                FMaterialId = item.ItemNo,
-                FUnitID = C_ITEM_UNIT,
-                FAppQty =  qty,
-                FActualQty =  qty,
-                FStockId = item.DepotCode,
-                FPPBomEntryId = erpid,
-                F_UNW_Text_xsddh = xsddh,
-                F_UNW_TEXT_WZH = wzh,
-                F_MES_ENTRYID = id
+                throw new NotImplementedException("閲囪喘璁㈠崟琛屽彿涓嶈兘涓虹┖");
+            }
+
+            //if (string.IsNullOrEmpty(itemOutList.AsnLineNo))
+            //{
+            //    throw new NotImplementedException("ASN琛屽彿涓嶈兘涓虹┖");
+            //}
+
+            if (string.IsNullOrEmpty(itemOutList.itemId))
+            {
+                throw new NotImplementedException("鐗╂枡ID涓嶈兘涓虹┖");
+            }
+
+            var mesRohInData = Db.Queryable<MesRohInData>()
+                .Where(s => s.BillNo == itemOutList.SrcDocNo
+                            && s.OrderLineId == itemOutList.SrcDocLineNo)
+                .First();
+
+            if (mesRohInData == null)
+            {
+                throw new NotImplementedException("閲囪喘璁㈠崟涓嶅瓨鍦�");
+            }
+
+            //var deliveryDetail = Db.Queryable<DeliveryDetail>()
+            //    .Where(a =>  Int32.Parse(a.ZzitemId) ==
+            //                Int32.Parse(itemOutList.AsnLineNo))
+            //    .Count();
+
+            //if (deliveryDetail <= 0)
+            //{
+            //    throw new NotImplementedException("[" + from.AsnNo + "]鐨勬槑缁嗚[" +
+            //                                      itemOutList.AsnLineNo +
+            //                                      "]涓嶅瓨鍦�");
+            //}
+
+            var itemIdLinkU9 = Db.Queryable<MesLinkU9>()
+                .Where(s => s.TableType == "MES_ITEMS"
+                            && s.U9Id == itemOutList.itemId).First();
+
+            if (mesLinkU9 == null)
+            {
+                throw new NotImplementedException("渚涘簲鍟咺D涓嶅瓨鍦ㄦ垨鏈悓姝ヤ簬U9");
+            }
+
+            var mesItems = Db.Queryable<MesItems>()
+                .Where(s => s.Id == Decimal.Parse(itemIdLinkU9.MesId))
+                .First();
+
+            if (mesItems == null)
+            {
+                throw new NotImplementedException("[" + itemOutList.itemId +
+                                                  "]鐗╂枡涓嶅瓨鍦紝璇峰悓姝ョ粰MES");
+            }
+
+            var mesInvItemInCItems = Db.Queryable<MesInvItemInCItems>()
+                .Where(s => s.ItemInId == mesInvItemIns.Id
+                            && s.ItemNo == mesItems.ItemNo
+                            && s.Ebeln == itemOutList.SrcDocNo
+                            && s.EbelnLineNo ==
+                            Decimal.Parse(itemOutList.SrcDocLineNo)
+                            && s.SuppNo == mesSupplier.SuppNo
+                            ).First();
+
+            if (mesInvItemInCItems == null)
+            {
+                throw new NotImplementedException("娌℃湁瀵瑰簲鐨勫叆搴撴槑缁�");
+            }
+
+
+            // 纭繚CbillNo涓嶄负绌�
+            if (string.IsNullOrEmpty(mesInvItemIns.CbillNo))
+            {
+                throw new NotImplementedException("鍏ュ簱鍗曞叧鑱旂殑閲囪喘鍗曞彿涓嶈兘涓虹┖");
+            }
+
+            mesInvItemOutItems.Add(new MesInvItemOutItems
+            {
+                ItemOutId = nextSequenceValue,
+                ItemNo = mesItems.ItemNo,
+                Quantity = Decimal.Parse(itemOutList.qty),
+                CreateBy = "PL017",
+                CreateDate = DateTime.Now,
+                Factory = "1000",
+                Company = "1000",
+                DepotCode = mesDepots.DepotCode,
+                WorkNo = itemOutList.SrcDocNo, // 纭繚WorkNo鏈夊��
+                WorkLine =
+                    Decimal.Parse(itemOutList.SrcDocLineNo), // 纭繚WorkLine鏈夊��
+                EbelnK3id = Decimal.Parse(mesRohInData.ErpId),
+                LineK3id = Decimal.Parse(mesRohInData.EbelnK3id),
+                FType = 0,
+                Status = 0,
+                PbillNo = mesInvItemIns.CbillNo, // 纭繚PbillNo鏈夊��
+                RkNo = from.MesNo, // 纭繚RkNo鏈夊��
+                RkLine = mesInvItemInCItems.Id, // 纭繚RkLine鏈夊��
+                RkQty = mesInvItemInCItems.Quantity,
+                TlQty = 0,
+                ItemId = Decimal.Parse(itemIdLinkU9.MesId), // 纭繚ItemId鏈夊��
+                SqNo = itemOutList.SqNo, // 纭繚ItemId鏈夊��
+                //ZzitemId = itemOutList.AsnLineNo, // 纭繚ItemId鏈夊��
+                // Unit = item.Unit,
             });
         }
 
-        var dataJson = new
+        var outItemCommand = Db.Insertable(mesInvItemOutItems)
+            .PageSize(1).IgnoreColumnsNull().ExecuteCommand();
+        if (outItemCommand <= 0)
         {
-            F_MES_ID = mesInvItemOuts.Id.ToString(),
-            FDate = DateTime.Now.ToString("yyyy-MM-dd"),
-            FPickerId = userName,
-            F_UNW_LargeText_BZ = " ",
-            F_UNW_KH = " ",
-            F_UNW_DDSL = womcaa.Caa012.ToString(),
-            F_UNW_Text_CZG = userName,
-            scllentry = scllentryList
-        };
+            throw new Exception("鍒涘缓閲囪喘閫�鏂欏崟瀛愯〃澶辫触");
+        }
 
-        return "taskname=SCLL&mesid=" + mesInvItemOuts.Id +
-               "&optype=create&datajson=" +
-               JsonConvert.SerializeObject(
-                   dataJson);
+        // 鎻掑叆閲囪喘閫�鏂欏崟璁板綍
+        var insertResult = Db.Insertable(mesInvItemOuts).IgnoreColumns(true)
+            .ExecuteCommand();
+        if (insertResult <= 0)
+        {
+            throw new Exception("鍒涘缓閲囪喘閫�鏂欏崟澶辫触");
+        }
+
+        return outItemCommand + insertResult >= 2;
     }
 
-    public bool AuditProduction(WarehouseQuery query)
+    private bool Remove(ItemOutFrom from)
     {
-        query.status = 1;
-        //瀹℃牳
-        return Update(query);
+        // 鏌ユ壘瑕佸垹闄ょ殑閲囪喘閫�鏂欏崟
+        var mesInvItemOuts = Db.Queryable<MesInvItemOuts>()
+            .Where(s => s.BillTypeId == BILL_TYPE_ID
+                        && s.TransactionNo == TRANSACTION_NO
+                        && s.ItemOutNo == from.RtnNo).ToList();
+
+        if (mesInvItemOuts == null || mesInvItemOuts.Count == 0)
+        {
+            throw new NotImplementedException("鎵句笉鍒板搴旂殑閲囪喘閫�鏂欏崟: " + from.RtnNo);
+        }
+
+        // 妫�鏌ユ槸鍚︽湁宸插鏍哥殑鍗曟嵁锛屽鏋滃瓨鍦ㄥ凡瀹℃牳(Status=1)鍒欎笉鍏佽鍒犻櫎
+        if (mesInvItemOuts.Any(item => item.Status == 1))
+        {
+            throw new NotImplementedException("瀛樺湪宸插鏍哥殑閲囪喘閫�鏂欏崟锛屼笉鍏佽鍒犻櫎");
+        }
+
+        // 鍒犻櫎鎵�鏈夌浉鍏冲崟鎹�
+        foreach (var itemOut in mesInvItemOuts)
+        {
+            // 鏌ユ壘瑕佸垹闄ょ殑閲囪喘閫�鏂欏崟鏄庣粏
+            var mesInvItemOutItems = Db.Queryable<MesInvItemOutItems>()
+                .Where(s => s.ItemOutId == itemOut.Id)
+                .ToList();
+
+            if (mesInvItemOutItems == null || mesInvItemOutItems.Count == 0)
+            {
+                throw new NotImplementedException(
+                    $"鎵句笉鍒伴噰璐��鏂欏崟[{itemOut.ItemOutNo}]瀵瑰簲鐨勬槑缁�");
+            }
+
+            // 鍒犻櫎閲囪喘閫�鏂欏崟鏄庣粏
+            var deleteItemsResult = Db.Deleteable<MesInvItemOutItems>()
+                .Where(s => s.ItemOutId == itemOut.Id)
+                .ExecuteCommand();
+
+            if (deleteItemsResult <= 0)
+            {
+                throw new Exception($"鍒犻櫎閲囪喘閫�鏂欏崟[{itemOut.ItemOutNo}]鏄庣粏澶辫触");
+            }
+
+            // 鍒犻櫎閲囪喘閫�鏂欏崟
+            var deleteResult = Db.Deleteable<MesInvItemOuts>()
+                .Where(s => s.Id == itemOut.Id)
+                .ExecuteCommand();
+
+            if (deleteResult <= 0)
+            {
+                throw new Exception($"鍒犻櫎閲囪喘閫�鏂欏崟[{itemOut.ItemOutNo}]澶辫触");
+            }
+        }
+
+        return true;
     }
 }
\ No newline at end of file

--
Gitblit v1.9.3