public without sharing class SendEmailController{

    public Mail_Merge__c mail{get; set;}

    public String id{get;set;}

    public String openType{get;set;}

    public String handleType{get;set;}

    public String errorMessage{get;set;}

    public Integer lineNum{get;set;}

    public String fileId{get;set;}

    public String type{get;set;}

    public String typeid{get;set;}

    public Integer allFileSize{get;set;}

    public Attachment attachment{get;set;}

    public List<Attachment> attachmentList{get;set;}
    public List<FileAddress__c> newAttachmentList{get;set;}

    //SWO_Email_Member__c 这个对象只是为了生成页面上的人员明细行
    // public List<SWO_Email_Member__c> lineDataList_new{get;set;}
    public List<MemberLine> memberLineDatas{get;set;}
    //用于接收人员查找页面查找返回的数据
    public String memberName{get;set;}
    //用于接收人员查找页面查找返回的数据
    public String memberEmail{get;set;}
    //用于接收人员查找页面查找返回的数据
    public String memberId{get;set;}

    public String baseUrl {get;set;}

    public String name {get;set;}

    public Boolean isOnClick{get;set;}


    public List<String> toAddresses ;
    public List<String> ccAddresses ;
    public List<String> bccAddresses ;

    public String AWSDataId{get;set;}
    public String staticResourceMail{get;set;}
    public String staticResourceMailMerge{get;set;}
    public String staticResourceDocument{get;set;}
    public SendEmailController() {
        id = System.currentPageReference().getParameters().get('id');
        type = System.currentPageReference().getParameters().get('type');
        typeid = System.currentPageReference().getParameters().get('typeid');
        openType = System.currentPageReference().getParameters().get('openType');
        staticResourceMail = JSON.serialize(PIHelper.getPIIntegrationInfo('Mail'));
        staticResourceMailMerge = JSON.serialize(PIHelper.getPIIntegrationInfo('Mail_Merge__c'));
        staticResourceDocument = JSON.serialize(PIHelper.getPIIntegrationInfo('Document'));
    }

    public SendEmailController(ApexPages.StandardController controller) {
        // 20220318 PI 改造 By Bright start
        // id = System.currentPageReference().getParameters().get('id');
        // type = System.currentPageReference().getParameters().get('type');
        // typeid = System.currentPageReference().getParameters().get('typeid');
        // openType = System.currentPageReference().getParameters().get('openType');
        this();
        // 20220318 PI 改造 By Bright end
    }

    public void init(){
        //URL获取
        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        String path = URL.getCurrentRequestUrl().getPath();
        if (path.indexOf('/apex') > 0) {
            baseUrl += path.substring(0,path.indexOf('/apex'));
        } else if (path.indexOf('production/') > 0) {
            baseUrl += '/production';
        }


        attachment = new Attachment();
        mail = new Mail_Merge__c();
        mail.RECORD__c = typeid;
        mail.RECORD_TYPE__c = type;
        memberLineDatas = new List<MemberLine>();

        if (!string.isBlank(typeid)) {
            Id rid = typeid;
            String sobjname = 'User_FaultInfo__c';
            sobjname = rid.getSobjectType().getDescribe().getName();
            List<sobject> lso = Database.query('select id,name from '+sobjname+' where id = :rid');
            System.debug('lso='+lso);
            if (lso.size()>0) {
                name = sobjname.replace('__c','')+':'+lso[0].get('Name');
                if (sobjname == 'User_FaultInfo__c') {
                    name = 'Case:'+lso[0].get('Name');
                }
            }
            System.debug('name='+name);
        }
        

        if(id == null){
            isOnClick = false;
            mail.FROM__c = UserInfo.getUserEmail();
            mail.TYPE__c = 'send';        
            MemberLine member = new MemberLine();
            member.lineNum = 0;
            member.to = true;
            memberLineDatas.add(member);
            // SWO不是批准后状态不能发送邮件
            if ('Quotes'.equals(mail.RECORD_TYPE__c)) {
                List<Quotes__c> quotesList = new List<Quotes__c>();
                quotesList = [SELECT  Id, Name, BILLING_SCHEDULE__c, BILL_TO__c, SHIP_TO__c, BILL_TO_SELECT__c,SWOStatusMark__c  FROM Quotes__c WHERE Id = :typeid];
                
                if (quotesList.size() > 0 ) {
                    if (quotesList[0].SWOStatusMark__c < 2) {
                        isOnClick = true;
                    }    
                }
            }
        }else{
            

            mail = [select id,send__c,MESSAGE__c,SUBJECT__c,TYPE__c,FROM__c,DATE__c,RECIPIENT__c,CC__c,BCC__c,RECORD__c,RECORD_TYPE__c,toName__c,ccName__c,bccName__c,ALL_MEMBER__c,ALL_MEMBER_NAME__c,ALL_MEMBER_TYPE__c,EMAIL_SENT__c,SWO__c,CaseF__c,Quotes__c,
            AWS_Data_Id__c // 20220222 PI改造 by Brigh
            from Mail_Merge__c where id =:id];
            AWSDataId=mail.AWS_Data_Id__c;
            //mail.TYPE__c == 'reply' 邮件为回复邮件 或者是系统自动发送的邮件
            //EMAIL_SENT__c =='YES' 邮件已发送
            if(mail.TYPE__c == 'reply' || mail.EMAIL_SENT__c =='YES'){
                //isOnClick = true; 在邮件页面所有的按钮都不可点击
                isOnClick = true;
            }
            type = mail.RECORD_TYPE__c;
            if(mail.RECORD_TYPE__c == 'SWO') typeid = mail.SWO__c;
            if(mail.RECORD_TYPE__c == 'Case') typeid = mail.CaseF__c;
            if(mail.RECORD_TYPE__c == 'Quotes') typeid = mail.Quotes__c;
            mail.RECORD__c = typeid;
            typeid = mail.RECORD__c;
            List<String> allEmails = String.isNotBlank(mail.ALL_MEMBER__c)?mail.ALL_MEMBER__c.split(';'):new List<String>();
            List<String> allName = String.isNotBlank(mail.ALL_MEMBER_NAME__c)?mail.ALL_MEMBER_NAME__c.split(';'):new List<String>();
            List<String> allType = String.isNotBlank(mail.ALL_MEMBER_TYPE__c)?mail.ALL_MEMBER_TYPE__c.split(';'):new List<String>();
            
            if(String.isNotBlank(openType) && openType == 'Reply' && mail.EMAIL_SENT__c == 'YES'){
                if(mail.EMAIL_SENT__c == 'YES' || mail.TYPE__c == 'reply'){
                    mail.Id = null;
                    mail.EMAIL_SENT__c = 'NO';
                }
                mail.TYPE__c = 'send';
                isOnClick = false;
                //mail.DATE__c = Datetime.now();
                if(String.isNotBlank(UserInfo.getUserEmail()) && !UserInfo.getUserEmail().equals(mail.FROM__c)){
                    MemberLine member_line = new MemberLine();
                    member_line.emailAddress = mail.FROM__c;
                    member_line.name = '';
                    member_line.to = true;
                    member_line.cc = false;
                    member_line.bcc = false;
                    member_line.lineNum = 0;
                    memberLineDatas.add(member_line);
                }
                isOnClick = false;
                String mailToAddressName = '';
                String mailCcAdressName = '';
                if(allEmails.size() != 0){
                    for(Integer i = 0 ; i<allEmails.size() ; i++){
                        if(allType[i] == 'to'){
                            mailToAddressName += allEmails[i]+'；';
                        }
                        if(allType[i] == 'cc'){
                            mailCcAdressName += allEmails[i]+'；';
                        }
                    }
                }
                String replyEmailHead = '';
                replyEmailHead    = '\n\n\n\n';
                replyEmailHead    += '-------------邮件原件--------------\n';
                replyEmailHead    += '发件人：' + mail.FROM__c + ';\n';
                replyEmailHead    += '发件时间：' + (mail.DATE__c==null?Datetime.now():mail.DATE__c.addHours(8)) + ';\n';
                replyEmailHead    += '收件人：' + mailToAddressName + '\n';
                replyEmailHead    += '抄送：' + mailCcAdressName + '\n';
                replyEmailHead    += '主题：' + mail.SUBJECT__c + ';\n\n';
                mail.MESSAGE__c   = replyEmailHead+(String.isNotBlank(mail.MESSAGE__c)?mail.MESSAGE__c:'');
                
                if(String.isNotBlank(mail.SUBJECT__c) && !mail.SUBJECT__c.replaceAll(' ','').contains('回复')){
                    mail.SUBJECT__c = '回复:'+mail.SUBJECT__c;
                }
            }

            if(allEmails.size() != 0){
                for(Integer i = 0 ; i<allEmails.size() ; i++){
                    MemberLine member_line = new MemberLine();
                    member_line.emailAddress = allEmails[i];
                    if(String.isNotBlank(openType) && openType == 'Reply'){
                        if(allEmails[i].equals(UserInfo.getUserEmail())){
                            continue;
                        }
                    }
                    //拆分name时 如果是拆分出“-”，则name为空
                    member_line.name = allName[i]=='-'?'':allName[i];
                    if(allType[i] == 'to'){
                        member_line.to = true;
                        member_line.cc = false;
                        member_line.bcc = false;
                    }
                    if(allType[i] == 'cc'){
                        member_line.to = false;
                        member_line.cc = true;
                        member_line.bcc = false;
                    }
                    if(allType[i] == 'bcc'){
                        member_line.to = false;
                        member_line.cc = false;
                        member_line.bcc = true;
                    }
                    member_line.lineNum = i+memberLineDatas.size();
                    memberLineDatas.add(member_line);
                }
            }else{
                 /*MemberLine member_line = new MemberLine();
                 member_line.lineNum = 0;
                 member_line.to = true;
                 memberLineDatas.add(member_line);*/
                 addLine();
            }
            attachmentList = [select Id,Name,CreatedDate,BodyLength,Body from Attachment where ParentId=:id];
            newAttachmentList = [select Id,CreatedDate,Name,ViewLink__c,AWS_File_Key__c,FileName__c from FileAddress__c where ParentRecordId__c=:id];
            /*if(String.isNotBlank(openType) && openType == 'Reply'){
                attachmentList.clear();
            }*/
        }
        mail.DATE__c = Datetime.now();
        mail.FROM__c = UserInfo.getUserEmail();
    }

    public PageReference SendEmail(){
        save();
        // System.debug('进入邮件发送');
        // List<String> toAddresses = new List<String>();
        // List<String> ccAddresses = new List<String>();
        // List<String> bccAddresses = new List<String>();
        // mail.RECIPIENT__c = '';
        // mail.toName__c = '';
        // mail.CC__c = '';
        // mail.ccName__c = '';
        // mail.BCC__c = '';
        // mail.bccName__c = '';
        // mail.ALL_MEMBER__c = '';
        // mail.ALL_MEMBER_NAME__c = '';
        // mail.ALL_MEMBER_TYPE__c = '';
        // if(memberLineDatas!=null && memberLineDatas.size()!=0){
        //     System.debug('memberLineDatas--->'+memberLineDatas);
        //     //拼接邮件收件信息
        //     for(MemberLine line : memberLineDatas){
        //         if(String.isNotBlank(line.emailAddress)){
        //             mail.ALL_MEMBER__c = mail.ALL_MEMBER__c + line.emailAddress + ';';
        //             //手动输入邮件地址时 name会空 用-占位保存 用于初始化时拆分
        //             mail.ALL_MEMBER_NAME__c = mail.ALL_MEMBER_NAME__c + (String.isNotBlank(line.name) ? line.name : '-') + ';';
        //             if(line.to){
        //                 if(String.isNotBlank(line.emailAddress)){
        //                     toAddresses.add(line.emailAddress);
        //                     mail.RECIPIENT__c = mail.RECIPIENT__c + line.emailAddress + ';';
        //                     mail.toName__c = mail.toName__c + (String.isNotBlank(line.name) ? line.name : line.emailAddress) + ';';
        //                     mail.ALL_MEMBER_TYPE__c = mail.ALL_MEMBER_TYPE__c + 'to;';
        //                 }
        //             }
        //             if(line.cc){
        //                 if(String.isNotBlank(line.emailAddress)){
        //                     ccAddresses.add(line.emailAddress);
        //                     mail.CC__c = mail.CC__c + line.emailAddress + ';';
        //                     mail.ccName__c = mail.ccName__c + (String.isNotBlank(line.name) ? line.name : line.emailAddress) + ';';
        //                     mail.ALL_MEMBER_TYPE__c = mail.ALL_MEMBER_TYPE__c + 'cc;';
        //                 }
        //             }
        //             if(line.bcc){
        //                 if(String.isNotBlank(line.emailAddress)){
        //                     bccAddresses.add(line.emailAddress);
        //                     mail.BCC__c = mail.BCC__c + line.emailAddress + ';';
        //                     mail.bccName__c = mail.bccName__c + (String.isNotBlank(line.name) ? line.name : line.emailAddress) + ';';
        //                     mail.ALL_MEMBER_TYPE__c = mail.ALL_MEMBER_TYPE__c + 'bcc;';
        //                 }
        //             }
        //         }
        //     }
        // }
        // if('SWO'.equals(mail.RECORD_TYPE__c)){
        //     mail.SWO__c = mail.RECORD__c;
        //     SWO__c swo = [select Id,Name from SWO__c where Id=:mail.RECORD__c];
        //     name = 'SWO:'+swo.Name;
        // }
        // if('Case'.equals(mail.RECORD_TYPE__c)){
        //     mail.CaseF__c = mail.RECORD__c;
        //     User_FaultInfo__c caseInfo = [select Id,Name from User_FaultInfo__c where Id=:mail.RECORD__c];
        //     name = 'Case:'+caseInfo.Name;
        // }
        // if('Quotes'.equals(mail.RECORD_TYPE__c)){
        //     mail.Quotes__c = mail.RECORD__c;
        //     Quotes__c quotes = [select Id,Name from Quotes__c where Id=:mail.RECORD__c];
        //     name = 'Quotes:'+quotes.Name;
        // }
        // //判断是否时点击发送按钮，进入提交方法
        // if(String.isNotBlank(handleType) && !'send'.equals(handleType)){
        //     mail.EMAIL_SENT__c = 'NO';
        //     upsert mail;
        //     id = mail.Id;
        // }
        System.debug('邮件标题mail.subject'+mail.SUBJECT__c);
        System.debug('邮件Name'+mail.toName__c);
        errorMessage = '';
        System.debug('handleType:'+handleType);
        //点击发送按钮，并且邮件接收地址不为空 发送邮件
        if(String.isNotBlank(handleType) && 'send'.equals(handleType)){
            if(toAddresses.size()!=0){
                mail.DATE__c = Datetime.now();
                if(String.isNotBlank(mail.SUBJECT__c) && String.isNotBlank(mail.MESSAGE__c)){
                    //关联信息拼入到标题中供，回复邮件关联使用
                    //mail.SUBJECT__c = mail.SUBJECT__c;
                    mail.Name = mail.SUBJECT__c;
                    mail.SUBJECTCOPY__c = mail.SUBJECT__c + '~' + (name!=null ? name : '');
                    System.debug('标题：'+mail.SUBJECTCOPY__c);
                    Messaging.SingleEmailMessage sendMail = new Messaging.SingleEmailMessage();
                    sendMail.setToAddresses(toAddresses);
                    sendMail.setBccAddresses(bccAddresses);
                    //sendMail.setReplyTo('');
                    sendMail.setSubject(mail.SUBJECTCOPY__c);
                    sendMail.setPlainTextBody(mail.MESSAGE__c);
                    sendMail.setBccSender(false);
                    sendMail.setUseSignature(false);
                    //如果给客户发送报价单SWO需要抓取发送时间 是否抓取时间的标记
                    Boolean isSaveTime = false;
                    if(attachmentList!=null&&attachmentList.size()!=0){
                        List<Messaging.EmailFileAttachment> sendMailFileList = new List<Messaging.EmailFileAttachment>();
                        for(Attachment att : attachmentList){
                            Messaging.EmailFileAttachment sendMailFile = new Messaging.EmailFileAttachment();
                            sendMailFile.setBody(att.Body);
                            sendMailFile.setFileName(att.Name);
                            //报价页面发送邮件，如果包含“报价单”开头的附件则SWO需要抓取当前时间
                            if('Quotes'.equals(mail.RECORD_TYPE__c) && att.Name.startsWith('报价单')){
                                // isSaveTime = true;
                                continue;
                            }
                            sendMailFileList.add(sendMailFile);
                        }
                        if (!isSaveTime && 'Quotes'.equals(mail.RECORD_TYPE__c)) {
                            sendMailFileList.add(SendEmailaddPDF());
                            isSaveTime = true;
                        }
                        sendMail.setFileAttachments(sendMailFileList);
                    } else {
                        List<Messaging.EmailFileAttachment> sendMailFileList = new List<Messaging.EmailFileAttachment>();
                        if ('Quotes'.equals(mail.RECORD_TYPE__c)) {
                            sendMailFileList.add(SendEmailaddPDF());
                            isSaveTime = true;
                        }
                        sendMail.setFileAttachments(sendMailFileList);
                        isSaveTime = true;
                    }
                    //三种邮件客户回复时，回复到不同的邮件服务监听中。
                    if('SWO'.equals(mail.RECORD_TYPE__c)){
                        SWO__c swo = new SWO__c();
                        swo.Id =  mail.RECORD__c;
                        //标记跳过邮件回复监听
                        swo.notSaveEmail__c = true;
                        update swo;
                    }
                    if('Case'.equals(mail.RECORD_TYPE__c)){
                        User_FaultInfo__c caseInfo = new User_FaultInfo__c();
                        caseInfo.Id = mail.RECORD__c;
                        //标记跳过邮件回复监听
                        caseInfo.notSaveEmail__c = true;
                        update caseInfo;
                    }
                    if('Quotes'.equals(mail.RECORD_TYPE__c)){
                        Quotes__c quotes = [select Id,Name,notSaveEmail__c,SWO__c,SWO__r.Quotation_send__c from Quotes__c where Id=:mail.RECORD__c];
                       /* Quotes__c quotes = new Quotes__c();
                        quotes.Id = mail.RECORD__c;*/
                        //标记跳过邮件回复监听
                        quotes.notSaveEmail__c = true;
                        update quotes;
                        if (isSaveTime && String.isNotBlank(quotes.SWO__c) && quotes.SWO__r.Quotation_send__c == null) {
                            SWO__c swo = new SWO__c();
                            swo.Id = quotes.SWO__c;
                            swo.Quotation_send__c = Datetime.now();
                            update swo;
                        }    
                    }

                
                    //ccAddresses.add('email@sqtxllncwbyghx9lphlh50gefur2jyyj95io4r968llbumzh7.0t-8aptuaq.cs112.apex.sandbox.salesforce.com');
                    ccAddresses.add(System.label.EmailComeBackListen);
                    ccAddresses.add('dai_Prectech@olympus.com.cn');
                    ccAddresses.add('Xin_Prectech@olympus.com.cn');

                    sendMail.setCcAddresses(ccAddresses);
                    system.debug('=====sendMail---->'+sendMail);
                    Messaging.SendEmailResult[] result_list = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { sendMail });
                    for (Integer i = 0; i < result_list.size(); i++) {
                        if (result_list[i].success == true ) {
                            system.debug('=====send mail success');
                        } else {
                            system.debug('=====send mail error:' + result_list[i].errors[0].message);
                        }
                    }
                    mail.EMAIL_SENT__c = 'YES';
                    System.debug('mail='+mail);
                    upsert mail;
                    // 返回点击邮件页面
                    PageReference ref = new Pagereference('/'+mail.RECORD__c+'?type=mail');
                    ref.setRedirect(true);
                    return ref;
                }else{
                    errorMessage='邮件标题和信息不可为空！';
                }
            }else{
                errorMessage='必须至少有一个收件人！';
            }
        }
        return null;
    }

    public void save() {
        System.debug('handleType='+handleType);
        toAddresses = new List<String>();
        ccAddresses = new List<String>();
        bccAddresses = new List<String>();

        // System.debug('进入邮件发送');
        // List<String> toAddresses = new List<String>();
        // List<String> ccAddresses = new List<String>();
        // List<String> bccAddresses = new List<String>();
        mail.RECIPIENT__c = '';
        mail.toName__c = '';
        mail.CC__c = '';
        mail.ccName__c = '';
        mail.BCC__c = '';
        mail.bccName__c = '';
        mail.ALL_MEMBER__c = '';
        mail.ALL_MEMBER_NAME__c = '';
        mail.ALL_MEMBER_TYPE__c = '';
        if(memberLineDatas!=null && memberLineDatas.size()!=0){
            System.debug('memberLineDatas--->'+memberLineDatas);
            //拼接邮件收件信息
            for(MemberLine line : memberLineDatas){
                if(String.isNotBlank(line.emailAddress)){
                    mail.ALL_MEMBER__c = mail.ALL_MEMBER__c + line.emailAddress + ';';
                    //手动输入邮件地址时 name会空 用-占位保存 用于初始化时拆分
                    mail.ALL_MEMBER_NAME__c = mail.ALL_MEMBER_NAME__c + (String.isNotBlank(line.name) ? line.name : '-') + ';';
                    if(line.to){
                        if(String.isNotBlank(line.emailAddress)){
                            toAddresses.add(line.emailAddress);
                            mail.RECIPIENT__c = mail.RECIPIENT__c + line.emailAddress + ';';
                            mail.toName__c = mail.toName__c + (String.isNotBlank(line.name) ? line.name : line.emailAddress) + ';';
                            mail.ALL_MEMBER_TYPE__c = mail.ALL_MEMBER_TYPE__c + 'to;';
                        }
                    }
                    if(line.cc){
                        if(String.isNotBlank(line.emailAddress)){
                            ccAddresses.add(line.emailAddress);
                            mail.CC__c = mail.CC__c + line.emailAddress + ';';
                            mail.ccName__c = mail.ccName__c + (String.isNotBlank(line.name) ? line.name : line.emailAddress) + ';';
                            mail.ALL_MEMBER_TYPE__c = mail.ALL_MEMBER_TYPE__c + 'cc;';
                        }
                    }
                    if(line.bcc){
                        if(String.isNotBlank(line.emailAddress)){
                            bccAddresses.add(line.emailAddress);
                            mail.BCC__c = mail.BCC__c + line.emailAddress + ';';
                            mail.bccName__c = mail.bccName__c + (String.isNotBlank(line.name) ? line.name : line.emailAddress) + ';';
                            mail.ALL_MEMBER_TYPE__c = mail.ALL_MEMBER_TYPE__c + 'bcc;';
                        }
                    }
                }
            }
        }
        if('SWO'.equals(mail.RECORD_TYPE__c)){
            mail.SWO__c = mail.RECORD__c;
            SWO__c swo = [select Id,Name from SWO__c where Id=:mail.RECORD__c];
            name = 'SWO:'+swo.Name;
        }
        if('Case'.equals(mail.RECORD_TYPE__c)){
            mail.CaseF__c = mail.RECORD__c;
            User_FaultInfo__c caseInfo = [select Id,Name from User_FaultInfo__c where Id=:mail.RECORD__c];
            name = 'Case:'+caseInfo.Name;
        }
        if('Quotes'.equals(mail.RECORD_TYPE__c)){
            mail.Quotes__c = mail.RECORD__c;
            Quotes__c quotes = [select Id,Name from Quotes__c where Id=:mail.RECORD__c];
            name = 'Quotes:'+quotes.Name;
        }
        //判断是否时点击发送按钮，进入提交方法
        if(String.isNotBlank(handleType) && !'send'.equals(handleType)){
            mail.EMAIL_SENT__c = 'NO';
            upsert mail;
            id = mail.Id;
        }

        // return mail;
    }

    public void addLine(){
        MemberLine member = new MemberLine();
        member.lineNum = memberLineDatas.size();
        member.memberId = '';
        member.name = '';
        member.emailAddress = '';
        member.to = true;
        member.cc = false;
        member.bcc = false;
        memberLineDatas.add(member);
    }

    public void deLine(){
        //保证页面上最少有一行人员信息栏
        if(memberLineDatas.size() == 1){
            memberLineDatas[0].memberId = '';
            memberLineDatas[0].emailAddress = '';
            memberLineDatas[0].name = '';
            memberLineDatas[0].to = true;
            memberLineDatas[0].cc = false;
            memberLineDatas[0].bcc = false;
            return;
        }
        memberLineDatas.remove(lineNum);
        //删除一行人员信息，重新给行标赋值
        for(Integer i = 0 ; i<memberLineDatas.size() ; i++){
            memberLineDatas[i].lineNum = i;
        }
    }
    
    public void kong(){
        System.debug('空提交');
    }

    public PageReference uploadFile(){
        handleType = 'uploadFile';
        SendEmail();
        PageReference ref = new Pagereference('/p/attach/NoteAttach?pid=' + id + '&retURL=%2Fapex/SendEmail?id=' + id + '&type=' + type + '&typeid='+typeid);
        ref.setRedirect(true);
        return ref;
    }

    public void uploadFileS(){
        handleType = 'uploadFile';
        save();
        
    }

    public PageReference RefreshPage(){
        PageReference ref = new Pagereference('/apex/SendEmail?id=' + id + '&type=' + type + '&typeid='+typeid);
        ref.setRedirect(true);
        return ref;
    }

    public PageReference seeFile(){
        if(String.isNotBlank(fileId)){
            for(Integer i = 0; i< attachmentList.size();i++){
                if(fileId.equals(attachmentList[i].Id)){
                    PageReference acctPage = new ApexPages.StandardController(attachmentList[i]).view();
                    acctPage.setRedirect(true);
                    return acctPage;
                }
            }
        }
        return null;
    }

    public void deleteFile(){
        System.debug('fileId'+fileId);
        if(String.isNotBlank(fileId)){
            for(Integer i = 0; i< attachmentList.size();i++){
                if(fileId.equals(attachmentList[i].Id)){
                    System.debug('id'+attachmentList[i].Id);
                    System.debug('fileId'+fileId);
                    delete attachmentList[i];
                    attachmentList.remove(i);
                    break;
                }
            }
        }
    }

    public void addPDF(){
        handleType = 'uploadFile';
        SendEmail();
        PageReference pdfPage ;
        pdfPage = new PageReference('/apex/QuotesPDF?id='+typeid);
        // pdfPage.getParameters().put('id',laId);
        pdfPage.setRedirect(false);
        Blob b = pdfPage.getContentAsPDF();
        // attach the pdf to the Opportunity
        Attachment attach = new Attachment();
        attach.Body = b;
        attach.Name = '报价单.pdf';
        System.debug('id--'+ id );
        attach.ParentId = id;
        insert attach;
        attachmentList = [select Id,Name,CreatedDate,BodyLength,Body from Attachment where ParentId=:id];

    }

    public Messaging.EmailFileAttachment SendEmailaddPDF(){
        handleType = 'uploadFile';
        
        if (String.isBlank(id)) {
            SendEmail();   
        }
        
        PageReference pdfPage ;
        pdfPage = new PageReference('/apex/QuotesPDF?id='+typeid);
        // pdfPage.getParameters().put('id',laId);
        pdfPage.setRedirect(false);
        Blob b = pdfPage.getContentAsPDF();
        // attach the pdf to the Opportunity
        Attachment attach = new Attachment();
        attach.Body = b;
        attach.Name = '报价单.pdf';
        System.debug('id--'+ id );
        attach.ParentId = id;
        insert attach;
        Messaging.EmailFileAttachment sendMailFile = new Messaging.EmailFileAttachment();
        sendMailFile.setBody(attach.Body);
        sendMailFile.setFileName(attach.Name);
        return sendMailFile;
        // attachmentList = [select Id,Name,CreatedDate,BodyLength,Body from Attachment where ParentId=:id];

    }

    //上传附件
    @RemoteAction
    public static String AddAttachment(List<String> nameList, List<String> typeList, List<String> bodyList, String parentId) {
        String operateResult;
        if (nameList.size() > 0) {
            List<Attachment> insertAttachmentList = new List<Attachment>();
            for (Integer num = 0; num < nameList.size(); num ++ ) {
                Attachment tmpAttachment = new Attachment();
                tmpAttachment.Name = nameList[num];
                tmpAttachment.Body = EncodingUtil.base64Decode(bodyList[num]);
                tmpAttachment.ParentId = parentId;
                tmpAttachment.ContentType = typeList[num];
                insertAttachmentList.add(tmpAttachment);
            }

            try {
                insert insertAttachmentList;
                operateResult = '文件上传成功';
            } catch (Exception e) {
                operateResult = '文件上传失败';
            }
        }


        return operateResult;
    }
    public void addMemberData(){
        System.debug(memberName);
        System.debug('memberEmail:'+memberEmail);
        System.debug(memberId);
        if(lineNum!=null){
            if(String.isNotBlank(memberName)){
                memberLineDatas[lineNum].name = memberName;
            }
            if(String.isNotBlank(memberEmail)){
                memberLineDatas[lineNum].emailAddress = memberEmail;
            }
            if(String.isNotBlank(memberId)){
                memberLineDatas[lineNum].memberId = memberId;
            }
        }
    }

    public class MemberLine{
        public String memberId{get;set;}
        public String emailAddress{get;set;}
        public String name{get;set;}
        public Boolean to{get;set;}
        public Boolean cc{get;set;}
        public Boolean bcc{get;set;}
        public Integer lineNum{get;set;}
    }
}