public without sharing class ConsumEquipmentRentalResponseController {
    // 借出申请
    public Consum_Apply__c ra { get; set; }
    /**
     * 1.画面输入用借出申请
     * 2.邮件cc用，最多5个
     * 经理(服务) JingliApprovalManager__c        => cc_1
     * 经理(销售) SalesManager__c                 => cc_2
     * 部长(服务) BuchangApprovalManager__c       => cc_3
     * 部长(销售) BuchangApprovalManagerSales__c  => cc_4
     * 总监       ZongjianApprovalManager__c      => cc_5
     */
    public Consum_Apply__c cc { get; set; }
    // 借出申请ID
    public Id raid { get; private set; }
    // To:备品中心(response2center),To:申请者(response2user)
    public String type { get; set; }

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


    public ConsumEquipmentRentalResponseController() {
        //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');
    }

    public ConsumEquipmentRentalResponseController(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;
        }

        List<Consum_Apply__c> raList = [
                SELECT Id
                     , Name
                     , Response__c
                     , ResponseNew__c
                     , Person_In_Charge__c
                     , Person_In_Charge__r.Name
                     , Person_In_Charge__r.Email
                     , ApplyUser__c
                     , ApplyUser__r.Name
                     , ApplyUser__r.Email
                     , Loaner_centre_mail_address__c
                     //, Demo_purpose1__c
                     , Demo_purpose2__c
                     , SalesManager__c
                     , JingliApprovalManager__c
                     , Department_name__c
                     , Hospital__r.Name
                     //, GI_Diff__c
                     , Application_accept_time__c
                     , Consum_Assistant__c
                     , Consum_Assistant2__c
                     , Consum_Assistant3__c
                  FROM Consum_Apply__c
                 WHERE Id = :raid];
        if (raList.size() > 0) {
            ra = raList[0];
            cc = raList[0];
        }
        else{
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL, '无效的耗材申请Id');
            Apexpages.addMessage(myMsg);
            return;
        }

        cc.JingliApprovalManager__c = null;
        cc.SalesManager__c = null;
        cc.BuchangApprovalManager__c = null;
        cc.BuchangApprovalManagerSales__c = null;
        cc.ZongjianApprovalManager__c = null;
        cc.ResponseNew__c = null;

        // 邮件默认cc
        if (type == 'response2center') {
            // 删除了根据使用目的设定CC人的逻辑
        //    //(备品借出申请: 使用目的1等于其他)) :抄送销售部长
        //    if (ra.Demo_purpose1__c == '其他') {
        //          cc.JingliApprovalManager__c = ra.SalesManager__c;
        //    } else{

        //        //((备品借出申请: 使用目的2等于引发询价,询价跟进,已购待货,学会展会,新产品评价)
        //        //抄送销售经理
        //        if (ra.demo_purpose2__c == FixtureUtil.raDemo_purpose2MAP.get('shiyongwuxunjia') ||
        //                ra.demo_purpose2__c == FixtureUtil.raDemo_purpose2MAP.get('shiyongyouxunjia') ||
        //                ra.demo_purpose2__c == FixtureUtil.raDemo_purpose2MAP.get('yigoudaihuo') ||
        //                ra.demo_purpose2__c == FixtureUtil.raDemo_purpose2MAP.get('xuehuizhanhui') ||
        //                ra.demo_purpose2__c == FixtureUtil.raDemo_purpose2MAP.get('xinchanpinpingjia')) {
        //            cc.JingliApprovalManager__c =  ra.SalesManager__c;
        //        }

        //        //(备品借出申请: 使用目的2等于索赔QIS,一般用户)
        //        //抄送服务经理
        //        if (ra.demo_purpose2__c == FixtureUtil.raDemo_purpose2MAP.get('suopeiQIS') ||
        //                ra.demo_purpose2__c == FixtureUtil.raDemo_purpose2MAP.get('zaixiuli') ||
        //                ra.demo_purpose2__c == FixtureUtil.raDemo_purpose2MAP.get('yibanyonghu')){
        //            // OLY_OCM-585 因为逻辑里面没有使用到这里设置的值,所以不需要修改 Start
        //            cc.JingliApprovalManager__c = ra.JingliApprovalManager__c;
        //            // OLY_OCM-585 End
        //        }

        //        //(备品借出申请: 使用目的2等于临床研究,保修用户,培训中心)
        //        //不需要抄送经理
        //        if (ra.demo_purpose2__c == FixtureUtil.raDemo_purpose2MAP.get('linchuangyanjiu') ||
        //                ra.demo_purpose2__c == FixtureUtil.raDemo_purpose2MAP.get('baoxiuyonghu') ||
        //                ra.demo_purpose2__c == '培训中心') {
        //            cc.JingliApprovalManager__c = ra.ApplyUser__c;
        //        }
        //    }
        }
        else if(type == 'response2user' ){
            // CC给备品助理、备品助理2、备品助理3、备品中心的邮箱地址。 备品中心的邮箱不作为可选项,此处未设置
            cc.JingliApprovalManager__c = ra.Consum_Assistant__c;
            cc.SalesManager__c = ra.Consum_Assistant2__c;
            cc.BuchangApprovalManager__c = ra.Consum_Assistant3__c;
        }
    }

    // 保存按钮
    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;
        }


        // 送信者
        String username = UserInfo.getName();
        // 发送时间
        Datetime dt = Datetime.now();
        // 相关用户检索
        List<Id> ccList = new List<Id>();
        ccList.add(ra.Person_In_Charge__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.ZongjianApprovalManager__c != null) {
            ccList.add(cc.ZongjianApprovalManager__c);
        }

        Map<Id, User> userMap = new Map<Id, User>([
            select Id, Name, Email from User where Id in :ccList
        ]);
        // 收信者
        List <String> toNameListWithoutAddonMessage = new List<String> ();
        List <String> toNameListWithAddonMessage = new List<String> ();

        List<String> toMailList = new List<String>();
        if (type == 'response2center') {
            toNameListWithoutAddonMessage.add(ra.Loaner_centre_mail_address__c);
            toMailList.add(ra.Loaner_centre_mail_address__c);
        } else if (type == 'response2user') {
            toNameListWithoutAddonMessage.add(userMap.get(ra.Person_In_Charge__c).Name);
            toNameListWithAddonMessage.add(userMap.get(ra.ApplyUser__c).Name + '（操作者）');
            toMailList.add(userMap.get(ra.Person_In_Charge__c).Email);
            toMailList.add(userMap.get(ra.ApplyUser__c).Email);
        }

        // 抄送者
        List <String> ccNameList = new List<String> ();
        List<String> ccMailList = new List<String>();
        if(type == 'response2user'){
            ccNameList.add(ra.Loaner_centre_mail_address__c);
            ccMailList.add(ra.Loaner_centre_mail_address__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.ZongjianApprovalManager__c != null) {
            ccNameList.add(userMap.get(cc.ZongjianApprovalManager__c).Name);
            ccMailList.add(userMap.get(cc.ZongjianApprovalManager__c).Email);
        }

        String toName = '';
        if (toNameListWithoutAddonMessage.size() > 0) {
            String toNameWithoutAddonMessage = String.join(toNameListWithoutAddonMessage,'，');
            toName += toNameWithoutAddonMessage;
        }
        if (toNameListWithAddonMessage.size() > 0) {
            String toNameWithAddonMessage = String.join(toNameListWithAddonMessage,'，');
            toName += '，' + toNameWithAddonMessage;
        }
        String ccName = '';
        if (ccNameList.size() > 0) {
            ccName = String.join(ccNameList,'，');
        }

        // 原应答沟通信息
        String oldResponse = ra.Response__c;
        // 现应答沟通信息
        String temp = '';
        
        // 20211105 ljh 应答沟通 update start
        /*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 +' ';
        }*/
        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 {
            // 更新应答沟通
            Consum_Apply__c updra = new Consum_Apply__c();
            updra.Id = ra.Id;
            updra.Response__c = temp;

            update updra;

            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.Name + ' ' +
                                ra.Hospital__r.Name + ' ' +
                                ra.Department_name__c + ' ' +
                                ra.Demo_purpose2__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('邮件发送失败。');
                throw new ControllerUtil.myException('邮件发送失败。');
                return null;
                //hasError=true;
            }else{
                //邮件发送成功
                // 更新申请受理时间
                if (ra.Application_accept_time__c == null && type == 'response2user') {
                    Consum_Apply__c upAppTime = new Consum_Apply__c();
                    upAppTime.Id = ra.Id;
                    upAppTime.Application_accept_time__c = dt;
                    update upAppTime;
                }
                Apexpages.Message msg = new ApexPages.message(ApexPages.severity.INFO, '邮件发送成功');
                ApexPages.addmessage(msg);
                hasError=false;
                return null;
            }
        } catch (Exception ex) {
            system.debug('=====' + ex.getMessage());
            //hasError = true;
            ApexPages.addMessages(ex);
            return null;
        }

        return null;
    }

    @TestVisible private static void test() {
        if (false == Test.isRunningTest()) return;
        Integer i = 0;
        
    }
}