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
public without sharing class TransferApplyResponseController {
    // 借出申请
    public TransferApply__c ra { get; set; }
    /**
     * 1.画面输入用借出申请
     * 2.邮件cc用,最多5个
     * 经理(服务) JingliApprovalManager__c        => cc_1
     * 经理(销售) SalesManager__c                 => cc_2
     * 部长(服务) BuchangApprovalManager__c       => cc_3
     * 部长(销售) BuchangApprovalManagerSales__c  => cc_4
     * 总监       ZongJian__c      => cc_5
     */
    public TransferApply__c cc { get; set; }
    // 借出申请ID
    public Id raid { get; private set; }
    // To:备品中心(responsebefore),To:申请者(responseafter)
    public String type { get; set; }
 
    public Boolean hasError { get; private set; }
    public String baseUrl { get; private set; }
 
    public String toString { get; private set; }
 
    public List <String> toNameListWithoutAddonMessage = new List<String> ();
    public List <String> toMailList = new List<String> ();
 
 
    public TransferApplyResponseController() {
        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        raid = ApexPages.currentPage().getParameters().get('raid');
        type = ApexPages.currentPage().getParameters().get('type');
        toString = '';
    }
 
    public TransferApplyResponseController(ApexPages.StandardController stdController) {
        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        raid = stdController.getId();
        type = ApexPages.currentPage().getParameters().get('type');
    }
 
    // 画面初始化
    public void init() {
        hasError = true;
        if(String.isBlank(raid)){
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL, '无效的调拨申请Id');
            Apexpages.addMessage(myMsg);
            return;
        }
        ra = new TransferApply__c();
        cc = new TransferApply__c();
        List<TransferApply__c> raList = [select Id
                                              , Name
                                              , Response__c
                                              , ResponseNew__c
                                              , Contact_Person__c
                                              , Contact_Person__r.Name
                                              , Contact_Person__r.Email
                                              , After_Office_Assistant1__c
                                              , After_Office_Assistant1__r.Name
                                              , After_Office_Assistant1__r.Email
                                              , After_Office_Assistant2__c
                                              , After_Office_Assistant2__r.Name
                                              , After_Office_Assistant2__r.Email
                                              , AfterCheckEmail_F__c
                                              , Destination_location__c
                                              , RecordType.Name
                                              , Loaner_centre_accept_Email__c
                                              , AfterOCMAssetEmail_F__c
                                              , CreatedById
                                              , CreatedBy.Email
                                              , CreatedBy.Name
                                              , RecordType.DeveloperName
                                              , ApplyUser__c
                                              , ApplyUser__r.Name
                                              , ApplyUser__r.Email
                                              , Loaner_centre_mail_address__c
                                              , SalesManager__c
                                              , JingliApprovalManager__c
                                              , BuchangApprovalManager__c
                                              , BuchangApprovalManagerSales__c
                                              , Application_accept_time__c
                                           from TransferApply__c
                                          where Id = :raid];
        if (raList.size() > 0) {
            ra = raList[0];
            cc = raList[0];
            cc.JingliApprovalManager__c = null;
            cc.SalesManager__c = null;
            cc.BuchangApprovalManager__c = null;
            cc.BuchangApprovalManagerSales__c = null;
            cc.Zongjian__c = null;
            cc.ResponseNew__c = null;
 
            if (String.isNotBlank(type)) {
                if (type == 'responsebefore') {
                    setList(ra.CreatedBy.Name, ra.CreatedBy.Email, '(调拨单创建人)', toNameListWithoutAddonMessage, toMailList);
                } else if (type == 'responseafter') {
                    // 现场移交
                    if (ra.RecordType.DeveloperName == 'AgencyToCenter' || ra.RecordType.DeveloperName == 'CenterToCenter' || ra.RecordType.DeveloperName == 'CenterToOther') {
                        setList(ra.Contact_Person__r.Name, ra.Contact_Person__r.Email, '(联络人)', toNameListWithoutAddonMessage, toMailList);
                        if (toNameListWithoutAddonMessage.size() == 0) {
                            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL, '没有设置联络人无法发送应答沟通邮件');
                            Apexpages.addMessage(myMsg);
                            return;
                        }
                    }
                    // 分配现地
                    else if (ra.RecordType.DeveloperName == 'CenterToAgency') {
                        setList(ra.After_Office_Assistant1__r.Name, ra.After_Office_Assistant1__r.Email, '(办事处助理1)', toNameListWithoutAddonMessage, toMailList);
                        setList(ra.After_Office_Assistant2__r.Name, ra.After_Office_Assistant2__r.Email, '(办事处助理2)', toNameListWithoutAddonMessage, toMailList);
                        if (toNameListWithoutAddonMessage.size() == 0) {
                            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL, '没有设办事处助理无法发送应答沟通邮件');
                            Apexpages.addMessage(myMsg);
                            return;
                        }
                    }
                    else {
                        ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL, '此调拨单无法使用此功能');
                        Apexpages.addMessage(myMsg);
                        return;
                    }
                }
            }
        }
        else{
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL, '无效的调拨申请Id');
            Apexpages.addMessage(myMsg);
            return;
        }
    }
 
    private void setList(String userName, String userEmail, String msg, List<String> tomsgList, List<String> toEmailList) {
        if (String.isBlank(userEmail)) {
            return;
        }
        tomsgList.add(userName + msg);
        toEmailList.add(userEmail);
        toString += String.isBlank(toString) ? userEmail + msg : ',' + userEmail + msg;
    }
 
    // 保存按钮
    public PageReference saveBtn() {
        hasError = true;
 
        String response = cc.ResponseNew__c;
        if (response == null || response.trim().length() == 0) {
            cc.ResponseNew__c.addError('请输入内容。');
            //hasError=true;
            return null;
        }
 
        if (toNameListWithoutAddonMessage.size() == 0) {
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL, '没有设办事处助理无法发送应答沟通邮件');
            Apexpages.addMessage(myMsg);
            return null;
        }
 
        // 送信者
        String username = UserInfo.getName();
        // 发送时间
        Datetime dt = Datetime.now();
        // 相关用户检索
        List<Id> ccList = new List<Id>();
        ccList.add(ra.Contact_Person__c);
        ccList.add(ra.ApplyUser__c);
        if (cc.JingliApprovalManager__c != null) {
            ccList.add(cc.JingliApprovalManager__c);
        }
        if (cc.SalesManager__c != null) {
            ccList.add(cc.SalesManager__c);
        }
        if (cc.BuchangApprovalManager__c != null) {
            ccList.add(cc.BuchangApprovalManager__c);
        }
        if (cc.BuchangApprovalManagerSales__c != null) {
            ccList.add(cc.BuchangApprovalManagerSales__c);
        }
        if (cc.ZongJian__c != null) {
            ccList.add(cc.ZongJian__c);
        }
        Map<Id, User> userMap = new Map<Id, User>([
            select Id, Name, Email from User where Id in :ccList
        ]);
 
        // 抄送者
        List <String> ccNameList = new List<String> ();
        List<String> ccMailList = new List<String>();
        if(type == 'responseafter'){
 
            if (ra.RecordType.DeveloperName == 'AgencyToCenter' || ra.RecordType.DeveloperName == 'CenterToCenter') {
                if (String.isNotBlank(ra.AfterOCMAssetEmail_F__c)) {
                    ccNameList.add(ra.AfterOCMAssetEmail_F__c);
                    ccMailList.add(ra.AfterOCMAssetEmail_F__c);
                }
                if (String.isNotBlank(ra.AfterCheckEmail_F__c)) {
                    ccNameList.add(ra.AfterCheckEmail_F__c);
                    ccMailList.add(ra.AfterCheckEmail_F__c);
                }
            }
        }
        if (cc.JingliApprovalManager__c != null) {
            ccNameList.add(userMap.get(cc.JingliApprovalManager__c).Name);
            ccMailList.add(userMap.get(cc.JingliApprovalManager__c).Email);
        }
        if (cc.SalesManager__c != null) {
            ccNameList.add(userMap.get(cc.SalesManager__c).Name);
            ccMailList.add(userMap.get(cc.SalesManager__c).Email);
        }
        if (cc.BuchangApprovalManager__c != null) {
            ccNameList.add(userMap.get(cc.BuchangApprovalManager__c).Name);
            ccMailList.add(userMap.get(cc.BuchangApprovalManager__c).Email);
        }
        if (cc.BuchangApprovalManagerSales__c != null) {
            ccNameList.add(userMap.get(cc.BuchangApprovalManagerSales__c).Name);
            ccMailList.add(userMap.get(cc.BuchangApprovalManagerSales__c).Email);
        }
        if (cc.ZongJian__c != null) {
            ccNameList.add(userMap.get(cc.ZongJian__c).Name);
            ccMailList.add(userMap.get(cc.ZongJian__c).Email);
        }
 
        String toName = '';
        if (toNameListWithoutAddonMessage.size() > 0) {
            String toNameWithoutAddonMessage = String.join(toNameListWithoutAddonMessage,',');
            toName += toNameWithoutAddonMessage;
        }
 
        String ccName = '';
        if (ccNameList.size() > 0) {
            ccName = String.join(ccNameList,',');
        }
 
        // 原应答沟通信息
        String oldResponse = ra.Response__c;
        // 现应答沟通信息
        String temp = '';
        /*temp += '****** ' + username + ' ' + dt.format() + ' ******\n';
        temp += '*** To:' + toName + '\n';
        temp += '*** Cc:' + ccName + '\n';
        temp += cc.ResponseNew__c;
        if (oldResponse != null && oldResponse.trim().length() > 0) {
            temp += '\n\n' + oldResponse;
        } else {
            //于2016-07-01加入<a></a>
            temp += '\n\n备品调拨申请链接: ' + baseUrl + '/' + ra.Id +' ';
        }*/
        // 20211105 ljh 应答沟通 update start
        temp += '****** ' + username + ' ' + dt.format() + ' ******<br/>';
        temp += '*** To:' + toName + '<br/>';
        temp += '*** Cc:' + ccName + '<br/>';
        temp += cc.ResponseNew__c;
        if (oldResponse != null && oldResponse.trim().length() > 0) {
            temp += '<br/><br/>' + oldResponse;
        } else {
            //于2016-07-01加入<a></a>
            temp += '<br/><br/>备品调拨申请链接: ' + baseUrl + '/' + ra.Id +' ';
        }
        // 20211105 ljh 应答沟通 update end
 
        try {
            // 更新应答沟通
            TransferApply__c updra = new TransferApply__c();
            updra.Id = ra.Id;
            updra.Response__c = temp;
 
            update updra;
 
            //Create a dummy instance of outbound email object
    //        Messaging.SingleEmailMessage message= new Messaging.SingleEmailMessage();
            //set a roolback point
    //        Savepoint sp = Database.setSavepoint();
            //set desired email template id
    //        message.templateId = 'xxxxxx';
            //set the target object record id(this is mandatory while using email template)
    //        Id recId = [select Id from Contact where Email != null limit 1].id;
    //        message.targetObjectId = recId;
            //fire dummy email
    //        messaging.sendEmail(new Messaging.SingleEmailMessage[] {message});
            //roll back to savepoint so that email is not sent
    //        Database.rollback(sp);
            //Create insatnce of actual email
            Messaging.SingleEmailMessage messageNEW= new Messaging.SingleEmailMessage();
            //get the bode from above dummy instance and set it to your actual email
            //messageNEW.HTMLBody = message.getHtmlBody();
            //messageNEW.Subject = '备品借出申请' + ra.Name + '' + '应答沟通';
            messageNEW.Subject = ra.RecordType.Name + ' ' + ra.Name + ' ' +
                                // ra.Hospital__r.Name + ' ' +
                                // ra.Department_name__c + ' ' +
                                // ra.Demo_purpose1__c + '/' +
                                // ra.Demo_purpose2__c + ' ' +
                                // ra.GI_Diff__c
                                '-备品调拨申请联络';
            // 20211105 ljh 应答沟通 update start
            // messageNEW.PlainTextBody = temp;
            messageNEW.HtmlBody = temp;
            // 20211105 ljh  应答沟通 update end
            //set desired email addresses
            messageNEW.setCharset('UTF-8');
            messageNEW.toAddresses = toMailList;
            messageNEW.ccAddresses = ccMailList;
            //send the mail
            Messaging.SendEmailResult[] results = messaging.sendEmail(new Messaging.SingleEmailMessage[] {messageNEW});
            if(!results[0].success){
                system.debug('=====' + results[0].errors[0].message);
                cc.ResponseNew__c.addError('邮件发送失败。');
                return null;
                //hasError=true;
            }else{
                //邮件发送成功
                // 更新申请受理时间
                if (ra.Application_accept_time__c == null && type == 'responseafter') {
                    TransferApply__c upAppTime = new TransferApply__c();
                    upAppTime.Id = ra.Id;
                    upAppTime.Application_accept_time__c = dt;
                    update upAppTime;
                }
                hasError=false;
                return null;
            }
        } catch (Exception ex) {
            system.debug('=====' + ex.getMessage());
            //hasError = true;
            ApexPages.addMessages(ex);
            return null;
        }
 
        // return null;
    }
 
    
}