// 因为延期申请只和申请书相关的一览或者关联的修理有关所以可以使用without sharing
public without sharing class RentalApplyExtensionsController extends CreateRelationListPagingCtrlBase {
    private Date today;
    private Datetime now;
    private String wher;//where 条件
    public List<String> ParentIdList;//存放批量延期时，传过来的参数
    public String muchExtensionEntrance;//如果为批量延期，那么需要一个主单id
    public Boolean buttonFlag{get;set;}//判断前段是展示返回还是关闭按钮
    public override Integer getSearchNumMax() {
        //各ページに制御あれば、最大件数を指定する
        // searchNumMax = Integer.valueOf(Label.Product_Select_Limit);
        // searchNumMax = 20;
        pagesize = '20';
        return searchNumMax;
    }

    /* 選択されたデータ取得用Soql　Fromから*/
    public override String getSelectedDataSql() {
        // オブジェクトAPI名
        selectedDataSql = ' From Rental_Apply_Equipment_Set__c';
        selectedDataSql += ' where Cancel_Reason__c = null ';
        //update            wangweipeng           2021/11/30                     start
        if(String.isNotBlank(wher)){
            selectedDataSql +=  wher;
        }
        //selectedDataSql += ' where Rental_Apply__c = \'' + String.escapeSingleQuotes(parentId) + '\'';
        //update            wangweipeng           2021/11/30                     start
        selectedDataSql += ' order by Rental_Apply__r.Name ASC';
        if (myComponentController.columnLeftRW != null) {
            for (String key : myComponentController.columnLeftRW.keySet()) {
                myComponentController.columnLeftRW.put(key, 'r');
            }
        }
        if (myComponentController.columnRightRW != null) {
            for (String key : myComponentController.columnRightRW.keySet()) {
                myComponentController.columnRightRW.put(key, 'r');
            }
        }
        return selectedDataSql;
    }

    public override String getOriginObjColumns() {
        // 項目セット
        originObjColumns = '';
        return originObjColumns;
    }

    public override String getObjName() {
        // オブジェクトAPI名
        objName = 'Rental_Apply_Equipment_Set__c';
        return objName;
    }
    public override String getColumnLeftFieldSetName() {
        // 左の項目セット
        columnLeftFieldSetName = 'RentalApplyExtensions_L';
        return columnLeftFieldSetName;
    }
    public override String getColumnRightFieldSetName() {
        // 右の項目セット
        columnRightFieldSetName = 'RentalApplyExtensions_R';
        return columnRightFieldSetName;
    }

    public override List<String> getColumnFieldList() {
        // strColumus 里加 field
        // FixtureUtil#raesdGroupByAssetId()の項目も必要
        return new List<String>{'Rental_Apply__c'
                                , 'Rental_Apply__r.Repair__r.Agreed_Date__c'
                                , 'Rental_Apply__r.Repair__r.Repair_Estimated_date_formula__c'
                                , 'Rental_Apply__r.NewRepair__c'
                                , 'Rental_Apply__r.NewRepair__r.Agreed_Date__c'
                                , 'Rental_Apply__r.NewRepair__r.Status__c'
                                , 'Rental_Apply__r.NewRepair__r.ReRepairObject_F__c'
                                , 'Rental_Apply__r.NewRepair__r.Repair_Shipped_Date__c'
                                , 'Rental_Apply__r.QISRepair__r.Repair_Shipped_Date__c'
                                , 'Rental_Apply__r.RC_return_to_office__c'
                                , 'Rental_Apply__r.AgreementBorrowingExtensionDate__c'
                                , 'Rental_Apply__r.ExtensionApprovalTime_Initial__c '
                                , 'Rental_Apply__r.ExtensionApplicationTime_Final__c '
                                , 'Rental_Apply__r.Name'
                                , 'Final_reply_day__c'
                                , 'Asset_return_time__c'
                                , 'Bollow_Date__c'
                                , 'demo_purpose2__c'
                                , 'demo_purpose1__c'
                                , 'Request_demo_time__c'
                                , 'Loaner_received_time__c'
                                , 'Received_Confirm__c'
                                , 'Loaner_received_day2__c'
                                , 'RcUnexpectExpiryDelay__c'};
    }

    public override List<String> getHiddenFieldList() {
        return new List<String>();
    }

    public override String getOriginObjName() {
        // オブジェクトAPI名
        originObjName = '';
        return originObjName;
    }

    public override String getRecordTypeId() {
        //ページレイアウトを収得するのレコードタイプ
        recordTypeId = '';
        return recordTypeId;
    }

    public override String getSqlWhereStr() {
        sqlWhereStr = '';

        // if (getIsNeedRunSearch()) {
            sqlWhereStr = 'where id != null';
        // }

        return sqlWhereStr;
    }

    public override String getFKColumnField() {
        // getObjName 连 getOriginObjName 的 FK
        return '';
    }

    public override Boolean getIsNeedRunSearch() {
        return true;
    }


    public override String getOrderbyStr() {
        String ordStr = '';
        // if (isFirstTime) {
        //     ordStr = ', Equipment_Type__c DESC  nulls last';
        //     isFirstTime = false;
        // }
        return '';
    }

    public override void setViewList(List<sObject> queryList) {
        viewList = new List<WrapperInfo>();
        for (SObject raes : selectedData) {
            Rental_Apply_Equipment_Set__c raesObj = (Rental_Apply_Equipment_Set__c)raes;
            WrapperInfo info = new WrapperInfo(raesObj, myComponentController);
            info.check = false;
            info.canEdit = false;
            if (true == RentalApplyTriggerHandler.checkCan_Extend_Request(raesObj, true)) {
                info.check = true;
            }

            viewList.add(info);
        }
    }

    public RentalApplyExtensionsController() {
        parentId = ApexPages.currentPage().getParameters().get('parentId');
        //如果为批量延期，那么需要确认延期入口是哪个申请单
        muchExtensionEntrance = ApexPages.currentPage().getParameters().get('entranceId');
        if(String.isNotBlank(muchExtensionEntrance)){
            muchExtensionEntrance = muchExtensionEntrance.substring(0,15);
            buttonFlag = true;
        }else{
            buttonFlag = false;
        }
        today = Date.today();
        now = Datetime.now();
        wher = '';
        ParentIdList = new List<String>();
        
    }

    public void init() {
        isNeedSearchFirst = false;
        isNeedCheckEvent = true;
        //add            wangweipeng             2021/11/30             start
        //啊，不知道为啥不能使用 in,所有循环然后拼接 OR
        if(String.isNotBlank(parentId)){
            for(String st : parentId.split(',')){
                if(String.isNotBlank(st)){
                    ParentIdList.add(st);
                    if(String.isNotBlank(wher)){
                        wher += ' OR Rental_Apply__c = \''+st+'\' ';
                        
                    }else{
                        wher = ' Rental_Apply__c = \''+st+'\' ';
                    }
                }
            }
            if(String.isNotBlank(wher)){
                wher = ' and ('+wher+')';
            }
        }
        //add            wangweipeng             2021/11/30             end
        getSqlWhereStr();
    }

    //update            wangweipeng             2021/11/30             start
    public PageReference submitExtensionRequest() {
        Savepoint sp = Database.setSavepoint();
        try {
            Set<String> expectRaesSet = new Set<String>();
            List<String> emailRentalApplyEquipmentSet = new List<String>();
            Map<String,List<String>> emailRentalApplyEquipmentMap = new Map<String,List<String>>();
            List<Rental_Apply_Equipment_Set__c> toUpdateRaesList = new List<Rental_Apply_Equipment_Set__c>();
            //存放延期截止日期
            Date extension_Deadline;

            List<Rental_Apply__c> raList = [
                SELECT Id
                     , name
                     , demo_purpose1__c
                     , demo_purpose2__c
                     , Loaner_received_ng_num__c
                     , ExtensionDays__c
                     , Email_Rental_Apply_Equipment_Set__c
                     , ExtensionStatus__c
                     , Return_dadeline_final__c
                     , RcUnexpectExpiryDelay__c
                     , RcUnexpectExpiryDelay_Mail__c
                     , AgreementBorrowingExtensionDate__c
                     , ExtensionApprovalTime_Initial__c
                     , ExtensionApplicationTime_Final__c
                     , ExtensionApprovalTime_Final__c
                     , ExtensionSuccessTimes__c
                     , NewRepair__c
                     , NewRepair__r.Agreed_Date__c
                     , NewRepair__r.Status__c
                     , NewRepair__r.ReRepairObject_F__c
                     , NewRepair__r.Repair_Shipped_Date__c
                     , next_action__c
                     , Bollow_Date_Add_10_WD__c
                     , RC_Ordered_Date__c
                     , Extension_List_RentalApply__c
                     , Extension_Type__c
                     , Extension_Parent_Entrance__c
                     , ExtensionApplicationTime_Initial__c
                     , Extension_Much_ID__c
                     , Is_Delete_Extension__c
                     , ExtensionContent__c
                     , Root_Rental_Apply__c
                     , Extension_Deadline__c
                  FROM Rental_Apply__c
                  WHERE Id in : this.ParentIdList
                 //WHERE Id = : this.parentId
            ];

            if (1 > raList.size()) {
                throw new ControllerUtil.myException('备品借出申请不存在，请确认数据');
            }
            //如果此变量有值，证明是批量延期
            //如果为从单，那么也需要走批量延期的逻辑
            if(String.isNotBlank(muchExtensionEntrance) 
                || (raList.size() == 1 && String.isNotBlank(raList[0].Root_Rental_Apply__c) && (raList[0].demo_purpose2__c == '试用（无询价）' || raList[0].demo_purpose2__c == '试用（有询价）'))){
                String pqq = '';
                if(String.isNotBlank(muchExtensionEntrance)){
                    //qq = muchExtensionEntrance+'%';
                    pqq = ' Id = \''+this.muchExtensionEntrance+'\' OR Root_Rental_Apply__c like \''+muchExtensionEntrance+'%\' ';
                }
                if(raList.size() == 1 && String.isNotBlank(raList[0].Root_Rental_Apply__c)){
                    String reacId = raList[0].Root_Rental_Apply__c;
                    reacId = reacId.substring(0,15);
                    pqq = ' Id = \''+raList[0].Id+'\' or Root_Rental_Apply__c like \''+reacId+'%\' or ID = \''+reacId+'\' ';
                }
                String accSql = 'SELECT Id, name, demo_purpose1__c, demo_purpose2__c, Loaner_received_ng_num__c, ExtensionDays__c, Email_Rental_Apply_Equipment_Set__c, ExtensionStatus__c, Return_dadeline_final__c, RcUnexpectExpiryDelay__c, RcUnexpectExpiryDelay_Mail__c, AgreementBorrowingExtensionDate__c, ExtensionApprovalTime_Initial__c, ExtensionApplicationTime_Final__c, ExtensionApprovalTime_Final__c, ExtensionSuccessTimes__c, NewRepair__c, NewRepair__r.Agreed_Date__c, NewRepair__r.Status__c, NewRepair__r.ReRepairObject_F__c, NewRepair__r.Repair_Shipped_Date__c, next_action__c, Bollow_Date_Add_10_WD__c, RC_Ordered_Date__c, Extension_List_RentalApply__c, Extension_Type__c, Extension_Parent_Entrance__c, ExtensionApplicationTime_Initial__c, Extension_Much_ID__c, Is_Delete_Extension__c, ExtensionContent__c,Extension_Deadline__c FROM Rental_Apply__c WHERE '+ pqq;
                List<Rental_Apply__c> raList1 = Database.query(accSql);
                //获取满足延期的配套
                for (Rental_Apply_Equipment_Set__c raesObj : RentalApplyTriggerHandler.getCan_Extend_RequestList(raList1)) {
                    for(Rental_Apply__c raa :raList){
                        if(raa.Id == raesObj.Rental_Apply__c){
                            if ((raesObj.Received_Confirm__c == 'OK' || raesObj.Received_Confirm__c == '默认签收-OK') && raesObj.Asset_return_time__c != null) {
                                throw new ControllerUtil.myException('此单不满足延期条件');
                            }else{
                                expectRaesSet.add(raesObj.Id);    
                            }
                        }
                    }
                }

                extension_Deadline = getExtensionDeadline(raList[0]);
            }else{
                //获取满足延期的配套
                for (Rental_Apply_Equipment_Set__c raesObj : RentalApplyTriggerHandler.getCan_Extend_RequestList(raList)) {
                    expectRaesSet.add(raesObj.Id);
                }
            }

            if(0 == expectRaesSet.size()){
                throw new ControllerUtil.myException('没有要可以延期的配套一览');
            }
            //viewList  为前端展示的所有数据
            for (WrapperInfo wpInfo : viewList) {
                Rental_Apply_Equipment_Set__c raesObj = (Rental_Apply_Equipment_Set__c)wpInfo.sobj;
                if (true == wpInfo.check) {//获取勾选的配套数据
                    if (false == expectRaesSet.contains(raesObj.Id)) {
                        throw new ControllerUtil.myException('借出备品配套一览已变动，请刷新画面重试');
                    } else {
                        expectRaesSet.remove(raesObj.Id);
                    }
                    emailRentalApplyEquipmentSet.add(raesObj.Rental_Apply__r.Name +'：'+raesObj.First_RAESD_Model_No_F__c);
                    if(emailRentalApplyEquipmentMap.containsKey(raesObj.Rental_Apply__c)){
                        emailRentalApplyEquipmentMap.get(raesObj.Rental_Apply__c).add(raesObj.Rental_Apply__r.Name +'：'+raesObj.First_RAESD_Model_No_F__c);
                    }else{
                        emailRentalApplyEquipmentMap.put(raesObj.Rental_Apply__c, new List<String>{raesObj.Rental_Apply__r.Name +'：'+ raesObj.First_RAESD_Model_No_F__c});
                    }
                    // 第二次延期のみ
                    if (null != raList[0].ExtensionApprovalTime_Initial__c) {
                        if ('维修代用' == raList[0].demo_purpose1__c) {
                            // 一覧のRC未定到期延时
                            raesObj.RcUnexpectExpiryDelay__c = raList[0].Return_dadeline_final__c.addDays(30);
                            toUpdateRaesList.add(raesObj);
                        } else if ('协议借用' == raList[0].demo_purpose1__c) {
                            abedCheck(raList[0].AgreementBorrowingExtensionDate__c, raList[0].Return_dadeline_final__c);
                            // 一覧のRC未定到期延时
                            raesObj.RcUnexpectExpiryDelay__c = raList[0].AgreementBorrowingExtensionDate__c;
                            toUpdateRaesList.add(raesObj);
                        }
                    }
                }
            }
            if (0 < expectRaesSet.size()) {
                throw new ControllerUtil.myException('借出备品配套一览已变动，请刷新画面重试');
            }
            //如果此变量有值，那么证明此次延期为批量延期，因为单个延期不会给这个参数赋值
            if(String.isNotBlank(muchExtensionEntrance)){
                //用于存放批量延期的申请单，此变量针对于从单，并且如果不是批量延期，那么也不会赋值
                String muchRentalApplyHtml = '';
                //存放此次批量延期的从单申请单id
                //方便出现一些奇怪的情况时，可以快速的操作从单：主单没有延期，从单延期，我们延期过程中需要同步一些字段状态给从单
                String extensionMuchID = '';

                Map<String,Rental_Apply__c> rentalApplyMap = new Map<String,Rental_Apply__c>();
                Datetime dt = Datetime.now();
                //Date da;
                for(Rental_Apply__c ra : raList){
                    if(emailRentalApplyEquipmentMap.containsKey(ra.Id)){
                        if (ra.ExtensionStatus__c == '申请中' || ra.ExtensionStatus__c == '填写完毕') {
                            throw new ControllerUtil.myException('请确认延期申请状态，'+ra.Name+':已经提交过的申请，不能重复提交');
                        }
                        //目前批量延期只能延期 有询价和无询价的，所有如果是批量延期，必定只能延期一次
                        if (null != ra.ExtensionApprovalTime_Initial__c) {
                            throw new ControllerUtil.myException('申请单：'+ra.Name+'已经延期过一次了，不能再次延期');
                        }
                        if ('产品试用' == ra.demo_purpose1__c) {
                            // 延期天数
                            ra.ExtensionDays__c = 7;
                            // 邮件用借出备品一览中文名
                            ra.Email_Rental_Apply_Equipment_Set__c = String.join(emailRentalApplyEquipmentMap.get(ra.Id), '<BR>');
                            //延期类型
                            ra.Extension_Type__c = '批量延期';
                            // RC未定到期延时(邮件用)
                            if(ra.Return_dadeline_final__c != null){
                                ra.RcUnexpectExpiryDelay_Mail__c = ra.Return_dadeline_final__c.addDays((Integer)ra.ExtensionDays__c);
                            }
                            /*if(da != null){
                                if(da < ra.RcUnexpectExpiryDelay_Mail__c){
                                    da = ra.RcUnexpectExpiryDelay_Mail__c;
                                }
                            }else{
                                da = ra.RcUnexpectExpiryDelay_Mail__c;
                            }*/
                            
                            //收集从单
                            if(String.isNotBlank(muchExtensionEntrance)){
                                String racId = ra.Id;
                                racId = racId.substring(0,15);
                                if(!racId.equals(muchExtensionEntrance)){
                                    if(String.isNotBlank(muchRentalApplyHtml)){
                                        muchRentalApplyHtml += '<a href="/'+ra.Id+'" id="'+ra.Id+'" name="'+dt+'">'+ra.Name+'</a><br/>';
                                    }else{
                                        muchRentalApplyHtml = '<a href="/'+ra.Id+'" id="'+ra.Id+'" name="'+dt+'">'+ra.Name+'</a><br/>';
                                    }
                                    //延期入口
                                    ra.Extension_Parent_Entrance__c = muchExtensionEntrance;
                                    //延期申请时间(最初)  批量延期时，从单的此字段手动赋值
                                    ra.ExtensionApplicationTime_Initial__c = DateTime.now();
                                    // 延期状态
                                    ra.ExtensionStatus__c = '申请中';
                                    //RC未定到期延时
                                    ra.RcUnexpectExpiryDelay__c = ra.RcUnexpectExpiryDelay_Mail__c;
                                    //延期内容
                                    ra.ExtensionContent__c = '申请延期从' + ra.Return_dadeline_final__c + '延期到' + ra.RcUnexpectExpiryDelay__c;
                                    //存放此次批量延期的从单申请单id
                                    //方便出现一下情况时，可以快速的操作从单：主单没有延期，从单延期，我们延期过程中需要同步一些字段状态给从单
                                    if(String.isNotBlank(extensionMuchID)){
                                        extensionMuchID += ','+ra.Id;
                                    }else{
                                        extensionMuchID = ra.Id;
                                    }
                                }
                                rentalApplyMap.put(racId,ra);
                            }
                        }else{
                            throw new ControllerUtil.myException('申请单：'+ra.Name+'字段：试用目的2的值不为【使用（无询价）】或【使用（有询价）】，不能延期');
                        }
                    }
                }
                //赋值，由于批量延期的审批流程在主单上，所有要找到主单，并给主单一些字段赋值
                if(String.isNotBlank(muchExtensionEntrance)){
                    //查询此次批量延期，延期主单来了吗
                    if (rentalApplyMap.containsKey(muchExtensionEntrance)) {
                        //批量延期申请单
                        rentalApplyMap.get(muchExtensionEntrance).Extension_List_RentalApply__c = muchRentalApplyHtml;
                        //延期状态
                        rentalApplyMap.get(muchExtensionEntrance).ExtensionStatus__c = '填写完毕';
                        // 邮件用借出备品一览中文名
                        rentalApplyMap.get(muchExtensionEntrance).Email_Rental_Apply_Equipment_Set__c = String.join(emailRentalApplyEquipmentSet, '<BR>');
                        //批量延期申请单id
                        rentalApplyMap.get(muchExtensionEntrance).Extension_Much_ID__c = extensionMuchID;
                        //是否需要删除延期信息
                        rentalApplyMap.get(muchExtensionEntrance).Is_Delete_Extension__c = false;
                        //批量延期时，获取所有申请单的最大 RC未定到期延时(邮件用) 值，赋给主单
                        /*if(da != null){
                            if(da > rentalApplyMap.get(muchExtensionEntrance).RcUnexpectExpiryDelay_Mail__c){
                                rentalApplyMap.get(muchExtensionEntrance).RcUnexpectExpiryDelay_Mail__c = da;
                            }
                        }*/
                        //RC未定到期延时
                        rentalApplyMap.get(muchExtensionEntrance).RcUnexpectExpiryDelay__c = rentalApplyMap.get(muchExtensionEntrance).RcUnexpectExpiryDelay_Mail__c;
                        //延期内容
                        rentalApplyMap.get(muchExtensionEntrance).ExtensionContent__c = '申请延期从' + rentalApplyMap.get(muchExtensionEntrance).Return_dadeline_final__c + '延期到' + rentalApplyMap.get(muchExtensionEntrance).RcUnexpectExpiryDelay__c;

                        //延期截止日期
                        rentalApplyMap.get(muchExtensionEntrance).Extension_Deadline__c = extension_Deadline;
                    }else{
                        //如果没有延期原单，那么就需要做一下特殊处理
                        List<Rental_Apply__c> zra = [SELECT id
                                                            ,Extension_List_RentalApply__c
                                                            ,ExtensionStatus__c
                                                            ,ExtensionDays__c
                                                            ,Email_Rental_Apply_Equipment_Set__c
                                                            ,RcUnexpectExpiryDelay_Mail__c
                                                            ,Is_Delete_Extension__c
                                                            ,Return_dadeline_final__c
                                                            ,Extension_Much_ID__c
                                                            ,Extension_Type__c
                                                            ,ExtensionContent__c
                                                            ,RcUnexpectExpiryDelay__c
                                                            ,Extension_Deadline__c
                                                         FROM Rental_Apply__c 
                                                         WHERE id = :muchExtensionEntrance];
                        if(zra != null && zra.size() > 0){
                            for(Rental_Apply__c racc : zra){
                                // 延期状态
                                racc.ExtensionStatus__c = '填写完毕';
                                // 延期天数
                                racc.ExtensionDays__c = 7;
                                // 邮件用借出备品一览中文名
                                racc.Email_Rental_Apply_Equipment_Set__c = String.join(emailRentalApplyEquipmentSet, '<BR>');
                                //批量延期申请单
                                racc.Extension_List_RentalApply__c = muchRentalApplyHtml;
                                //是否需要删除延期信息
                                racc.Is_Delete_Extension__c = true;
                                //批量延期申请单id
                                racc.Extension_Much_ID__c = extensionMuchID;
                                //延期类型
                                racc.Extension_Type__c = '批量延期';
                                // RC未定到期延时(邮件用)
                                //批量延期时，获取所有申请单的最大 RC未定到期延时(邮件用) 值，赋给主单
                                if(racc.Return_dadeline_final__c != null){
                                    racc.RcUnexpectExpiryDelay_Mail__c = racc.Return_dadeline_final__c.addDays((Integer)racc.ExtensionDays__c);
                                }
                                //RC未定到期延时
                                racc.RcUnexpectExpiryDelay__c = racc.RcUnexpectExpiryDelay_Mail__c;
                                //延期内容
                                racc.ExtensionContent__c = '申请延期从' + racc.Return_dadeline_final__c + '延期到' + racc.RcUnexpectExpiryDelay__c;

                                racc.Extension_Deadline__c = extension_Deadline;
                                rentalApplyMap.put(racc.Id,racc);
                            }
                        }
                    }
                }
                //最后更新数据
                if (0 < rentalApplyMap.values().size()) {
                    update rentalApplyMap.values();
                }
            }else{
                Rental_Apply__c ra = raList[0];
                if (ra.ExtensionStatus__c == '申请中' || ra.ExtensionStatus__c == '填写完毕') {
                    throw new ControllerUtil.myException('请确认延期申请状态，已经提交过的申请，不能重复提交');
                }
                if ('维修代用' == ra.demo_purpose1__c) {
                    // 第一次延期
                    if (null == ra.ExtensionApprovalTime_Initial__c) {
                        // 延期状态
                        ra.ExtensionStatus__c = '填写完毕';
                        // 延期天数
                        ra.ExtensionDays__c = 30 + 14;
                    }
                    // 第二次延期
                    else {
                        // 延期天数
                        ra.ExtensionDays__c = 30;
                        // RC未定到期延时
                        ra.RcUnexpectExpiryDelay__c = ra.Return_dadeline_final__c.addDays(30);
                        // 延期申请时间(最终)
                        ra.ExtensionApplicationTime_Final__c = this.now;
                        // 延期批准时间(最终)
                        ra.ExtensionApprovalTime_Final__c = this.now;
                        // 延期内容
                        ra.ExtensionContent__c = '申请延期从' + ra.Return_dadeline_final__c + '延期到' + ra.RcUnexpectExpiryDelay__c;
                        // 延期成功次数
                        ra.ExtensionSuccessTimes__c ++;
                    }
                    // 邮件用借出备品一览中文名
                    ra.Email_Rental_Apply_Equipment_Set__c = String.join(emailRentalApplyEquipmentSet, '<BR>');
                } else if ('产品试用' == ra.demo_purpose1__c) {
                    // 第一次延期
                    if (null == ra.ExtensionApprovalTime_Initial__c) {
                        // 延期状态
                        ra.ExtensionStatus__c = '填写完毕';
                        // 延期天数
                        ra.ExtensionDays__c = 7;
                        // 邮件用借出备品一览中文名
                        ra.Email_Rental_Apply_Equipment_Set__c = String.join(emailRentalApplyEquipmentSet, '<BR>');

                        if(extension_Deadline != null){
                            ra.Extension_Deadline__c = extension_Deadline;
                        }
                    }
                } else if ('协议借用' == ra.demo_purpose1__c)  {
                    abedCheck(ra.AgreementBorrowingExtensionDate__c, ra.Return_dadeline_final__c);
                    // 第一次延期
                    // if (null == ra.ExtensionApprovalTime_Initial__c) {
                        // 延期状态
                        ra.ExtensionStatus__c = '填写完毕';
                    // } else {
                        // // 延期申请时间(最终)
                        // ra.ExtensionApplicationTime_Final__c = this.now;
                        // // 延期批准时间(最终)
                        // ra.ExtensionApprovalTime_Final__c = this.now;
                        // // 延期内容
                        // ra.ExtensionContent__c = '申请延期从' + ra.Return_dadeline_final__c + '延期到' + ra.AgreementBorrowingExtensionDate__c;
                        // // 延期成功次数
                        // ra.ExtensionSuccessTimes__c++;
                        // // RC未定到期延时
                        // ra.RcUnexpectExpiryDelay__c = ra.AgreementBorrowingExtensionDate__c;
                    // }
                    // 延期天数
                    ra.ExtensionDays__c = ra.Return_dadeline_final__c.daysBetween(ra.AgreementBorrowingExtensionDate__c);
                    // 邮件用借出备品一览中文名
                    ra.Email_Rental_Apply_Equipment_Set__c = String.join(emailRentalApplyEquipmentSet, '<BR>');
                }

                // RC未定到期延时(邮件用)
                ra.RcUnexpectExpiryDelay_Mail__c = ra.Return_dadeline_final__c.addDays((Integer)ra.ExtensionDays__c);
                
                if (0 < raList.size()) {
                    update raList;
                }
                
                if (0 < toUpdateRaesList.size() && null != ra.ExtensionApprovalTime_Initial__c) {
                    update toUpdateRaesList;
                }
            }
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, '延期申请提交成功！', 'detail - confirm'));
            return null;
        } catch (Exception e) {
            Database.rollback(sp);
            System.debug('RentalApplyExtensionsController submitExtensionRequest ErrorLog: ' + ' msg: ' + e.getMessage() + ' stk : ' + e.getStackTraceString());
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '延期申请提交失败！' + e.getMessage(), 'detail - error')); 
            return null;
        }
    }

    //
    /**
     * [getExtensionDeadline 获取延期截止日期]
     * @param  rac [description]
     * @return     [description]
     *
     * 需在NG且7天寄回的申请单：备品中心发货后14天内以及备品借用期限内完成延期的提交和审批。如有2单以上NG满足条件时，借用期限取2单中最晚那个。
     * 使用目的2为有询价或无询价，如果批量延期或从单单独延期，那么需要有一个延期截止日期
     */
    public Date getExtensionDeadline(Rental_Apply__c rac){
        Date da;
        String likeParentId = '';
        if(String.isNotBlank(rac.Root_Rental_Apply__c)){
            String aa = rac.Root_Rental_Apply__c;
            aa = aa.substring(0,15);
            likeParentId = aa+'%';
        }else{
            String aa = rac.Id;
            aa = aa.substring(0,15);
            likeParentId = aa+'%';
        }
        
        List<Rental_Apply_Equipment_Set__c> raes = [SELECT Id,Name
                                                    , Rental_Apply__c
                                                    , Rental_Apply__r.Repair__r.Agreed_Date__c
                                                    , Rental_Apply__r.Repair__r.Repair_Estimated_date_formula__c
                                                    , Rental_Apply__r.NewRepair__c
                                                    , Rental_Apply__r.NewRepair__r.Agreed_Date__c
                                                    , Rental_Apply__r.NewRepair__r.Status__c
                                                    , Rental_Apply__r.NewRepair__r.ReRepairObject_F__c
                                                    , Rental_Apply__r.NewRepair__r.Repair_Shipped_Date__c
                                                    , Rental_Apply__r.QISRepair__r.Repair_Shipped_Date__c
                                                    , Rental_Apply__r.RC_return_to_office__c
                                                    , Rental_Apply__r.AgreementBorrowingExtensionDate__c
                                                    , Rental_Apply__r.ExtensionApprovalTime_Initial__c
                                                    , Rental_Apply__r.ExtensionApplicationTime_Final__c
                                                    , Rental_Apply__r.RcUnexpectExpiryDelay__c
                                                    , Final_reply_day__c
                                                    , Asset_return_time__c
                                                    , Bollow_Date__c
                                                    , demo_purpose2__c
                                                    , demo_purpose1__c
                                                    , Request_demo_time__c
                                                    , Loaner_received_time__c
                                                    , Received_Confirm__c
                                                    , Loaner_received_day2__c
                                                    , RcUnexpectExpiryDelay__c
                                                 FROM Rental_Apply_Equipment_Set__c
                                                WHERE (Rental_Apply__c = :rac.Id 
                                                    OR Rental_Apply__r.Root_Rental_Apply__c like :likeParentId 
                                                    OR Rental_Apply__c = :rac.Root_Rental_Apply__c)
                                                  AND Cancel_Reason__c = null];
        if(raes != null && raes.size() > 0){
            for(Rental_Apply_Equipment_Set__c raesc : raes){
                //NG7天内寄回的一览
                if(raesc.Received_Confirm__c == 'NG' && raesc.Asset_return_time__c != null && raesc.Loaner_received_day2__c != null){
                    Date d2 = Date.valueOf(raesc.Asset_return_time__c);
                    if (raesc.Loaner_received_day2__c.daysBetween(d2) <= 7) {
                        //
                        Date bollow_Date14 = raesc.Bollow_Date__c.addDays(14);
                        Date d1 = bollow_Date14  > raesc.Final_reply_day__c ? raesc.Final_reply_day__c : bollow_Date14;
                        if(da != null){
                            if(da < d1){
                                da = d1; 
                            }
                        }else{
                          da = d1; 
                        }
                    }
                }
            }
            System.debug('--------------543--'+da);
            Date dat = Date.today();
            if(da == null || da < dat){
                throw new ControllerUtil.myException('延期截止日期小于当前时间，不能延期。');
            }
        }
        return da;
    }

    //update            wangweipeng             2021/11/30             end

    public PageReference comeBack() {
        PageReference ret = null;
        if (!String.isBlank(this.parentId)) {
            ret = new PageReference('/' + this.parentId);
        }
        return ret;
    }

    private void abedCheck (Date abed, Date rdf) {
        if (null == abed) {
            throw new ControllerUtil.myException('协议借用的延期申请的【协议借用延期日期】不能为空。');
        } else if (abed <= rdf) {
            throw new ControllerUtil.myException('协议借用的延期申请的【协议借用延期日期】必须大于最新预定归还日。');
        } else if (abed <= this.today) {
            throw new ControllerUtil.myException('协议借用的延期申请的【协议借用延期日期】必须大于今天。');
        }
    }
}