1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
using AngleSharp.Dom;
using Castle.Core.Resource;
using MES.Service.DB;
using MES.Service.Dto.webApi;
using MES.Service.Modes;
using MES.Service.util;
using SqlSugar;
using System.Collections.Generic;
using System.Security.Cryptography;
 
namespace MES.Service.service.BasicData;
 
public class MesCustomerManager : Repository<MesCustomer>
{
    public bool Save(ErpCustomer customer)
    {
        var entity = GetSysDepartment(customer);
 
        return UseTransaction(db =>
        {
            switch (customer.Type)
            {
                case "0":
                    if (UpdateCustomerStatusBatch(db, entity, "A"))
                        return 1;
                    break;
                case "1":
                    if (UpdateCustomerStatusBatch(db, entity, "B"))
                        return 1;
                    break;
                case "3":
                    if (DeleteCustomerBatch(db, entity))
                        return 1;
                    break;
                case "2":
                case "4":
                    //先删除,后新增
                    if (InsertOrUpdateBatch(db, entity))
                        return 1;
                    break;
                default:
                    throw new ArgumentNullException(
                        $"type没有{customer.Type}这个类型的参数");
            }
 
            throw new NotImplementedException("操作失败");
        }) > 0;
    }
 
    public bool SaveList(List<ErpCustomer> customers)
    {
        //var list = customers.Select(GetSysDepartment).ToList();
 
        //因为U9的模式,会导致多组织的基础数据被处理成List<>,所以需要修改方法,SaveLits中应该是把单条处理出来的List数据加起来,而不是之前的方法处理。
        List<MesCustomer> mes_customers = new List<MesCustomer>();
        foreach (ErpCustomer customer in customers)
        {
            var mesCustomerList = GetSysDepartment(customer);
            if (mesCustomerList != null)
            {
                mes_customers.AddRange(mesCustomerList);
            }
        }
 
        var groupBy = mes_customers.GroupBy(s => s.Type)
            .ToDictionary(g => g.Key, g => g.ToList());
 
        return UseTransaction(db =>
        {
            foreach (var customerGroup in groupBy)
                switch (customerGroup.Key)
                {
                    case "0":
                        if (!UpdateCustomerStatusBatch(db, customerGroup.Value,"A"))
                            throw new NotImplementedException("启用失败");
                        break;
                    case "1":
                        if (!UpdateCustomerStatusBatch(db, customerGroup.Value,"B"))
                            throw new NotImplementedException("禁用失败");
                        break;
                    case "3":
                        if (!DeleteCustomerBatch(db, customerGroup.Value))
                            throw new NotImplementedException("删除失败");
                        break;
                    case "2":
                    case "4":
                        if (!InsertOrUpdateBatch(db, customerGroup.Value))
                            throw new NotImplementedException("同步失败");
                        break;
                    default:
                        throw new ArgumentNullException(
                            $"type没有{customerGroup.Key}这个类型的参数");
                }
 
            return 1;
        }) > 0;
    }
 
    private bool UpdateCustomerStatus(SqlSugarScope db, decimal customerId,
        string status)
    {
        var result = db.Updateable<MesCustomer>()
            .SetColumns(s => s.Fforbidstatus == status)
            .Where(s => s.Id == customerId).ExecuteCommand();
 
        if (result > 0)
            return true;
 
        throw new NotImplementedException(status == "A" ? "启用失败" : "禁用失败");
    }
 
    private bool InsertCustomer(SqlSugarScope db, MesCustomer entity)
    {
        var insert = db.Insertable(entity).ExecuteCommand();
        if (insert > 0)
            return true;
 
        throw new NotImplementedException("插入失败");
    }
 
    private bool DeleteCustomer(SqlSugarScope db, decimal customerId)
    {
        var deleteById = db.Deleteable<MesCustomer>().In(customerId)
            .ExecuteCommand();
        if (deleteById > 0)
            return true;
 
        throw new NotImplementedException("删除失败");
    }
 
    private List<MesCustomer> GetSysDepartment(ErpCustomer customer)
    {
        var db = SqlSugarHelper.GetInstance();
        //var id = db.Insertable(insertObj).ExecuteReturnIdentity();
        //根据序列获取新的MES_ID
        
 
 
        List<MesCustomer> customers = new List<MesCustomer>();
 
        foreach (ErpDetail erpDetail in customer.ErpDetails)
        {
            decimal mesId = 0;
            var exists = db.Queryable<MesLinkU9>().Any(u => u.U9Id == customer.Id && u.OrgId == erpDetail.FUseOrgId && u.TableType == "MES_CUSTOMER");
            if (!exists)
            {
                mesId = GetSeqUtil.GetSeq("U9_MES_ID");
                var entity = new MesLinkU9
                {
                    CreateDate = DateTime.Now,
                    MesId = mesId.ToString(),
                    U9Id = customer.Id.ToString(),
                    OrgId = erpDetail.FUseOrgId.ToString(),
                    TableType = "MES_CUSTOMER"
 
                };
                var insertUser = db.Insertable(entity).ExecuteCommand();
            }
            else
            {
                mesId = Convert.ToDecimal(db.Queryable<MesLinkU9>()
                    .Where(u => u.U9Id == customer.Id && u.OrgId == erpDetail.FUseOrgId && u.TableType == "MES_CUSTOMER")
                    .Select(u => u.MesId) // 选择 MesId 字段
                    .First());
            }
 
            var mesCustomer = new MesCustomer
            {
                Id = mesId,
                CustNo = customer.FNumber,
                CustSname = customer.FShortName,
                CustName = customer.FName,
                Anred = customer.FContact,
                Telf1 = customer.FMobilephone,
                Fseller = customer.FSeller,
                CUSTOMER_STATE = customer.State,
                Fforbidstatus = customer.FForbidStatus,
                UseOrg = Convert.ToDecimal(erpDetail.FUseOrgId),
                Type = customer.Type
            };
 
            customers.Add(mesCustomer);
        }
 
 
       
 
        //customers = customer.ErpDetails.Select(ErpDetails => new MesCustomer
        //{
        //    Id = GetSeqUtil.GetSeq("U9_MES_ID"),
        //    CustNo = customer.FNumber,
        //    CustSname = customer.FShortName,
        //    CustName = customer.FName,
        //    Anred = customer.FContact,
        //    Telf1 = customer.FMobilephone,
        //    Fseller = customer.FSeller,
        //    CUSTOMER_STATE = customer.State,
        //    Fforbidstatus = customer.FForbidStatus,
        //    UseOrg = Convert.ToDecimal(ErpDetails.FUseOrgId),
 
        //}).ToList();
        
        return customers;
    }
 
    private bool UpdateCustomerStatusBatch(SqlSugarScope db,
        List<MesCustomer> customerList, string status)
    {
        var ids = customerList.Select(it => it.Id).ToArray();
        var result = db.Updateable<MesCustomer>()
            .SetColumns(s => s.Fforbidstatus == status)
            .Where(s => ids.Contains(s.Id)).ExecuteCommand();
 
        if (result > 0)
            return true;
 
        throw new NotImplementedException(status == "A" ? "启用失败" : "禁用失败");
    }
 
    private bool InsertCustomerBatch(SqlSugarScope db,
        List<MesCustomer> customerList)
    {
        var insertRange = db.Insertable(customerList).ExecuteCommand();
        if (insertRange > 0)
            return true;
 
        throw new NotImplementedException("插入失败");
    }
 
    private bool DeleteCustomerBatch(SqlSugarScope db,
        List<MesCustomer> customerList)
    {
        // 提取所有需要的 MesId 组合
        var mesIds = customerList.Select(customer => customer.Id.ToString()).ToList();
 
        // 使用这些 MesId 去查询 MesLinkU9 表,找到对应的 U9Id
        var u9Ids = db.Queryable<MesLinkU9>()
                       .Where(u => mesIds.Contains(u.MesId) && u.TableType == "MES_CUSTOMER")
                       .Select(u => u.U9Id)
                       .Distinct() // 应用 Distinct 去重
                       .ToList();
 
        // 根据 U9Id 找到所有对应的 MesId,进行删除
        // 注意:这里假设您确实想要删除这些记录。如果不确定,请先查询以验证结果。
        var idsToDelete = db.Queryable<MesLinkU9>()
                            .Where(u => u9Ids.Contains(u.U9Id) && u.TableType == "MES_CUSTOMER")
                            .Select(u => u.MesId)
                            .Distinct() // 应用 Distinct 去重
                            .ToList();
 
 
        //以上方法可以考虑优化,将U9id找个新建字段存在MES_CUSTOMER中,就可以少一步查询了。
 
        var deleteByIds = db.Deleteable<MesCustomer>().In(idsToDelete).ExecuteCommand();
        if (deleteByIds > 0)
            return true;
 
        throw new NotImplementedException("删除失败");
    }
 
    /// <summary>
    /// "插入或更新的方法"调整:修改为先删除再插入。
    /// </summary>
    /// <remarks>
    /// 修改人:池南骏
    /// 修改日期:2024-12-30
    /// 修改说明:`
    /// </remarks>
 
    //// - 原代码:
    //private bool InsertOrUpdate(SqlSugarScope db, MesCustomer entity)
    //{
    //    var exists = db.Queryable<MesCustomer>().Any(e => e.Id == entity.Id);
    //    if (exists)
    //    {
    //        var update = db.Updateable(entity).ExecuteCommand();
    //        if (update > 0)
    //            return true;
    //    }
    //    else
    //    {
    //        var insert = db.Insertable(entity).ExecuteCommand();
    //        if (insert > 0)
    //            return true;
    //    }
 
    //    return false;
    //}
 
    /// 新代码
    private bool InsertOrUpdate(SqlSugarScope db, MesCustomer entity)
    {
        //db.Deleteable<MesCustomer>()
        //    .Where(s => s.Id == entity.Id)
        //    .ExecuteCommand();
 
        var insert = db.Insertable(entity).ExecuteCommand();
        return insert > 0;
    }
 
    private bool InsertOrUpdateBatch(SqlSugarScope db,
        List<MesCustomer> customerList)
    {
        //先删除,再新增
        if (!DeleteCustomerBatch(db, customerList))
            return false;
 
        foreach (var entity in customerList)
            if (!InsertOrUpdate(db, entity))
                return false;
 
        return true;
    }
}