高章伟
2022-03-18 a0bc3e3af59aed35334bdc38256a7a1dfe8aecf3
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
public with sharing class ConsumEquipmentSetShipmentController extends CreateRelationListPagingCtrlBase{
    private String cesIdsStr;
    private List<String> cesIdList;
    public String c_apply_no { get; private set; }
    public Boolean done_flg { get;  set; }
    public Boolean readOnly { get;  set; }
    private String keywdSort = null;
    public FixtureDeliverySlip__c slip { get; set; }
    public String keepWher { get; set; }
    public String keyword { get; set; }
    public String changeMessage { get; set; }
    public String keywordDate { get; set; }
    public Boolean saveBtnDisabled { get; private set; }
    private List<Consum_Apply_Equipment_Set_Detail__c> useCaesdList;
    private Boolean cancelAction;
 
    public ConsumEquipmentSetShipmentController() {
        cesIdsStr = ApexPages.currentPage().getParameters().get('id');
    }
 
    public override Integer getSearchNumMax() {
        //各ページに制御あれば、最大件数を指定する
        // searchNumMax = Integer.valueOf(Label.Product_Select_Limit);
        // searchNumMax = 20;
        pagesize = '500';
        return searchNumMax;
    }
 
    /* 選択されたデータ取得用Soql Fromから*/
    public override String getSelectedDataSql() {
        // オブジェクトAPI名
        selectedDataSql = ' where Id != null ';
        selectedDataSql += '   and (';
 
        for (String caesStr : cesIdList) {
            selectedDataSql += ' Consum_Apply_Equipment_Set__r.Name = \'' + String.escapeSingleQuotes(caesStr) + '\' OR Consum_Apply_Equipment_Set__c = \'' + String.escapeSingleQuotes(caesStr) + '\' OR';
        }
        selectedDataSql = selectedDataSql.removeEnd('OR');
        selectedDataSql += ')';
        selectedDataSql += '   and Shipment_request_time2__c != null';
        selectedDataSql += '   and Cancel_Select__c = False';
        //selectedDataSql += ' order by Id ASC nulls last';
        keepWher = selectedDataSql;
        selectedDataSql = ' From Consum_Apply_Equipment_Set_Detail__c' + selectedDataSql + ' order by Fixture_Model_No_F__c nulls last, Consumable_Guaranteen_end_F__c nulls last';
        myComponentController.columnRightRW.put('Inspection_Cnt_Jia__c', 'w');
        return selectedDataSql;
    }
 
    // 検索元対象オブジェクトAPI名
    public override String getOriginObjName() {
        // オブジェクトAPI名
        originObjName = 'Consum_Apply_Equipment_Set_Detail__c';
        return originObjName;
    }
    public override String getOriginObjColumns() {
        // 項目セット
        originObjColumns =  'Id';
        return originObjColumns;
    }
 
    public override String getObjName() {
        // オブジェクトAPI名
        objName = 'Consum_Apply_Equipment_Set_Detail__c';
        return objName;
    }
    public override String getColumnLeftFieldSetName() {
        // 左の項目セット
        columnLeftFieldSetName = '';
        return columnLeftFieldSetName;
    }
    public override String getColumnRightFieldSetName() {
        // 右の項目セット
        columnRightFieldSetName = 'ConsumEquipmentSetShipment_R';
        return columnRightFieldSetName;
    }
    public override List<String> getColumnFieldList() {
        // strColumus 里加 field
        // FixtureUtil#raesdGroupBy()の項目も必要
        return new List<String>{'Id', 'Asset__c', 'DeliverySlip__c', 'Shippment_loaner_time__c', 'Consum_Apply__r.demo_purpose2__c', 'Consum_Apply__r.Shipment_requested_cnt__c', 'Shipment_Saved_Flg__c', 'Shipment_request_time2__c', 'Consum_Apply_Equipment_Set__r.Yi_Shipment_request__c'};
    }
    public override List<String> getHiddenFieldList() {
        return new List<String>{'Product_Serial_No_F__c'};
    }
    // getObjName 连 getOriginObjName 的 FK
    public override String getFKColumnField() {
        return null;
    }
 
    public override String getRecordTypeId() {
        //ページレイアウトを収得するのレコードタイプ
        recordTypeId = '';
        return recordTypeId;
    }
 
    // ページコントローラに検索処理は、WhereSoql作成のみ、パラメータとして、コンポーネントに渡される
    public override String getSqlWhereStr() {
        sqlWhereStr = '';
 
        if(getIsNeedRunSearch()){
            System.debug('getIsNeedRunSearch enter');
            sqlWhereStr = this.makeSoql();
            System.debug('sqlWhereStr is:' + sqlWhereStr);
        }
 
        return sqlWhereStr;
 
    }
 
    public override String getOrderbyStr() {
        return ' order by Fixture_Model_No_F__c nulls last, Consumable_Guaranteen_end_F__c nulls last';
    }
 
    public override Boolean getIsNeedRunSearch() {
 
      //   if (String.isBlank(keyword)) {
            // isNeedRunSearch = false;
      //   }else{
            // isNeedRunSearch = true;
      //   }
        return true;
    }
 
    public void init() {
 
        Set<Id> rnsIdSet = new Set<Id>();
        String jsonStr;
        cancelAction = false;
        // 当前User
        String userid = Userinfo.getUserId();
        if (cesIdsStr != null) {
            cesIdList = cesIdsStr.split(',');
 
            User user = [select Id,Name from User where Id = :userid];
            // 借出耗材备品一览
            List<Consum_Apply_Equipment_Set__c> rnsList = [select Id, Consum_Apply__c, Consum_Apply__r.Yi_loaner_arranged__c, Consum_Apply__r.Name, Consum_Apply__r.Shipment_Slip_tmp__c
                                            from Consum_Apply_Equipment_Set__c
                                           where (Name in :cesIdList or Id in :cesIdList)
                                             ];
            readOnly = false;
            if (rnsList.size() > 0) {
                for (Consum_Apply_Equipment_Set__c rns : rnsList) {
                    rnsIdSet.add(rns.Id);
                    if (rns.Consum_Apply__r.Shipment_Slip_tmp__c != null && jsonStr == null) {
                        jsonStr = rns.Consum_Apply__r.Shipment_Slip_tmp__c;
                    }
                    c_apply_no = rns.Consum_Apply__r.Name;
                    if (rns.Consum_Apply__r.Yi_loaner_arranged__c > 0) {
                        readOnly = true;
                    }
                }
                parentId = rnsList[0].Consum_Apply__c;
            } else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '借出耗材备品一览不存在'));
                saveBtnDisabled = true;
                return;
            }
        }
        System.debug(jsonStr);
        if (jsonStr != null) {
            try {
                slip = (FixtureDeliverySlip__c)JSON.deserialize(jsonStr, FixtureDeliverySlip__c.class);
            } catch (Exception ex) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
                slip = new FixtureDeliverySlip__c();
            }
        } else {
            slip = new FixtureDeliverySlip__c();
        }
        if (slip.Wh_Staff__c == null) slip.Wh_Staff__c = userid;
        slip.ConsumSlip__c = true;
 
        searchOppSetParam();
        getSqlWhereStr();
 
        // return null;
    }
 
    private void searchOppSetParam() {
        keywdSort = keyword;
    }
 
    public void searchOpp() {
        searchOppSetParam();
 
        if (!getIsNeedRunSearch()) {
            return;
        }
 
        // 選択済みの製品を取得
        myComponentController.getSelectedDataInfo();
        getSqlWhereStr();
        // コンポーネントにSoqlを発行して、ページングする
        myComponentController.searchAndPaging();
    }
 
    public void searchSlip() {
        String qryString = 'select Id, Shippment_loaner_time__c, ConsumSlip__c, Name, DeliveryCompany__c, Wh_Staff__c, Combine_Pack__c, Distributor_method__c, DeliveryType__c, DeliveryCompany_SlipNo__c '
                + 'from FixtureDeliverySlip__c '
                + 'where Name =\''+ slip.Name +'\' and DeliveryType__c = \'发货\'';
        if (String.isNotBlank(slip.Distributor_method__c)) {
            qryString += ' and Distributor_method__c = \''+ slip.Distributor_method__c +'\'';
        }
        if (String.isNotBlank(slip.DeliveryCompany__c)) {
            qryString += ' and DeliveryCompany__c = \''+ slip.DeliveryCompany__c +'\'';
        }
        List<FixtureDeliverySlip__c> slipList = Database.query(qryString);
 
        if (slipList.size() > 0) {
            if (slipList.size() > 1) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '当前条件检索到复数条运输单,请追加检索条件!'));
            }
            slip = slipList[0];
            if (slip.Wh_Staff__c == null) slip.Wh_Staff__c = Userinfo.getUserId();
        }
    }
 
    public void save() {
        done_flg = false;
        if (readOnly) return;
        Map<String, Integer> sendAssetKey = new Map<String, Integer>();
        for (WrapperInfo wi : viewList) {
            if (!wi.check) continue;
            Consum_Apply_Equipment_Set_Detail__c caesd = (Consum_Apply_Equipment_Set_Detail__c)wi.sobj;
            Integer cnt = caesd.Inspection_Cnt_Jia__c == null ? 0 : Integer.valueOf(caesd.Inspection_Cnt_Jia__c);
            sendAssetKey.put(caesd.Asset__c, cnt);
        }
        List<Consum_Apply_Equipment_Set_Detail__c> updList = new List<Consum_Apply_Equipment_Set_Detail__c>();
        for (Consum_Apply_Equipment_Set_Detail__c caesd : useCaesdList) {
            if (sendAssetKey.containsKey(caesd.Asset__c)) {
                Integer cnt = sendAssetKey.get(caesd.Asset__c);
                if (cnt > 0) {
                    caesd.Shipment_Saved_Flg__c = true;
                    cnt--;
                } else {
                    caesd.Shipment_Saved_Flg__c = false;
                }
                sendAssetKey.put(caesd.Asset__c, cnt);
                updList.add(caesd);
            }
        }
 
        Savepoint sp = Database.setSavepoint();
        try {
 
            String jsonstr = JSON.serialize(slip);
            Consum_Apply__c upd_ca = new Consum_Apply__c(Id=parentId, Shipment_Slip_tmp__c=jsonstr);
            update upd_ca;
            if (updList.size() > 0) {
                update updList;    
            }
            done_flg = true;
        } catch (Exception ex) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
            Database.rollback(sp);
            done_flg = false;
        }
    }
 
    public void send() {
        done_flg = false;
        Set<String> sendAssetKey = new Set<String>();
        Set<String> sendEquipmentSet = new Set<String>();
        for (WrapperInfo wi : viewList) {
            Consum_Apply_Equipment_Set_Detail__c caesd = (Consum_Apply_Equipment_Set_Detail__c)wi.sobj;
            if (!wi.check) {
                continue;
            }
            String guaranteen_end = '';
            if (caesd.Consumable_Guaranteen_end_F__c != null) {
                guaranteen_end = caesd.Consumable_Guaranteen_end_F__c.format();                     
            }
            if (caesd.Consumable_Guaranteen_end_F__c != null && Date.today().daysBetween(caesd.Consumable_Guaranteen_end_F__c) <= 0 && caesd.Consum_Apply__r.demo_purpose2__c != '动物实验' && caesd.Consum_Apply__r.demo_purpose2__c != 'ET展箱'  ) { //2021-04-30 mzy  备品课题-1577
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '消耗品已过期['+caesd.Fixture_Model_No_F__c+']('+caesd.Consumable_Guaranteen_end_F__c.format()+')'));
                return;
            }
            if (caesd.Inspection_Cnt_Jia__c > caesd.Yi_Chu_Ku_Zhi_Shi_Jia__c) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '发货件数大于已出库指示件数['+caesd.Fixture_Model_No_F__c+']('+guaranteen_end+')'));
                return;
            } 
            if (caesd.Inspection_Cnt_Jia__c == null || caesd.Inspection_Cnt_Jia__c < caesd.Yi_Chu_Ku_Zhi_Shi_Jia__c) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '发货件数小于已出库指示件数['+caesd.Fixture_Model_No_F__c+']('+guaranteen_end+')'));
                return;
            }
 
            if (slip.Name == null || slip.DeliveryType__c == null || slip.Distributor_method__c == null || slip.DeliveryCompany__c == null || slip.Wh_Staff__c == null ) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请填写发货信息'));
                return;
            }
 
            sendEquipmentSet.add(caesd.Consum_Apply_Equipment_Set__c);
            sendAssetKey.add(caesd.Asset__c);
        }        
 
        Integer needCnt = 0;
        Integer hadCnt = 0;
        for (Consum_Apply_Equipment_Set_Detail__c caesd : (List<Consum_Apply_Equipment_Set_Detail__c>)selectedData) {
            if (caesd.Shipment_request_time2__c != null && caesd.DeliverySlip__c == null) {
                needCnt++;
            }
        }
        Set<Id> assetIdSet = new Set<Id>();
        List<Consum_Apply_Equipment_Set_Detail__c> updList = new List<Consum_Apply_Equipment_Set_Detail__c>();
        for (Consum_Apply_Equipment_Set_Detail__c caesd : useCaesdList) {
            if (sendAssetKey.contains(caesd.Asset__c)) {
                hadCnt++;
                updList.add(caesd);
                assetIdSet.add(caesd.Asset__c);
            }
        }
 
        if (viewList.size() > 0 && (sendEquipmentSet.size() != ((Consum_Apply_Equipment_Set_Detail__c)viewList[0].sobj).Consum_Apply__r.Shipment_requested_cnt__c || hadCnt != needCnt)) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '必须整单发货,部分发货请进行分单'));
            return;
        } 
 
        List<Consum_Apply_Equipment_Set_Detail__c> updateList = [select Id, Shipment_request_time2__c from Consum_Apply_Equipment_Set_Detail__c where Id in :updList for update];
        for (Consum_Apply_Equipment_Set_Detail__c upd : updateList) {
            if (upd.Shipment_request_time2__c == null) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '出库指示时间为空,不能发货'));
                break;
            }
        }
        if (ApexPages.hasMessages(ApexPages.severity.Error)) {
            done_flg = false;
            return;
        }
        
 
        Savepoint sp = Database.setSavepoint();
        try {
            if (updList.size() > 0) {
                List<Asset> assetList = [
                    SELECT Id
                      FROM Asset
                     WHERE Id IN:assetIdSet
                     FOR UPDATE
                ];
                slip.Shippment_loaner_time__c = Datetime.now();
                FixtureUtil.withoutUpsertObjects(new List<FixtureDeliverySlip__c>{slip});
 
                Datetime nowtime = Datetime.now();
                List<Consum_Apply_Equipment_Set_Detail__c> upsertList = new List<Consum_Apply_Equipment_Set_Detail__c>();
                for (Consum_Apply_Equipment_Set_Detail__c upd : updList) {
                    //upd.DeliverySlip__c = slip.Id;
                    //upd.Shippment_loaner_time__c = nowtime;
                    //upd.StockDown__c = true;
                    //upd.StockDown_time__c = nowtime;
                    upsertList.add(
                        new Consum_Apply_Equipment_Set_Detail__c(
                            id = upd.id, 
                            Inspection_Cnt_Jia__c = upd.Inspection_Cnt_Jia__c,
                            DeliverySlip__c = slip.Id,
                            Shippment_loaner_time__c = nowtime,
                            StockDown__c = true
                            //, StockDown_time__c = nowtime 
                            ));
                }
                FixtureUtil.withoutUpdate(upsertList);
 
                Consum_Apply__c upd_ca = new Consum_Apply__c(Id=parentId, DeliverySlip__c=slip.Id);
                FixtureUtil.withoutUpdate(new List<Consum_Apply__c>{upd_ca});
            }
            searchOpp();
            done_flg = true;
        } catch (Exception ex) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
            Database.rollback(sp);
            done_flg = false;
        }
    }
 
    public void cancel() {
        Set<Id> clearAssetId = new Set<Id>();
        List<Consum_Apply_Equipment_Set_Detail__c> updList = new List<Consum_Apply_Equipment_Set_Detail__c>();
        for (WrapperInfo wi : viewList) {
            Consum_Apply_Equipment_Set_Detail__c caesd = (Consum_Apply_Equipment_Set_Detail__c)wi.sobj;
            if (caesd.DeliverySlip__c == null) {
                caesd.Inspection_Cnt_Jia__c = null;
                clearAssetId.add(caesd.Asset__c);
            }
        }
 
        for (Consum_Apply_Equipment_Set_Detail__c caesd : useCaesdList) {
            if (clearAssetId.contains(caesd.Asset__c)) {
                caesd.Shipment_Saved_Flg__c = false;
                updList.add(caesd);
            }
        }
        
        Savepoint sp = Database.setSavepoint();
        try {
            if (updList.size() > 0) {
                slip = new FixtureDeliverySlip__c();
                slip.Wh_Staff__c = Userinfo.getUserId();
                String jsonstr = JSON.serialize(slip);
                Consum_Apply__c upd_ca = new Consum_Apply__c(Id=parentId, Shipment_Slip_tmp__c=jsonstr);
                update upd_ca;
                update updList;    
            }
            keyword = null;
            keywordDate = null;
            cancelAction = true;
            searchOpp();
            done_flg = true;
        } catch (Exception ex) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
            Database.rollback(sp);
            done_flg = false;
        }
    }
 
    private String makeSoql() {
        // 検索条件
 
        // from asset
        String soql = keepWher;
        if (String.isNotBlank(keywordDate)) {
            soql += ' AND Consumable_Guaranteen_end_F__c = ' + String.escapeSingleQuotes(keywordDate.replaceAll('/', '-'));
        }
        if (String.isNotBlank(keyword)) {
            soql += ' AND Fixture_Model_No__c like \'%' + String.escapeSingleQuotes(keyword) + '%\'';
        }
        return soql;
    }
 
    public override void setViewList(List<Sobject> queryList) {
        viewList = new List<WrapperInfo>();
        if (queryList.size() > 0) {
            List<Consum_Apply_Equipment_Set_Detail__c> tmpList = (List<Consum_Apply_Equipment_Set_Detail__c>)queryList;
            Map<Id, Consum_Apply_Equipment_Set_Detail__c> smap = new Map<Id, Consum_Apply_Equipment_Set_Detail__c>((List<Consum_Apply_Equipment_Set_Detail__c>)selectedData);
            useCaesdList = new List<Consum_Apply_Equipment_Set_Detail__c>();
            for (Consum_Apply_Equipment_Set_Detail__c caeid : tmpList) {
                useCaesdList.add(smap.get(caeid.Id));
            }
        }
        else {
            useCaesdList = (List<Consum_Apply_Equipment_Set_Detail__c>)selectedData;
        }
        Map<Id, List<Consum_Apply_Equipment_Set_Detail__c>> caesdMap = new Map<Id, List<Consum_Apply_Equipment_Set_Detail__c>>();
        Map<Id, Integer> cntMap = new Map<Id, Integer>();
        Map<Id, Integer> cntShipmentReqMap = new Map<Id, Integer>();
        Map<Id, Boolean> hasShipment = new Map<Id, Boolean>();
        for (Consum_Apply_Equipment_Set_Detail__c caesd : useCaesdList) {
            if (caesdMap.containsKey(caesd.Asset__c) == false) {
                caesdMap.put(caesd.Asset__c, new List<Consum_Apply_Equipment_Set_Detail__c>());
            }
            caesdMap.get(caesd.Asset__c).add(caesd);
 
            if (caesd.Shipment_Saved_Flg__c == true) {
                Integer cnt = cntMap.containsKey(caesd.Asset__c) ? (cntMap.get(caesd.Asset__c) + 1) : 1;
                cntMap.put(caesd.Asset__c, cnt);
            }
            if (caesd.Shipment_request_time2__c != null) {
                Integer cnt = cntShipmentReqMap.containsKey(caesd.Asset__c) ? (cntShipmentReqMap.get(caesd.Asset__c) + 1) : 1;
                cntShipmentReqMap.put(caesd.Asset__c, cnt);
            }
            if (caesd.DeliverySlip__c != null) {
                hasShipment.put(caesd.Asset__c, true);
            }
        }
        for (Id assId : caesdMap.keySet()) {
            Consum_Apply_Equipment_Set_Detail__c wiInfo = caesdMap.get(assId)[0];
            if (cntMap.containsKey(wiInfo.Asset__c)) {
                wiInfo.Inspection_Cnt_Jia__c = cntMap.get(wiInfo.Asset__c);
            }
            if (cntShipmentReqMap.containsKey(wiInfo.Asset__c)) {
                wiInfo.Yi_Chu_Ku_Zhi_Shi_Jia__c = cntShipmentReqMap.get(wiInfo.Asset__c);
            }
 
            WrapperInfo wi = new WrapperInfo(wiInfo, myComponentController);
            wi.additionalInfoMap.put('Product_Serial_No_F__c', wiInfo.Product_Serial_No_F__c);
            if (hasShipment.containsKey(wiInfo.Asset__c) && hasShipment.get(wiInfo.Asset__c)) {
                wi.canEdit = false;
            }
            
            viewList.add(wi);
        }
        if (cancelAction) {
            changeMessage = '取消';
            cancelAction = false;
        } else {
            changeMessage = ''+viewList.size();
        }
        
 
    }
}