public without sharing class AccChangeApprovalResponseController {
    // 客户变更申请
    public Account_Delay_Apply__c ra { get; set; }
    public Account_Delay_Apply__c cc { get; set; }
    // 客户ID
    public Id accid { get; private set; }
    // To:当前审批人(response2system),To:申请者(response2user)
    public String type { get; set; }

    public Boolean hasError { get; private set; }
    public String baseUrl { get; private set; }

    public User systemUser { get; set; }

    public AccChangeApprovalResponseController() {
        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        accid = ApexPages.currentPage().getParameters().get('accid');
        type = ApexPages.currentPage().getParameters().get('type');
    }

    public AccChangeApprovalResponseController(ApexPages.StandardController stdController) {
        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        accid = stdController.getId();
        type = ApexPages.currentPage().getParameters().get('type');
    }

    // 画面初始化
    public void init() {
        hasError = true;
        List<Account_Delay_Apply__c> raList = [select Id, Name, Is_Active__c, Response__c, 
                                                      ResponseNew__c, CreatedById, CreatedBy.Name, 
                                                      CreatedBy.Email, Response_Cc_User1__c, 
                                                      Response_Cc_User2__c, Response_Cc_User3__c, 
                                                      Response_Cc_User4__c, Response_Cc_User5__c,
                                                      Response_Cc_User6__c
                                               from Account_Delay_Apply__c 
                                               where id = : accid ];
        
        if (raList.size() > 0) {
            ra = raList[0];
            cc = raList[0];
        }
        cc.Response_Cc_User1__c = null;
        cc.Response_Cc_User2__c = null;
        cc.Response_Cc_User3__c = null;
        cc.Response_Cc_User4__c = null;
        cc.Response_Cc_User5__c = null;
        cc.Response_Cc_User6__c = null;

        // List<User> toSysUser = [select Id, Name, Email from User where Id = : System.Label.LeaderID_Zhu];
        // if (toSysUser.size() > 0) {
        //     systemUser = toSysUser[0];
        // }

        // 邮件默认cc
        if (type == 'response2system') {
            
        } else if (type == 'response2user') {
            
        }
    }

    // 保存按钮
    public PageReference saveBtn() {
        hasError = true;

        String response = cc.ResponseNew__c;
        if (String.isBlank(response) == true || response.trim().length() == 0) {
            cc.ResponseNew__c.addError('请输入内容。');
            return null;
        }

        
        // 送信者
        String username = UserInfo.getName();
        // 发送时间
        Datetime dt = Datetime.now();
        // 相关用户检索
        List<Id> ccList = new List<Id>();
        if (String.isBlank(cc.Response_Cc_User1__c) == false) {
            ccList.add(cc.Response_Cc_User1__c);
        }
        if (String.isBlank(cc.Response_Cc_User2__c) == false) {
            ccList.add(cc.Response_Cc_User2__c);
        }
        if (String.isBlank(cc.Response_Cc_User3__c) == false) {
            ccList.add(cc.Response_Cc_User3__c);
        }
        if (String.isBlank(cc.Response_Cc_User4__c) == false) {
            ccList.add(cc.Response_Cc_User4__c);
        }
        if (String.isBlank(cc.Response_Cc_User5__c) == false) {
            ccList.add(cc.Response_Cc_User5__c);
        }
        Map<Id, User> userMap = new Map<Id, User>([
            select Id, Name, Email from User where Id in :ccList
        ]);

        List<Id> toList = new List<Id>();
        if (String.isBlank(cc.Response_Cc_User6__c) == false) {
            toList.add(cc.Response_Cc_User6__c);
        }
        Map<Id, User> touserMap = new Map<Id, User>([
            select Id, Name, Email from User where Id in :toList
        ]);

        // 收信者
        String toName = '';
        List<String> toMailList = new List<String>();
        if (type == 'response2system') {
            // toName = systemUser.Name;
            // toMailList.add(systemUser.Email);
            if (touserMap.size() > 0) {
                for (Id id : touserMap.keySet()) {
                    toName += touserMap.get(id).Name + ', ';
                    toMailList.add(touserMap.get(id).Email);
                }
            }
            System.debug('lt123---toname---'+toName);
            System.debug('lt123---String.isBlank(toName)---'+String.isBlank(toName));
            if (toName != '') {
                toName = toName.left(toName.length() - 2);
            }else if(String.isBlank(toName) == true){
                cc.Response_Cc_User6__c.addError('to审批人必填。');
                return null;
            }
        } else if (type == 'response2user') {
            toName = ra.CreatedBy.Name;
            toMailList.add(ra.CreatedBy.Email);
        }
        // 抄送者
        String ccName = '';
        List<String> ccMailList = new List<String>();


        //WLIG-BS2CJW  ---20200807---update By rentongxiao ---Start
        //获取 郭 和 油 的信息
        // String ydIdsStr = System.Label.LeaderId_YD;
        // List<String> ydIds = ydIdsStr.split(',');

        // List<User> yds = [select Id, Name, Email from User where Id in : ydIds];

        // if(type == 'response2user'){
        //     // ccName += systemUser.Name + ', ';
        //     // ccMailList.add(systemUser.Email);
        //     if (yds.size() > 0) {
        //         for(User u : yds){
        //             ccName += u.Name +', ';
        //             ccMailList.add(u.Email);
        //         }
        //     }
        // }

        //WLIG-BS2CJW ---20200807---update By rentongxiao---End

        if (userMap.size() > 0) {
            for (Id id : userMap.keySet()) {
                ccName += userMap.get(id).Name + ', ';
                ccMailList.add(userMap.get(id).Email);
            }
        }

        if (ccName != '') {
            ccName = ccName.left(ccName.length() - 2);
        }

        // 原应答沟通信息
        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 +' ';
        }

        try {
            //Create insatnce of actual email
            Messaging.SingleEmailMessage messageNEW= new Messaging.SingleEmailMessage();

            messageNEW.Subject = '客户变更 ' + ra.Name + ' -审批联络';
            messageNEW.PlainTextBody = temp;
            //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){
                cc.ResponseNew__c.addError('邮件发送失败。');
                return null;
            }else{
                // 更新应答沟通
                Account_Delay_Apply__c updacc = new Account_Delay_Apply__c();
                updacc.Id = ra.Id;
                updacc.Response__c = temp;
                update updacc;

                hasError=false;
                return null;
            }
        } catch (Exception ex) {
            ApexPages.addMessages(ex);
            return null;
        }
    }
}