19626
2023-04-25 4b671c08a55ee55e437a392fb572127f332ac6dc
Merge branch 'LEX_dev' of http://47.92.229.245:8089/r/lightningupdate into LEX_dev
39个文件已添加
29248 ■■■■■ 已修改文件
force-app/main/default/classes/RepPAEDecisionRecordController.cls 1036 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/classes/SelectAssetEstimateController.cls 3191 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/classes/SelectAssetEstimateController.cls-meta.xml 5 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/classes/SelectAssetEstimateControllerTest.cls 987 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/classes/SelectAssetEstimateControllerTest.cls-meta.xml 5 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/classes/SelectAssetEstimateURFController.cls 4841 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/classes/SelectAssetEstimateURFController.cls-meta.xml 5 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/classes/SelectAssetEstimateURFControllerTest.cls 1594 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/classes/SelectAssetEstimateURFControllerTest.cls-meta.xml 5 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/classes/SelectAssetEstimateVMController.cls 4458 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/classes/SelectAssetEstimateVMController.cls-meta.xml 5 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/classes/SelectAssetEstimateVMControllerTest.cls 1614 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/classes/SelectAssetEstimateVMControllerTest.cls-meta.xml 5 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/ChangeDealerApproval.page 119 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/ChangeDealerApproval.page-meta.xml 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/EquipmentRentalExtend.page 573 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/EquipmentRentalExtend.page-meta.xml 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/ListShip.page 315 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/ListShip.page-meta.xml 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/NewOnCall.page 427 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/NewOnCall.page-meta.xml 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/NewPaymentPlanLoad.page 676 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/NewPaymentPlanLoad.page-meta.xml 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/NewRentalApply.page 661 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/NewRentalApply.page-meta.xml 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/PaymentPlanLoad.page 468 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/PaymentPlanLoad.page-meta.xml 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/PrintInspectupReport.page 400 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/PrintInspectupReport.page-meta.xml 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/RepPAEDecisionRecord.page 402 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/RepPAEDecisionRecord.page-meta.xml 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/SelectAssetEstimate.page 1713 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/SelectAssetEstimate.page-meta.xml 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/SelectAssetEstimateJumpPage.page 22 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/SelectAssetEstimateJumpPage.page-meta.xml 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/SelectAssetEstimateURF.page 2613 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/SelectAssetEstimateURF.page-meta.xml 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/SelectAssetEstimateVM.page 3017 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/pages/SelectAssetEstimateVM.page-meta.xml 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
force-app/main/default/classes/RepPAEDecisionRecordController.cls
New file
@@ -0,0 +1,1036 @@
public with sharing class RepPAEDecisionRecordController {
    public PAE_DecisionRecord__c rdRecord {
        get;
        set;
    }
    //PAE判定记录的Id
    public String Id {
        get;
        set;
    }
    //PAE判定记录的记录类型Id
    public String RecordTypeId;
    public String RecordTypeIdD;
    public String RecordTypeName {
        get;
        set;
    }
    public String ASac_ASrc;
    public Boolean editAble {
        get;
        set;
    }
    // 保存按钮 需要考虑再现/不再现的更新了。
    // 简档:2F4_技术推进部,2F4_技术推进部_非SSO,2F2B_服务管理,系统管理员的人操作的时候,需要允许操作【保存】。
    public Boolean savebuton {
        get;
        set;
    }
    public Integer CancelineFlag {
        get;
        set;
    }
    public String OCSM_QARA {
        get;
        set;
    } //20200310
    public String OCSM_Cording {
        get;
        set;
    } //20200310
    public String intakePAEReappearConfirm {
        get;
        set;
    }
    public Integer pageLimit{get;set;}
    // 如果Repair__c     中DOJ_Status__c       的字段值为待EtQ Response 或者
    //     Report__c 中ComplaintStatus__c  的字段值为待EtQ Response 将标记改为true
    // 影响至对应页面中的按钮是否可用
    public Boolean editFlag {
        get;
        set;
    }
    // 当前报告书
    public Report__c repa {
        get;
        set;
    }
    // 是否是OSH
    public Boolean isOSH {
        get;
        set;
    }
    public String ReportId {
        get;
        set;
    }
    public String productIdx {
        get;
        set;
    }
    //页面的明细
    public List < PAE_DecisionRecordDetailInfo > paedRecordDetailView {
        get;
        set;
    }
    public Integer paedRecordDetailViewCount {
        get {
            return paedRecordDetailView == null ? 0 : paedRecordDetailView.size();
        }
    }
    public RepPAEDecisionRecordController(ApexPages.StandardController stdController) {
        Id = ApexPages.currentPage().getParameters().get('Id');
        String profileId = UserInfo.getProfileId();
        // 当前用户是否在 OSH自定义标签中
        isOSH = System.label.OSH.contains(profileId);
        System.debug('isOSH+' + isOSH);
        // 判断Report__c的ComplaintStatus__c字段值是否为待EtQ Response
        ReportId = ApexPages.currentPage().getParameters().get('ReportId');
        List < Report__c > Rep = [select id, name, ComplaintStatus__c, AsyncData__c from Report__c where id = : ReportId];
        //精琢科技  zxk  2021-11-03 根据修理进行的修改   start
         if (Rep.size() > 0){
              repa = Rep.get(0);
              system.debug('+++++++++++++++++'+repa);
                if ('待EtQ Response'.equals(Rep.get(0).ComplaintStatus__c)) {
                    editFlag = true;
                }
            }
        //精琢科技  zxk  2021-11-03 根据修理进行的修改   end
        // if (Rep.size() > 0 && '待EtQ Response'.equals(Rep.get(0).ComplaintStatus__c)) {
        //     editFlag = true;
        // }
        paedRecordDetailView = new List < PAE_DecisionRecordDetailInfo > ();
        editAble = false;
        CancelineFlag = 2;
        productIdx = '';
        // PAE_DecisionRecord__c 记录类型 ASRCDecision ASACDecision
        // ASRCDecision --> Intake
        // ASACDecision --> Final
        RecordTypeName = ApexPages.currentPage().getParameters().get('RecordTypeIds');
        pageLimit = Integer.valueOf(System.Label.mpddetPageLimitsize);//系统标签
    }
    public void init() {
        editAble = true;
        //当前登录着的ProfileId
        String profileId = UserInfo.getProfileId().substring(0, 15);
        //118_CFDA(质量法规本部)担当 简档ID和 118_CFDA(质量法规本部)窗口 简档ID和管理员
        if (profileId.equals(System.Label.ProfileId_OCSM_QARA1) || profileId.equals(System.Label.ProfileId_OCSM_QARA2) || UserInfo.getProfileId().equals(System.Label.ProfileId_SystemAdmin)) {
            OCSM_QARA = '1';
        } else {
            OCSM_QARA = '0';
        }
        //ProfileId 2F2B_2F4
        if (System.Label.ProfileId2F2B_2F4.contains(profileId)) {
            OCSM_Cording = '1';
        } else {
            OCSM_Cording = '0';
        }
        if (System.Label.ProfileId2F2B_2F4.contains(profileId) || UserInfo.getProfileId() == System.Label.ProfileId_SystemAdmin) {
            savebuton = true;
        } else {
            savebuton = false;
        }
        if (String.isNotBlank(RecordTypeName)) {
            RecordTypeId = Schema.SObjectType.PAE_DecisionRecord__c.getRecordTypeInfosByDeveloperName().get(RecordTypeName).getRecordTypeId();
        } else {
            List < PAE_DecisionRecord__c > paedRdList = [select Id, PAE_Report__c, RecordTypeId, PAEDetail_DetermineResults__c, RecordType.DeveloperName from PAE_DecisionRecord__c where Id = : Id];
            if (paedRdList.size() > 0) {
                RecordTypeName = paedRdList[0].RecordType.DeveloperName;
                RecordTypeId = paedRdList[0].PAE_Report__c;
            }
        }
        if ('ASRCDecision' == RecordTypeName) {
            ASac_ASrc = 'Intake';
            RecordTypeIdD = Schema.SObjectType.PAE_DecisionRecordDetail__c.getRecordTypeInfosByDeveloperName().get('intake').getRecordTypeId();
        } else if ('ASACDecision' == RecordTypeName) {
            ASac_ASrc = 'Final';
            RecordTypeIdD = Schema.SObjectType.PAE_DecisionRecordDetail__c.getRecordTypeInfosByDeveloperName().get('final').getRecordTypeId();
        }
        rdRecord = new PAE_DecisionRecord__c();
        Report__c repair1OrQIS1;
        if (!string.isBlank(ReportId)) {
            repair1OrQIS1 = [select id, PAE_codez__c, PAE_temp_final_code__c, PAE_reappear_confirm__c from Report__c where id = : ReportId];
        }
        Map < String, PAE_DecisionRecordDetailInfo > MidMap = new Map < String, PAE_DecisionRecordDetailInfo > ();
        if (Id == NULL || Id == '') {
            if (string.isnotBlank(ReportId)) {
                rdRecord.PAE_reappear_confirm__c = repair1OrQIS1.PAE_reappear_confirm__c;
            }
            //预留一行
            PAE_DecisionRecordDetail__c paedrd = new PAE_DecisionRecordDetail__c();
            paedrd.PAED_Status__c = '有效';
            paedrd.RecordTypeId = RecordTypeIdD;
            paedRecordDetailView.add(new PAE_DecisionRecordDetailInfo(paedrd));
            //预留一行
        } else {
            List < PAE_DecisionRecord__c > rdRecordList = new List < PAE_DecisionRecord__c > ();
            List < PAE_DecisionRecordDetail__c > rdRecordDetailList = new List < PAE_DecisionRecordDetail__c > ();
            rdRecordList = [SELECT Id, Name, CurrencyIsoCode, CreatedDate, CreatedById, LastModifiedDate, LastModifiedById,
                SystemModstamp, PAE_DetermineResults__c, PAE_ConfirmationDate__c,
                PAE_Authenticator__c, PAE_reappear_confirm__c,
                PAEDetail_DetermineResults__c, PAE_DetermineResults_Text__c
                FROM PAE_DecisionRecord__c where Id = : Id
            ];
            if (rdRecordList.size() > 0) {
                rdRecord = rdRecordList[0];
            }
            //PAE_reappear_confirm__c  再现结果确认
            if (string.isnotBlank(ReportId)) {
                rdRecord.PAE_reappear_confirm__c = repair1OrQIS1.PAE_reappear_confirm__c;
            }
            rdRecordDetailList = [SELECT Id, IsDeleted, Name, CurrencyIsoCode, CreatedDate, CreatedById,
                LastModifiedDate, LastModifiedById, SystemModstamp, PAE_DecisionRecordD__c,
                PAED_ManagementCode__c, PAE_Judge__c, PAED_Reappear_Result__c, PAED_ResultAffirmant__r.Name,
                PAED_ResultConfirmationDate__c, Final_universal_code__c,
                PAED_Status__c, PAED_ConfirmationDate__c, PAED_Affirmant__c, PAE_is_save__c,
                PAED_Affirmant__r.Name, PAED_RCAC__c, PAED_CancellationDate__c, PAED_Nullifier__c,
                PAED_Nullifier__r.Name, isInterfaceCreate__c, Location__c, LocationGroup__c, FinalUniversalDesc__c,
                Phenomenon__c, IntakeUniversalDesc__c, PhenomenonDesc__c,
                // NFM109信息获取,Gzw add 20200826
                Description__c, Cause__c, EtqPart__c, EtqAsAnalyzed__c, EtqCause__c,
                InspectionCategory109__c, PAED_Affirmant_F__c, PAED_ConfirmationDate_F__c,
                //课题94 add by rentongxiao 2020-10-10 start
                PAED_ResultAffirmant_new__c
                //add by rentx 2020-11-04
                , isedit__c, RecordTypeId
                // RVS005信息获取 gzw add 20201126 start
                , RVSDetailNo__c, RVS_Date__c, RVS_Time__c, RVS_Decision_Person__c, Monitor_PAE__c
                // RVS005信息获取 gzw add 20201126 end
                FROM PAE_DecisionRecordDetail__c
                where PAE_DecisionRecordD__c = : Id Order by PAED_Status__c, PAED_ManagementCode__c ASC
            ];
            for (Integer i = 0; i < rdRecordDetailList.size(); i++) {
                MidMap.put(rdRecordDetailList[i].Id, new PAE_DecisionRecordDetailInfo(rdRecordDetailList[i]));
            }
            for (PAE_DecisionRecordDetailInfo paeDrd: MidMap.values()) {
                paedRecordDetailView.add(paeDrd);
            }
        }
    }
    //保存并关闭
    public PageReference SaveAndClose() {
        // 取消行
        if (CancelineFlag == 3) {
            Integer FLG = 0;
            Integer Count = 0;
            for (PAE_DecisionRecordDetailInfo CheckCount: paedRecordDetailView) {
                FLG = FLG + 1;
                if (CheckCount.check == false) {
                    Count = Count + 1;
                }
            }
            if (Count == FLG) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请选择要取消的行'));
                return null;
            }
        }
        List < PAE_DecisionRecordDetail__c > insertPaeDRDList = new List < PAE_DecisionRecordDetail__c > ();
        Savepoint sp = Database.setSavepoint();
        PAE_DecisionRecord__c paedRecord = new PAE_DecisionRecord__c();
        String paedRecordId = '';
        //明细有效状态此记录的总数量
        //明细有效状态此记录的PAE数量
        //明细有效状态此记录的Unknown数量
        //明细有效状态此记录的NonPAE数量
        Integer PAE_Judge_num = 0;
        Integer PAE_Judge_num_PAE = 0;
        Integer PAE_Judge_num_Unknown = 0;
        Integer PAE_Judge_num_nonPAE = 0;
        String PAE_DetermineResults = null;
        String prevDetermineResults = null;
        // try {
            //明细有效状态此记录的总数量
            //明细有效状态此记录的PAE数量
            //明细有效状态此记录的Unknown数量
            //明细有效状态此记录的NonPAE数量
            //如果Code包含汉字或超过15字数的化,需要提醒。【Intake universal code不可以使用汉字,不可以超过15字数】
            for (PAE_DecisionRecordDetailInfo rdRecorddl: paedRecordDetailView) {
                if (!(rdRecorddl.check && CancelineFlag == 3) && rdRecorddl.paedrdd.PAED_Status__c != '取消') {
                    PAE_Judge_num++;
                    if (rdRecorddl.paedrdd.PAE_Judge__c == 'PAE') {
                        PAE_Judge_num_PAE++;
                    }
                    if (rdRecorddl.paedrdd.PAE_Judge__c == 'Unknown') {
                        PAE_Judge_num_Unknown++;
                    }
                    if (rdRecorddl.paedrdd.PAE_Judge__c == 'nonPAE') {
                        PAE_Judge_num_nonPAE++;
                    }
                    // gzw 20210409 修改参数为空时,表达式判断出错问题
                    if (Schema.SObjectType.PAE_DecisionRecordDetail__c.getRecordTypeInfosByDeveloperName().get('intake').getRecordTypeId() == rdRecorddl.paedrdd.RecordTypeId && (containsChineseCharacters(rdRecorddl.paedrdd.PAED_ManagementCode__c) || (String.isNotBlank(rdRecorddl.paedrdd.PAED_ManagementCode__c) && rdRecorddl.paedrdd.PAED_ManagementCode__c.length() > 15))) {
                        rdRecorddl.paedrdd.PAED_ManagementCode__c.adderror('Intake universal code不可以使用汉字,不可以超过15字数。');
                        return null;
                    }
                }
                System.debug('rdRecorddl.paedrdd.Location__c' + rdRecorddl.paedrdd.Location__c);
            }
            if (PAE_Judge_num_PAE > 0) {
                PAE_DetermineResults = 'PAE';
            } else if (PAE_Judge_num_Unknown > 0) {
                PAE_DetermineResults = 'Unknown';
            } else if (PAE_Judge_num_nonPAE == PAE_Judge_num && PAE_Judge_num_nonPAE > 0) {
                PAE_DetermineResults = 'nonPAE';
            } else {
                PAE_DetermineResults = null;
            }
            rdRecord.PAE_DetermineResults_Text__c = PAE_DetermineResults;
            //System.debug('-----------------------:' + PAE_DetermineResults);
            //新增PAE判定
            if (String.isBlank(Id)) {
                //检查明细的编码是否为空---20200107 add 检查明细的PAE判定是否必填
                if (IsEmptyManagementCode(paedRecordDetailView)) {
                    return null;
                }
                paedRecord.PAE_Report__c = ReportId;
                paedRecord.PAE_reappear_confirm__c = rdRecord.PAE_reappear_confirm__c; // 20200908 Gzw Final 再现结果丢失问题 add
                paedRecord.RecordTypeId = RecordTypeId;
                insert paedRecord;
                paedRecordId = paedRecord.Id;
                UpsertPAE_DecisionRecordDetail(null, paedRecordDetailView, paedRecordId, false, prevDetermineResults);
            } else {
                //修改PAE变更
                List < PAE_DecisionRecord__c > paedRecordList = [select Id, PAE_DetermineResults__c, PAE_DetermineResults_Text__c, PAE_reappear_confirm__c from PAE_DecisionRecord__c where Id = : Id];
                List < PAE_DecisionRecordDetail__c > rdRecordDetailList = new List < PAE_DecisionRecordDetail__c > ();
                //存在的明细Map
                Map < Id, PAE_DecisionRecordDetail__c > paedRecordStatusMap = new Map < Id, PAE_DecisionRecordDetail__c > ();
                rdRecordDetailList = [SELECT Id, IsDeleted, Name, CurrencyIsoCode, CreatedDate, CreatedById,
                    LastModifiedDate, LastModifiedById, SystemModstamp, PAE_DecisionRecordD__c,
                    PAED_ManagementCode__c, PAE_Judge__c, PAED_Reappear_Result__c, PAED_ResultAffirmant__r.Name,
                    PAED_ResultConfirmationDate__c, Final_universal_code__c,
                    PAED_Status__c, PAED_ConfirmationDate__c, PAED_Affirmant__c, PAE_is_save__c,
                    PAED_Affirmant__r.Name, PAED_RCAC__c, PAED_CancellationDate__c, PAED_Nullifier__c,
                    PAED_Nullifier__r.Name, isInterfaceCreate__c, Location__c, LocationGroup__c, FinalUniversalDesc__c,
                    Phenomenon__c, IntakeUniversalDesc__c, PhenomenonDesc__c,
                    // NFM109信息获取,Gzw add 20200826
                    Description__c, Cause__c, EtqPart__c, EtqAsAnalyzed__c, EtqCause__c,
                    InspectionCategory109__c, PAED_Affirmant_F__c, PAED_ConfirmationDate_F__c,
                    //课题94 add by rentongxiao 2020-10-10 start
                    PAED_ResultAffirmant_new__c
                    //add by rentx
                    , isedit__c, RecordTypeId
                    // RVS005信息获取 gzw add 20201126 start
                    , RVSDetailNo__c, RVS_Date__c, RVS_Time__c, RVS_Decision_Person__c, Monitor_PAE__c
                    // RVS005信息获取 gzw add 20201126 end
                    FROM PAE_DecisionRecordDetail__c
                    where PAE_DecisionRecordD__c = : Id Order by PAED_Status__c, PAED_ManagementCode__c
                ];
                if (rdRecordDetailList.size() > 0) {
                    for (PAE_DecisionRecordDetail__c paedrd: rdRecordDetailList) {
                        paedRecordStatusMap.put(paedrd.Id, paedrd);
                    }
                }
                system.debug('paedRecordStatusMap===========>'+paedRecordStatusMap);
                if (paedRecordList.size() > 0) {
                    //PAE判定的Id
                    paedRecordId = paedRecordList[0].Id;
                    //PAE判定记录的状态不变
                    prevDetermineResults = paedRecordList[0].PAE_DetermineResults_Text__c;
                    if (paedRecordList[0].PAE_DetermineResults_Text__c == PAE_DetermineResults) {
                        //检查明细的编码是否为空---20200107 add 检查明细的PAE判定是否必填
                        if (IsEmptyManagementCode(paedRecordDetailView)) {
                            return null;
                        }
                        UpsertPAE_DecisionRecordDetail(paedRecordStatusMap, paedRecordDetailView, paedRecordId, false, prevDetermineResults);
                    } else if (paedRecordList[0].PAE_DetermineResults_Text__c != PAE_DetermineResults) {
                        //PAE判定记录的状态改变
                        //检查明细的编码是否为空---20200107 add 检查明细的PAE判定是否必填
                        if (IsEmptyManagementCode(paedRecordDetailView)) {
                            return null;
                        }
                        insertPaeDRDList = new List < PAE_DecisionRecordDetail__c > ();
                        paedRecord.PAE_DetermineResults_Text__c = PAE_DetermineResults;
                        paedRecord.PAE_Report__c = ReportId;
                        paedRecord.RecordTypeId = RecordTypeId;
                        insert paedRecord;
                        paedRecordId = paedRecord.Id;
                        UpsertPAE_DecisionRecordDetail(paedRecordStatusMap, paedRecordDetailView, paedRecordId, true, prevDetermineResults);
                    }
                }
            }
        // } catch (Exception e) {
        //     ApexPages.addMessages(e);
        //     Database.rollback(sp);
        //     return null;
        // }
        if (CancelineFlag != 2) {
            return RefreshOriginalInterface(paedRecordId);
        } else {
            return ReturnReportInterface();
        }
    }
    //返回报告书页面
    public PageReference ReturnReportInterface() {
        PageReference ref;
        system.debug('啦啦啦ReportId1' + ReportId);
        if (String.isnotBlank(ReportId)) {
            ref = new Pagereference('/' + ReportId);
        }
        //PageReference ref = new Pagereference('/' + ReportId);
        ref.setRedirect(true);
        return ref;
    }
    //留在当前页面
    public PageReference RefreshOriginalInterface(String paedRecordId) {
        PageReference ref;
        if (String.isnotBlank(ReportId)) {
            ref = new Pagereference('/apex/RepPAEDecisionRecord?Id=' + paedRecordId + '&ReportId=' + ReportId + '&RecordTypeIds=' + RecordTypeName);
        }
        ref.setRedirect(true);
        return ref;
    }
    //返回Intake页面
    public PageReference toIntake() {
        String url = null;
        if (String.isnotBlank(ReportId)) {
            List < PAE_DecisionRecord__c > pAE_DecisionRecord = [SELECT LastModifiedDate, Id, Name, LastModifiedById, RecordType.DeveloperName FROM PAE_DecisionRecord__c where PAE_Report__c = : ReportId And RecordType.DeveloperName = 'ASRCDecision'
                Order by LastModifiedDate desc
            ];
            if (pAE_DecisionRecord.size() > 0) {
                url = '/apex/RepPAEDecisionRecord?Id=' + pAE_DecisionRecord[0].Id + '&ReportId=' + ReportId + '&RecordTypeIds=ASRCDecision';
            } else {
                url = '/apex/RepPAEDecisionRecord?ReportId=' + ReportId + '&RecordTypeIds=ASRCDecision';
            }
        }
        PageReference ref = new Pagereference(url);
        ref.setRedirect(true);
        return ref;
    }
   //插入空行
    public PageReference InsertRow() {
        // 2021-12-08  zxk  精琢科技   手动赋值逻辑  start
        List < String > codeNumDataList = new List < String > ();
        for (PAE_DecisionRecordDetailInfo pdrdInFoCode: paedRecordDetailView) {
            String managementCodeStr = pdrdInFoCode.paedrdd.PAED_ManagementCode__c;
            if (String.isBlank(pdrdInFoCode.paedrdd.id) && String.isNotBlank(managementCodeStr)) {
                codeNumDataList.add(managementCodeStr);
            }
        }
        Map < String, String > strMapData = updateIsPae(codeNumDataList);
        for (PAE_DecisionRecordDetailInfo pdrdInFoCode: paedRecordDetailView) {
            String managementCodeStr = pdrdInFoCode.paedrdd.PAED_ManagementCode__c;
            if (String.isBlank(pdrdInFoCode.paedrdd.Id)) {
                if (String.isNotBlank(managementCodeStr)) {
                    if (pdrdInFoCode.paedrdd.PAE_Judge__c != strMapData.get(managementCodeStr) || String.isBlank(strMapData.get(managementCodeStr))) {
                        pdrdInFoCode.monitorPAE = true;
                    } else {
                        pdrdInFoCode.monitorPAE = false;
                    }
                }
            }
        }
        // 2021-12-08  zxk  精琢科技   手动赋值逻辑  end
        PAE_DecisionRecordDetail__c paedrd = new PAE_DecisionRecordDetail__c();
        paedrd.PAED_Status__c = '有效';
        paedrd.RecordTypeId = RecordTypeIdD;
        // Integer styNum = paedRecordDetailView.size();
        paedRecordDetailView.add(new PAE_DecisionRecordDetailInfo(paedrd));
        return null;
    }
    //批量插入空行字符串
    public void InsertMoreRows() {
        // 精琢科技   zxk  2021-10-21  start  给PAE判定记录赋值
        List < String > codeNumDataList = new List < String > ();
        for (PAE_DecisionRecordDetailInfo pdrdInFoCode: paedRecordDetailView) {
            String managementCodeStr = pdrdInFoCode.paedrdd.PAED_ManagementCode__c;
            if (String.isBlank(pdrdInFoCode.paedrdd.id) && String.isNotBlank(managementCodeStr)) {
                // && pdrdInFoCode.paedrdd.PAE_is_save__c != '1'
                for (String codeStr: managementCodeStr.split(',')) {
                    if (String.isNotBlank(codeStr)) {
                        codeNumDataList.add(codeStr);
                    }
                }
            }
        }
        Map < String, String > strMapData = updateIsPae(codeNumDataList);
        // 精琢科技   zxk  2021-10-21  end  给PAE判定记录赋值
        List < PAE_DecisionRecordDetailInfo > paedRecordDetailViewTemporary = new List < PAE_DecisionRecordDetailInfo > ();
        List < String > codeList = new List < String > ();
        for (PAE_DecisionRecordDetailInfo paedRDInfo: paedRecordDetailView) {
            String managementCode = paedRDInfo.paedrdd.PAED_ManagementCode__c;
            String finalUniversalCode = paedRDInfo.paedrdd.Final_universal_code__c;
            Date confirmationDate = paedRDInfo.paedrdd.PAED_ConfirmationDate__c;
            String pStatus = paedRDInfo.paedrdd.PAED_Status__c;
            PAE_DecisionRecordDetail__c paedrd = new PAE_DecisionRecordDetail__c();
            // 20210719 gzw LJPH-C4Y57Q start
            if (managementCode == '000' && paedRDInfo.paedrdd.PAE_Judge__c == null) {
                paedRDInfo.paedrdd.PAE_Judge__c = 'Unknown';
            }
            // 20210719 gzw LJPH-C4Y57Q end
            if (paedRDInfo.paedrdd.PAED_Status__c != '取消') {
                if (String.isBlank(finalUniversalCode) && confirmationDate == null) {
                    if (String.isNotBlank(managementCode)) {
                        if (managementCode.indexof(',') != -1) {
                            Integer q = 1;
                            for (String code: managementCode.split(',')) {
                                 // 2021-12-08  zxk  精琢科技   手动赋值逻辑  start
                                PAE_DecisionRecordDetailInfo info = new PAE_DecisionRecordDetailInfo();
                                // 2021-12-08  zxk  精琢科技   手动赋值逻辑  end
                                // bug fix gzw 已有的空code数据,数据数据时,会新建  20201214 start
                                PAE_DecisionRecordDetail__c paedrdtemp;
                                if (q == 1) {
                                    paedrdtemp = paedRDInfo.paedrdd;
                                } else {
                                    paedrdtemp = new PAE_DecisionRecordDetail__c();
                                }
                                paedrd = ReproduceResult(paedrdtemp, paedRDInfo); //20200106 add
                                // bug fix gzw 已有的空code数据,数据数据时,会新建  20201214 start
                                paedrd.PAED_Status__c = '有效';
                                paedrd.PAED_ManagementCode__c = code;
                                if (code == '000') {
                                    paedrd.PAE_Judge__c = 'Unknown';
                                }
                                paedrd.RecordTypeId = RecordTypeIdD;
                                paedrd.PAE_is_save__c = '';
                                  // 精琢科技   zxk  2021-10-21  start  给PAE判定记录赋值
                                if (strMapData.containsKey(code)) {
                                    paedrd.PAE_Judge__c = strMapData.get(code);
                                    info.strJudge = strMapData.get(code);
                                    info.monitorPAE = false;
                                    paedrd.Monitor_PAE__c = false;
                                } else if (managementCode.indexof(code) != -1) {
                                        paedrd.PAE_Judge__c = null;
                                        info.strJudge = paedRDInfo.strJudge;
                                        info.monitorPAE = true;
                                }
                                if (paedrd.PAE_Judge__c == null || paedrd.PAE_Judge__c == '') {
                                    paedrd.Monitor_PAE__c = true;
                                    info.monitorPAE = true;
                                }
                                info.paedrdd = paedrd;
                                paedRecordDetailViewTemporary.add(info);
                                // 精琢科技   zxk  2021-10-21  end  给PAE判定记录赋值
                                q++;
                            }
                        } else {
                             // 2021-12-08  zxk  精琢科技   手动赋值逻辑  start
                            PAE_DecisionRecordDetailInfo info = new PAE_DecisionRecordDetailInfo();
                            // 2021-12-08  zxk  精琢科技   手动赋值逻辑  end
                            // bug fix gzw 已有的空code数据,数据数据时,会新建  20201214 start
                            PAE_DecisionRecordDetail__c paedrdtemp = paedRDInfo.paedrdd;
                            paedrd = ReproduceResult(paedrdtemp, paedRDInfo); //20200106 add
                            // bug fix gzw 已有的空code数据,数据数据时,会新建  20201214 end
                            paedrd.PAED_Status__c = '有效';
                            paedrd.RecordTypeId = RecordTypeIdD;
                            paedrd.PAED_ManagementCode__c = managementCode;
                             // 精琢科技   zxk  2021-10-21  start  给PAE判定记录赋值
                            if (strMapData.containsKey(managementCode) && productIdx == managementCode) {
                                paedrd.PAE_Judge__c = strMapData.get(managementCode);
                                info.strJudge = strMapData.get(managementCode);
                                info.monitorPAE = false;
                                paedrd.Monitor_PAE__c = false;
                            } else {
                                 info.strJudge = paedRDInfo.strJudge;
                                if (strMapData.get(managementCode) != paedRDInfo.paedrdd.PAE_Judge__c || (paedrd.PAE_Judge__c == null || paedrd.PAE_Judge__c == '')) {
                                    info.monitorPAE = true;
                                }
                            }
                            if (paedrd.PAE_Judge__c == null || paedrd.PAE_Judge__c == '') {
                                paedrd.Monitor_PAE__c = true;
                                // info.monitorPAE = true;
                            }
                            info.paedrdd = paedrd;
                            paedRecordDetailViewTemporary.add(info);
                            // 精琢科技   zxk  2021-10-21  end  给PAE判定记录赋值
                        }
                    } else {
                        // Gzw 20201215 编辑页面空白行失去焦点后行消失 对应
                        paedRecordDetailViewTemporary.add(paedRDInfo);
                    }
                } else {
                    paedRecordDetailViewTemporary.add(paedRDInfo);
                }
            } else {
                paedRecordDetailViewTemporary.add(paedRDInfo);
            }
        }
        if (paedRecordDetailViewTemporary != null) {
            paedRecordDetailView = new List < PAE_DecisionRecordDetailInfo > ();
            paedRecordDetailView.addAll(paedRecordDetailViewTemporary);
            if (paedRecordDetailView.size() == 0) {
                PAE_DecisionRecordDetail__c paedrd = new PAE_DecisionRecordDetail__c();
                paedrd.PAED_Status__c = '有效';
                paedrd.RecordTypeId = RecordTypeIdD;
                paedRecordDetailView.add(new PAE_DecisionRecordDetailInfo(paedrd));
            }
        }
    }
    //检查明细的编码是否为空---20200107 add 检查明细的PAE判定是否必填
    public Boolean IsEmptyManagementCode(List < PAE_DecisionRecordDetailInfo > paedRecordDetailView) {
        String isEmpty = '';
        if (paedRecordDetailView.size() == 0) {
            return true;
        }
        // gzw 20201215 取消时不需要判断编码和状态 追加 && CancelineFlag != 3
        for (PAE_DecisionRecordDetailInfo paedRDInfo: paedRecordDetailView) {
            // gzw 20201215 取消时,不判断报错
            if (paedRDInfo.paedrdd.PAED_Status__c == '取消') {
                continue;
            }
            if (paedRDInfo.paedrdd != null) {
                system.debug('paedRDInfo.paedrdd.PAED_ManagementCode__c==========>'+paedRDInfo.paedrdd.PAED_ManagementCode__c);
                system.debug('CancelineFlag=========>'+CancelineFlag);
                system.debug('paedRDInfo.paedrdd.PAE_Judge__c==========>'+paedRDInfo.paedrdd.PAE_Judge__c);
                if (String.isBlank(paedRDInfo.paedrdd.PAED_ManagementCode__c) && CancelineFlag != 3) {
                    isEmpty = 'PAE判定记录明细的编码不能为空';
                }
                if (String.isBlank(paedRDInfo.paedrdd.PAE_Judge__c) && CancelineFlag != 3) {
                    isEmpty = 'PAE判定记录明细的PAE判定不能为空';
                }
            } else {
                if (String.isBlank(paedRDInfo.paedrdd.PAED_ManagementCode__c) && CancelineFlag != 3) {
                    isEmpty = 'PAE判定记录明细的编码不能为空';
                }
                if (String.isBlank(paedRDInfo.paedrdd.PAE_Judge__c) && CancelineFlag != 3) {
                    isEmpty = 'PAE判定记录明细的PAE判定不能为空';
                }
            }
            // gzw 20210409 修改参数为空时,表达式判断出错问题
            if (Schema.SObjectType.PAE_DecisionRecordDetail__c.getRecordTypeInfosByDeveloperName().get('intake').getRecordTypeId() == paedRDInfo.paedrdd.RecordTypeId && (containsChineseCharacters(paedRDInfo.paedrdd.PAED_ManagementCode__c) || (String.isNotBlank(paedRDInfo.paedrdd.PAED_ManagementCode__c) && paedRDInfo.paedrdd.PAED_ManagementCode__c.length() > 15))) {
                isEmpty = 'Intake universal code不可以使用汉字,不可以超过15字数。';
                paedRDInfo.paedrdd.PAED_ManagementCode__c.adderror('Intake universal code不可以使用汉字,不可以超过15字数。');
                return true;
            }
        }
        if (String.isNotBlank(isEmpty)) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '包含无效数据:' + isEmpty));
            return true;
        }
        return false;
    }
    //更新PAE明细
    public void UpsertPAE_DecisionRecordDetail(Map < Id, PAE_DecisionRecordDetail__c > paedRecordStatusMap, List < PAE_DecisionRecordDetailInfo > paedRecordDetailView, String paedRecordId, Boolean updateStatusFlag, String prevDetermineResults) {
         system.debug('paedRecordStatusMap.size()===============>'+paedRecordStatusMap);
        List < PAE_DecisionRecordDetail__c > upsertPaedrDetailList = new List < PAE_DecisionRecordDetail__c > ();
        String repair_PAED_ManagementCodes = '';
        String repair_PAED_ManagementCodesZ = '';
        String PAE_codez = '';
        String reappear_confirm = null;
        Integer PAED_Reappear_Result_noSelect_num = 0;
        Integer valid_num = 0;
         // 精琢科技   zxk  2021-10-21  start  给PAE判定记录赋值
        List < String > codeNumDataList = new List < String > ();
        for (PAE_DecisionRecordDetailInfo pdrdInFoCode: paedRecordDetailView) {
            String managementCodeStr = pdrdInFoCode.paedrdd.PAED_ManagementCode__c;
            if (String.isBlank(pdrdInFoCode.paedrdd.id) && String.isNotBlank(managementCodeStr)) {
                for (String codeStr: managementCodeStr.split(',')) {
                    if (String.isNotBlank(codeStr)) {
                        codeNumDataList.add(codeStr);
                    }
                }
            }
        }
        Map < String, String > strMapData = updateIsPae(codeNumDataList);
        // 精琢科技   zxk  2021-10-21  end  给PAE判定记录赋值
        System.debug('paedRecordDetailView ++++++++ ' + paedRecordDetailView.size());
        for (PAE_DecisionRecordDetailInfo paedRDInfo: paedRecordDetailView) {
            PAE_DecisionRecordDetail__c paedrd = new PAE_DecisionRecordDetail__c();
            if (paedRDInfo.paedrdd != null) {
                paedrd.PAED_Report__c = ReportId;
                paedrd.PAED_RCAC__c = ASac_ASrc;
                paedrd.PAE_DecisionRecordD__c = paedRecordId;
                paedrd.RecordTypeId = RecordTypeIdD;
                paedrd.PAE_is_save__c = '1'; //20200319 add
                system.debug('paedRecordStatusMap.containsKey(paedRDInfo.paedrdd.Id)===============>'+paedRDInfo.paedrdd.Id);
                if (paedRecordStatusMap != null && paedRecordStatusMap.size() > 0 && paedRecordStatusMap.containsKey(paedRDInfo.paedrdd.Id)) {
                    // Gzw add 20200821 PAE结果变化时,保存接口信息字段 start
                    paedrd.isInterfaceCreate__c = paedRecordStatusMap.get(paedRDInfo.paedrdd.Id).isInterfaceCreate__c;
                    paedrd.LocationGroup__c = paedRecordStatusMap.get(paedRDInfo.paedrdd.Id).LocationGroup__c;
                    paedrd.Location__c = paedRecordStatusMap.get(paedRDInfo.paedrdd.Id).Location__c;
                    paedrd.Phenomenon__c = paedRecordStatusMap.get(paedRDInfo.paedrdd.Id).Phenomenon__c;
                    paedrd.Description__c = paedRecordStatusMap.get(paedRDInfo.paedrdd.Id).Description__c;
                    paedrd.Cause__c = paedRecordStatusMap.get(paedRDInfo.paedrdd.Id).Cause__c;
                    paedrd.EtqPart__c = paedRecordStatusMap.get(paedRDInfo.paedrdd.Id).EtqPart__c;
                    paedrd.EtqAsAnalyzed__c = paedRecordStatusMap.get(paedRDInfo.paedrdd.Id).EtqAsAnalyzed__c;
                    paedrd.EtqCause__c = paedRecordStatusMap.get(paedRDInfo.paedrdd.Id).EtqCause__c;
                    paedrd.FinalUniversalDesc__c = paedRecordStatusMap.get(paedRDInfo.paedrdd.Id).FinalUniversalDesc__c;
                    paedrd.InspectionCategory109__c = paedRecordStatusMap.get(paedRDInfo.paedrdd.Id).InspectionCategory109__c;
                    // Gzw add 20200821 PAE结果变化时,保存接口信息字段 end
                    // Gzw add 20200821 PAE结果变化时,保存RVS005接口信息字段 start
                    paedrd.RVSDetailNo__c = paedRecordStatusMap.get(paedRDInfo.paedrdd.Id).RVSDetailNo__c;
                    paedrd.PhenomenonDesc__c = paedRecordStatusMap.get(paedRDInfo.paedrdd.Id).PhenomenonDesc__c;
                    paedrd.RVS_Date__c = paedRecordStatusMap.get(paedRDInfo.paedrdd.Id).RVS_Date__c;
                    paedrd.RVS_Time__c = paedRecordStatusMap.get(paedRDInfo.paedrdd.Id).RVS_Time__c;
                    paedrd.RVS_Decision_Person__c = paedRecordStatusMap.get(paedRDInfo.paedrdd.Id).RVS_Decision_Person__c;
                    // Gzw add 20200821 PAE结果变化时,保存RVS005接口信息字段 start
                    paedrd.PAED_Affirmant__c = paedRecordStatusMap.get(paedRDInfo.paedrdd.Id).PAED_Affirmant__c;
                    paedrd.PAED_ConfirmationDate__c = paedRecordStatusMap.get(paedRDInfo.paedrdd.Id).PAED_ConfirmationDate__c;
                     // 精琢科技  zxk  为Monitor_PAE__c赋值   start
                    paedrd.Monitor_PAE__c = paedRecordStatusMap.get(paedRDInfo.paedrdd.Id).Monitor_PAE__c;
                    // 精琢科技  zxk  为Monitor_PAE__c赋值   end
                    paedrd = ReproduceResult(paedrd, paedRDInfo);
                    if (CancelineFlag == 3 && paedRDInfo.check && paedRDInfo.paedrdd.PAED_Status__c != '取消') {
                        //有效变成取消
                        paedrd.PAED_ManagementCode__c = paedRecordStatusMap.get(paedRDInfo.paedrdd.Id).PAED_ManagementCode__c;
                        paedrd.PAED_Status__c = '取消';
                        paedrd.PAED_CancellationDate__c = Date.toDay();
                        paedrd.PAED_Nullifier__c = UserInfo.getUserId();
                    } else if (paedRDInfo.paedrdd.PAED_Status__c == '有效') {
                        //有效PAE明细编码
                        paedrd.PAED_Status__c = '有效';
                        paedrd.PAED_ManagementCode__c = paedRDInfo.paedrdd.PAED_ManagementCode__c;
                        if (String.isBlank(repair_PAED_ManagementCodes)) {
                            repair_PAED_ManagementCodes = paedRDInfo.paedrdd.PAED_ManagementCode__c;
                        } else {
                            repair_PAED_ManagementCodes += ',' + paedRDInfo.paedrdd.PAED_ManagementCode__c;
                        }
                        if (paedRDInfo.paedrdd.PAED_Reappear_Result__c == '不再現' && !paedRDInfo.paedrdd.PAED_ManagementCode__c.equals('000')) {
                            // WLIG-BWMB4S gzw start
                            String pmcode = paedRDInfo.paedrdd.PAED_ManagementCode__c.trim();
                            if (pmcode.length() == 3 && (pmcode.endsWith('V') || pmcode.endsWith('W') || pmcode.endsWith('X') || pmcode.endsWith('Y'))) {
                                PAE_codez = pmcode.substring(0, pmcode.length() - 1) + 'Z';
                            } else {
                                PAE_codez = pmcode + 'Z';
                            }
                            // WLIG-BWMB4S gzw end
                            if (String.isBlank(repair_PAED_ManagementCodesZ)) {
                                repair_PAED_ManagementCodesZ = PAE_codez;
                            } else {
                                repair_PAED_ManagementCodesZ += ',' + PAE_codez;
                            }
                        }
                        valid_num++;
                        if (paedrd.PAED_Reappear_Result__c == null) {
                            PAED_Reappear_Result_noSelect_num++;
                        }
                    } else if (paedRDInfo.paedrdd.PAED_Status__c == '取消') {
                        paedrd.PAED_Status__c = '取消';
                        paedrd.PAED_ManagementCode__c = paedRDInfo.paedrdd.PAED_ManagementCode__c;
                        paedrd.PAED_Nullifier__c = paedRecordStatusMap.get(paedRDInfo.paedrdd.Id).PAED_Nullifier__c; //UserInfo.getUserId();
                        paedrd.PAED_CancellationDate__c = paedRecordStatusMap.get(paedRDInfo.paedrdd.Id).PAED_CancellationDate__c; //Date.toDay();
                    }
                } else if ((paedRecordStatusMap != null && paedRecordStatusMap.size() > 0 && !paedRecordStatusMap.containsKey(paedRDInfo.paedrdd.Id)) || paedRecordStatusMap == null) {
                    paedrd = ReproduceResult(paedrd, paedRDInfo);
                    if (paedRDInfo.check && CancelineFlag == 3) {
                        //新增取消PAE判定明细
                        paedrd.PAED_CancellationDate__c = Date.toDay();
                        paedrd.PAED_Nullifier__c = UserInfo.getUserId();
                        paedrd.PAED_Status__c = '取消';
                    } else {
                        paedrd.PAED_Affirmant__c = UserInfo.getUserId();
                        paedrd.PAED_ConfirmationDate__c = Date.toDay();
                        paedrd.PAED_Status__c = paedRDInfo.paedrdd.PAED_Status__c;
                        if (String.isBlank(repair_PAED_ManagementCodes)) {
                            repair_PAED_ManagementCodes = paedRDInfo.paedrdd.PAED_ManagementCode__c;
                        } else {
                            repair_PAED_ManagementCodes += ',' + paedRDInfo.paedrdd.PAED_ManagementCode__c;
                        }
                        //20191217 add
                        if (paedRDInfo.paedrdd.PAED_Reappear_Result__c == '不再現' && !paedRDInfo.paedrdd.PAED_ManagementCode__c.equals('000')) {
                            // WLIG-BWMB4S gzw start
                            String pmcode = paedRDInfo.paedrdd.PAED_ManagementCode__c.trim();
                            if (pmcode.length() == 3 && (pmcode.endsWith('V') || pmcode.endsWith('W') || pmcode.endsWith('X') || pmcode.endsWith('Y'))) {
                                PAE_codez = pmcode.substring(0, pmcode.length() - 1) + 'Z';
                            } else {
                                PAE_codez = pmcode + 'Z';
                            }
                            // WLIG-BWMB4S gzw end
                            if (String.isBlank(repair_PAED_ManagementCodesZ)) {
                                repair_PAED_ManagementCodesZ = PAE_codez;
                            } else {
                                repair_PAED_ManagementCodesZ += ',' + PAE_codez;
                            }
                        }
                        valid_num++;
                        if (paedrd.PAED_Reappear_Result__c == null) {
                            PAED_Reappear_Result_noSelect_num++;
                        }
                    }
                    paedrd.PAED_ManagementCode__c = paedRDInfo.paedrdd.PAED_ManagementCode__c;
                    // 精琢科技   zxk   2021-11-15  为Monitor_PAE__c赋值   start
                    if (String.isBlank(strMapData.get(paedrd.PAED_ManagementCode__c))) {
                        paedrd.Monitor_PAE__c = true;
                    } else {
                        if (strMapData.get(paedrd.PAED_ManagementCode__c) != paedrd.PAE_Judge__c) {
                            paedrd.Monitor_PAE__c = true;
                        }
                    }
                    // 精琢科技   zxk   2021-11-15  为Monitor_PAE__c赋值   end
                    // Gzw add 20200821 PAE结果变化时,保存接口信息字段 start
                    paedrd.isInterfaceCreate__c = paedRDInfo.paedrdd.isInterfaceCreate__c;
                    paedrd.LocationGroup__c = paedRDInfo.paedrdd.LocationGroup__c;
                    paedrd.Location__c = paedRDInfo.paedrdd.Location__c;
                    paedrd.Phenomenon__c = paedRDInfo.paedrdd.Phenomenon__c;
                    paedrd.Description__c = paedRDInfo.paedrdd.Description__c;
                    paedrd.Cause__c = paedRDInfo.paedrdd.Cause__c;
                    // paedrd.PAE_Judge__c = paedRDInfo.paedrdd.PAE_Judge__c;
                    paedrd.EtqPart__c = paedRDInfo.paedrdd.EtqPart__c;
                    paedrd.EtqAsAnalyzed__c = paedRDInfo.paedrdd.EtqAsAnalyzed__c;
                    paedrd.EtqCause__c = paedRDInfo.paedrdd.EtqCause__c;
                    paedrd.FinalUniversalDesc__c = paedRDInfo.paedrdd.FinalUniversalDesc__c;
                    // paedrd.PAED_RCAC__c = paedRDInfo.paedrdd.PAED_RCAC__c;
                    paedrd.InspectionCategory109__c = paedRDInfo.paedrdd.InspectionCategory109__c;
                    // Gzw add 20200821 PAE结果变化时,保存接口信息字段 end
                }
                //20191216 ljh start
                //状态是否改变
                System.debug('+++++++++++++++++++++: ' + updateStatusFlag);
                if (updateStatusFlag) {
                    //改变状态--->复制新的更新需要更新的
                    upsertPaedrDetailList.add(paedrd);
                } else {
                    //更新需要更新的
                    paedrd.Id = paedRDInfo.paedrdd.Id;
                    upsertPaedrDetailList.add(paedrd);
                }
            }
        }
        if (upsertPaedrDetailList.size() > 0) {
            upsert upsertPaedrDetailList;
        }
        System.debug('PAED_Reappear_Result_noSelect_num' + PAED_Reappear_Result_noSelect_num);
        if (PAED_Reappear_Result_noSelect_num > 0) {
            reappear_confirm = '未确认';
        } else if (valid_num > 0 && PAED_Reappear_Result_noSelect_num == 0) {
            reappear_confirm = '已确认';
        }
        AssignValuesOtherObjects(repair_PAED_ManagementCodes, paedRecordId, repair_PAED_ManagementCodesZ, reappear_confirm, prevDetermineResults);
    }
    //为PAE判定和相关的修理赋值
    public void AssignValuesOtherObjects(String stitchingCode, String paedRecordId, String stitchingCodeZ, String reappear_confirm, String prevDetermineResults) {
        if (String.isNotBlank(stitchingCode) && stitchingCode.contains(',')) {
            String[] stitchingCodeArr = stitchingCode.split(',');
            stitchingCodeArr.sort();
            String stitchingCode1 = '';
            for (Integer i = 0; i < stitchingCodeArr.size(); i++) {
                if (i < (stitchingCodeArr.size() - 1)) {
                    stitchingCode1 += stitchingCodeArr[i] + ',';
                } else {
                    stitchingCode1 += stitchingCodeArr[i] + '';
                }
            }
            stitchingCode = stitchingCode1;
        }
        //报告书相关
        if (!string.isBlank(ReportId)) {
            Report__c Report = [select id, PAE_DetermineAC__c, PAE_Determine__c, PAE_codez__c, PAE_temp_final_code__c, PAE_reappear_confirm__c,
                PAE_intakePrevDetermineResults__c, PAE_finalPrevDetermineResults__c, Repair_Authenticator__c, OCSM_RC_CordingUser__c
                from Report__c where id = : ReportId
            ];
            List < PAE_DecisionRecord__c > rdRecordList = [SELECT Id, Name, PAE_DetermineResults__c, PAE_DetermineResults_Text__c, PAE_ConfirmationDate__c,
                PAE_Authenticator__c
                FROM PAE_DecisionRecord__c where Id = : paedRecordId
            ];
            PAE_DecisionRecord__c paedRecord = new PAE_DecisionRecord__c();
            paedRecord.Id = paedRecordId;
            if (ASac_ASrc == 'Intake') {
                paedRecord.PAE_reappear_confirm__c = reappear_confirm;
                Report.PAE_reappear_confirm__c = reappear_confirm;
            } else {
                paedRecord.PAE_reappear_confirm__c = Report.PAE_reappear_confirm__c;
            }
            if (rdRecordList[0].PAE_ConfirmationDate__c == null) {
                paedRecord.Id = paedRecordId;
                paedRecord.PAE_ConfirmationDate__c = Date.toDay();
                paedRecord.PAE_Authenticator__c = UserInfo.getUserId();
            }
            if (paedRecord != null) {
                update paedRecord;
            }
            List < Report__c > repList;
            if (ASac_ASrc == 'Intake') {
                repList = [select Id, Name, RC_PAED__c, AC_PAED__c from Report__c where RC_PAED__c = : paedRecordId];
                if (repList.size() == 0) {
                    if (String.isBlank(Report.Repair_Authenticator__c)) {
                        Report.Repair_ConfirmationDate__c = Date.toDay();
                        Report.Repair_Authenticator__c = UserInfo.getName();
                    }
                    Report.RC_PAED__c = paedRecordId;
                } else {
                    if (String.isBlank(Report.Repair_Authenticator__c)) {
                        Report.Repair_ConfirmationDate__c = rdRecord.PAE_ConfirmationDate__c;
                        Report.Repair_Authenticator__c = rdRecord.PAE_Authenticator__c;
                    }
                    Report.RC_PAED__c = paedRecordId;
                }
            } else {
                repList = [select Id, Name, RC_PAED__c, AC_PAED__c from Report__c where AC_PAED__c = : paedRecordId];
                if (repList.size() == 0) {
                    if (String.isBlank(Report.OCSM_RC_CordingUser__c)) {
                        Report.OCSM_RC_CordingDate__c = Date.toDay();
                        Report.OCSM_RC_CordingUser__c = UserInfo.getName();
                    }
                    Report.AC_PAED__c = paedRecordId;
                } else {
                    if (String.isBlank(Report.OCSM_RC_CordingUser__c)) {
                        Report.OCSM_RC_CordingDate__c = rdRecord.PAE_ConfirmationDate__c;
                        Report.OCSM_RC_CordingUser__c = rdRecord.PAE_Authenticator__c;
                    }
                    Report.AC_PAED__c = paedRecordId;
                }
            }
            if (String.isNotBlank(stitchingCode)) {
                if (ASac_ASrc == 'Intake') {
                    Report.ASReportedCode__c = stitchingCode;
                    // 2020/08/04 taoqz modify
                    Report.PAE_Determine__c = rdRecord.PAE_DetermineResults_Text__c;
                    Report.PAE_intakePrevDetermineResults__c = prevDetermineResults;
                    //如果有不在现 则更新repair.ASReportedCodeAC__c
                    if (String.isNotBlank(stitchingCodeZ)) {
                        if (String.isNotBlank(Report.PAE_temp_final_code__c)) {
                            Report.ASReportedCodeAC__c = Report.PAE_temp_final_code__c + ',' + stitchingCodeZ;
                        } else {
                            Report.ASReportedCodeAC__c = stitchingCodeZ;
                        }
                        Report.PAE_codez__c = stitchingCodeZ;
                    } else {
                        //202003224 add 如果没有有不在现 则更新repair.ASReportedCodeAC__c
                        Report.ASReportedCodeAC__c = Report.PAE_temp_final_code__c;
                        Report.PAE_codez__c = stitchingCodeZ;
                    }
                } else {
                    if (String.isNotBlank(Report.PAE_codez__c)) {
                        Report.ASReportedCodeAC__c = stitchingCode + ',' + Report.PAE_codez__c;
                    } else {
                        Report.ASReportedCodeAC__c = stitchingCode;
                    }
                    Report.PAE_temp_final_code__c = stitchingCode;
                    // 2020/08/04 taoqz modify
                    Report.PAE_DetermineAC__c = rdRecord.PAE_DetermineResults_Text__c;
                    Report.PAE_finalPrevDetermineResults__c = prevDetermineResults;
                }
            } else {
                if (ASac_ASrc == 'Intake') {
                    Report.ASReportedCode__c = stitchingCode;
                    Report.PAE_codez__c = stitchingCodeZ;
                    Report.ASReportedCodeAC__c = Report.PAE_temp_final_code__c;
                    // 2020/08/04 taoqz modify
                    Report.PAE_Determine__c = rdRecord.PAE_DetermineResults_Text__c;
                    Report.PAE_intakePrevDetermineResults__c = prevDetermineResults;
                } else {
                    Report.ASReportedCodeAC__c = stitchingCode;
                    Report.PAE_temp_final_code__c = stitchingCode;
                    // 2020/08/04 taoqz modify
                    Report.PAE_DetermineAC__c = rdRecord.PAE_DetermineResults_Text__c;
                    Report.PAE_finalPrevDetermineResults__c = prevDetermineResults;
                    Report.OCSM_RC_CordingDate__c = null;
                    Report.OCSM_RC_CordingUser__c = null;
                }
            }
            update Report;
        }
    }
    //20191209 ljh 新字段添加 start
    public static PAE_DecisionRecordDetail__c ReproduceResult(PAE_DecisionRecordDetail__c paedrd, PAE_DecisionRecordDetailInfo paedRDInfo) {
        paedrd.PAE_Judge__c = paedRDInfo.paedrdd.PAE_Judge__c;
        // 20201126 gzw 获取RVS005接口信息数据 start
        paedrd.RVSDetailNo__c = paedRDInfo.paedrdd.RVSDetailNo__c;
        paedrd.LocationGroup__c = paedRDInfo.paedrdd.LocationGroup__c;
        paedrd.Location__c = paedRDInfo.paedrdd.Location__c;
        paedrd.PhenomenonDesc__c = paedRDInfo.paedrdd.PhenomenonDesc__c;
        paedrd.RVS_Date__c = paedRDInfo.paedrdd.RVS_Date__c;
        paedrd.RVS_Time__c = paedRDInfo.paedrdd.RVS_Time__c;
        paedrd.RVS_Decision_Person__c = paedRDInfo.paedrdd.RVS_Decision_Person__c;
        // 20201126 gzw 获取RVS005接口信息数据 end
        if (paedRDInfo.paedrdd.PAED_Reappear_Result__c == '不再現') {
            paedrd.PAED_Reappear_Result__c = '不再現';
            paedrd.PAED_ResultAffirmant__c = UserInfo.getUserId();
            paedrd.PAED_ResultConfirmationDate__c = Date.toDay();
        } else {
            paedrd.PAED_Reappear_Result__c = paedRDInfo.paedrdd.PAED_Reappear_Result__c;
            paedrd.PAED_ResultAffirmant__c = null;
            paedrd.PAED_ResultConfirmationDate__c = null;
        }
        return paedrd;
    }
    // 正则表达式 判断是否包含汉字
    // gzw 20210409 修改参数为空时,表达式判断出错问题
    public static Boolean containsChineseCharacters(String InputString) {
        if (String.isNotblank(InputString)) {
            Pattern p = Pattern.compile('\\p{IsHan}');
            Matcher m = p.matcher(InputString);
            return m.find();
        } else {
            return false;
        }
    }
    // 精琢科技   zxk  2021-10-21  start  给PAE判定记录赋值
    public Map < String, String > updateIsPae(List < String > codeNumDataList) {
        Map < String, String > paeStrMap = new Map < String, String > ();
        String sql = 'select RSS_CODE__C, IS_INTAKE_ESTIMATION__C, IS_PAE__c, IS_INACTIVE__C FROM RSA_master_data__c  WHERE RSS_CODE__C in: codeNumDataList AND IS_INACTIVE__C = \'No\'';
        if ('ASRCDecision' == RecordTypeName) {
            sql += ' AND IS_INTAKE_ESTIMATION__C like \'%Intake%\'';
        }
        if ('ASACDecision' == RecordTypeName) {
            sql += ' AND IS_INTAKE_ESTIMATION__C like \'%Estimation%\'';
        }
        List < RSA_master_data__c > rsaMasterDataSqlList = DataBase.query(sql);
        String result = null;
        for (RSA_master_data__c rsaMaster: rsaMasterDataSqlList) {
            if ('ASRCDecision' == RecordTypeName) {
                if (rsaMaster.IS_PAE__c == 'YES') {
                    result = 'PAE';
                }
                if (rsaMaster.IS_PAE__c == 'No') {
                    result = 'nonPAE';
                }
                if (rsaMaster.IS_PAE__c == 'Unknown') {
                    result = 'Unknown';
                }
            }
            if ('ASACDecision' == RecordTypeName) {
                if (rsaMaster.IS_PAE__c == 'YES') {
                    result = 'PAE';
                }
                if (rsaMaster.IS_PAE__c == 'No') {
                    result = 'nonPAE';
                }
                if (rsaMaster.IS_PAE__c == 'Unknown') {
                    result = 'Unknown';
                }
            }
            paeStrMap.put(rsaMaster.RSS_CODE__C, result);
        }
        return paeStrMap;
    }
    // 精琢科技   zxk  2021-10-21  start  给PAE判定记录赋值
    //20191209 ljh 新字段添加 end
    class PAE_DecisionRecordDetailInfo {
         public Boolean check {
            get;
            set;
        }
        public Boolean oldCheck {
            get;
            set;
        }
        public Boolean canSelect {
            get;
            set;
        }
        public String strJudge {
            get;
            set;
        }
        public Boolean monitorPAE {
            get;
            set;
        }
        public PAE_DecisionRecordDetail__c paedrdd {
            get;
            set;
        }
        public PAE_DecisionRecordDetailInfo() {
            paedrdd = new PAE_DecisionRecordDetail__c();
            check = false;
            oldCheck = false;
            canSelect = false;
        }
        public PAE_DecisionRecordDetailInfo(PAE_DecisionRecordDetail__c paedrd) {
            check = false;
            oldCheck = false;
            paedrdd = paedrd;
            if (String.isNotBlank(paedrd.Id)) {
                monitorPAE = paedrd.Monitor_PAE__c;
            }
            strJudge = paedrd.PAE_Judge__c;
            //IISE来的明细允许删除。
            canSelect = false;
        }
    }
}
force-app/main/default/classes/SelectAssetEstimateController.cls
New file
@@ -0,0 +1,3191 @@
global class  SelectAssetEstimateController {
    //test
    private String targetHospitalId = null;            // 今後系列病院用
    private String targetMaintenanceContractId = null;
    public String targetEstimateId { get; private set; }
    public Boolean changedAfterPrint {get; set;}       // true の場合、画面に confirm メッセージが表示します。quoIdを新しいinsert。判定はjsにて実施
    public Decimal lastFriYearsPriceSum {get; set;}
    public Decimal lastSecYearsPriceSum {get; set;}
    Public String  alertString {get; set;}
    Public String  alertString2 {get; set;}
    Public String  alertString3 {get; set;}
    public Boolean printAsset { get; private set; }
    public Boolean printContract { get; private set; }
    public Boolean printTripartite { get; private set; }
    public Boolean printAgent { get; private set; }
    public boolean inDicideFlag {get; set;} //作为补充,对应报价决定之后,却未能讲合同起止日期传递给合同的问题
    public String isPaymentSet {get; set;}
    //public String PaymentSet {get;set;}
    // 引数のサービス契約の情報を格納する。
    public Maintenance_Contract__c contract { get; private set; }
    public Maintenance_Contract_Estimate__c estimate { get; set; }
    // 2021、8、26 合同报价页面的优化,无保有设备点检对象选择框变黑 fxk star
    public Asset ass { get; set; }
    // 2021、8、26 合同报价页面的优化,无保有设备点检对象选择框变黑 fxk end
    // 病院配下の納入機器の情報を格納する。
    private List<Asset> assetRecords;                       // TODO 系列病院の場合、この配列は固定できないです。
    public List<AssetInfo> checkedAssets { get; set; }
    private List<AssetInfo> unCheckedAssets = new List<AssetInfo>();
    //public List<List<AssetInfo>> checkedAssetsView { get; set; }
    public List<List<AssetInfo>> unCheckedAssetsView { get; set; }
    // 分页用
    public Integer currPage { get; set; } // 当前页
    public Integer totalPage { get; set; } // 总页数
    public Integer selctRecordNum { get { return Integer.valueOf(selRecordOption); } } // 选择的每页记录数
    public Integer totalRecords { get; set; }  // 总记录数
    public String selRecordOption { get; set; }
    public static List<SelectOption> recordNum { get; private set; } // 选择每页记录数List
    //HWAG-B399Q8 2018/08/20  检验是否显示'请提交待审批' start
    public Boolean IS_Clone_After_Decide { get; set; }
    //HWAG-B399Q8 2018/08/20  检验是否显示'请提交待审批' end
    static {
        recordNum = new List<SelectOption>();
        recordNum.add(new SelectOption('10', '10'));
        recordNum.add(new SelectOption('20', '20'));
        recordNum.add(new SelectOption('50', '50'));
        recordNum.add(new SelectOption('100', '100'));
        recordNum.add(new SelectOption('200', '200'));
    }
    private List<String> checkIdList = new List<String> (); // 合同对象设备的设备ID
    //-------HWAG-B4R3SS----------------update----------------------------
    public Boolean activeOn { get; set; }
    public String sortKey { get; set; }
    public Boolean sortOrderAsc { get; private set; }
    private String[] columus = new String[] {'Asset_situation__c', 'Name', 'SerialNumber', 'CurrentContract__r.Management_Code__c', 'Department_Name__c', 'Status', 'Installation_Site__c', 'Room_Number__c', 'InstallDate', 'Asset_Owner__c', 'Accumulation_Repair_Amount__c', 'AssetMark__c'};
    private Boolean isSoft;
    // 显示数据条数限制
    private static Integer SELECT_LIMIT = 200;
    public List<AssetInfo> unCheckedInfoList { get; set; }
    private String text1ForSort = null;
    private String cond1ForSort = null;
    private String val1ForSort = null;
    /*****************select option******************/
    public static List<SelectOption> textOpts { get; private set; }
    public Decimal countorder { get; set; }
    public List<String> assetSerialNumberList = new List<String>();
    static {
        textOpts = new List<SelectOption>();
        //LJPH-BSS6E2  ---20200911 ---update by rentongxiao start
        // textOpts.add(new SelectOption('','-无-'));
        //LJPH-BSS6E2  ---20200911 ---update by rentongxiao end
        //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start
        /* 在查询语句中 新增了 AssetMark__c 的字段 */
        // textOpts.add(new SelectOption('S:Asset_situation__c'  , Schema.SObjectType.Asset.fields.Asset_situation__c.label));
        // 添加新条件 -- 耗材/主机
        textOpts.add(new SelectOption('S:AssetMark__c', '主机/耗材'));
        //JZHG-BSDUT4 ---20200825---update By rentongxiao---End
        textOpts.add(new SelectOption('S:Name'                , Schema.SObjectType.Asset.fields.Name.label));
        textOpts.add(new SelectOption('S:SerialNumber'        , Schema.SObjectType.Asset.fields.SerialNumber.label));
        textOpts.add(new SelectOption('S:CurrentContract__r.Management_Code__c'  , Schema.SObjectType.Asset.fields.CurrentContract__c.label));
        //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start
        // textOpts.add(new SelectOption('S:Status'              , Schema.SObjectType.Asset.fields.Status.label));
        //JZHG-BSDUT4 ---20200825---update By rentongxiao---End
        textOpts.add(new SelectOption('S:Installation_Site__c', Schema.SObjectType.Asset.fields.Installation_Site__c.label));
        textOpts.add(new SelectOption('S:Department_Name__c'  , Schema.SObjectType.Asset.fields.Department_Name__c.label));
    }
    public static List<SelectOption> equalOpts { get; private set; }
    static {
        equalOpts = new List<SelectOption>();
        equalOpts.add(new SelectOption('equals', '等于'));
        equalOpts.add(new SelectOption('contains', '包含'));
        //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start
        //新加匹配符 不等于
        equalOpts.add(new SelectOption('notequals', '不等于'));
        //JZHG-BSDUT4 ---20200825---update By rentongxiao---End
    }
    public String text1 { get; set; } // 对象
    public String cond1 { get; set; } // 条件
    public String val1 { get; set; }  // 值
    //LJPH-BSS6E2  ---20200911 ---add by rentongxiao start
    public String contr {get; set; } //判断是否init
    //LJPH-BSS6E2  ---20200911 ---add by rentongxiao end
    // 检索按钮
    public PageReference searchBtn() {
        countorder = 1;
        //验证
        assetSerialNumberList.clear();
        getAssetSerialNumber();
        totalRecords = 0;
        List<Asset> assetconfimList = getAssetconfim(text1, cond1, val1);
        for (Asset ast : assetconfimList) {
            totalRecords ++;
        }
        // 获取assets
        List<Asset> assetList = getAsset(text1, cond1, val1);
        // 作成明细行
        getSortedUnCheckedInfoList(assetList);
        // 排序用检索条件退避
        text1ForSort = text1;
        cond1ForSort = cond1;
        val1ForSort = val1;
        currPage = 1;
        totalPage = (totalRecords / selctRecordNum) + (Math.mod(totalRecords, selctRecordNum) > 0 ? 1 : 0);
        return null;
    }
    // 取已选择资产的机身编码
    public void getAssetSerialNumber() {
        //LJPH-BSS6E2  ---20200911 ---add by rentongxiao start
        contr = '2';
        //LJPH-BSS6E2  ---20200911 ---add by rentongxiao end
        assetSerialNumberList = new List<String>();
        assetSerialNumberList.clear();
        for (AssetInfo ai : this.checkedAssets) {
            system.debug('checkedAssets1111111' + this.checkedAssets);
            //system.debug('ai.ah.SerialNumber__c' + ai.ah.SerialNumber__c);
            if (String.isNotEmpty(ai.rec.SerialNumber)) {
                assetSerialNumberList.add(ai.rec.SerialNumber);
            }
        }
    }
    //
    private void getSortedUnCheckedInfoList(List<Asset> assetList) {
        Boolean overLimit = false;
        Map<Id, AssetInfo> markUpUnCheckMap = new Map<Id, AssetInfo>();
        for (AssetInfo unCheckinfo : unCheckedAssets) {
            // 打勾,视为优先显示明细
            if (unCheckinfo.rec_checkBox_c == true) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO , 'unCheckinfo.rec_checkBox_c' + unCheckinfo.rec_checkBox_c));
                markUpUnCheckMap.put(unCheckinfo.rec.Id, unCheckinfo);
            }
        }
        unCheckedAssets.clear();
        // 优先显示明细放在最前面
        unCheckedInfoList = new List<AssetInfo>();
        for (AssetInfo asInfo : markUpUnCheckMap.values()) {
            unCheckedAssets.add(asInfo);
        }
        SELECT_LIMIT = selctRecordNum;
        Integer selectCnt = unCheckedAssets.size();
        for (Asset asset : assetList) {
            // 201を超えた場合前200のみを出す
            if (unCheckedAssets.size() >= SELECT_LIMIT) { overLimit = true; break; }
            if (markUpUnCheckMap.containsKey(asset.Id) == false) {
                //unCheckedInfoList.add(unCheckMap.get(asset.Id));
                unCheckedAssets.add(new AssetInfo(unCheckedAssets.size(), asset));
            }
        }
    }
    //检索验证
    private List<Asset> getAssetconfim(String txt, String con, String val) {
        String soql = this.makeSoqlconfim();
        soql += makeTextSql(txt, con, val);
        system.debug('makeTextSql_soql' + soql);
        if (isSoft) {
            soql += ' order by ' + this.columus[Integer.valueOf(this.sortKey)] + ' ' + (this.sortOrderAsc == true ? 'asc nulls first' : 'desc nulls last ');
        } else {
            soql += ' order by SerialNumber, Name, Department_Name__c, InstallDate';
        }
        system.debug('====getAssetconfim:' + soql);
        return Database.query(soql);
    }
    private List<Asset> getAsset(String txt, String con, String val) {
        String soql = this.makeSoqlconfim();
        soql += makeTextSql(txt, con, val);
        if (isSoft) {
            soql += ' order by ' + this.columus[Integer.valueOf(this.sortKey)] + ' ' + (this.sortOrderAsc == true ? 'asc nulls first' : 'desc nulls last ');
        } else {
            soql += ' order by SerialNumber, Name, Department_Name__c, InstallDate';
        }
        soql += ' limit ' + System.Label.Asset_Maxcount;
        soql += ' OFFSET ' + (countorder - 1) * Integer.valueOf(System.Label.Asset_Maxcount);
        return Database.query(soql);
    }
    public Integer soqlNos() {
        List<Asset> assetconfimList = getAssetconfim(text1, cond1, val1);
        totalRecords = assetconfimList.size() ;
        //totalPage = (totalRecords/selctRecordNum) + (Math.mod(totalRecords, selctRecordNum) > 0 ? 1 : 0);
        return totalRecords;
    }
    private String makeSoqlconfim() {
        String sqlTail = '(\'';
        system.debug('assetSerialNumberList.size()' + assetSerialNumberList.size());
        for (Integer i = 0 ; i < assetSerialNumberList.size(); i++) {
            if (i < assetSerialNumberList.size() - 1) {
                sqlTail += assetSerialNumberList[i] + '\',\'';
            } else {
                sqlTail += assetSerialNumberList[i] + '\')';
            }
        }
        String soql = 'SELECT Id, Name, Asset_situation__c, SerialNumber, Department_Name__c, Installation_Site__c, '
                      + 'Posting_Date__c,Management_Code__c,IF_Warranty__c,Reson_Can_not_Warranty__c, InstallDate, '
                      + 'Asset_Owner__c, Accumulation_Repair_Amount__c, Maintenance_Price_Month__c, Final_Examination_Date__c, '
                      + 'CurrentContract_F__c,CurrentContract_F__r.Maintenance_Contract_No_F__c,CurrentContract_F__r.Contract_End_Date__c,CurrentContract_F__r.Estimate_Contract_endDate__c,'
                      + 'CurrentContract_End_Date__c, Extend_Gurantee_DateTo__c,AssetMark__c,NoPartRiskDate_F__c,NoPartRiskDate__c,SignableFlag__c FROM Asset WHERE Hospital__c = \'' + this.targetHospitalId + '\' ';
        //HWAG-BDJ43R ---XHL---20190729---
        //soql +=  ' AND AssetMark__c != \'耗材\' AND Product2.Family != \'ET\' ';
        soql +=  ' AND ( AssetMark__c != \'耗材\' OR Product2.Family != \'ET\' ) ';
        //HWAG-BDJ43R ---XHL---20190729---
        if (assetSerialNumberList.size() > 0) {
            soql += ' AND SerialNumber not in ' + sqlTail ;
        }
        return soql;
    }
    // 拼接检索条件sql文
    private String makeTextSql(String txt1, String con, String val) {
        String soql = '';
        if (String.isBlank(con)) {
            con = 'equals';
        }
        // containsの場合、日報画面の病院検索を真似し、spaceで分けて、and検索
        // equalsの場合、SF標準の検索を真似し、「,」で分けて、or検索
        if (!String.isBlank(txt1)) {
            if ((con == 'contains' || con == 'notcontains') && val.contains(' ')) {
                String[] vals = val.split(' ');
                String cSql = '';
                if (vals.size() > 0) {
                    String txt = txt1.substring(2);
                    soql += ' and ( ';
                    for (String v : vals) {
                        if (String.isNotBlank(v)) {
                            if (con == 'contains') {
                                soql += txt + ' like \'%' + v + '%\' or ';
                            } else {
                                soql += txt + ' not like \'%' + v + '%\' and ';
                            }
                        }
                    }
                    soql = soql.substring(0, soql.length() - 4);
                    soql += ')';
                }
                system.debug('containssoql:     ' + soql);
            } else if ((con == 'equals' || con == 'notequals') && val.contains(',')) {
                String[] vals = val.split(',');
                if (vals.size() > 0) {
                    String txt = txt1.substring(2);     // S:Name 、最初の2文字がタイプです
                    soql += ' and ( ';
                    for (String v : vals) {
                        if (con == 'equals') {
                            soql += txt + ' = \'' + v + '\' or ';
                        } else {
                            // notequals
                            soql += txt + ' <> \'' + v + '\' and ';
                        }
                    }
                    soql = soql.substring(0, soql.length() - 4);
                    soql += ')';
                }
            } else {
                String cSql = this.makeTextSqlStr(txt1, con, val);
                if (con != 'notcontains') {
                    soql += this.makeTextSqlStr(txt1, con, val);
                } else {
                    // notcontains
                    if (!String.isBlank(cSql)) {
                        cSql = cSql.substring(5);       // ' and ' の5文字を外す
                        soql += ' and (NOT ' + cSql + ') ';
                    }
                }
            }
        }
        // //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start
        // else {
        //     soql += 'AND AssetMark__c = \'主机\'';
        // }
        // //JZHG-BSDUT4 ---20200825---update By rentongxiao---End
        return soql;
    }
    private String makeTextSqlStr(String txt1, String con, String val) {
        String soql = '';
        if (!String.isBlank(txt1)) {
            String txt = txt1.substring(2);
            String colType = txt1.substring(0, 2);
            String tmpVal = val.trim();
            // 空白の場合''にする
            if (String.isBlank(tmpVal)) {
                if (con == 'equals') {
                    //soql += ' and ' + txt + ' = ' + tmpVal;
                    soql += ' and ' + txt + ' = null';
                } else if (con == 'notequals') {
                    soql += ' and ' + txt + ' <> null';
                } else {
                    // 空白の場合、contains, notcontains と starts withは無視
                }
            } else {
                soql += ' and ' + txt;
                if (con == 'equals') {
                    if (colType == 'S:') {
                        soql += ' = \'' + tmpVal + '\'';
                    } else {
                        soql += ' = ' + tmpVal + ' ';
                    }
                } else if (con == 'notequals') {
                    if (colType == 'S:') {
                        soql += ' <> \'' + tmpVal + '\'';
                    } else {
                        soql += ' <> ' + tmpVal + ' ';
                    }
                } else if (con == 'contains' || con == 'notcontains') {
                    soql += ' like \'%' + String.escapeSingleQuotes(tmpVal.replaceAll('%', '\\%')) + '%\'';
                } else if (con == 'starts with') {
                    soql += ' like \'' + String.escapeSingleQuotes(tmpVal.replaceAll('%', '\\%')) + '%\'';
                } else {
                    if (colType == 'S:') {
                        soql += ' ' + con + '\'' + tmpVal + '\'';
                    } else {
                        soql += ' ' + con + ' ' + tmpVal + ' ';
                    }
                }
            }
        }
        return soql;
    }
    //----------HWAG-B4R3SS------------------------------------------------------------
    public Boolean getEnablePrintContract() {
        if (String.isBlank(this.contract.Decided_Estimation__c) == false) {
            return this.estimate.Estimation_Decision__c;
        } else {
            return false;
        }
    }
    public Boolean getUnDecideBtnDisabled() {
        // 見積もりdecide取消しできない条件の判断
        if (String.isBlank(this.contract.Decided_Estimation__c) == false) {
            if (this.estimate.Estimation_Decision__c) {
                return false;
            }
        }
        // TODO 本当は特別資格があれば 決定可能にする
        return true;
    }
    public Boolean getDecideBtnDisabled() {
        // 見積もりdecideできない条件の判断
        if (String.isBlank(this.contract.Decided_Estimation__c) == false) {
            if (this.estimate.Estimation_Decision__c) {
                return true;
            }
            // TODO 特別資格があれば 決定可能にする
            return true;
        }
        if (this.estimate.Process_Status__c != '批准') {
            return true;
        } else {
            if (String.isBlank(this.estimate.Change_Dealer_Approval__c) == false
                    && this.estimate.Change_Dealer_Approval__c != '批准'
                    && this.estimate.Change_Dealer_Approval__c != '未批准') {
                return true;
            }
        }
        return false;
    }
    public Boolean getApprovalBtnDisabled() {
        // 見積もり申請できない条件の判断
        if (String.isBlank(this.contract.Decided_Estimation__c) == false) {
            // TODO 特別資格があれば 申請可能にする
            return true;
        }
        if (String.isBlank(this.estimate.Process_Status__c) == false
                && this.estimate.Process_Status__c != '草案中'
                //&& this.estimate.Process_Status__c != '不批准'
           ) {
            return true;
        }
        return false;
    }
    public Boolean getSaveBtnDisabled() {
        // 見積もりsaveできない条件の判断
        if (String.isBlank(this.contract.Decided_Estimation__c) == false) {
            return true;
        }
        if (String.isBlank(this.estimate.Process_Status__c) == false
                && this.estimate.Process_Status__c != '草案中'
                //&& this.estimate.Process_Status__c != '不批准'
           ) {
            return true;
        }
        return false;
    }
    public Boolean getPrintBtnDisabled() {
        // 印刷できない条件の判断
        if (this.estimate.Process_Status__c != '批准' || !this.contract.Status__c.equals('引合中') ) {
            return true;
        } else {
            if (String.isBlank(this.estimate.Change_Dealer_Approval__c) == false
                    && this.estimate.Change_Dealer_Approval__c != '批准'
                    && this.estimate.Change_Dealer_Approval__c != '未批准') {
                return true;
            }
        }
        return false;
    }
    // 页面项目非活性设定
    public Boolean getPageDisabled() {
        if (String.isBlank(this.contract.Decided_Estimation__c) == false) {
            return true;
        }
        if (String.isBlank(this.estimate.Process_Status__c) == false
                && this.estimate.Process_Status__c != '草案中'
           ) {
            return true;
        }
        return false;
    }
    // 2021、8、26 合同报价页面的优化,无保有设备点检对象选择框变黑 fxk star
    // public Boolean getPageDisabled1() {
    //     if (
    //         String.isBlank(this.ass.Name)
    //     ) {
    //         return true;
    //     }
    //     return false;
    // }
    // 2021、8、26 合同报价页面的优化,无保有设备点检对象选择框变黑 fxk end
    public Integer productCount {
        get {
            return checkedAssets == null ? 0 : checkedAssets.size();
        }
    }
    public Integer productCount2 {
        get {
            return unCheckedAssets == null ? 0 : unCheckedAssets.size();
        }
    }
    public Integer productCount3 {
        get {
            Integer cnt = 0;
            for (AssetInfo input : this.checkedAssets) {
                if (!input.isManual || input.isManual && !String.isBlank(input.mcae.Product_Manual__c)) {
                    cnt += 1;
                }
            }
            return cnt;
        }
    }
    // TODO カスタムラベルから取得
    public static Decimal oxygenPriceAdj { get { return 0.1; } }          // TODO katsu 酸化水を使用しないように変更
    public Decimal isNewPriceAdj {
        // HWAG-BGT66T 2019-10-01 后不打折
        get{
            Decimal count = 0;
            if (estimate.CreatedDate == null || estimate.CreatedDate.date() >= Date.valueOf('2019-10-08')) {
                count = 1.0;
            } else{
                count = 0.7;
            }
            return count;
        }
    }
    //public String productName { get; set; }
    public Integer productIdx { get; set; }
    public Integer isNewAddMonth { get { return Integer.valueOf(System.Label.MC_New_AddMonth); } }
    public Integer keepPriceMonth { get { return Integer.valueOf(System.Label.MC_KeepPrice_Month); } }
    public Boolean isPageAction = false;
    private Integer PosttoInstall { get { return Integer.valueOf(System.Label.Post_to_Install); }}
    public Boolean changedSubmitPrice {get; set;}
    public Boolean isSaveOrApproval {get; set;}
    public String OldContractStartDate {get; set;}
    public String OldMaintenancePrice { get; set; }
    /**
     * コンストラクタ
     */
    public SelectAssetEstimateController() {
        currPage = 1;
        selRecordOption = '20';
        totalRecords = 0;
    }
    /**
     * Visaulforceから呼ばれるコンストラクタ
     */
    public SelectAssetEstimateController(ApexPages.StandardController controller) {
        //HWAG-B4R3SS  START 20181026
        currPage = 1;
        selRecordOption = '20';
        //this.targetEstimateId = (String)(ApexPages.currentPage().getParameters().get('id'));
        totalRecords = 0;
        //HWAG-B4R3SS  END 20181026
    }
    private void setThisEstimate() {
        //HWAG-B399Q8 2018/08/20  添加一额外字段 IS_Clone_After_Decide__c start
        this.estimate = [SELECT Id, Name, Maintenance_Contract__c, Estimation_Decision__c, CreatedDate, Service_Contract_Staff__c,
                         JingliApprovalManager__c, BuchangApprovalManager__c, ZongjianApprovalManager__c, Finally_Approved_Staff__c,
                         Contract_Esti_Start_Date__c, Contract_Esti_End_Date__c, Contract_Range__c, Contract_Start_Date__c, Contract_End_Date__c,
                         Maintenance_Contract_Status__c, Discount_reason__c, Improve_ConsumptionRate_Idea__c, Process_Status__c,
                         Estimate_Trial_Money__c, Maintenance_Price__c, Department__c, PrintDate__c, Quote_Date__c, Submit_quotation_day__c,
                         Examination_Price__c, Service_contract_target_number__c,
                         Maintenance_Contract__r.Payment_Plan_Sum_First__c, Maintenance_Contract__r.Payment_Plan_Date_First__c,
                         Maintenance_Contract__r.Payment_Plan_Sum_Second__c,
                         Maintenance_Contract__r.Payment_Plan_Sum_Third__c,
                         Maintenance_Contract__r.Payment_Plan_Sum_Forth__c,
                         Maintenance_Contract__r.Payment_Plan_Sum_Fifth__c,
                         Maintenance_Contract__r.Payment_Plan_Sum_Sixth__c,
                         Discount_Price__c, Discount_Percentage__c, IsSyncing__c,
                         NotUse_Oxygenated_Water__c, Estimate_Target__c, Dealer__c,
                         Append_Condition_Price__c, Asset_Sum_Price__c, Asset_Repair_Sum_Price__c,
                         Print_Contract__c, Print_RepairPrice__c, Print_DiscountPercentage__c, Print_Agent__c, Change_Dealer_Approval__c,
                         Print_DiscountPrice__c, Print_ListPrice__c, Print_MaintePrice__c, Print_SumPrice__c, Print_Tripartite__c, TKZongjianApprovalManager__c
                         , IS_Clone_After_Decide__c
                         // 上期五个合同信息 Gzw 20200810
                         , LastMContract1__c, LastMContract2__c, LastMContract3__c, LastMContract4__c, LastMContract5__c
                         , LastMContract1_ConCount__c, LastMContract2_ConCount__c, LastMContract3_ConCount__c, LastMContract4_ConCount__c, LastMContract5_ConCount__c,
                         LastMContract1_NO__c, LastMContract2_NO__c, LastMContract3_NO__c, LastMContract4_NO__c, LastMContract5_NO__c
                         FROM Maintenance_Contract_Estimate__c WHERE Id = :this.targetEstimateId];
        //HWAG-B399Q8 2018/08/20  添加一额外字段 IS_Clone_After_Decide__c end
        decimal PriceSum =  (this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_First__c == null ? 0 : this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_First__c) +
                            (this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_Second__c == null ? 0 : this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_Second__c) +
                            (this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_Third__c == null ? 0 : this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_Third__c) +
                            (this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_Forth__c == null ? 0 : this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_Forth__c) +
                            (this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_Fifth__c == null ? 0 : this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_Fifth__c) +
                            (this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_Sixth__c == null ? 0 : this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_Sixth__c);
        if ( this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_First__c == null
                //102018/10/26 HWAG-B5C88S 不再根据是否填写第一次付款日期判断
           ) {
            isPaymentSet = 'false';
        } else if (this.estimate.Maintenance_Price__c != PriceSum) {
            isPaymentSet = 'Denied';
        } else {
            isPaymentSet = 'true';
        }
    }
    public void init() {
        changedAfterPrint = false;
        changedSubmitPrice = false;
        isSaveOrApproval = false;
        OldContractStartDate = null;
        OldMaintenancePrice = null;
        isSoft = false;
        activeOn = true;
        //LJPH-BSS6E2  ---20200911 ---update by rentongxiao start
        contr = '1';
        val1 = '主机';
        //LJPH-BSS6E2  ---20200911 ---update by rentongxiao end
        Date systemToday = System.today();
        if (isPageAction == false) {
            //HWAG-B399Q8 2018/08/20  添加状态5,为按save 按键后状态 start
            if (String.isBlank(ApexPages.currentPage().getParameters().get('completion')) == false) {
                if (ApexPages.currentPage().getParameters().get('completion') == '1') {
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, System.Label.Message_002));
                } else if (ApexPages.currentPage().getParameters().get('completion') == '2') {
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, '审批提交成功。'));
                } else if (ApexPages.currentPage().getParameters().get('completion') == '3') {
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, 'Decided。'));
                } else if (ApexPages.currentPage().getParameters().get('completion') == '4') {
                } else if (ApexPages.currentPage().getParameters().get('completion') == '5') {
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, System.Label.Message_002));
                }
            }
            //HWAG-B399Q8 2018/08/20  添加状态5,为按save 按键后状态 end
        }
        this.printAsset = false;
        this.printContract = false;
        this.printTripartite = false;
        this.printAgent = false;
        String copyid = '';
        Boolean ret = false;
        if (isPageAction == false) {
            this.targetEstimateId = ApexPages.currentPage().getParameters().get('copyid');
            copyid = ApexPages.currentPage().getParameters().get('copyid');
            if (this.targetEstimateId == null) {
                String paramId = ApexPages.currentPage().getParameters().get('id');
                if (String.isBlank(paramId) == false && paramId.startsWith('a0z')) {
                    Maintenance_Contract_Asset_Estimate__c mcaeParam = [Select Maintenance_Contract_Estimate__c from Maintenance_Contract_Asset_Estimate__c where Id = :paramId];
                    this.targetEstimateId = mcaeParam.Maintenance_Contract_Estimate__c;
                } else {
                    this.targetEstimateId = paramId;
                }
            }
            this.targetMaintenanceContractId = ApexPages.currentPage().getParameters().get('mcid');
        }
        // 編集から
        if (String.isBlank(this.targetEstimateId) == false) {
            setThisEstimate();
            this.targetMaintenanceContractId = this.estimate.Maintenance_Contract__c;
            this.setContractInfo(this.targetMaintenanceContractId);
        }
        // 新規から
        else if (!String.isBlank(this.targetMaintenanceContractId)) {
            this.estimate = new Maintenance_Contract_Estimate__c();
            this.estimate.Maintenance_Contract__c = this.targetMaintenanceContractId;
            this.estimate.Contract_Esti_Start_Date__c = systemToday;
            this.estimate.Contract_Start_Date__c = systemToday;
            this.setContractInfo(this.targetMaintenanceContractId);
        }
        // 何もなければ、念のため
        // update 维修合同报价,保存时,把记录类型赋值一下(由于报错) 2021.6.8 fxk start
        else {
            ret = true;
            throw new ControllerUtil.myException('无法显示维修合同报价');
        }
        if (ret) {
            return;
        }
        // update 维修合同报价,保存时,把记录类型赋值一下(由于报错) 2021.6.8 fxk end
        //HWAG-B399Q8 2018/08/20  检验是否显示'请提交待审批' start
        IS_Clone_After_Decide = false;
        if (String.isBlank(ApexPages.currentPage().getParameters().get('completion')) == false &&
                ApexPages.currentPage().getParameters().get('completion') == '5' &&
                this.estimate != null && this.estimate.IS_Clone_After_Decide__c) {
            IS_Clone_After_Decide = true;
        }
        //HWAG-B399Q8 2018/08/20  检验是否显示'请提交待审批' end
        // 納入機器の情報を取得
        if (!String.isBlank(this.targetHospitalId) && (this.targetHospitalId.length() == 15 || this.targetHospitalId.length() == 18)) {
            assetRecords = [SELECT Id, Name, Asset_situation__c, SerialNumber, Department_Name__c, Installation_Site__c, Posting_Date__c, Management_Code__c, IF_Warranty__c, Reson_Can_not_Warranty__c,
                            InstallDate, Asset_Owner__c, Accumulation_Repair_Amount__c, Maintenance_Price_Month__c, Final_Examination_Date__c, CurrentContract_End_Date__c,
                            CurrentContract_F__c, CurrentContract_F__r.Maintenance_Contract_No_F__c, CurrentContract_F__r.Contract_End_Date__c, CurrentContract_F__r.Estimate_Contract_endDate__c, AssetMark__c,
                            // 2021-01-29 LJPH-BX9CVX mzy   add  合同报价时判断零件风险
                            NoPartRiskDate_F__c, NoPartRiskDate__c, SignableFlag__c,
                            Product2.PartSupplyFinishDate__c , Product2.PartSupplyFinishDateExp__c
                            // 2021-01-29 LJPH-BX9CVX mzy   add  合同报价时判断零件风险
                            FROM Asset WHERE Hospital__c = :this.targetHospitalId AND ( AssetMark__c != '耗材' OR Product2.Family != 'ET' ) ORDER BY ID, IF_Warranty__c asc];
            // FROM Asset WHERE Hospital__c = :this.targetHospitalId AND AssetMark__c = '主机' ORDER BY ID,IF_Warranty__c asc];
        } else {
            assetRecords = new List<Asset>();
        }
        //sqlStr += ' AND AssetMark__c != \'耗材\' AND Product2.Family != \'ET\' ';
        this.checkedAssets = new List<AssetInfo>();
        this.unCheckedAssets = new List<AssetInfo>();
        // 選択済みの納入機器情報を取得
        Map<Id, Integer> selectedAssetIds = new Map<Id, Integer>();
        List<Maintenance_Contract_Asset_Estimate__c> selectedMcaes = new List<Maintenance_Contract_Asset_Estimate__c>();
        List<Maintenance_Contract_Asset_Estimate__c> newMcaes = new List<Maintenance_Contract_Asset_Estimate__c>();
        // 新規、且つ1つ目見積もりの場合、コピー元の保有設備を持つ
        if (String.isBlank(this.targetEstimateId) && this.contract.Estimate_Num__c == 0) {
            List<Maintenance_Contract_Asset__c> oldVals = [
                        select Id, Name, Asset__c, Asset__r.InstallDate, Asset__r.Posting_Date__c, Asset__r.Maintenance_Price_Month__c
                        from Maintenance_Contract_Asset__c
                        where Maintenance_Contract__c = :this.targetMaintenanceContractId];
            for (Maintenance_Contract_Asset__c mca : oldVals) {
                // oldより更新したい項目
                Boolean isNew = false;
                Decimal listPrice = mca.Asset__r.Maintenance_Price_Month__c;
                // InstallDate と 今日を比較
//                if (systemToday.addMonths(-6) < mca.Asset__r.InstallDate) {
//                if (estimate.Contract_Esti_Start_Date__c.addMonths(isNewAddMonth) < mca.Asset__r.InstallDate) {
                Date createdDate = (estimate.CreatedDate == null || !String.isBlank(copyid)) ? systemToday : estimate.CreatedDate.date();
                System.debug(createdDate + '.addMonths(' + isNewAddMonth + ')' + createdDate.addMonths(isNewAddMonth) + ' < mca.Asset__r.InstallDate:' + mca.Asset__r.InstallDate);
                if (createdDate.addMonths(isNewAddMonth) < mca.Asset__r.InstallDate) {
                    isNew = true;
                    listPrice = mca.Asset__r.Maintenance_Price_Month__c * isNewPriceAdj;
                }
                selectedAssetIds.put(mca.Asset__c, selectedMcaes.size());
                selectedMcaes.add(new Maintenance_Contract_Asset_Estimate__c(
                                      Asset__c = mca.Asset__c,
                                      isNew__c = isNew,
                                      Estimate_List_Price__c = listPrice
                                  ));
            }
        } else {
            for (Maintenance_Contract_Asset_Estimate__c mcae : [SELECT   Id,
                    Name,
                    Maintenance_Contract_Estimate__c,
                    Asset__c,
                    Asset__r.Maintenance_Price_Month__c,
                    Asset__r.InstallDate,
                    Product_Manual__c,
                    Product_Manual__r.Maintenance_Price_Month__c,
                    //add 2021-02-07 mzy  start
                    //Product_Manual__r.NoPartRiskDate_F__c,
                    //Product_Manual__r.SignableFlag__c,
                    Product_Manual__r.Name,
                    //add 2021-02-07 mzy  end
                    //add 2021.6.4 fxk  Start
                    Check_Object__c,
                    //add 2021.6.4 fxk  end
                    IsNew__c,
                    Asset__r.CurrentContract_F__c,
                    Asset__r.CurrentContract_F__r.First_Estimate_Date__c,
                    Asset__r.CurrentContract_F__r.Contract_Consumption_rate__c,
                    Asset__r.CurrentContract_F__r.First_contract_usage_Rate__c,
                    Asset__r.CurrentContract_F__r.Estimate_Contract_endDate__c,
                    Asset__r.CurrentContract_F__r.Contract_Range__c,
                    Asset__r.CurrentContract_F__r.Contract_End_Date__c,
                    Asset__r.CurrentContract_F__r.Gurantee_Estimate_startDate__c,
                    Estimate_List_Price__c,
                    Last_inspection_day__c,
                    Check_Result__c,
                    Repair_Price__c,
                    Comment__c,
                    Asset__r.Posting_Date__c,
                    Asset__r.AssetMark__c
                    FROM    Maintenance_Contract_Asset_Estimate__c
                    WHERE   Maintenance_Contract_Estimate__c = :this.targetEstimateId
                            ORDER BY
                            Id,
                    Asset__c,
                    Product_Manual__c,
                    Asset__r.SerialNumber,
                    Asset__r.Name,
                    Asset__r.Department_Name__c,
                    Asset__r.InstallDate,
                    Asset__r.AssetMark__c
                                                               ]) {
                if (String.isBlank(copyid) == false) {
                    if (mcae.Asset__c <> null) {
                        if (systemToday.addMonths(isNewAddMonth) < mcae.Asset__r.InstallDate) {
                            mcae.IsNew__c = true;
                            mcae.Estimate_List_Price__c = mcae.Asset__r.Maintenance_Price_Month__c * isNewPriceAdj;
                        } else {
                            mcae.IsNew__c = false;
                            mcae.Estimate_List_Price__c = mcae.Asset__r.Maintenance_Price_Month__c;
                        }
                    } else if (mcae.Product_Manual__c <> null) {
                        mcae.IsNew__c = true;
                        mcae.Estimate_List_Price__c = mcae.Product_Manual__r.Maintenance_Price_Month__c * isNewPriceAdj;
                    }
                }
                if (mcae.Asset__c <> null) {
                    selectedAssetIds.put(mcae.Asset__c, selectedMcaes.size());
                    selectedMcaes.add(mcae);
                } else {
                    newMcaes.add(mcae);
                }
            }
        }
        // 選択済みのものにチェックを付ける
        // TODO xudan 一覧に出る明細件数が足りないケースがある
        // ①AssetA―明細Aで明細登録
        // ②Assetの検索条件変更により、AssetAは永遠に取得できない
        // ③Assetを元にデータをマッピングする時、明細マップからAssetAを取得できない?一覧に明細Aが出ない
        // 次回、Assetの検索条件が大きく変更する時、対応必要
        for (Asset ast : this.assetRecords) {
            Boolean isNew = false;
            Decimal listPrice = ast.Maintenance_Price_Month__c;
            if (selectedAssetIds.containsKey(ast.Id)) {
                Maintenance_Contract_Asset_Estimate__c selectedLocal = selectedMcaes.get(selectedAssetIds.get(ast.Id));
                isNew = selectedLocal.isNew__c;
                listPrice = selectedLocal.Estimate_List_Price__c;
                // xudan 20160110 新品判断ここ要らない、contractStartDateChangeがやる
//                if (systemToday.addMonths(-6) < ast.InstallDate) {
//                if (estimate.Contract_Esti_Start_Date__c.addMonths(isNewAddMonth) < ast.InstallDate) {
//                Date createdDate = (estimate.CreatedDate == null || !String.isBlank(copyid)) ? systemToday : estimate.CreatedDate.date();
//System.debug(createdDate + '.addMonths(' + isNewAddMonth + ')' + createdDate.addMonths(isNewAddMonth) + ' < ast.InstallDate:' + ast.InstallDate);
//                if (createdDate.addMonths(isNewAddMonth) < ast.InstallDate) {
//                    isNew = true;
//                    listPrice = ast.Maintenance_Price_Month__c * isNewPriceAdj;
//                }
                checkedAssets.add(new AssetInfo(checkedAssets.size(), ast, isNew, listPrice, selectedLocal));
            } else {
                //update by rentongxiao 2020-09-23 start
                if (ast.AssetMark__c == '主机') {
                    totalRecords ++;
                    if (unCheckedAssets.size() < selctRecordNum) {
                        unCheckedAssets.add(new AssetInfo(unCheckedAssets.size(), ast));
                    }
                }
                //update by rentongxiao 2020-09-23 end
            }
            listCut(unCheckedAssets);
            /*
            if (ast.CheckBox__c) {
                checkedAssets.add(new AssetInfo(checkedAssets.size(), ast, isNew, listPrice));
            } else {
                unCheckedAssets.add(new AssetInfo(unCheckedAssets.size(), ast));
            }
            */
        }
        totalPage = (totalRecords / selctRecordNum) + (Math.mod(totalRecords, selctRecordNum) > 0 ? 1 : 0);
        system.debug('顺序检测' + checkedAssets);
        for (Maintenance_Contract_Asset_Estimate__c mcae : newMcaes) {
            checkedAssets.add(new AssetInfo(checkedAssets.size(), mcae));
        }
        // 最後10行追加
        if (Schema.getGlobalDescribe().get('Maintenance_Contract_Asset_Estimate__c').getDescribe().isCreateable()) {
            this.addNewRows();
        }
        if (!String.isBlank(copyid)) {
            this.targetEstimateId = null;
            this.estimate = new Maintenance_Contract_Estimate__c();
            this.estimate.Maintenance_Contract__c = this.targetMaintenanceContractId;
        }
        assetRecords.clear();
        // 根据合同开始日重新计算维修合同价格
        contractStartDateChange();
    }
    //
    // 取得分页数据
    private void setPageRecord() {
        checkIdList = new List<String> ();
        if ((currPage * selctRecordNum) <= 2000) {
            String notInId = '(\'';
            if (checkIdList.size() > 0) {
                for (String str : checkIdList) {
                    notInId += str + '\', \'';
                }
            }
            notInId += '\')';
            String sqlStr = 'SELECT Id, Name, Asset_situation__c, SerialNumber, Department_Name__c, Installation_Site__c, '
                            + 'Posting_Date__c,Management_Code__c,IF_Warranty__c,Reson_Can_not_Warranty__c, InstallDate, '
                            + 'Asset_Owner__c, Accumulation_Repair_Amount__c, Maintenance_Price_Month__c, Final_Examination_Date__c, '
                            + 'CurrentContract_F__c,CurrentContract_F__r.Maintenance_Contract_No_F__c,CurrentContract_F__r.Contract_End_Date__c,'
                            + 'CurrentContract_End_Date__c, Extend_Gurantee_DateTo__c,AssetMark__c,NoPartRiskDate_F__c,NoPartRiskDate__c,SignableFlag__c,Product2.PartSupplyFinishDate__c,Product2.PartSupplyFinishDateExp__c FROM Asset WHERE Hospital__c = \'' + this.targetHospitalId + '\' '
                            + 'AND Id NOT IN ' + notInId ;
            //HWAG-B4R3SS  START 20181026
            if (String.isNotBlank(text1) && String.isNotBlank(cond1) && String.isNotBlank(val1)) {
                sqlStr += makeTextSql(text1, cond1, val1);
            }
            //JZHG-BSDUT4 ---20200904---update By rentongxiao---Start
            else {
                sqlStr += ' AND AssetMark__c = \'主机\'';
            }
            //JZHG-BSDUT4 ---20200904---update By rentongxiao---end
            //HWAG-B4R3SS  END 20181026
            //HWAG-BDJ43R---XHL---20190729---
            sqlStr += ' AND ( AssetMark__c != \'耗材\' OR Product2.Family != \'ET\' )';
            //HWAG-BDJ43R---XHL---20190729---
            sqlStr += ' ORDER BY ID,IF_Warranty__c asc ';
            if (currPage == 1) {
                sqlStr += 'limit ' + selRecordOption;
            } else {
                sqlStr += 'limit ' + selRecordOption + ' offset ' + String.valueOf((currPage - 1) * selctRecordNum);
            }
            //system.debug();
            //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,
            //               '222222222222_____'+sqlStr));
            //return;
            assetRecords = Database.query(sqlStr);
        } else {
            assetRecords.clear();
            Integer sqlLimit = currPage * selctRecordNum;
            List<Asset> temAsset = new List<Asset> ();
            //HWAG-BDJ43R ---XHL---20190729---
            String sqlStr = '';
            sqlStr  = 'SELECT Id, Name, Asset_situation__c, SerialNumber, Department_Name__c, Installation_Site__c,';
            sqlStr += 'Posting_Date__c,Management_Code__c,IF_Warranty__c,Reson_Can_not_Warranty__c,InstallDate,' ;
            sqlStr += 'Asset_Owner__c, Accumulation_Repair_Amount__c, Maintenance_Price_Month__c, Final_Examination_Date__c,';
            sqlStr += 'CurrentContract_F__c,CurrentContract_F__r.Maintenance_Contract_No_F__c,CurrentContract_F__r.Contract_End_Date__c,';
            sqlStr += 'CurrentContract_End_Date__c,Extend_Gurantee_DateTo__c,AssetMark__c,NoPartRiskDate_F__c,NoPartRiskDate__c,SignableFlag__c,Product2.PartSupplyFinishDate__c,Product2.PartSupplyFinishDateExp__c';
            sqlStr += ' FROM Asset WHERE Hospital__c = \'' + this.targetHospitalId + '\'';
            sqlStr += '  AND ( AssetMark__c != \'耗材\' OR Product2.Family != \'ET\' ) ';
            //HWAG-B4R3SS  START 20181026
            if (String.isNotBlank(text1) && String.isNotBlank(cond1) && String.isNotBlank(val1)) {
                sqlStr += makeTextSql(text1, cond1, val1);
            }
            //JZHG-BSDUT4 ---20200904---update By rentongxiao---Start
            else {
                sqlStr += 'AND AssetMark__c = \'主机\'';
            }
            //JZHG-BSDUT4 ---20200904---update By rentongxiao---end
            //HWAG-B4R3SS  END 20181026
            if (checkIdList.size() > 0) {
                sqlStr += '  AND Id NOT IN ' + checkIdList;
                //temAsset = [SELECT Id, Name, Asset_situation__c, SerialNumber, Department_Name__c, Installation_Site__c, Posting_Date__c,Management_Code__c,IF_Warranty__c,Reson_Can_not_Warranty__c,
                //            InstallDate, Asset_Owner__c, Accumulation_Repair_Amount__c, Maintenance_Price_Month__c, Final_Examination_Date__c,CurrentContract_End_Date__c,Extend_Gurantee_DateTo__c
                //            FROM Asset WHERE Hospital__c = :this.targetHospitalId AND Id NOT IN : checkIdList AND AssetMark__c != '耗材' AND Product2.Family != 'ET' ORDER BY ID,IF_Warranty__c asc limit : sqlLimit];
            } else {
                //temAsset = [SELECT Id, Name, Asset_situation__c, SerialNumber, Department_Name__c, Installation_Site__c, Posting_Date__c,Management_Code__c,IF_Warranty__c,Reson_Can_not_Warranty__c,
                //            InstallDate, Asset_Owner__c, Accumulation_Repair_Amount__c, Maintenance_Price_Month__c, Final_Examination_Date__c,CurrentContract_End_Date__c,Extend_Gurantee_DateTo__c
                //            FROM Asset WHERE Hospital__c = :this.targetHospitalId AND AssetMark__c != '耗材' AND Product2.Family != 'ET' ORDER BY ID,IF_Warranty__c asc limit : sqlLimit];
            }
            sqlStr += ' ORDER BY ID,IF_Warranty__c asc limit ' + sqlLimit;
            temAsset = Database.query(sqlStr);
            //HWAG-BDJ43R ---XHL---20190729---
            if (temAsset.size() >= (currPage * selctRecordNum)) {
                for (Integer i = ((currPage - 1) * selctRecordNum); i < (currPage * selctRecordNum); i++) {
                    assetRecords.add(temAsset.get(i));
                }
            } else {
                for (Integer i = ((currPage - 1) * selctRecordNum); i < temAsset.size(); i++) {
                    assetRecords.add(temAsset.get(i));
                }
            }
        }
        this.unCheckedAssets = new List<AssetInfo>();
        for (Asset ast : assetRecords) {
            this.unCheckedAssets.add(new AssetInfo(unCheckedAssets.size(), ast));
        }
        listCut(unCheckedAssets);
        // 根据合同开始日重新计算维修合同价格
        contractStartDateChange();
    }
    // 翻页到首页
    public void firstPage() {
        getAssetSerialNumber();
        currPage = 1;
        //HWAG-B4R3SS  END 20181026
        totalRecords = soqlNos();
        totalPage = (totalRecords / selctRecordNum) + (Math.mod(totalRecords, selctRecordNum) > 0 ? 1 : 0);
        //HWAG-B4R3SS  END 20181026
        this.setPageRecord();
    }
    // 向前翻页
    public void previousPage() {
        getAssetSerialNumber();
        currPage --;
        //HWAG-B4R3SS  START 20181026
        totalRecords = soqlNos();
        totalPage = (totalRecords / selctRecordNum) + (Math.mod(totalRecords, selctRecordNum) > 0 ? 1 : 0);
        //HWAG-B4R3SS  END 20181026
        this.setPageRecord();
    }
    // 向后翻页
    public void nextPage() {
        getAssetSerialNumber();
        //HWAG-B4R3SS  START 20181026
        totalRecords = soqlNos();
        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO , 'totalRecords——————' + totalRecords));
        totalPage = (totalRecords / selctRecordNum) + (Math.mod(totalRecords, selctRecordNum) > 0 ? 1 : 0);
        if (totalRecords == 0) {
            currPage  = 1;
            //this.unCheckedAssets.clear();
        } else {
            currPage ++;
            this.setPageRecord();
        }
        //HWAG-B4R3SS  END 20181026
    }
    // 翻页到尾页
    public void endPage() {
        getAssetSerialNumber();
        //HWAG-B4R3SS  START 20181026
        totalRecords = soqlNos();
        totalPage = (totalRecords / selctRecordNum) + (Math.mod(totalRecords, selctRecordNum) > 0 ? 1 : 0);
        if (totalRecords == 0) {
            currPage  = 1;
            this.unCheckedAssets.clear();
        } else {
            currPage = totalPage;
            this.setPageRecord();
        }
        //HWAG-B4R3SS  END 20181026
    }
    // 每页显示记录数变更
    public void recordNumChange() {
        currPage = 1;
        //totalRecords = soqlNos();
        totalPage = (totalRecords / selctRecordNum) + (Math.mod(totalRecords, selctRecordNum) > 0 ? 1 : 0);
        this.setPageRecord();
    }
    //list分割 集合大小超过1000对应
    private void listCut(List<AssetInfo> records) {
        List<AssetInfo> recordsbreak = new List<AssetInfo>();
        List<AssetInfo> recordsbreakover = new List<AssetInfo>();
        unCheckedAssetsView = new List<List<AssetInfo>>();
        AssetInfo c = null;
        recordsbreak.clear();
        recordsbreakover.clear();
        unCheckedAssetsView.clear();
        //if(records.size() > 1000){
        //    for(Integer i = 0; i < records.size(); i++){
        //        if(i < 1000){
        //            c = records.get(i);
        //            recordsbreak.add(c);
        //        }else{
        //            c = records.get(i);
        //            recordsbreakover.add(c);
        //        }
        //    }
        //    unCheckedAssetsView.add(recordsbreak);
        //    unCheckedAssetsView.add(recordsbreakover);
        //}else{
        unCheckedAssetsView.add(records);
        //}
    }
    /*
    *显示过去两年的维修实绩
    *计算该维修合同报价的所有保佑设备,过去两年的修理实绩
    */
    public static void ComputeLTYRepair(String targetHospitalId) {
        system.debug('ComputeLTYRepair=====Start');
        List<Maintenance_Contract_Asset_Estimate__c> McaeList = new List<Maintenance_Contract_Asset_Estimate__c>();
        McaeList = [select id, asset__c, Lastyear_Repair_Cost_Text__c, Last_Second_Years_Repair_Cost_Text__c, Last_Third_Years_Repair_Cost_Text__c
                    from Maintenance_Contract_Asset_Estimate__c
                    where Maintenance_Contract_Estimate__c = :targetHospitalId];
        List<id> AsList = new List<id>();
        Map<id, id> McaecToAsset = new Map<id, id>();
        for (Maintenance_Contract_Asset_Estimate__c Mcaes : McaeList) {
            AsList.add(Mcaes.asset__c);
            McaecToAsset.put(Mcaes.id, Mcaes.asset__c);
        }
        Maintenance_Contract_Estimate__c mcec = [select id, createdDate, Submit_quotation_day__c from Maintenance_Contract_Estimate__c where id = :targetHospitalId];
        //1年前维修实绩
        Date today = null;
        Date LastYearDate = null;
        Date LastSecondYearDate = null;
        Date LastThirdYearDate = null;
        Decimal LastYearPriceForMCAEC = 0;
        if (mcec.Submit_quotation_day__c != null && String.valueOf(mcec.Submit_quotation_day__c) != '') {
            today = mcec.Submit_quotation_day__c;
            LastYearDate = mcec.Submit_quotation_day__c;
            LastSecondYearDate = mcec.Submit_quotation_day__c;
            LastThirdYearDate = mcec.Submit_quotation_day__c;
        } else {
            today = mcec.Submit_quotation_day__c;
            LastYearDate = Date.valueOf(mcec.createdDate);
            LastSecondYearDate = Date.valueOf(mcec.createdDate);
            LastThirdYearDate = Date.valueOf(mcec.createdDate);
        }
        system.debug('去年' + LastYearDate + '前年' + LastSecondYearDate + '大前年' + LastThirdYearDate);
        LastYearDate = LastYearDate.addYears(-1);
        // LastYearDate = LastYearDate.addDays(1);
        //LastSecondYearDate = LastSecondYearDate.addDays(1);
        LastSecondYearDate = LastSecondYearDate.addYears(-2);
        // LastThirdYearDate = LastThirdYearDate.addDays(1);
        LastThirdYearDate = LastThirdYearDate.addYears(-3);
        system.debug('去年' + LastYearDate + '前年' + LastSecondYearDate + '大前年' + LastThirdYearDate);
        List<AggregateResult> FriRepairList = [
                select
                sum(Discount_Price_formula__c) SumPrice,
                //2019/1添加
                sum(Repair_Quotation_Id__r.sales_discount__c) sales_discount,
                sum(Repair_Quotation_Id__r.Contract_target__c) contract_target,
                sum(Repair_Quotation_Id__r.Loaner_repair__c) loaner_repair,
                sum(Repair_Quotation_Id__r.long_term_insurance__c) long_term_insurance,
                sum(Repair_Quotation_Id__r.Set_discount__c) set_discount,
                sum(Repair_Quotation_Id__r.Servince_contract_discount_amount__c) sercince,
                sum(Repair_Quotation_Id__r.Delivery_compensation__c) delivery,
                sum(Repair_Quotation_Id__r.Other_discount__c) other,
                Delivered_Product__c
                from
                Repair__c
                where
                Delivered_Product__c in:AsList
                /*and (
                            (
                                Repair_Quotation_Id__c!=null
                                    and     (Repair_Quotation_Id__r.New_QIS_free__c = 0
                                            or
                                                Repair_Quotation_Id__r.New_QIS_free__c = null)
                                    and     (Repair_Quotation_Id__r.Contract_free__c= 0
                                            or
                                                Repair_Quotation_Id__r.Contract_free__c= null)
                            )
                        or  Repair_Quotation_Id__c =null
                    )
                and Status2__c != '00.关闭'
                and Status2__c != '00.取消'
                and Status2__c != '00.删除'
                and Return_Without_Repair_IF__c = false*/
                and Agreed_Date__c != null
                and Agreed_Date__c > :LastYearDate
                and Agreed_Date__c <= :today
                group by Delivered_Product__c
                                              ];
        List<AggregateResult> SecRepairList = [
                select
                sum(Discount_Price_formula__c) SumPrice,
                //2019/1添加
                sum(Repair_Quotation_Id__r.sales_discount__c) sales_discount,
                sum(Repair_Quotation_Id__r.Contract_target__c) contract_target,
                sum(Repair_Quotation_Id__r.Loaner_repair__c) loaner_repair,
                sum(Repair_Quotation_Id__r.long_term_insurance__c) long_term_insurance,
                sum(Repair_Quotation_Id__r.Set_discount__c) set_discount,
                sum(Repair_Quotation_Id__r.Servince_contract_discount_amount__c) sercince,
                sum(Repair_Quotation_Id__r.Delivery_compensation__c) delivery,
                sum(Repair_Quotation_Id__r.Other_discount__c) other,
                Delivered_Product__c
                from
                Repair__c
                where
                Delivered_Product__c in:AsList
                /*and (
                            (
                                Repair_Quotation_Id__c!=null
                                    and     (Repair_Quotation_Id__r.New_QIS_free__c = 0
                                            or
                                                Repair_Quotation_Id__r.New_QIS_free__c = null)
                                    and     (Repair_Quotation_Id__r.Contract_free__c= 0
                                            or
                                                Repair_Quotation_Id__r.Contract_free__c= null)
                            )
                        or  Repair_Quotation_Id__c =null
                    )
                and Status2__c != '00.关闭'
                and Status2__c != '00.取消'
                and Status2__c != '00.删除'
                and Return_Without_Repair_IF__c = false*/
                and Agreed_Date__c != null
                and Agreed_Date__c <= :LastYearDate
                and Agreed_Date__c > :LastSecondYearDate
                group by Delivered_Product__c];
        List<AggregateResult> ThiRepairList = [
                select
                sum(Discount_Price_formula__c) SumPrice,
                //2019/1添加
                sum(Repair_Quotation_Id__r.sales_discount__c) sales_discount,
                sum(Repair_Quotation_Id__r.Contract_target__c) contract_target,
                sum(Repair_Quotation_Id__r.Loaner_repair__c) loaner_repair,
                sum(Repair_Quotation_Id__r.long_term_insurance__c) long_term_insurance,
                sum(Repair_Quotation_Id__r.Set_discount__c) set_discount,
                sum(Repair_Quotation_Id__r.Servince_contract_discount_amount__c) sercince,
                sum(Repair_Quotation_Id__r.Delivery_compensation__c) delivery,
                sum(Repair_Quotation_Id__r.Other_discount__c) other,
                Delivered_Product__c
                from
                Repair__c
                where
                Delivered_Product__c in:AsList
                /*and (
                            (
                                Repair_Quotation_Id__c!=null
                                    and     (Repair_Quotation_Id__r.New_QIS_free__c = 0
                                            or
                                                Repair_Quotation_Id__r.New_QIS_free__c = null)
                                    and     (Repair_Quotation_Id__r.Contract_free__c= 0
                                            or
                                                Repair_Quotation_Id__r.Contract_free__c= null)
                            )
                        or  Repair_Quotation_Id__c =null
                    )
                and Status2__c != '00.关闭'
                and Status2__c != '00.取消'
                and Status2__c != '00.删除'
                and Return_Without_Repair_IF__c = false*/
                and Agreed_Date__c != null
                and Agreed_Date__c <= :LastSecondYearDate
                and Agreed_Date__c > :LastThirdYearDate
                group by Delivered_Product__c];
        system.debug('++++++++' + FriRepairList + '++++++++' + SecRepairList + '+++++++' + ThiRepairList + '+++++');
        Map<id, Decimal> LastFriYearPriceSumMap = new Map<id, Decimal>();
        Map<id, Decimal> LastSecYearPriceSumMap = new Map<id, Decimal>();
        Map<id, Decimal> LastThiYearPriceSumMap = new Map<id, Decimal>();
        for (AggregateResult Rpc : FriRepairList) {
            id idf        = String.valueOf(Rpc.get('Delivered_Product__c'));
            //Decimal Defir = decimal.valueOf(Rpc.get('SumPrice')+'');
            Decimal Defir = sumPrice1(Rpc);
            LastFriYearPriceSumMap.put(idf, Defir);
        }
        for (AggregateResult Rpc : SecRepairList) {
            id idf        = String.valueOf(Rpc.get('Delivered_Product__c'));
            //Decimal Defir = decimal.valueOf(Rpc.get('SumPrice')+'');
            Decimal Defir = sumPrice1(Rpc);
            LastSecYearPriceSumMap.put(idf, Defir);
        }
        for (AggregateResult Rpc : ThiRepairList) {
            id idf        = String.valueOf(Rpc.get('Delivered_Product__c'));
            //Decimal Defir = decimal.valueOf(Rpc.get('SumPrice')+'');
            Decimal Defir = sumPrice1(Rpc);
            LastThiYearPriceSumMap.put(idf, Defir);
        }
        for (Maintenance_Contract_Asset_Estimate__c Mca : McaeList) {
            Mca.Lastyear_Repair_Cost_Text__c = LastFriYearPriceSumMap.get(McaecToAsset.get(Mca.id)) == null ? 0 : LastFriYearPriceSumMap.get(McaecToAsset.get(Mca.id));
            Mca.Last_Second_Years_Repair_Cost_Text__c = LastSecYearPriceSumMap.get(McaecToAsset.get(Mca.id)) == null ? 0 : LastSecYearPriceSumMap.get(McaecToAsset.get(Mca.id));
            Mca.Last_Third_Years_Repair_Cost_Text__c = LastThiYearPriceSumMap.get(McaecToAsset.get(Mca.id)) == null ? 0 : LastThiYearPriceSumMap.get(McaecToAsset.get(Mca.id));
            /* if( LastFriYearPriceSumMap.get(McaecToAsset.get(Mca.id))!=null){
                  Mca.Lastyear_Repair_Cost_Text__c = LastFriYearPriceSumMap.get(McaecToAsset.get(Mca.id));
                 system.debug(McaecToAsset.get(Mca.id)+'::::::'+Mca.Lastyear_Repair_Cost_Text__c);
             }
             if(LastSecYearPriceSumMap.get(McaecToAsset.get(Mca.id)) !=null){
                  Mca.Last_Second_Years_Repair_Cost_Text__c = LastSecYearPriceSumMap.get(McaecToAsset.get(Mca.id));
                  system.debug(McaecToAsset.get(Mca.id)+'#######'+Mca.Last_Second_Years_Repair_Cost_Text__c);
             }
             if(LastThiYearPriceSumMap.get(McaecToAsset.get(Mca.id)) !=null){
                  Mca.Last_Third_Years_Repair_Cost_Text__c = LastThiYearPriceSumMap.get(McaecToAsset.get(Mca.id));
                  system.debug(McaecToAsset.get(Mca.id)+'#######'+Mca.Last_Third_Years_Repair_Cost_Text__c);
             }*/
            Mca.The_Date_Of_Compute_The_RPCost__c = Date.today();
        }
        try {
            system.debug('McaeList:::::' + McaeList);
            update McaeList;
            //return '';
        } catch (Exception e) {
            //return 'McaeList Update Failed : '+e;
        }
    }
    public void ComputeLTYRepair() {
        system.debug('ComputeLTYRepair=====Start');
        List<Maintenance_Contract_Asset_Estimate__c> McaeList = new List<Maintenance_Contract_Asset_Estimate__c>();
        McaeList = [select id, asset__c, Lastyear_Repair_Cost_Text__c, Last_Second_Years_Repair_Cost_Text__c
                    from Maintenance_Contract_Asset_Estimate__c
                    where Maintenance_Contract_Estimate__c = :targetEstimateId];
        List<id> AsList = new List<id>();
        Map<id, id> McaecToAsset = new Map<id, id>();
        for (Maintenance_Contract_Asset_Estimate__c Mcaes : McaeList) {
            AsList.add(Mcaes.asset__c);
            McaecToAsset.put(Mcaes.id, Mcaes.asset__c);
        }
        Maintenance_Contract_Estimate__c mcec = [select id, createdDate, Submit_quotation_day__c from Maintenance_Contract_Estimate__c where id = :targetEstimateId];
        //1年前维修实绩
        Date today = null;
        Date LastYearDate = null;
        Date LastSecondYearDate = null;
        Date LastThirdYearDate = null;
        Decimal LastYearPriceForMCAEC = 0;
        if (mcec.Submit_quotation_day__c != null && String.valueOf(mcec.Submit_quotation_day__c) != '') {
            today = mcec.Submit_quotation_day__c;
            LastYearDate = mcec.Submit_quotation_day__c;
            LastSecondYearDate = mcec.Submit_quotation_day__c;
            LastThirdYearDate = mcec.Submit_quotation_day__c;
        } else {
            today = mcec.Submit_quotation_day__c;
            LastYearDate = Date.valueOf(mcec.createdDate);
            LastSecondYearDate = Date.valueOf(mcec.createdDate);
            LastThirdYearDate = Date.valueOf(mcec.createdDate);
        }
        LastYearDate = LastYearDate.addYears(-1);
        // LastYearDate = LastYearDate.addDays(1);
        // LastSecondYearDate = LastSecondYearDate.addDays(1);
        LastSecondYearDate = LastSecondYearDate.addYears(-2);
        // LastThirdYearDate = LastThirdYearDate.addDays(1);
        LastThirdYearDate = LastThirdYearDate.addYears(-3);
        system.debug('去年' + LastYearDate + '前年' + LastSecondYearDate + '大前年' + LastThirdYearDate);
        List<AggregateResult> FriRepairList = [
                select
                sum(Discount_Price_formula__c) SumPrice,
                //2019/1添加
                sum(Repair_Quotation_Id__r.sales_discount__c) sales_discount,
                sum(Repair_Quotation_Id__r.Contract_target__c) contract_target,
                sum(Repair_Quotation_Id__r.Loaner_repair__c) loaner_repair,
                sum(Repair_Quotation_Id__r.long_term_insurance__c) long_term_insurance,
                sum(Repair_Quotation_Id__r.Set_discount__c) set_discount,
                sum(Repair_Quotation_Id__r.Servince_contract_discount_amount__c) sercince,
                sum(Repair_Quotation_Id__r.Delivery_compensation__c) delivery,
                sum(Repair_Quotation_Id__r.Other_discount__c) other,
                Delivered_Product__c
                from
                Repair__c
                where
                Delivered_Product__c in:AsList
                /*and (
                            (
                                Repair_Quotation_Id__c!=null
                                    and     (Repair_Quotation_Id__r.New_QIS_free__c = 0
                                            or
                                                Repair_Quotation_Id__r.New_QIS_free__c = null)
                                    and     (Repair_Quotation_Id__r.Contract_free__c= 0
                                            or
                                                Repair_Quotation_Id__r.Contract_free__c= null)
                            )
                        or  Repair_Quotation_Id__c =null
                    )
                and Status2__c != '00.关闭'
                and Status2__c != '00.取消'
                and Status2__c != '00.删除'
                and Return_Without_Repair_IF__c = false*/
                and Agreed_Date__c != null
                and Agreed_Date__c > :LastYearDate
                and Agreed_Date__c <= :today
                group by Delivered_Product__c];
        List<AggregateResult> SecRepairList = [
                select
                sum(Discount_Price_formula__c) SumPrice,
                //2019/1添加
                sum(Repair_Quotation_Id__r.sales_discount__c) sales_discount,
                sum(Repair_Quotation_Id__r.Contract_target__c) contract_target,
                sum(Repair_Quotation_Id__r.Loaner_repair__c) loaner_repair,
                sum(Repair_Quotation_Id__r.long_term_insurance__c) long_term_insurance,
                sum(Repair_Quotation_Id__r.Set_discount__c) set_discount,
                sum(Repair_Quotation_Id__r.Servince_contract_discount_amount__c) sercince,
                sum(Repair_Quotation_Id__r.Delivery_compensation__c) delivery,
                sum(Repair_Quotation_Id__r.Other_discount__c) other,
                Delivered_Product__c
                from
                Repair__c
                where
                Delivered_Product__c in:AsList
                /* and (
                             (
                                 Repair_Quotation_Id__c!=null
                                     and     (Repair_Quotation_Id__r.New_QIS_free__c = 0
                                             or
                                                 Repair_Quotation_Id__r.New_QIS_free__c = null)
                                     and     (Repair_Quotation_Id__r.Contract_free__c= 0
                                             or
                                                 Repair_Quotation_Id__r.Contract_free__c= null)
                             )
                         or  Repair_Quotation_Id__c =null
                     )
                 and Status2__c != '00.关闭'
                 and Status2__c != '00.取消'
                 and Status2__c != '00.删除'
                 and Return_Without_Repair_IF__c = false */
                and Agreed_Date__c != null
                and Agreed_Date__c <= :LastYearDate
                and Agreed_Date__c > :LastSecondYearDate
                group by Delivered_Product__c];
        List<AggregateResult> ThiRepairList = [
                select
                sum(Discount_Price_formula__c) SumPrice,
                //2019/1添加
                sum(Repair_Quotation_Id__r.sales_discount__c) sales_discount,
                sum(Repair_Quotation_Id__r.Contract_target__c) contract_target,
                sum(Repair_Quotation_Id__r.Loaner_repair__c) loaner_repair,
                sum(Repair_Quotation_Id__r.long_term_insurance__c) long_term_insurance,
                sum(Repair_Quotation_Id__r.Set_discount__c) set_discount,
                sum(Repair_Quotation_Id__r.Servince_contract_discount_amount__c) sercince,
                sum(Repair_Quotation_Id__r.Delivery_compensation__c) delivery,
                sum(Repair_Quotation_Id__r.Other_discount__c) other,
                Delivered_Product__c
                from
                Repair__c
                where
                Delivered_Product__c in:AsList
                /* and (
                             (
                                 Repair_Quotation_Id__c!=null
                                     and     (Repair_Quotation_Id__r.New_QIS_free__c = 0
                                             or
                                                 Repair_Quotation_Id__r.New_QIS_free__c = null)
                                     and     (Repair_Quotation_Id__r.Contract_free__c= 0
                                             or
                                                 Repair_Quotation_Id__r.Contract_free__c= null)
                             )
                         or  Repair_Quotation_Id__c =null
                     )
                 and Status2__c != '00.关闭'
                 and Status2__c != '00.取消'
                 and Status2__c != '00.删除'
                 and Return_Without_Repair_IF__c = false*/
                and Agreed_Date__c != null
                and Agreed_Date__c <= :LastSecondYearDate
                and Agreed_Date__c > :LastThirdYearDate
                group by Delivered_Product__c];
        Map<id, Decimal> LastFriYearPriceSumMap = new Map<id, Decimal>();
        Map<id, Decimal> LastSecYearPriceSumMap = new Map<id, Decimal>();
        Map<id, Decimal> LastThiYearPriceSumMap = new Map<id, Decimal>();
        system.debug('1' + FriRepairList);
        system.debug('2' + SecRepairList);
        system.debug('3' + ThiRepairList);
        for (AggregateResult Rpc : FriRepairList) {
            id idf        = String.valueOf(Rpc.get('Delivered_Product__c'));
            //Decimal Defir = decimal.valueOf(Rpc.get('SumPrice')+'');
            Decimal Defir = this.sumPrice(Rpc);
            LastFriYearPriceSumMap.put(idf, Defir);
        }
        for (AggregateResult Rpc : SecRepairList) {
            id idf        = String.valueOf(Rpc.get('Delivered_Product__c'));
            //Decimal Defir = decimal.valueOf(Rpc.get('SumPrice')+'');
            Decimal Defir = this.sumPrice(Rpc);
            LastSecYearPriceSumMap.put(idf, Defir);
        }
        for (AggregateResult Rpc : ThiRepairList) {
            id idf        = String.valueOf(Rpc.get('Delivered_Product__c'));
            //Decimal Defir = decimal.valueOf(Rpc.get('SumPrice')+'');
            Decimal Defir = this.sumPrice(Rpc);
            LastThiYearPriceSumMap.put(idf, Defir);
        }
        for (Maintenance_Contract_Asset_Estimate__c Mca : McaeList) {
            Mca.Lastyear_Repair_Cost_Text__c = LastFriYearPriceSumMap.get(McaecToAsset.get(Mca.id)) == null ? 0 : LastFriYearPriceSumMap.get(McaecToAsset.get(Mca.id));
            Mca.Last_Second_Years_Repair_Cost_Text__c = LastSecYearPriceSumMap.get(McaecToAsset.get(Mca.id)) == null ? 0 : LastSecYearPriceSumMap.get(McaecToAsset.get(Mca.id));
            Mca.Last_Third_Years_Repair_Cost_Text__c = LastThiYearPriceSumMap.get(McaecToAsset.get(Mca.id)) == null ? 0 : LastThiYearPriceSumMap.get(McaecToAsset.get(Mca.id));
            /*if( LastFriYearPriceSumMap.get(McaecToAsset.get(Mca.id))!=null){
                 Mca.Lastyear_Repair_Cost_Text__c = LastFriYearPriceSumMap.get(McaecToAsset.get(Mca.id));
                system.debug(McaecToAsset.get(Mca.id)+'::::::'+Mca.Lastyear_Repair_Cost_Text__c);
            }
            if(LastSecYearPriceSumMap.get(McaecToAsset.get(Mca.id)) !=null){
                 Mca.Last_Second_Years_Repair_Cost_Text__c = LastSecYearPriceSumMap.get(McaecToAsset.get(Mca.id));
                 system.debug(McaecToAsset.get(Mca.id)+'#######'+Mca.Last_Second_Years_Repair_Cost_Text__c);
            }
            if(LastThiYearPriceSumMap.get(McaecToAsset.get(Mca.id)) !=null){
                 Mca.Last_Third_Years_Repair_Cost_Text__c = LastThiYearPriceSumMap.get(McaecToAsset.get(Mca.id));
                 system.debug(McaecToAsset.get(Mca.id)+'#######'+Mca.Last_Third_Years_Repair_Cost_Text__c);
            }*/
            Mca.The_Date_Of_Compute_The_RPCost__c = Date.today();
        }
        try {
            update McaeList;
            //return '';
        } catch (Exception e) {
            //return 'McaeList Update Failed : '+e;
        }
    }
    private Decimal sumPrice(AggregateResult rpc) {
        Decimal SumPrice = Decimal.valueOf(rpc.get('SumPrice') + '');
        system.debug(rpc.get('sales_discount') == null ? 0 : rpc.get('sales_discount'));
        Decimal sales_discount = Decimal.valueOf((rpc.get('sales_discount') == null ? 0 : rpc.get('sales_discount')) + '') * -1;
        Decimal contract_target = Decimal.valueOf((rpc.get('contract_target') == null ? 0 : rpc.get('contract_target')) + '') * -1;
        Decimal loaner_repair = Decimal.valueOf((rpc.get('loaner_repair') == null ? 0 : rpc.get('loaner_repair')) + '') * -1;
        Decimal long_term_insurance = Decimal.valueOf((rpc.get('long_term_insurance') == null ? 0 : rpc.get('long_term_insurance')) + '') * -1;
        Decimal set_discount = Decimal.valueOf((rpc.get('set_discount') == null ? 0 : rpc.get('set_discount')) + '') * -1;
        Decimal sercince = Decimal.valueOf((rpc.get('sercince') == null ? 0 : rpc.get('sercince')) + '') * -1;
        Decimal delivery = Decimal.valueOf((rpc.get('delivery') == null ? 0 : rpc.get('delivery')) + '') * -1;
        Decimal other = Decimal.valueOf((rpc.get('other') == null ? 0 : rpc.get('other')) + '') * -1;
        system.debug(rpc.get('SumPrice') + '--' + rpc.get('sales_discount') + '--' + rpc.get('contract_target') + '--' +
                     rpc.get('loaner_repair') + '--' + rpc.get('long_term_insurance') + '--' + rpc.get('set_discount') + '--' + rpc.get('sercince')
                     + '--' + rpc.get('delivery') + '--' + rpc.get('other') + '--');
        return SumPrice + sales_discount + contract_target + loaner_repair + long_term_insurance + set_discount + sercince + delivery + other;
    }
    private static Decimal sumPrice1(AggregateResult rpc) {
        Decimal SumPrice = Decimal.valueOf(rpc.get('SumPrice') + '');
        Decimal sales_discount = Decimal.valueOf((rpc.get('sales_discount') == null ? 0 : rpc.get('sales_discount')) + '') * -1;
        Decimal contract_target = Decimal.valueOf((rpc.get('contract_target') == null ? 0 : rpc.get('contract_target')) + '') * -1;
        Decimal loaner_repair = Decimal.valueOf((rpc.get('loaner_repair') == null ? 0 : rpc.get('loaner_repair')) + '') * -1;
        Decimal long_term_insurance = Decimal.valueOf((rpc.get('long_term_insurance') == null ? 0 : rpc.get('long_term_insurance')) + '') * -1;
        Decimal set_discount = Decimal.valueOf((rpc.get('set_discount') == null ? 0 : rpc.get('set_discount')) + '') * -1;
        Decimal sercince = Decimal.valueOf((rpc.get('sercince') == null ? 0 : rpc.get('sercince')) + '') * -1;
        Decimal delivery = Decimal.valueOf((rpc.get('delivery') == null ? 0 : rpc.get('delivery')) + '') * -1;
        Decimal other = Decimal.valueOf((rpc.get('other') == null ? 0 : rpc.get('other')) + '') * -1;
        system.debug(rpc.get('SumPrice') + '--' + rpc.get('sales_discount') + '--' + rpc.get('contract_target') + '--' +
                     rpc.get('loaner_repair') + '--' + rpc.get('long_term_insurance') + '--' + rpc.get('set_discount') + '--' + rpc.get('sercince')
                     + '--' + rpc.get('delivery') + '--' + rpc.get('other') + '--');
        return SumPrice + sales_discount + contract_target + loaner_repair + long_term_insurance + set_discount + sercince + delivery + other;
    }
    //废弃中=========20161024==============//
    public void ShowLTYRepair() {
        system.debug('ShowLTYRepair=====Start');
        lastFriYearsPriceSum = 0;
        lastSecYearsPriceSum = 0;
        //
        List<Maintenance_Contract_Estimate__c> McecList = new List<Maintenance_Contract_Estimate__c>();
        McecList = [select
                    Last_Year_Repair_Sum__c,
                    Year_Before_Last_Year_Re_Sum__c,
                    Last_Two_Year_Repair_sum__c,
                    Process_Status__c,//报价状态
                    Repair_Sum_Compute_Date__c
                    from
                    Maintenance_Contract_Estimate__c
                    where
                    id = :targetEstimateId
                   ];
        Maintenance_Contract_Estimate__c McecEle = new Maintenance_Contract_Estimate__c();
        if (McecList.size() > 0) {
            McecEle = McecList[0];
            Date ComputeD = McecEle.Repair_Sum_Compute_Date__c == null ? Date.today() : McecEle.Repair_Sum_Compute_Date__c;
            String DateString1 = ComputeD + '';
            String DateString2 = ComputeD.addYears(-2).addDays(1) + '';
            alertString = '集計対象期間:' + DateString1.substring(0, 10) + '~' + DateString2.substring(0, 10) + '';
            alertString2 = '去年修理実績合計:' + McecEle.Last_Year_Repair_Sum__c + ' RMB ';
            alertString3 = '前年修理実績合計:' + McecEle.Year_Before_Last_Year_Re_Sum__c + ' RMB';
        } else {
            alertString = '没有有效的维修合同报价';
        }
    }
    /**
     * 手動で商品選択後のリフレッシュ
    **/
    public void refreshProductData() {
        for (Integer i = 0; i < checkedAssets.size(); i++) {
            if (i == productIdx) {
                AssetInfo ai = checkedAssets[i];
                if (ai.mcae.Product_Manual__c == null) {
                    ai.mcae.Estimate_List_Price__c = null;
                    // add by fxk 2021/9/9 控制点检对象是否可选 Star
                    ai.CheckRows = true;
                    // add by fxk 2021/9/9 控制点检对象是否可选 End
                } else {
                    // add by mzy 2021-02-04  LJPH-BX9CVX  select 中添加 NoPartRiskDate_F__c
                    List<Product2> prd = [select Id, Maintenance_Price_Month__c, Name from Product2 where Id = :ai.mcae.Product_Manual__c];
                    ai.mcae.Estimate_List_Price__c = prd[0].Maintenance_Price_Month__c * isNewPriceAdj;
                    ai.orgPrice = prd[0].Maintenance_Price_Month__c;
                    //add by rentx 2020-11-12 LJPH-BV93RZ start
                    ai.proName = prd[0].Name;
                    //add by rentx 2020-11-12 LJPH-BV93RZ start
                    //add by mzy 2021-02-04 LJPH-BX9CVX start
                    //ai.NoPartRiskDate = prd[0].NoPartRiskDate_F__c;
                    ai.proName2 = prd[0].Name;
                    // add by fxk 2021/9/9 控制点检对象是否可选 Star
                    ai.CheckRows = false;
                    // add by fxk 2021/9/9 控制点检对象是否可选 End
                    //ai.SignableFlag = prd[0].SignableFlag__c;
                    //add by mzy 2021-02-04 LJPH-BX9CVX start
                }
            }
        }
        // HWAG-BA73ZP
        contractStartDateChange();
    }
    /**
     * 選択済み/未選択製品の置き換え
     */
    public PageReference exchangeAsset() {
        System.debug('exchangeAsset start');
        Date systemToday = System.today();
        List<AssetInfo> tmpChecked = new List<AssetInfo>();
        List<AssetInfo> tmpNewRows = new List<AssetInfo>();
        List<AssetInfo> tmpUnChecked = new List<AssetInfo>();
        for (AssetInfo ass : this.checkedAssets) {
            if (ass.isManual) {
                tmpNewRows.add(ass);
            } else if (ass.rec_checkBox_c) {
                tmpChecked.add(ass);
            } else {
                ass.mcae = null;
                tmpUnChecked.add(ass);
                totalRecords ++;
            }
        }
        for (AssetInfo ass : this.unCheckedAssets) {
            Boolean isNew = false;
            // add点检改善:新增一个点检对象复选框字段,默认为true 2021.6.8 fxk Star
            boolean isCheck = true;
            // add点检改善:新增一个点检对象复选框字段,默认为true 2021.6.8 fxk End
            Decimal listPrice = ass.rec.Maintenance_Price_Month__c;
            if (ass.rec_checkBox_c) {
                // xudan 20160110 新品判断ここ要らない、contractStartDateChangeがやる
//                if (systemToday.addMonths(-6) < ass.rec.InstallDate) {
//                if (estimate.Contract_Esti_Start_Date__c.addMonths(isNewAddMonth) < ass.rec.InstallDate) {
//                Date createdDate = estimate.CreatedDate == null ? systemToday : estimate.CreatedDate.date();
//                if (createdDate.addMonths(isNewAddMonth) < ass.rec.InstallDate) {
//                    isNew = true;
//                    listPrice = ass.rec.Maintenance_Price_Month__c * isNewPriceAdj;
//                }
                Maintenance_Contract_Asset_Estimate__c mcae = new Maintenance_Contract_Asset_Estimate__c(
                    isNew__c = isNew,
                    // add点检改善:新增一个点检对象复选框字段,默认为true 2021.6.8 fxk Star
                    Check_Object__c = isCheck,
                    // add点检改善:新增一个点检对象复选框字段,默认为true 2021.6.8 fxk end
                    Estimate_List_Price__c = listPrice
                );
                ass.mcae = mcae;
                tmpChecked.add(ass);
                totalRecords --;
            } else {
                ass.mcae = null;
                tmpUnChecked.add(ass);
            }
        }
        this.checkedAssets = new List<AssetInfo>();
        for (AssetInfo ass : tmpChecked) {
            ass.lineNo = this.checkedAssets.size();
            this.checkedAssets.add(ass);
        }
        for (AssetInfo ass : tmpNewRows) {
            ass.lineNo = this.checkedAssets.size();
            this.checkedAssets.add(ass);
        }
        this.unCheckedAssets = new List<AssetInfo>();
        this.unCheckedAssets.addAll(tmpUnChecked);
        totalPage = (totalRecords / selctRecordNum) + (Math.mod(totalRecords, selctRecordNum) > 0 ? 1 : 0);
        this.setPageRecord();
        //listCut(unCheckedAssets);
        // 根据合同开始日重新计算维修合同价格
        //contractStartDateChange();
        return null;
    }
    // 合同开始日变更,重新计算新品
    public PageReference contractStartDateChange() {
        Date systemToday = System.today();
        // 创建日
        Date createdDate = estimate.CreatedDate == null ? systemToday : estimate.CreatedDate.date();
        // 创建日3个月
        Date threeMonthAfter = createdDate.addMonths(keepPriceMonth);
        // 创建日6个月
        Date isNewAfter = createdDate.addMonths(-isNewAddMonth);
        // 合同开始日
        Date contractDate = estimate.Contract_Start_Date__c == null ? systemToday : estimate.Contract_Start_Date__c;
        /**********************HWAG-AYDCZX 2018/5/8 DEL START***************************/
        //// 合同开始日大于创建日6个月,都不算新品
        //if (contractDate >= isNewAfter) {
        //    system.debug('===== greater than createddate 6 months');
        //    for (AssetInfo info : checkedAssets) {
        //        if (!info.isManual) {
        //            info.mcae.isNew__c = false;
        //            info.mcae.Estimate_List_Price__c = info.orgPrice;
        //        } else if (info.isManual && !String.isBlank(info.mcae.Product_Manual__c)) {
        //            info.mcae.isNew__c = false;
        //            info.mcae.Estimate_List_Price__c = info.orgPrice;
        //        }
        //    }
        //}
        //// 合同开始日大于创建日3个月,使用合同开始日计算新品
        //else if (contractDate >= threeMonthAfter) {
        //    system.debug('===== greater than createddate 3 months');
        //    for (AssetInfo info : checkedAssets) {
        //        if (!info.isManual) {
        //            // xudan 20151224 新規、又はコピー、又は作成日から3ヶ月経過、又は3ヶ月以内且つ未提出、価格更新
        //            if (this.estimate.CreatedDate == null
        //                || String.isBlank(ApexPages.currentPage().getParameters().get('copyid')) == false
        //                || contractDate.addMonths(keepPriceMonth) < systemToday
        //                || this.estimate.Process_Status__c == '草案中') {
        //                info.mcae.isNew__c = false;
        //                info.mcae.Estimate_List_Price__c = info.orgPrice;
        //                // 110からの場合、Postあり、Installなし
        //                if (info.rec.Posting_Date__c != null && info.rec.InstallDate == null) {
        //                    if (contractDate.addMonths(isNewAddMonth) < info.rec.Posting_Date__c) {
        //                        info.mcae.isNew__c = true;
        //                        info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
        //                    }
        //                }
        //                // Installあり
        //                else if (info.rec.Posting_Date__c != null && info.rec.InstallDate != null) {
        //                    // Postから6月経ってもInstallしてない
        //                    if (info.rec.Posting_Date__c.addMonths(PosttoInstall) < info.rec.InstallDate) {
        //                        // 新品適用しない
        //                    }
        //                    else {
        //                        if (contractDate.addMonths(isNewAddMonth) < info.rec.InstallDate) {
        //                            info.mcae.isNew__c = true;
        //                            info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
        //                        }
        //                    }
        //                }
        //                // Postなし
        //                else if (info.rec.Posting_Date__c == null && info.rec.InstallDate != null) {
        //                    if (contractDate.addMonths(isNewAddMonth) < info.rec.InstallDate) {
        //                        info.mcae.isNew__c = true;
        //                        info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
        //                    }
        //                }
        //                // (info.rec.Posting_Date__c == null && info.rec.InstallDate == null)
        //                else {
        //                    // 特殊処理なし
        //                }
        //            }
        //            if (contractDate.addMonths(isNewAddMonth) < info.rec.InstallDate) {
        //                info.mcae.isNew__c = true;
        //                info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
        //            }
        //        } else if (info.isManual && !String.isBlank(info.mcae.Product_Manual__c)) {
        //            info.mcae.isNew__c = true;
        //            info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
        //        }
        //    }
        //}
        //// 使用创建日计算新品
        //else {
        //    system.debug('===== calculate by createddate');
        //    for (AssetInfo info : checkedAssets) {
        //        if (!info.isManual) {
        //            // xudan 20151224 新規、又は作成日から3ヶ月経過、又は3ヶ月以内且つ未提出、価格更新
        //            if (this.estimate.CreatedDate == null
        //                || String.isBlank(ApexPages.currentPage().getParameters().get('copyid')) == false
        //                || contractDate.addMonths(keepPriceMonth) < systemToday
        //                || this.estimate.Process_Status__c == '草案中') {
        //                info.mcae.isNew__c = false;
        //                info.mcae.Estimate_List_Price__c = info.orgPrice;
        //                // 110からの場合、Postあり、Installなし
        //                if (info.rec.Posting_Date__c != null && info.rec.InstallDate == null) {
        //                    if (createdDate.addMonths(isNewAddMonth) < info.rec.Posting_Date__c) {
        //                        info.mcae.isNew__c = true;
        //                        info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
        //                    }
        //                }
        //                // Installあり
        //                else if (info.rec.Posting_Date__c != null && info.rec.InstallDate != null) {
        //                    // Postから6月経ってもInstallしてない
        //                    if (info.rec.Posting_Date__c.addMonths(PosttoInstall) < info.rec.InstallDate) {
        //                        // 新品適用しない
        //                    }
        //                    else {
        //                        if (createdDate.addMonths(isNewAddMonth) < info.rec.InstallDate) {
        //                            info.mcae.isNew__c = true;
        //                            info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
        //                        }
        //                    }
        //                }
        //                // Postなし
        //                else if (info.rec.Posting_Date__c == null && info.rec.InstallDate != null) {
        //                    if (createdDate.addMonths(isNewAddMonth) < info.rec.InstallDate) {
        //                        info.mcae.isNew__c = true;
        //                        info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
        //                    }
        //                }
        //                // (info.rec.Posting_Date__c == null && info.rec.InstallDate == null)
        //                else {
        //                    // 特殊処理なし
        //                }
        //            }
        //            /*
        //            if (createdDate.addMonths(isNewAddMonth) < info.rec.InstallDate) {
        //                info.mcae.isNew__c = true;
        //                info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
        //            }
        //            */
        //        } else if (info.isManual && !String.isBlank(info.mcae.Product_Manual__c)) {
        //            info.mcae.isNew__c = true;
        //            info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
        //        }
        //    }
        //}
        /**********************HWAG-AYDCZX 2018/5/8 DEL END***************************/
        /**********************HWAG-AYDCZX 2018/5/8 ADD START***************************/
        // 新规、再报价、草案中 维修合同价格显示
        System.debug('********changedAfterPrint:' + (changedAfterPrint ? 'true' : 'false'));
        if (this.estimate.CreatedDate == null
                || String.isBlank(ApexPages.currentPage().getParameters().get('copyid')) == false
                || this.estimate.Process_Status__c == '草案中'
                || changedAfterPrint) {
            for (AssetInfo info : checkedAssets) {
                System.debug('********contractDate changed:' + String.valueOf(contractDate));
                // 合同开始日大于创建日6个月,都不算新品
                if (contractDate >= isNewAfter) {
                    if (!info.isManual) {
                        info.mcae.isNew__c = false;
                        info.mcae.Estimate_List_Price__c = info.orgPrice;
                    } else if (info.isManual && !String.isBlank(info.mcae.Product_Manual__c)) {
                        info.mcae.isNew__c = false;
                        info.mcae.Estimate_List_Price__c = info.orgPrice;
                    }
                }
                // 合同开始日大于创建日3个月,使用合同开始日计算新品
                // 使用创建日计算新品
                else {
                    Date isNewDate = null;
                    if (contractDate >= threeMonthAfter) {
                        isNewDate = contractDate;
                    } else {
                        isNewDate = createdDate;
                    }
                    if (!info.isManual) {
                        info.mcae.isNew__c = false;
                        info.mcae.Estimate_List_Price__c = info.orgPrice;
                        // 110からの場合、Postあり、Installなし
                        if (info.rec.Posting_Date__c != null && info.rec.InstallDate == null) {
                            if (isNewDate.addMonths(isNewAddMonth) < info.rec.Posting_Date__c) {
                                info.mcae.isNew__c = true;
                                info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
                            }
                        }
                        // Installあり
                        else if (info.rec.Posting_Date__c != null && info.rec.InstallDate != null) {
                            // Postから6月経ってもInstallしてない
                            if (info.rec.Posting_Date__c.addMonths(PosttoInstall) < info.rec.InstallDate) {
                                // 新品適用しない
                            } else {
                                if (isNewDate.addMonths(isNewAddMonth) < info.rec.InstallDate) {
                                    info.mcae.isNew__c = true;
                                    info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
                                }
                            }
                        }
                        // Postなし
                        else if (info.rec.Posting_Date__c == null && info.rec.InstallDate != null) {
                            if (isNewDate.addMonths(isNewAddMonth) < info.rec.InstallDate) {
                                info.mcae.isNew__c = true;
                                info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
                            }
                        } else {
                            // 特殊処理なし
                        }
                    } else if (info.isManual && !String.isBlank(info.mcae.Product_Manual__c)) {
                        info.mcae.isNew__c = true;
                        info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
                    }
                }
            }
        }
        // 新规、草案中以外
        //else {
        //    for (AssetInfo info : checkedAssets) {
        //        if ((!info.isManual) || (info.isManual && !String.isBlank(info.mcae.Product_Manual__c)) ) {
        //            boolean isNewChange =false;
        //            // 合同开始日大于创建日6个月,都不算新品
        //            if (contractDate >= isNewAfter) {
        //            }
        //            // 合同开始日大于创建日3个月,使用合同开始日计算新品
        //            // 使用创建日计算新品
        //            else {
        //                if (contractDate.addMonths(keepPriceMonth) < systemToday) {
        //                    Date isNewDate = null;
        //                    if (contractDate >= threeMonthAfter) {
        //                        isNewDate = contractDate;
        //                    } else {
        //                        isNewDate = createdDate;
        //                    }
        //                    if (!info.isManual) {
        //                        if (info.rec.Posting_Date__c != null && info.rec.InstallDate == null) {
        //                            if (isNewDate.addMonths(isNewAddMonth) < info.rec.Posting_Date__c) {
        //                                isNewChange = true;
        //                            }
        //                        }
        //                        // Installあり
        //                        else if (info.rec.Posting_Date__c != null && info.rec.InstallDate != null) {
        //                            // Postから6月経ってもInstallしてない
        //                            if (info.rec.Posting_Date__c.addMonths(PosttoInstall) < info.rec.InstallDate) {
        //                                // 新品適用しない
        //                            }
        //                            else {
        //                                if (isNewDate.addMonths(isNewAddMonth) < info.rec.InstallDate) {
        //                                    isNewChange = true;
        //                                }
        //                            }
        //                        }
        //                        // Postなし
        //                        else if (info.rec.Posting_Date__c == null && info.rec.InstallDate != null) {
        //                            if (isNewDate.addMonths(isNewAddMonth) < info.rec.InstallDate) {
        //                                isNewChange = true;
        //                            }
        //                        }
        //                        else {
        //                            // 特殊処理なし
        //                        }
        //                    } else if (info.isManual && !String.isBlank(info.mcae.Product_Manual__c)) {
        //                        isNewChange = true;
        //                    }
        //                }
        //            }
        //            if (isNewChange != info.mcae.isNew__c) {
        //                changedSubmitPrice = true;
        //            }
        //            if (info.mcae.isNew__c) {
        //                if (info.mcae.Estimate_List_Price__c.setScale(2) != (info.orgPrice * isNewPriceAdj).setScale(2)) {
        //                    changedSubmitPrice = true;
        //                }
        //            } else {
        //                if (info.mcae.Estimate_List_Price__c.setScale(2) != info.orgPrice.setScale(2)) {
        //                    changedSubmitPrice = true;
        //                }
        //            }
        //        }
        //    }
        //}
        /**********************HWAG-AYDCZX 2018/5/8 ADD END***************************/
        return null;
    }
    /**
     * 保存メソッド
     */
    public PageReference save() {
        System.debug('save start');
        //add by rentx 2020-11-13 LJPH-BV93RZ start
        if (estimate.Contract_Range__c == null) {
            this.estimate.Contract_Range__c.addError('必须输入合同月数!');
            return null;
        }
        NextMaintenanceContract();
        //add by rentx 2020-11-13 LJPH-BV93RZ end
        // add 维修合同报价,保存时,把记录类型赋值一下 2021.6.8 fxk start
        Id Maintenance_Contract = Schema.SObjectType.Maintenance_Contract_Estimate__c.getRecordTypeInfosByDeveloperName().get('Maintenance_Quote').getRecordTypeId();
        estimate.recordtypeid = Maintenance_Contract;
        // add 维修合同报价,保存时,把记录类型赋值一下 2021.6.8 fxk end
        if (changedSubmitPrice) {
            priceChangeReset();
            return null;
        }
        if (syncEstimate(false, false)) {
            ComputeLTYRepair();
            return new PageReference('/' + this.targetEstimateId + '/e?completion=5');
        }
        return null;
    }
    /**
     * 印刷メソッド、decide前は保有設備、decide後は合同配置
     */
    public void print() {
        System.debug('print start');
        this.printAsset = false;
        this.printContract = false;
        this.printTripartite = false;
        this.printAgent = false;
        this.estimate.PrintDate__c = Date.today();
        //SelectAssetEstimateController.ComputeLTYRepair(targetEstimateId);
        if (this.estimate.Quote_Date__c == null) {
            this.estimate.Quote_Date__c = Date.today();
        }
        if (this.estimate.Print_Tripartite__c && this.estimate.Print_Agent__c) {
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, '不能同时选中三方协议和代理商合同!'));
        } else
            // 保存ボタンできない場合、印刷ボタンはフラグのみ保存
            if (this.getSaveBtnDisabled()) {
                if (savePrintFlg()) {
                    // 2018/10/26 HWAG-B5C88S 原来打印逻辑 start
                    /*if (this.estimate.Print_Contract__c && !this.estimate.Print_Tripartite__c && !this.estimate.Print_Agent__c) {
                        // 打印医院合同配置
                        this.printContract = true;
                    } else if(this.estimate.Print_Tripartite__c && !this.estimate.Print_Agent__c){
                        //打印三方合同
                        this.printTripartite = true;
                    } else if(!this.estimate.Print_Tripartite__c && this.estimate.Print_Agent__c){
                        //打印经销商合同
                        this.printAgent = true;
                    }else{
                        // 打印保有設備
                        this.printAsset = true;
                    }*/
                    // 2018/10/26 HWAG-B5C88S 原来打印逻辑 end
                    // 2018/10/26 HWAG-B5C88S start 选择三方打印三方,否则decide前打印保有设备,decide后根据报价对象打印医院或经销商合同
                    if (this.estimate.Print_Tripartite__c ) {
                        //打印三方合同
                        this.printTripartite = true;
                    } else if (!this.estimate.Estimation_Decision__c) {
                        this.printAsset = true;
                    } else if (this.estimate.Estimate_Target__c != null && this.estimate.Estimate_Target__c.equals('医院')) {
                        this.printContract = true;
                    } else if (this.estimate.Estimate_Target__c != null && this.estimate.Estimate_Target__c.equals('经销商')) {
                        this.printAgent = true;
                    }
                    // 2018/10/26 HWAG-B5C88S end
                }
            }
        // 保存ボタンできる場合、印刷ボタンは全部保存
            else {
                if (syncEstimate(false, false)) {
                    // 2018/10/26 HWAG-B5C88S 原来打印逻辑 start
                    /*
                    if (this.estimate.Print_Contract__c && !this.estimate.Print_Tripartite__c && !this.estimate.Print_Agent__c) {
                        // 打印医院合同配置
                        this.printContract = true;
                    } else if(this.estimate.Print_Tripartite__c && !this.estimate.Print_Agent__c){
                        //打印三方合同
                        this.printTripartite = true;
                    } else if(!this.estimate.Print_Tripartite__c && this.estimate.Print_Agent__c){
                        //打印经销商合同
                        this.printAgent = true;
                    }else{
                        // 打印保有設備
                        this.printAsset = true;
                    }
                    */
                    // 2018/10/26 HWAG-B5C88S 原来打印逻辑 end
                    // 2018/10/26 HWAG-B5C88S start 选择三方打印三方,否则decide前打印保有设备,decide后根据报价对象打印医院或经销商合同
                    if (this.estimate.Print_Tripartite__c ) {
                        //打印三方合同
                        this.printTripartite = true;
                    } else if (!this.estimate.Estimation_Decision__c) {
                        this.printAsset = true;
                    } else if (this.estimate.Estimate_Target__c != null && this.estimate.Estimate_Target__c.equals('医院')) {
                        this.printContract = true;
                    } else if (this.estimate.Estimate_Target__c != null && this.estimate.Estimate_Target__c.equals('经销商')) {
                        this.printAgent = true;
                    }
                    // 2018/10/26 HWAG-B5C88S end
                }
            }
        //ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, '合同'+this.printContract +'三方'+this.printTripartite+'保有'+this.printAsset+'经销商合同'+this.printAgent));
    }
    /**
     * 申請メソッド、最後必ず承認プロセスに載せる
     */
    public PageReference approvalProcess() {
        //SelectAssetEstimateController Sc2 = new SelectAssetEstimateController();
        //Sc2.targetEstimateId = this.targetEstimateId;
        //Sc2.ComputeLTYRepair();
        System.debug('approvalProcess start');
        if (changedSubmitPrice) {
            priceChangeReset();
            return null;
        }
        if (syncEstimate(true, false)) {
            Savepoint sp = Database.setSavepoint();
            // 承認プロセスに載せる
            try {
                // 已填写申请状态
                this.estimate.ApprovalProcess_Status__c = '已填写完并申请';
                ControllerUtil.updateMaintenance_Contract_Estimate(new Maintenance_Contract_Estimate__c[] {this.estimate});
                // 承認プロセス
                Approval.ProcessSubmitRequest psr = new Approval.ProcessSubmitRequest();
                psr.setObjectId(this.estimate.id);
                Approval.ProcessResult submitResult = Approval.process(psr);
                if (changedAfterPrint) {
                    return new PageReference('/' + this.targetEstimateId + '/e?completion=1');
                } else {
                    return new PageReference('/' + this.targetEstimateId + '/e?completion=2');
                }
            } catch (Exception ex) {
                System.debug('=====Exception:' + ex.getMessage());
                Database.rollback(sp);
                this.estimate.ApprovalProcess_Status__c = null;
                ApexPages.addMessages(ex);
            }
        }
        return null;
    }
    /**
     * 決定取消メソッド
     */
    public PageReference undecide() {
        System.debug('undecide start');
        this.estimate.Estimation_Decision__c = false;
        this.estimate.Print_Contract__c = false;
        // 删除报价日期
        this.estimate.Quotation_Determines_Time__c = null;
        try {
            ControllerUtil.updateMaintenance_Contract_Estimate(new Maintenance_Contract_Estimate__c[] {this.estimate});
            return new PageReference('/' + this.targetEstimateId + '/e?completion=1');
        } catch (Exception ex) {
            ApexPages.addMessages(ex);
        }
        return null;
    }
    /**
     * 決定メソッド
     */
    public PageReference decide() {
        System.debug('decide start');
        NextMaintenanceContract();
        inDicideFlag = true;
        // TODO check decide 资格
        Savepoint sp = Database.setSavepoint();
        if (syncEstimate(false, true)) {
            if (changedAfterPrint) {
                return new PageReference('/' + this.targetEstimateId + '/e?completion=1');
            } else {
                return new PageReference('/' + this.targetEstimateId + '/e?completion=3');
            }
        }
        return null;
    }
    //  public PageReference dosomething() {
    //     System.debug('dosomething start');
    //     NextMaintenanceContract();
    //     return null;
    // }
    public void NextMaintenanceContract() {
            // 20220810 询价2期开发
        List<String> asslocalList = new List<String>();
        List<String> mcalocalList = new List<String>();
        Map<Id, Maintenance_Contract__c> map3 = new Map<Id, Maintenance_Contract__c>();
        List<Maintenance_Contract_Asset__c> mcaupdateList = new List<Maintenance_Contract_Asset__c>();
        for (AssetInfo ass : this.checkedAssets) {
            if (!ass.isManual) {
                asslocalList.add(ass.rec.Id);
                map3.put(ass.rec.Id,this.contract);
            }
        }
        System.debug('asslocalList====%%%' +asslocalList);
         List<Maintenance_Contract_Asset__c> mcalist1 = [select id,Asset__c,Next_Maintenance_Contract__c,Maintenance_Contract__c
                                             from Maintenance_Contract_Asset__c
                                            where id in (select CurrentContract_F_asset__c
                                                                from asset
                                                                where id in :asslocalList and CurrentContract_F_asset__c!=null)];
            System.debug('mcalist1====%%%' +mcalist1);
            System.debug('map3====%%%' +map3);
        for (Maintenance_Contract_Asset__c mca : mcalist1) {
            Maintenance_Contract_Asset__c mca3 = new Maintenance_Contract_Asset__c();
            if (map3.containsKey(mca.Asset__c)) {
                mca3.id = mca.id;
                mca3.Next_Maintenance_Contract__c = map3.get(mca.Asset__c).id;
                System.debug('mca3.id====%%%' +mca3.id);
                if (mca3.id!=null&&!mcaupdateList.contains(mca3)) {
                    mcaupdateList.add(mca3);
                }
            }
        }
        System.debug('mcaupdateList====%%%' +mcaupdateList);
        if (mcaupdateList!=null&&!mcaupdateList.isEmpty()) {
            update mcaupdateList;
        }
        System.debug('更新完成mcaupdateList');
    }
    public PageReference decideCancle() {
        return new PageReference('/' + this.targetEstimateId + '/e?completion=4');
    }
    /**
     * Process用のユーザー情報をセット、新規見積もり時用
     */
    private void setApprovalManager() {
        User loginUser = [SELECT Id, Name, JingliApprovalManager__c, BuchangApprovalManager__c, ZongjianApprovalManager__c, TongkuoZongjian__c FROM User WHERE Id = :UserInfo.getUserId()];
        // 要注意 SaveMaintenanceByCopyController と copyのurlにも、下記の項目もクリア
        this.estimate.JingliApprovalManager__c = loginUser.JingliApprovalManager__c == null ? loginUser.Id : loginUser.JingliApprovalManager__c;
        this.estimate.BuchangApprovalManager__c = loginUser.BuchangApprovalManager__c == null ? loginUser.Id : loginUser.BuchangApprovalManager__c;
        this.estimate.ZongjianApprovalManager__c = loginUser.ZongjianApprovalManager__c == null ? loginUser.Id : loginUser.ZongjianApprovalManager__c;
        this.estimate.Service_Contract_Staff__c = this.contract.Service_Contract_Staff__c;
        this.estimate.TKZongjianApprovalManager__c = loginUser.TongkuoZongjian__c == null ? loginUser.Id : loginUser.TongkuoZongjian__c;
    }
    /**
    * 印刷フラグのみを保存
    */
    @TestVisible
    private Boolean savePrintFlg() {
        try {
            Maintenance_Contract_Estimate__c mce = new Maintenance_Contract_Estimate__c();
            mce.Id = this.targetEstimateId;
            mce.Print_ListPrice__c = this.estimate.Print_ListPrice__c;
            mce.Print_RepairPrice__c = this.estimate.Print_RepairPrice__c;
            mce.Print_SumPrice__c = this.estimate.Print_SumPrice__c;
            mce.Print_DiscountPercentage__c = this.estimate.Print_DiscountPercentage__c;
            mce.Print_DiscountPrice__c = this.estimate.Print_DiscountPrice__c;
            mce.Print_MaintePrice__c = this.estimate.Print_MaintePrice__c;
            mce.Print_Contract__c = this.estimate.Print_Contract__c;
            ControllerUtil.updateMaintenance_Contract_Estimate(new Maintenance_Contract_Estimate__c[] {mce});
            return true;
        } catch (Exception ex) {
            ApexPages.addMessages(ex);
        }
        return false;
    }
    /**
     * 画面で入力データcheck, save, 親と同期 のロジック
     */
    // TODO xudan チェック追加、clsにも合計金額を計算、clsの合計金額と画面からjsの合計金額を比較
    // 異なる場合、保存完了したらwarningを出す
    private Boolean syncEstimate(boolean isApproval, boolean isDecide) {
        System.debug('syncEstimate start');
        Boolean hasDatabaseError = false;
        Savepoint sp = Database.setSavepoint();
        try {
            if (!checkValidate()) {
                return false;
            }
            if (checkChangedAfterPrint()) {
                if (isDecide) {
                    // まず Approval
                    isApproval = true;
                    isDecide = false;
                }
            }
            //>>>
            if (isApproval || isDecide) {
                Boolean hasError = false;
                if (this.estimate.Maintenance_Price__c <= 0) {
                    this.estimate.Maintenance_Price__c.addError('合同价格必需大于0');
                    hasError = true;
                }
                /*for (AssetInfo input : this.checkedAssets) {
                    if (!input.isManual || input.isManual && !String.isBlank(input.mcae.Product_Manual__c)) {
                        if (String.isBlank(input.mcae.Check_Result__c)) {
                            input.mcae.Check_Result__c.addError('点检结果必填');
                            hasError = true;
                        }
                    }
                }*/
                if (this.estimate.Discount_Price__c > 0 && String.isBlank(this.estimate.Discount_reason__c)) {
                    this.estimate.Discount_Price__c.addError('减价申请理由必填');
                    hasError = true;
                }
                if (this.estimate.Discount_Price__c > 0 && String.isBlank(this.estimate.Improve_ConsumptionRate_Idea__c)) {
                    this.estimate.Improve_ConsumptionRate_Idea__c.addError('消费率改善方案必填');
                    hasError = true;
                }
                if (hasError) {
                    return false;
                }
            }
            if (isDecide && getDecideBtnDisabled()) {
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, '已经是Decide过的合同 或 不是批准的报价,不能Decide'));
                return false;
            }
            // 追加上期合同信息 start
            List<lastMContract> lastMContractRes = getlastMContract(this.checkedAssets);
            this.estimate.LastMContract1__c = lastMContractRes[0].contractId ;
            this.estimate.LastMContract1_NO__c = lastMContractRes[0].contractNo ;
            this.estimate.LastMContract1_ConCount__c = lastMContractRes[0].count ;
            this.estimate.LastMContract2__c = lastMContractRes[1].contractId ;
            this.estimate.LastMContract2_NO__c = lastMContractRes[1].contractNo ;
            this.estimate.LastMContract2_ConCount__c = lastMContractRes[1].count ;
            this.estimate.LastMContract3__c = lastMContractRes[2].contractId ;
            this.estimate.LastMContract3_NO__c = lastMContractRes[2].contractNo ;
            this.estimate.LastMContract3_ConCount__c = lastMContractRes[2].count ;
            this.estimate.LastMContract4__c = lastMContractRes[3].contractId ;
            this.estimate.LastMContract4_NO__c = lastMContractRes[3].contractNo ;
            this.estimate.LastMContract4_ConCount__c = lastMContractRes[3].count ;
            this.estimate.LastMContract5__c = lastMContractRes[4].contractId ;
            this.estimate.LastMContract5_NO__c = lastMContractRes[4].contractNo ;
            this.estimate.LastMContract5_ConCount__c = lastMContractRes[4].count ;
            // 追加上期合同信息 end
            // 同期処理
            // ①维修合同に既存の保有设备を削除
            // ②保存した维修合同报价の保有设备を维修合同にコピー(Asset__cが設定さているデータだけ)
            // ③他の维修合同报价の同期フラグを外す
            // ④维修合同の Estimate_Trial_Money__c、Contract_Amount__c, Service_contract_target_number__c を更新
            this.estimate.IsSyncing__c = true;
            if (isDecide) {
                // 添加决定报价日期
                this.estimate.Quotation_Determines_Time__c = date.today();
                // 报价决定
                this.estimate.Estimation_Decision__c = true;
            }
            // TODO validate
            // TODO validate check新品チェック(納品日で判断)
            // save
            // ③ start
            for (List<Maintenance_Contract_Estimate__c> otherEstimates : [select Id from Maintenance_Contract_Estimate__c where Id <> :this.estimate.Id
                    and Maintenance_Contract__c = :this.contract.Id
                                                  and IsSyncing__c = true]) {
                for (Maintenance_Contract_Estimate__c other : otherEstimates) {
                    other.IsSyncing__c = false;
                    if (isDecide) {
                        other.Estimation_Decision__c = false;
                    }
                }
                ControllerUtil.updateMaintenance_Contract_Estimate(otherEstimates);
            }
            // 合同结束预定日を算出
            Date t = this.estimate.Contract_Esti_Start_Date__c.addMonths(Integer.valueOf(this.estimate.Contract_Range__c));
            // 20151217 xudan 维修合同报价SH-RS-JS0046560-01 期间显示问题
            // うるう年特殊対応
            if (this.estimate.Contract_Esti_Start_Date__c.month() == 2 && this.estimate.Contract_Esti_Start_Date__c.day() == 29
                    && t.month() == 2) {
                t = t;
            } else {
                t = t.addDays(-1);
            }
            this.estimate.Contract_Esti_End_Date__c = t;
            // 合同开始日を结束日
            if (this.estimate.Contract_Start_Date__c == null) {
                this.estimate.Contract_Start_Date__c = this.estimate.Contract_Esti_Start_Date__c;
            }
            t = this.estimate.Contract_Start_Date__c.addMonths(Integer.valueOf(this.estimate.Contract_Range__c));
            t = t.addDays(-1);
            this.estimate.Contract_End_Date__c = t;
            Date createdDate = this.estimate.CreatedDate == null ? System.today() : this.estimate.CreatedDate.date();
            // 3ヶ月超過している場合には、Decideできない
            //if (createdDate.addMonths(3) <= System.today()) {
            //    this.estimate.addError('已超过3个月,请先更新报价。');
            //    return false;
            //}
            // 维修合同报价
            if (String.isBlank(this.targetEstimateId)) {
                this.estimate.Process_Status__c = '草案中';
                // nameに番号をセット
                List<Maintenance_Contract_Estimate__c> maxNameRecords = [select Name From Maintenance_Contract_Estimate__c Where Maintenance_Contract__c = :this.contract.Id order by Name desc limit 1];
                String oppNo;
                Integer l = 1;
                if (maxNameRecords.size() > 0) {
                    try {
                        oppNo = maxNameRecords[0].Name;
                        l = Integer.valueOf(oppNo.substring(oppNo.length() - 2)) + 1;
                    } catch (System.TypeException e) {
                        System.debug('maxNameRecords Error: Maintenance_Contract__c.id=' + maxNameRecords[0].id);
                    }
                } else {
                    System.debug('first Maintenance_Contract_Estimate__c');
                }
                oppNo = '00' + String.valueof(l);
                oppNo = oppNo.substring(oppNo.length() - 2);
                this.estimate.Name = this.contract.Management_Code__c + '-' + oppNo;
                setApprovalManager();
                System.debug('Process_Status__c=' + this.estimate.Process_Status__c);
                insert this.estimate;
                this.targetEstimateId = this.estimate.Id;
                setThisEstimate();
            } else {
                if (isApproval) {
                    setApprovalManager();
                }
                ControllerUtil.updateMaintenance_Contract_Estimate(new Maintenance_Contract_Estimate__c[] {this.estimate});
            }
            // 维修合同报价/保有设备
            // delete and insertする
            List<Maintenance_Contract_Asset_Estimate__c> insertTarget = new List<Maintenance_Contract_Asset_Estimate__c>();
            for (AssetInfo input : this.checkedAssets) {
                if (!input.isManual || input.isManual && !String.isBlank(input.mcae.Product_Manual__c)) {
                    //Maintenance_Contract_Asset_Estimate__c mcae = new Maintenance_Contract_Asset_Estimate__c();
                    input.mcae.Id = null;                               // insertのため
                    // 同じの場合設定しない
                    if (input.mcae.Maintenance_Contract_Estimate__c != this.targetEstimateId) {
                        // 親変更できない可能性があるため、設定するときエラーになるが、エラーにならないように他のロジックを工夫してください。
                        input.mcae.Maintenance_Contract_Estimate__c = this.targetEstimateId;
                    }
                    input.mcae.Maintenance_Price_Month__c = input.rec.Maintenance_Price_Month__c;
                    // 病院に所属する保有設備
                    if (!input.isManual) {
                        input.mcae.Asset__c = input.rec.Id;
                        input.mcae.Product_Manual__c = null;
                    }
                    // Manual商品
                    if (input.isManual && !String.isBlank(input.mcae.Product_Manual__c)) {
                        input.mcae.Asset__c = null;
                        //mcae.Product_Manual__c = input.mcae.Product_Manual__c;
                    }
                    //mcae.Estimate_List_Price__c = input.mcae.Estimate_List_Price__c;
                    //mcae.IsNew__c = input.mcae.isNew__c;
                    //mcae.Check_Result__c = input.mcae.Check_Result__c;
                    //mcae.Repair_Price__c = input.mcae.Repair_Price__c;
                    //mcae.Comment__c = input.mcae.Comment__c;
                    insertTarget.add(input.mcae);
                }
            }
            // 本当に保存した納入機器があれば削除
            List<Maintenance_Contract_Asset_Estimate__c> selectedAsset = [SELECT Id, Name, Maintenance_Contract_Estimate__c, Asset__c, IsNew__c FROM Maintenance_Contract_Asset_Estimate__c WHERE Maintenance_Contract_Estimate__c = :this.targetEstimateId];
            if (selectedAsset.size() > 0) {
                ControllerUtil.deleteMaintenance_Contract_Asset_Estimate(selectedAsset);
            }
            if (insertTarget.size() > 0) {
                ControllerUtil.insertMaintenance_Contract_Asset_Estimate(insertTarget);
            }
            // ① start
            for (List<Maintenance_Contract_Asset__c> oldList : [select Id from Maintenance_Contract_Asset__c
                    where Maintenance_Contract__c = :this.estimate.Maintenance_Contract__c]) {
                delete oldList;
            }
            // ② start
            {
                List<Maintenance_Contract_Asset__c> newValue = new List<Maintenance_Contract_Asset__c>();
                for (Maintenance_Contract_Asset_Estimate__c target : [select Id, Asset__c, Estimate_List_Price__c,
                        //add 点检改善:合同保有设备下的点检对象与报价保有设备下的点检对象同步 2021.6.9 fxk start
                        Check_Object__c,
                        //add 点检改善:合同保有设备下的点检对象与报价保有设备下的点检对象同步 2021.6.9 fxk end
                        IsNew__c from Maintenance_Contract_Asset_Estimate__c
                        where Maintenance_Contract_Estimate__c = :this.estimate.Id and Asset__c <> null]) {
                    Maintenance_Contract_Asset__c newVal = new Maintenance_Contract_Asset__c(
                        Maintenance_Contract__c = this.estimate.Maintenance_Contract__c,
                        Asset__c = target.Asset__c,
                        Maintenance_Contract_Asset_Estimate__c = target.Id,
                        Estimate_List_Price__c = target.Estimate_List_Price__c,
                        Estimate_IsNew__c = target.IsNew__c,
                        //add 点检改善:合同保有设备下的点检对象与报价保有设备下的点检对象同步 2021.6.9 fxk start
                        Check_Object__c = target.Check_Object__c
                                          //add 点检改善:合同保有设备下的点检对象与报价保有设备下的点检对象同步 2021.6.9 fxk end
                    );
                    newValue.add(newVal);
                }
                if (newValue.size() > 0) insert newValue;
            }
            // ④ start
            this.contract.Estimation_Id__c = this.targetEstimateId;
            this.contract.Contract_Esti_Start_Date__c = this.estimate.Contract_Esti_Start_Date__c;
            this.contract.Contract_Range__c = this.estimate.Contract_Range__c;
            this.contract.Contract_Esti_End_Date__c = this.estimate.Contract_Esti_End_Date__c;
            this.contract.Estimate_Target__c = this.estimate.Estimate_Target__c;
            this.contract.Dealer__c = this.estimate.Dealer__c;
            this.contract.NotUse_Oxygenated_Water__c = this.estimate.NotUse_Oxygenated_Water__c;
            this.contract.Estimate_Trial_Money__c = this.estimate.Estimate_Trial_Money__c;
            this.contract.Contract_Amount__c = this.estimate.Maintenance_Price__c;
            this.contract.Service_contract_target_number__c = this.estimate.Service_contract_target_number__c;
            this.contract.Contract_department_manual__c = this.estimate.Department__c;
            // 追加上期合同信息 start
            this.contract.LastMContract1__c = this.estimate.LastMContract1__c ;
            this.contract.LastMContract1_NO__c = this.estimate.LastMContract1_NO__c ;
            this.contract.LastMContract1_ConCount__c =  this.estimate.LastMContract1_ConCount__c;
            //add by rentx 2021-04-22 给合同1赋值的同时,给去年合同赋值 start
            this.contract.Last_year_service_contract__c = this.estimate.LastMContract1__c;
            //add by renrx 2021-04-22 给合同1赋值的同时, 给去年合同赋值 end
            this.contract.LastMContract2__c =  this.estimate.LastMContract2__c;
            this.contract.LastMContract2_NO__c = this.estimate.LastMContract2_NO__c ;
            this.contract.LastMContract2_ConCount__c =  this.estimate.LastMContract2_ConCount__c;
            this.contract.LastMContract3__c =  this.estimate.LastMContract3__c;
            this.contract.LastMContract3_NO__c = this.estimate.LastMContract3_NO__c ;
            this.contract.LastMContract3_ConCount__c =  this.estimate.LastMContract3_ConCount__c;
            this.contract.LastMContract4__c =  this.estimate.LastMContract4__c;
            this.contract.LastMContract4_NO__c = this.estimate.LastMContract4_NO__c ;
            this.contract.LastMContract4_ConCount__c =  this.estimate.LastMContract4_ConCount__c;
            this.contract.LastMContract5__c =  this.estimate.LastMContract5__c;
            this.contract.LastMContract5_NO__c = this.estimate.LastMContract5_NO__c ;
            this.contract.LastMContract5_ConCount__c =  this.estimate.LastMContract5_ConCount__c;
            // 追加上期合同信息 end
            system.debug('测算isDecide的结果_1::::::::' + isDecide);
            if (isDecide == true) {
                system.debug('测算isDecide的结果_2::::::::' + isDecide);
//              this.contract.Contract_Start_Date__c = this.estimate.Contract_Esti_Start_Date__c;
                this.contract.Contract_Start_Date__c = this.estimate.Contract_Start_Date__c;
                this.contract.Contract_Range__c = this.estimate.Contract_Range__c;
//              this.contract.Contract_End_Date__c = this.estimate.Contract_Esti_End_Date__c;
                this.contract.Contract_End_Date__c = this.estimate.Contract_End_Date__c;
                this.contract.JingliApprovalManager__c = this.estimate.JingliApprovalManager__c;
                this.contract.BuchangApprovalManager__c = this.estimate.BuchangApprovalManager__c;
                this.contract.ZongjianApprovalManager__c = this.estimate.ZongjianApprovalManager__c;
                this.contract.Finally_Approved_Staff__c = this.estimate.Finally_Approved_Staff__c;
                this.contract.TKZongjianApprovalManager__c = this.estimate.TKZongjianApprovalManager__c;
            }
            //添加的额外对应过程
            if (inDicideFlag == true && (this.contract.Contract_Start_Date__c == null || this.contract.Contract_End_Date__c == null)) {
                system.debug('测算inDicideFlag的结果_2::::::::' + isDecide);
//              this.contract.Contract_Start_Date__c = this.estimate.Contract_Esti_Start_Date__c;
                this.contract.Contract_Start_Date__c = this.estimate.Contract_Start_Date__c;
                this.contract.Contract_Range__c = this.estimate.Contract_Range__c;
//              this.contract.Contract_End_Date__c = this.estimate.Contract_Esti_End_Date__c;
                this.contract.Contract_End_Date__c = this.estimate.Contract_End_Date__c;
                this.contract.JingliApprovalManager__c = this.estimate.JingliApprovalManager__c;
                this.contract.BuchangApprovalManager__c = this.estimate.BuchangApprovalManager__c;
                this.contract.ZongjianApprovalManager__c = this.estimate.ZongjianApprovalManager__c;
                this.contract.Finally_Approved_Staff__c = this.estimate.Finally_Approved_Staff__c;
                this.contract.TKZongjianApprovalManager__c = this.estimate.TKZongjianApprovalManager__c;
            }
            String oldProcessStatus = this.estimate.Process_Status__c;
            try {
                ControllerUtil.updateMaintenance_Contract_Estimate(new Maintenance_Contract_Estimate__c[] {this.estimate});
                update this.contract;
            } catch (Exception e) {
                // TODO 今後複数件の場合どうする?
                this.estimate.addError(e);
                // 一部の値を戻す
                this.estimate.Process_Status__c = oldProcessStatus;
                hasDatabaseError = true;
                Database.rollback(sp);
                ApexPages.addMessages(e);
            }
            if (hasDatabaseError) {
                System.debug('syncEstimate hasDatabaseError');
                return false;
            }
            if (isApproval) {
                SelectAssetEstimateController.ComputeLTYRepair(targetEstimateId);
            }
            return true;
        } catch (DMLException ex) {
            // TODO Insert失敗のIDを消す必要?
            Database.rollback(sp);
            ApexPages.addMessages(ex);
        } catch (Exception ex) {
            Database.rollback(sp);
            ApexPages.addMessages(ex);
        }
        return false;
    }
    /**
     * 印刷後変更がある場合、true
     */
    @TestVisible
    private Boolean checkChangedAfterPrint() {
        System.debug('checkChangedAfterPrint start');
        if (changedAfterPrint) {
            this.targetEstimateId = null;
            this.estimate = this.estimate.clone();
            this.estimate.IS_Clone_After_Decide__c = true;
            this.estimate.PrintDate__c = null;
            this.estimate.Quote_Date__c = null;
            this.estimate.Print_Contract__c = false;
            this.estimate.Print_RepairPrice__c = false;
            this.estimate.Print_DiscountPercentage__c = false;
            this.estimate.Print_DiscountPrice__c = false;
            this.estimate.Print_ListPrice__c = false;
            this.estimate.Print_MaintePrice__c = false;
            this.estimate.Print_SumPrice__c = false;
            this.estimate.NotUse_Oxygenated_Water__c = false;
            this.estimate.Contract_Esti_Start_Date__c = this.estimate.Contract_Start_Date__c;
            //this.estimate.Process_Status__c = '草案中';
        }
        return changedAfterPrint;
    }
    /**
     * 行追加(10行ずつ)、前提必ず最後
     */
    public PageReference addNewRows() {
        for (Integer i = 0; i < 10; i++) {
            checkedAssets.add(new AssetInfo(checkedAssets.size()));
        }
        return null;
    }
    /** 保存返回 **/
    public PageReference saveAndCancel () {
        //add by rentx 2020-11-13 LJPH-BV93RZ start
        if (estimate.Contract_Range__c == null) {
            this.estimate.Contract_Range__c.addError('必须输入合同月数!');
            return null;
        }
        NextMaintenanceContract();
        //add by rentx 2020-11-13 LJPH-BV93RZ end
        if (syncEstimate(false, false)) {
            PageReference ret = null;
            if (this.targetMaintenanceContractId != null) {
                ret = new PageReference('/' + this.targetMaintenanceContractId);
            }
            return ret;
        }
        return null;
    }
    /**
     * キャンセルメソッド
     */
    public PageReference cancel() {
        PageReference ret = null;
        if (this.targetMaintenanceContractId != null) {
            ret = new PageReference('/' + this.targetMaintenanceContractId);
        }
        return ret;
    }
    private void setContractInfo(String id) {
        this.contract = [SELECT Id, Name, Status__c, Decided_Estimation__c, Service_Contract_Staff__c,
                         Estimate_Num__c, Management_Code__c, Hospital__c
                         FROM Maintenance_Contract__c WHERE Id = :id];
        this.targetHospitalId = this.contract.Hospital__c;
    }
    private Boolean checkValidate() {
        Boolean rtn = true;
        // 2021-02-26  mzy  LJPH-BX9CVX  add 获取合同结束日和合同月数 start
        //合同月数
        Decimal ContractRange = this.estimate.Contract_Range__c;
        //合同预定结束日期
        Date t = this.estimate.Contract_Esti_Start_Date__c.addMonths(Integer.valueOf(this.estimate.Contract_Range__c));
        if (this.estimate.Contract_Esti_Start_Date__c.month() == 2 && this.estimate.Contract_Esti_Start_Date__c.day() == 29
                && t.month() == 2) {
            t = t;
        } else {
            t = t.addDays(-1);
        }
        this.estimate.Contract_Esti_End_Date__c  = t;
        // 合同开始日を结束日
        if (this.estimate.Contract_Start_Date__c == null) {
            this.estimate.Contract_Start_Date__c = this.estimate.Contract_Esti_Start_Date__c;
        }
        t = this.estimate.Contract_Start_Date__c.addMonths(Integer.valueOf(this.estimate.Contract_Range__c));
        t = t.addDays(-1);
        this.estimate.Contract_End_Date__c = t;
        Date ContractEndDate = this.estimate.Contract_End_Date__c;
        System.debug('合同结束日期 :' + ContractEndDate);
        // 2021-02-26  mzy  LJPH-BX9CVX  add 获取合同结束日和合同月数 end
        // 部品供給停止の製品はエラー
        for (AssetInfo input : this.checkedAssets) {
            if (!input.isManual || input.isManual && !String.isBlank(input.mcae.Product_Manual__c)) {
                if (input.mcae.Estimate_List_Price__c == null || input.mcae.Estimate_List_Price__c == 0) {
                    //add by rentx 2020-11-12 LJPH-BV93RZ start
                    if (String.isNotBlank(input.proName)) {
                        // input.mcae.Product_Manual__c.addError(System.Label.Error_Message47);
                        input.mcae.Product_Manual__c.addError(System.Label.Error_Message47 + '(' + input.proName + ')');
                        //add by rentx 2020-11-12 LJPH-BV93RZ start
                    }
                    rtn = false;
                }
                if (isSaveOrApproval) {
                    if (input.rec.IF_Warranty__c == '否') {
                        input.rec.Name.addError(input.rec.Name + '(' + input.rec.SerialNumber + ') -- 不能选择不可参保设备');
                        rtn = false;
                    }
                }
                // 20200805 Gzw Bug修复
                // isSaveOrApproval = false;
            }
            // 2021-03-01 LJPH-BX9CVX mzy add 合同报价时判断零件风险
            if (input != null) {
                // System.debug('无零件风险日期 校验 end ');
                if ( input.rec != null && input.rec.NoPartRiskDate_F__c != null ) {
                    // 传入参数 : 无零件风险日期 , 可签约标识 , 合同结束日期 , 合同月数
                    String msg = SelectAssetEstimateVMController.checkAssetInfo(input.rec.NoPartRiskDate_F__c, input.rec.SignableFlag__c, ContractEndDate, ContractRange);
                    // 有错误信息则显示错误信息
                    if (msg != '') {
                        input.rec.Name.addError('[' + input.rec.Name + '] (机身编码为:' + input.rec.SerialNumber + ') ' + msg);
                        rtn = false;
                    }
                }
                /*else if(input.mcae!=null&&input.mcae.Product_Manual__c !=null&&input.NoPartRiskDate!=null ){
                    // 传入参数 : 无零件风险日期 , 可签约标识 , 合同结束日期 , 合同月数
                    String msg = SelectAssetEstimateVMController.checkAssetInfo(input.NoPartRiskDate,input.SignableFlag,ContractEstiEndDate,ContractRange);
                    // 有错误信息则显示错误信息
                    if(msg != ''){
                       input.mcae.Product_Manual__c.addError('['+input.proName2+'] '+msg);
                       rtn = false;
                    }
                }*/
            }
            // 2021-03-01 LJPH-BX9CVX mzy add 合同报价时判断零件风险
        }
        return rtn;
    }
    // 价格变更后克隆报价前重新计算价格
    @TestVisible
    private void priceChangeReset() {
        // 取得master中最新价格
        List<Id> assIds = new List<Id>();
        List<Id> pdIds = new List<Id>();
        for (AssetInfo input : this.checkedAssets) {
            if (!input.isManual) {
                assIds.add(input.rec.Id);
            }
            if (input.isManual && !String.isBlank(input.mcae.Product_Manual__c)) {
                pdIds.add(input.mcae.Product_Manual__c);
            }
        }
        Map<Id, Asset> assMap = new Map<Id, Asset>();
        Map<Id, Product2> pdMap = new Map<Id, Product2>();
        if (assIds.size() > 0) {
            assMap = new Map<Id, Asset>([select id, Maintenance_Price_Month__c from Asset where Id In: assIds]);
        }
        if (pdIds.size() > 0) {
            pdMap = new Map<Id, Product2>([select id, Maintenance_Price_Month__c from Product2 where Id In: pdIds]);
        }
        if (assMap.size() > 0 || pdMap.size() > 0) {
            for (AssetInfo info : this.checkedAssets) {
                if (!info.isManual) {
                    info.orgPrice = assMap.get(info.rec.Id).Maintenance_Price_Month__c;
                }
                if (info.isManual && !String.isBlank(info.mcae.Product_Manual__c)) {
                    info.orgPrice = pdMap.get(info.mcae.Product_Manual__c).Maintenance_Price_Month__c;
                }
            }
        }
        contractStartDateChange();
    }
    public class AssetInfo {
        public Integer lineNo {get; private set;}
        public Boolean rec_checkBox_c {get; set;}
        public Asset rec { get; set; }
        public Maintenance_Contract_Asset_Estimate__c mcae { get; set; }
        public Boolean isManual { get; set; }
        public Decimal orgPrice {get; private set;}
        // add by fxk 2021/9/9 控制点检对象是否可选 Star
        public Boolean CheckRows {get; private set;}
        // add by fxk 2021/9/9 控制点检对象是否可选 End
        //add by rentx 2020-11-12 LJPH-BV93RZ start
        public String proName;
        //add by rentx 2020-11-12 LJPH-BV93RZ start
        //add by mzy 2020-11-12 LJPH-BX9CVX start
        public Date NoPartRiskDate;
        public String proName2;
        public Boolean SignableFlag;
        //add by mzy 2020-11-12 LJPH-BX9CVX start
        public Id getRecId() {
            Id rtn = null;
            if (rec != null) {
                rtn = rec.Id;
            }
            return rtn;
        }
        public void setRecId(Id value) {
            // なにもしない
        }
        // Manual専用
        public AssetInfo(Integer lineNo) {
            this.lineNo = lineNo;
            this.rec = null;
            this.mcae = new Maintenance_Contract_Asset_Estimate__c(
                isNew__c = true,
                // add点检改善:新增一个点检对象复选框字段,默认为true 2021.6.8 fxk Star
                Check_Object__c = true
                                  // add点检改善:新增一个点检对象复选框字段,默认为true 2021.6.8 fxk end
            );
            this.isManual = true;
            this.rec_checkBox_c = false;
            this.orgPrice = 0;
            // add by fxk 2021/9/9 控制点检对象是否可选 Star
            this.CheckRows = true;
            // add by fxk 2021/9/9 控制点检对象是否可选 End
        }
        // 選択された用(非Manual)
        public AssetInfo(Integer lineNo, Asset record, Boolean isNew, Decimal listPrice, Maintenance_Contract_Asset_Estimate__c mcae) {
            this.lineNo = lineNo;
            this.rec = record;
            this.mcae = new Maintenance_Contract_Asset_Estimate__c(
//                id = mcae.Id,             // 本当にいらないの? セットしたら、新規権限がなくでも、更新できます。後藤さんに確認した、なくでもいいです。
                isNew__c = isNew,
                // add点检改善:新增一个点检对象复选框字段,默认为true 2021.6.8 fxk Star
                Check_Object__c = mcae.Check_Object__c,
                // add点检改善:新增一个点检对象复选框字段,默认为true 2021.6.8 fxk end
                Estimate_List_Price__c = listPrice,
                Check_Result__c = mcae.Check_Result__c,
                Repair_Price__c = mcae.Repair_Price__c,
                Comment__c = mcae.Comment__c
            );
            this.isManual = false;
            this.rec_checkBox_c = true;
            this.orgPrice = record.Maintenance_Price_Month__c;
            //add by rentx 2020-11-12 LJPH-BV93RZ start
            this.proName = '机身编码为:' + record.SerialNumber;
            //add by rentx 2020-11-12 LJPH-BV93RZ end
            //add by mzy 2021-02-07 start
            //this.NoPartRiskDate = mcae.Product_Manual__r.NoPartRiskDate_F__c;
            this.proName2 = mcae.Product_Manual__r.Name;
            //this.SignableFlag = mcae.Product_Manual__r.SignableFlag__c;
            //add by mzy 202-02-07  end
            // add by fxk 2021/9/9 控制点检对象是否可选 Star
            this.CheckRows = true;
            // add by fxk 2021/9/9 控制点检对象是否可选 End
        }
        // 選択された用、未納品用(Manual)
        public AssetInfo(Integer lineNo, Maintenance_Contract_Asset_Estimate__c mcae) {
            this.lineNo = lineNo;
            this.rec = null;
            this.mcae = new Maintenance_Contract_Asset_Estimate__c(
//                id = mcae.Id,             // 本当にいらないの? セットしたら、新規権限がなくでも、更新できます。後藤さんに確認した、なくでもいいです。
                isNew__c = mcae.IsNew__c,
                // add点检改善:新增一个点检对象复选框字段,默认为true 2021.6.8 fxk Star
                Check_Object__c = mcae.Check_Object__c,
                // add点检改善:新增一个点检对象复选框字段,默认为true 2021.6.8 fxk end
                Product_Manual__c = mcae.Product_Manual__c,
                Estimate_List_Price__c = mcae.Estimate_List_Price__c,
                Check_Result__c = mcae.Check_Result__c,
                Repair_Price__c = mcae.Repair_Price__c,
                Comment__c = mcae.Comment__c
            );
            this.isManual = true;
            this.rec_checkBox_c = false;
            this.orgPrice = mcae.Product_Manual__r.Maintenance_Price_Month__c;
            //add by mzy 2021-02-07 start
            //this.NoPartRiskDate = mcae.Product_Manual__r.NoPartRiskDate_F__c;
            this.proName2 = mcae.Product_Manual__r.Name;
            //this.SignableFlag = mcae.Product_Manual__r.SignableFlag__c;
            //add by mzy 2021-02-07 end
            // add by fxk 2021/9/9 控制点检对象是否可选 Star
            this.CheckRows = true;
            // add by fxk 2021/9/9 控制点检对象是否可选 End
        }
        // 選択されなかった用
        public AssetInfo(Integer lineNo, Asset record) {
            this.lineNo = lineNo;
            this.rec = record;
            this.isManual = false;
            this.rec_checkBox_c = false;
            this.orgPrice = record.Maintenance_Price_Month__c;
            // add by fxk 2021/9/9 控制点检对象是否可选 Star
            this.CheckRows = true;
            // add by fxk 2021/9/9 控制点检对象是否可选 End
        }
    }
    WebService static String pageDecide(String strId) {
        String rs = '';
        SelectAssetEstimateController saec = new SelectAssetEstimateController();
        saec.targetEstimateId = strId;
        saec.isPageAction = true;
        saec.init();
        if (saec.getDecideBtnDisabled()) {
            rs = '已经是Decide过的合同 或 不是批准的报价,不能Decide';
            return rs;
        }
        if (saec.syncEstimate(false, true)) {
            rs = '0';
        } else {
            rs = 'Decide失败';
        }
        return rs;
    }
    WebService static String pageUndecide(String strId) {
        String rs = '';
        Integer i = 0;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        SelectAssetEstimateController saec = new SelectAssetEstimateController();
        saec.targetEstimateId = strId;
        saec.isPageAction = true;
        saec.init();
        if (saec.getUnDecideBtnDisabled()) {
            rs = '不是Decide过的报价,不能Undecide';
            return rs;
        }
        if (saec.undecide() != null) {
            rs = '0';
        } else {
            rs = 'Undecide失败';
        }
        return rs;
    }
    // 计算过去五个合同信息 Gzw 20200810
    public static List<lastMContract> getlastMContract(List<AssetInfo> checkedAssets) {
        Map<String, lastMContract> lastMContractMap = new Map<String, lastMContract>();
        for (AssetInfo ai : checkedAssets) {
            lastMContract lM = new lastMContract(ai.rec.CurrentContract_F__c, ai.rec.CurrentContract_F__r.Maintenance_Contract_No_F__c, ai.rec.CurrentContract_F__r.Contract_End_Date__c, 1);
            if (String.isNotBlank(ai.rec.CurrentContract_F__c)) {
                //20201102 songxiaoqi start
                // if(ai.rec.CurrentContract_F__r.RecordType_DeveloperName__c == 'VM_Contract'){
                // }
                // 20201102  songxiaoqi end
                if (lastMContractMap.containsKey(ai.rec.CurrentContract_F__c)) {
                    lastMContractMap.get(ai.rec.CurrentContract_F__c).count ++;
                } else {
                    lastMContractMap.put(ai.rec.CurrentContract_F__c, lM);
                }
            }
        }
        List<lastMContract> listResulttemp = new List<lastMContract>();
        List<lastMContract> listResult = new List<lastMContract>();
        for ( lastMContract ll : lastMContractMap.values()) {
            listResulttemp.add(ll);
        }
        //ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, 'listResult +++++!' + listResult));
        listResulttemp.sort();
        for (Integer i = 0; i < 5 ; i++) {
            if (listResulttemp.size() >= i + 1) {
                listResult.add(listResulttemp[i]);
            } else {
                listResult.add(new lastMContract(null, null, null, null));
            }
        }
        //List<lastMContract> listResult = new List<lastMContract>();
        return listResult;
    }
    // 续签合同信息 class
    // 计算过去五个合同信息 Gzw 20200810
    public class lastMContract implements Comparable {
        public Date endDate { get; set; }
        public Integer count { get; set; }
        public String contractId { get; set; }
        public String contractNo { get; set; }
        public lastMContract(String contractId, String contractNo, Date  endDate, Integer count) {
            this.endDate = endDate;
            this.count = count;
            this.contractId = contractId;
            this.contractNo = contractNo;
        }
        // 排序
        public Integer compareTo(Object compareTo) {
            lastMContract compareToesd = (lastMContract)compareTo;
            Integer returnValue = 0;
            if (endDate  > compareToesd.endDate ) {
                returnValue = -1;
            } else if (endDate  < compareToesd.endDate ) {
                returnValue = 1;
            } else {
                if (count  > compareToesd.count ) {
                    returnValue = -1;
                } else if (count  < compareToesd.count ) {
                    returnValue = 1;
                }
            }
            return returnValue;
        }
    }
}
force-app/main/default/classes/SelectAssetEstimateController.cls-meta.xml
New file
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>51.0</apiVersion>
    <status>Active</status>
</ApexClass>
force-app/main/default/classes/SelectAssetEstimateControllerTest.cls
New file
@@ -0,0 +1,987 @@
@isTest
private class SelectAssetEstimateControllerTest {
    /*static testMethod void addRepairData(){
        Repair__c rpr = [select Id, Name, Account__c,Department_Class__c,
                         Delivered_Product__c,Hospital__c,SalesOfficeCode_selection__c,
                         SAPRepairNo__c,Status__c,Incharge_Staff__c,Repair_Detail__c
                         from Repair__c];
        Repair_Quotation__c rq = new Repair_Quotation__c();
        rq.Name                  = 'testNFM104';
        rq.Repair__c             = rpr.Id;
        rq.MessageGroupNumber__c = '1';
        insert rq;
    }*/
    static testMethod void addDatabase(){
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        insert u3;
        system.runAs(u3) {
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'耗材');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'主机');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            insert contract;
            // 维修合同报价を作成する
            Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 1',
                Contract_Esti_Start_Date__c = Date.today(),
                Contract_Range__c = 2,
                Maintenance_Contract__c = contract.Id
            );
            Maintenance_Contract_Estimate__c contactEsti2 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 2',
                Contract_Esti_Start_Date__c = Date.today().addMonths(6),
                Contract_Range__c = 3,
                Maintenance_Contract__c = contract.Id
            );
            insert new Maintenance_Contract_Estimate__c[] {contactEsti1, contactEsti2};
            // 调用方法测试, 参数
            Apexpages.currentPage().getParameters().put('mcid', contract.Id);
            Apexpages.currentPage().getParameters().put('completion', '5');
            Apexpages.currentPage().getParameters().put('id', contactEsti2.Id);
            // 创建对象,定义,调用方法测试
            SelectAssetEstimateController controller = new SelectAssetEstimateController();
            controller.init();
            controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller.estimate.Contract_Range__c = 2;
            controller.unCheckedAssetsView[0][0].rec_CheckBox_c = true;
            controller.exchangeAsset();
            controller.checkedAssets[0].mcae.Check_Result__c = 'OK';
            controller.savePrintFlg();
            controller.ShowLTYRepair();
            controller.getPageDisabled();
            controller.priceChangeReset();
        }
    }
    private static Id pricebookId = ControllerUtil.getStandardPricebook().Id;
    static Asset createAsset(String input, String accountid, String dcId, String hpId, String serialNo, String prId,String mark) {
        Asset asset = new Asset();
        asset.Name = input;
        asset.AccountId = accountid;
        asset.Department_Class__c = dcId;
        asset.Hospital__c = hpId;
        asset.SerialNumber = serialNo;
        asset.Product2Id = prId;
        asset.InstallDate = Date.today();
        //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start
        //在创建Asset的时候添加AssetMark__c 字段
        asset.AssetMark__c = mark;
        //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start
        insert asset;
        return asset;
    }
    public class AssetInfo {
        public Integer lineNo {get; private set;}
        public Boolean rec_checkBox_c {get; set;}
        public Asset rec { get; set; }
        public Maintenance_Contract_Asset_Estimate__c mcae { get; set; }
        public Boolean isManual { get; set; }
        public Decimal orgPrice {get; private set;}
        public Id getRecId() {
            Id rtn = null;
            if (rec != null) {
                rtn = rec.Id;
            }
            return rtn;
        }
        public void setRecId(Id value) {
            // なにもしない
        }
        // Manual専用
        public AssetInfo(Integer lineNo) {
            this.lineNo = lineNo;
            this.rec = null;
            this.mcae = new Maintenance_Contract_Asset_Estimate__c(
                isNew__c = true
            );
            this.isManual = true;
            this.rec_checkBox_c = false;
            this.orgPrice = 0;
        }
    }
    // 2つ見積もりがあり、親のサビコンと同期するのテスト
    static testMethod void testDecide_01() {
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        insert u3;
        system.runAs(u3) {
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'耗材');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'耗材');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'主机');
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            insert contract;
            // 维修合同报价を作成する
            Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 1',
                Contract_Esti_Start_Date__c = Date.today(),
                Contract_Range__c = 2,
                Maintenance_Contract__c = contract.Id
            );
            Maintenance_Contract_Estimate__c contactEsti2 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 2',
                Contract_Esti_Start_Date__c = Date.today().addMonths(6),
                Contract_Range__c = 3,
                Maintenance_Contract__c = contract.Id
            );
            insert new Maintenance_Contract_Estimate__c[] {contactEsti1, contactEsti2};
            System.Test.startTest();
            // 新規
            Apexpages.currentPage().getParameters().put('mcid', contract.Id);
            SelectAssetEstimateController controller = new SelectAssetEstimateController();
            controller.init();
            controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller.estimate.Contract_Range__c = 2;
            controller.unCheckedAssetsView[0][0].rec_CheckBox_c = true;
            controller.exchangeAsset();
            controller.save();
            controller.approvalProcess();
            // 维修合同报价1
            Apexpages.currentPage().getParameters().put('id', contactEsti1.Id);
            controller = new SelectAssetEstimateController();
            controller.init();
             //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start
            // System.assertEquals(5, controller.productCount2);
            //默认查询的是主机
            System.assertEquals(3, controller.productCount2);
             //JZHG-BSDUT4 ---20200825---update By rentongxiao---End
            controller.getEnablePrintContract();
            controller.getUnDecideBtnDisabled();
            controller.getDecideBtnDisabled();
            controller.getApprovalBtnDisabled();
            controller.getSaveBtnDisabled();
            controller.getPrintBtnDisabled();
            // System.Test.startTest();
            System.assertEquals(10, controller.productCount);
            controller.unCheckedAssetsView[0][0].rec_CheckBox_c = true;
            controller.exchangeAsset();
            System.assertEquals(11, controller.productCount);
            System.assertEquals(1, controller.productCount3);
            controller.productIdx = 1;
            controller.refreshProductData();
            controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller.estimate.Contract_Range__c = 2;
            controller.save();
            List<Maintenance_Contract_Asset__c> mcaList = [select Id, Asset__r.Name from Maintenance_Contract_Asset__c where Maintenance_Contract__c = :contract.Id];
            System.assertEquals(1, mcaList.size());
            System.assertEquals('asset01', mcaList[0].Asset__r.Name);
            controller.print();
            // 维修合同报价2の決定ロジック
            // Apexpages.currentPage().getParameters().put('id', contactEsti2.Id);
            // SelectAssetEstimateController controller2 = new SelectAssetEstimateController();
            // controller2.init();
            // controller2.unCheckedAssetsView[0][1].rec_CheckBox_c = true;
            // controller2.unCheckedAssetsView[0][2].rec_CheckBox_c = true;
            // System.assertEquals(10, controller2.productCount);
            // controller2.exchangeAsset();
            // System.assertEquals(12, controller2.productCount);
            // System.assertEquals(2, controller2.productCount3);
            // contactEsti1 = [select IsSyncing__c from Maintenance_Contract_Estimate__c where Id = :contactEsti1.Id];
            // System.assertEquals(true, contactEsti1.IsSyncing__c);
            // controller2.checkedAssets[0].mcae.Check_Result__c = 'test0';
            // controller2.checkedAssets[1].mcae.Check_Result__c = 'test1';
            // controller2.estimate.Contract_Esti_Start_Date__c = Date.today();
            // controller2.estimate.Contract_Range__c = 2;
            // controller2.estimate.Process_Status__c = '批准';
            // controller2.decide();
            // contactEsti1 = [select IsSyncing__c from Maintenance_Contract_Estimate__c where Id = :contactEsti1.Id];
            // System.assertEquals(false, contactEsti1.IsSyncing__c);
            // contactEsti2 = [select IsSyncing__c from Maintenance_Contract_Estimate__c where Id = :contactEsti2.Id];
            // System.assertEquals(true, contactEsti2.IsSyncing__c);
            // controller2.undecide();
            //mcaList = [select Id, Asset__r.Name from Maintenance_Contract_Asset__c where Maintenance_Contract__c = :contract.Id order by Asset__r.Name];
            //System.assertEquals(2, mcaList.size());
            //System.assertEquals('asset02', mcaList[0].Asset__r.Name);
            //System.assertEquals('asset04', mcaList[1].Asset__r.Name);
            System.Test.stopTest();
        }
    }
    static testMethod void testcopyid_01() {
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        insert u3;
        system.runAs(u3) {
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'耗材');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'耗材');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'主机');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            insert contract;
            // 维修合同报价を作成する
            Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 1',
                Maintenance_Contract__c = contract.Id
            );
            insert contactEsti1;
            Apexpages.currentPage().getParameters().put('copyid', contactEsti1.Id);
            SelectAssetEstimateController controller = new SelectAssetEstimateController();
            controller.init();
            controller.lastFriYearsPriceSum  =3322;
            controller.lastSecYearsPriceSum = 1222;
            controller.alertString ='';
            controller.alertString2 ='';
            controller.alertString3 ='';
            controller.getSaveBtnDisabled();
            controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller.estimate.Contract_Range__c = 2;
            controller.save();
            SelectAssetEstimateController.pageDecide(contactEsti1.Id);
            SelectAssetEstimateController.pageUndecide(contactEsti1.Id);
            controller.ComputeLTYRepair();
        }
    }
    static testMethod void testInit_01() {
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        insert u3;
        system.runAs(u3) {
            try {
                SelectAssetEstimateController controller001 = new SelectAssetEstimateController();
                controller001.init();
            } catch (Exception e) {
            }
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'耗材');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'主机');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'耗材');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'主机');
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            insert contract;
            // 维修合同/保有设备を作成する
            Maintenance_Contract_Asset__c mca1 = new Maintenance_Contract_Asset__c();
            mca1.Asset__c = asset01.Id;
            mca1.Estimate_List_Price__c = 100;
            mca1.Maintenance_Contract__c = contract.Id;
            Maintenance_Contract_Asset__c mca2 = new Maintenance_Contract_Asset__c();
            mca2.Asset__c = asset01.Id;
            mca2.Estimate_List_Price__c = 100;
            mca2.Maintenance_Contract__c = contract.Id;
            insert new Maintenance_Contract_Asset__c[] {mca1, mca2};
            Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 1',
                Maintenance_Contract__c = contract.Id,
                Contract_Esti_Start_Date__c = Date.today().addDays(1)
            );
            insert contactEsti1;
            Maintenance_Contract_Asset_Estimate__c mcae1 = new Maintenance_Contract_Asset_Estimate__c();
            mcae1.Asset__c = asset01.Id;
            mcae1.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae1.Estimate_List_Price__c = 1000;
            mcae1.Check_Result__c = 'OK';
            Maintenance_Contract_Asset_Estimate__c mcae2 = new Maintenance_Contract_Asset_Estimate__c();
            mcae2.Asset__c = asset01.Id;
            mcae2.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae2.Estimate_List_Price__c = 1000;
            mcae2.Check_Result__c = 'OK';
            insert new Maintenance_Contract_Asset_Estimate__c[] {mcae1, mcae2};
            Apexpages.currentPage().getParameters().put('mcid', contract.Id);
            Apexpages.currentPage().getParameters().put('completion', '1');
            SelectAssetEstimateController controller = new SelectAssetEstimateController();
            controller.init();
            controller.firstPage();
            controller.currPage = 3;
            controller.previousPage();
            controller.endPage();
            controller.currPage = 200;
            controller.nextPage();
            controller.recordNumChange();
            controller.getSaveBtnDisabled();
            //controller.ComputeLTYRepair();
            controller.cancel();
            controller.saveAndCancel();
        }
    }
    static testMethod void testInit_02() {
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        insert u3;
        system.runAs(u3) {
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,' ');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'主机');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'主机');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            insert contract;
            // 维修合同报价を作成する
            Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 1',
                Maintenance_Contract__c = contract.Id,
                Contract_Esti_Start_Date__c = Date.today().addDays(1)
            );
            insert contactEsti1;
            Maintenance_Contract_Asset_Estimate__c mcae1 = new Maintenance_Contract_Asset_Estimate__c();
            mcae1.Asset__c = asset01.Id;
            mcae1.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae1.Estimate_List_Price__c = 1000;
            mcae1.Check_Result__c = 'OK';
            Maintenance_Contract_Asset_Estimate__c mcae2 = new Maintenance_Contract_Asset_Estimate__c();
            mcae2.Asset__c = asset01.Id;
            mcae2.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae2.Estimate_List_Price__c = 1000;
            mcae2.Check_Result__c = 'OK';
            insert new Maintenance_Contract_Asset_Estimate__c[] {mcae1, mcae2};
            Apexpages.currentPage().getParameters().put('copyid', contactEsti1.Id);
            Apexpages.currentPage().getParameters().put('completion', '2');
            SelectAssetEstimateController controller = new SelectAssetEstimateController();
            controller.init();
            controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller.estimate.Contract_Range__c = 2;
            controller.save();
            Test.startTest();
            controller.ComputeLTYRepair();
            controller.saveAndCancel();
            SelectAssetEstimateController.ComputeLTYRepair(controller.targetEstimateId);
            Test.stopTest();
        }
    }
    static testMethod void testInit_03() {
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        insert u3;
        system.runAs(u3) {
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'耗材');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'耗材');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            insert contract;
            // 维修合同报价を作成する
            Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 1',
                Maintenance_Contract__c = contract.Id
            );
            insert contactEsti1;
            Maintenance_Contract_Asset_Estimate__c mcae1 = new Maintenance_Contract_Asset_Estimate__c();
            mcae1.Asset__c = asset01.Id;
            mcae1.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae1.Estimate_List_Price__c = 1000;
            mcae1.Check_Result__c = 'OK';
            Maintenance_Contract_Asset_Estimate__c mcae2 = new Maintenance_Contract_Asset_Estimate__c();
            mcae2.Product_Manual__c = productA.Id;
            mcae2.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae2.Estimate_List_Price__c = 1000;
            mcae2.Check_Result__c = 'OK';
            insert new Maintenance_Contract_Asset_Estimate__c[] {mcae1, mcae2};
            Apexpages.currentPage().getParameters().put('copyid', contactEsti1.Id);
            Apexpages.currentPage().getParameters().put('completion', '3');
            SelectAssetEstimateController controller = new SelectAssetEstimateController();
            controller.init();
            controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller.estimate.Contract_Range__c = 2;
            controller.save();
        }
    }
    static testMethod void testApprovalProcess_01() {
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        insert u3;
        system.runAs(u3) {
        ControllerUtil.EscapeNFM001Trigger = true;
        // 病院を作る
        Account hospital = new Account();
        hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
        hospital.Name = 'test hospital';
        insert hospital;
        // 戦略科室を得る
        List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
        // 診療科を作る
        Account dep = new Account();
        dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
        dep.Name = 'test dep';
        dep.ParentId = strategicDep[0].Id;
        dep.Department_Class__c = strategicDep[0].Id;
        dep.Hospital__c = hospital.Id;
        insert dep;
        // 製品を作る
        Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false);
        insert productA;
        // 価格表エントリを作成する
        PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
        entry.UnitPrice = 0;
        entry.IsActive = true;
        entry.UseStandardPrice = false;
        entry.CurrencyIsoCode = 'CNY';
        entry.Product2Id = productA.Id;
        insert entry;
        // 納入機器を作成する
        Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
        Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
        Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'耗材');
        Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'主机');
        Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
        // 维修合同を作成する
        Maintenance_Contract__c contract = new Maintenance_Contract__c();
        contract.Name = 'tect contract';
        contract.Hospital__c = hospital.Id;
        contract.Department_Class__c = strategicDep[0].Id;
        contract.Department__c = dep.Id;
        contract.Service_Contract_Staff__c = u3.Id;
        contract.Payment_Plan_Sum_First__c = 1;
        insert contract;
        // 维修合同报价を作成する
        Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
            Name = 'contract estimate 1',
            Contract_Esti_Start_Date__c = Date.today(),
            Contract_Range__c = 2,
            Maintenance_Contract__c = contract.Id
        );
        Maintenance_Contract_Estimate__c contactEsti2 = new Maintenance_Contract_Estimate__c(
            Name = 'contract estimate 2',
            Contract_Esti_Start_Date__c = Date.today().addMonths(6),
            Contract_Range__c = 3,
            Maintenance_Contract__c = contract.Id
        );
        insert new Maintenance_Contract_Estimate__c[] {contactEsti1, contactEsti2};
        // 新規
        Apexpages.currentPage().getParameters().put('mcid', contract.Id);
        SelectAssetEstimateController controller = new SelectAssetEstimateController();
        controller.init();
        controller.estimate.Contract_Esti_Start_Date__c = Date.today();
        controller.estimate.Contract_Range__c = 2;
        controller.unCheckedAssetsView[0][0].rec_CheckBox_c = true;
        controller.exchangeAsset();
        controller.checkedAssets[0].mcae.Check_Result__c = 'OK';
        controller.approvalProcess();
        // 提交待审批时,更新已填写申请状态
        List<Maintenance_Contract_Estimate__c> mcenew = [select id,ApprovalProcess_Status__c from Maintenance_Contract_Estimate__c where id = :controller.targetEstimateId];
        System.assertEquals('已填写完并申请', mcenew[0].ApprovalProcess_Status__c);
        }
    }
    static testMethod void EditUnitTest() {
        //Test.startTest();
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        insert u3;
        system.runAs(u3) {
            ControllerUtil.EscapeNFM001Trigger = true;
            //SelectAssetEstimateController controller = new SelectAssetEstimateController();
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false);
            insert productA;
            //// 価格表エントリを作成する
            //PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            //entry.UnitPrice = 0;
            //entry.IsActive = true;
            //entry.UseStandardPrice = false;
            //entry.CurrencyIsoCode = 'CNY';
            //entry.Product2Id = productA.Id;
            //insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'耗材');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'主机');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            contract.Payment_Plan_Sum_First__c = 1;
            insert contract;
            // 维修合同报价を作成する
            Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 1',
                Contract_Esti_Start_Date__c = Date.today(),
                Contract_Range__c = 2,
                Maintenance_Contract__c = contract.Id
            );
            Maintenance_Contract_Estimate__c contactEsti2 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 2',
                Contract_Esti_Start_Date__c = Date.today().addMonths(6),
                Contract_Range__c = 3,
                Maintenance_Contract__c = contract.Id
            );
            insert new Maintenance_Contract_Estimate__c[] {contactEsti1, contactEsti2};
            System.Test.startTest();
            Apexpages.currentPage().getParameters().put('id', contactEsti1.Id);
            SelectAssetEstimateController controller = new SelectAssetEstimateController();
            controller.init();
            controller.text1 = 'S:Name';
            controller.cond1 = 'equals';
            controller.val1 = 'asset01,asset02';
            controller.searchBtn();
            controller.cond1 = 'equals';
            controller.val1 = 'asset02';
            controller.searchBtn();
            controller.cond1 = 'contains';
            controller.val1 = ' asset02';
            controller.searchBtn();
            controller.cond1 = 'notequals';
            controller.searchBtn();
            controller.cond1 = 'starts with';
            controller.searchBtn();
            Test.stopTest();
        }
    }
}
force-app/main/default/classes/SelectAssetEstimateControllerTest.cls-meta.xml
New file
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>28.0</apiVersion>
    <status>Active</status>
</ApexClass>
force-app/main/default/classes/SelectAssetEstimateURFController.cls
New file
Diff too large
force-app/main/default/classes/SelectAssetEstimateURFController.cls-meta.xml
New file
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>44.0</apiVersion>
    <status>Active</status>
</ApexClass>
force-app/main/default/classes/SelectAssetEstimateURFControllerTest.cls
New file
@@ -0,0 +1,1594 @@
@isTest
private class SelectAssetEstimateURFControllerTest {
    private static Id pricebookId = ControllerUtil.getStandardPricebook().Id;
        static Asset createAsset(String input, String accountid, String dcId, String hpId, String serialNo, String prId, String mark ) {
        Asset asset = new Asset();
        asset.Name = input;
        asset.AccountId = accountid;
        asset.Department_Class__c = dcId;
        asset.Hospital__c = hpId;
        asset.SerialNumber = serialNo;
        asset.Product2Id = prId;
        asset.InstallDate = Date.today();
        //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start
        //在接收参数的时候新增了String类型的Mark字段,以及在调用该方法时传递了String类型的Mark字段
        asset.AssetMark__c = mark;
        //JZHG-BSDUT4 ---20200825---update By rentongxiao---End
        insert asset;
        return asset;
    }
    public class AssetInfo {
        public Integer lineNo {get; private set;}
        public Boolean rec_checkBox_c {get; set;}
        public Asset rec { get; set; }
        public Maintenance_Contract_Asset_Estimate__c mcae { get; set; }
        public Boolean isManual { get; set; }
        public Decimal orgPrice {get; private set;}
        public Id getRecId() {
            Id rtn = null;
            if (rec != null) {
                rtn = rec.Id;
            }
            return rtn;
        }
        public void setRecId(Id value) {
            // なにもしない
        }
        // Manual専用
        public AssetInfo(Integer lineNo) {
            this.lineNo = lineNo;
            this.rec = null;
            this.mcae = new Maintenance_Contract_Asset_Estimate__c(
                isNew__c = true
            );
            this.isManual = true;
            this.rec_checkBox_c = false;
            this.orgPrice = 0;
        }
    }
    // 2つ見積もりがあり、親のサビコンと同期するのテスト
    static testMethod void testDecide_01() {
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        insert u3;
        system.runAs(u3) {
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            StaticParameter.EscapeSyncProduct2Trigger = true;
            StaticParameter.EscapeAccountTrigger = true;
            StaticParameter.EscapeMaintenanceContractAfterUpdateTrigger = true;
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            ProductURF__c purf = new ProductURF__c(UFR_MaxRepairCount__c = 2,URFLimitSerial__c = 'URF-P',Maintenance_Price_Year_URF__c = 1200);
            insert purf;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false,ProductURF__c = purf.Id);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'耗材');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'耗材');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Not_Upper_limit_reason__c = 'tect contract';
            contract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            contract.URF_Contract__c = true;
            contract.agree_Upper_limit__c = true;
            insert contract;
            Maintenance_Contract_Asset__c mca1 = new Maintenance_Contract_Asset__c();
            mca1.Asset__c = asset01.Id;
            mca1.Estimate_List_Price__c = 100;
            mca1.Maintenance_Contract__c = contract.Id;
            insert new Maintenance_Contract_Asset__c[] {mca1};
            // 维修合同报价を作成する
            Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 1',
                RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
                Contract_Esti_Start_Date__c = Date.today(),
                Contract_Range__c = 2,
                Maintenance_Contract__c = contract.Id,
                Request_quotation_Amount__c = 1,
                EndUserType__c = '既有用户',
                mainTalksTime__c = 1,
                talksStartDate__c = Date.today(),
                Discount_reason__c = 'test',
                Improve_ConsumptionRate_Idea__c = 'test'
            );
            insert contactEsti1;
            System.Test.startTest();
            // 新規
            Apexpages.currentPage().getParameters().put('mcid', contract.Id);
            SelectAssetEstimateURFController controller = new SelectAssetEstimateURFController();
            controller.init();
            controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller.estimate.Contract_Range__c = 2;
            controller.unCheckedAssetsView[0][0].rec_CheckBox_c = true;
            controller.exchangeAsset();
            controller.save();
            controller.approvalProcess();
            // 维修合同报价1
            Apexpages.currentPage().getParameters().put('id', contactEsti1.Id);
            controller = new SelectAssetEstimateURFController();
            controller.init();
             //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start
            // System.assertEquals(5, controller.productCount2);
            //因为默认查询的保有设备类型为主机
            System.assertEquals(2,controller.productCount2);
             //JZHG-BSDUT4 ---20200825---update By rentongxiao---End
            controller.getEnablePrintContract();
            controller.getUnDecideBtnDisabled();
            controller.getDecideBtnDisabled();
            controller.getApprovalBtnDisabled();
            controller.getSaveBtnDisabled();
            controller.getPrintBtnDisabled();
            controller.getPageDisabled();
            controller.savePrintFlg();
            System.assertEquals(10, controller.productCount);
            controller.unCheckedAssetsView[0][0].rec_CheckBox_c = true;
            controller.exchangeAsset();
            System.assertEquals(11, controller.productCount);
            System.assertEquals(1, controller.productCount3);
            controller.productIdx = 1;
            controller.refreshProductData();
            controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller.estimate.Contract_Range__c = 2;
            controller.save();
            List<Maintenance_Contract_Asset__c> mcaList = [select Id, Asset__r.Name from Maintenance_Contract_Asset__c where Maintenance_Contract__c = :contract.Id];
            System.assertEquals(1, mcaList.size());
            System.assertEquals('asset01', mcaList[0].Asset__r.Name);
            controller.print();
            System.Test.stopTest();
        }
    }
    // 2つ見積もりがあり、親のサビコンと同期するのテスト
    static testMethod void testDecide_02() {
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        insert u3;
        system.runAs(u3) {
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            StaticParameter.EscapeSyncProduct2Trigger = true;
            StaticParameter.EscapeAccountTrigger = true;
            StaticParameter.EscapeMaintenanceContractAfterUpdateTrigger = true;
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            ProductURF__c purf = new ProductURF__c(UFR_MaxRepairCount__c = 2,URFLimitSerial__c = 'URF-P',Maintenance_Price_Year_URF__c = 1200);
            insert purf;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false,ProductURF__c = purf.Id);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'主机');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'主机');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'主机');
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Not_Upper_limit_reason__c = 'tect contract';
            contract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            contract.URF_Contract__c = true;
            contract.agree_Upper_limit__c = true;
            insert contract;
            // // 维修合同报价を作成する
            // Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
            //     Name = 'contract estimate 1',
            //     RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
            //     Contract_Esti_Start_Date__c = Date.today(),
            //     Contract_Range__c = 2,
            //     Maintenance_Contract__c = contract.Id
            // );
            Maintenance_Contract_Estimate__c contactEsti2 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 2',
                RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
                Contract_Esti_Start_Date__c = Date.today().addMonths(6),
                Contract_Range__c = 3,
                Maintenance_Contract__c = contract.Id,
                Request_quotation_Amount__c = 1,
                EndUserType__c = '既有用户',
                mainTalksTime__c = 1,
                talksStartDate__c = Date.today(),
                Discount_reason__c = 'test',
                Improve_ConsumptionRate_Idea__c = 'test'
            );
            insert  contactEsti2;
            System.Test.startTest();
            // 新規
            Apexpages.currentPage().getParameters().put('mcid', contract.Id);
            SelectAssetEstimateURFController controller = new SelectAssetEstimateURFController();
            controller.init();
            controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller.estimate.Contract_Range__c = 2;
            controller.unCheckedAssetsView[0][0].rec_CheckBox_c = true;
            controller.exchangeAsset();
            controller.save();
            controller.approvalProcess();
            // // 维修合同报价1
            // Apexpages.currentPage().getParameters().put('id', contactEsti1.Id);
            // controller = new SelectAssetEstimateURFController();
            // controller.init();
            // System.assertEquals(5, controller.productCount2);
            // controller.getEnablePrintContract();
            // controller.getUnDecideBtnDisabled();
            // controller.getDecideBtnDisabled();
            // controller.getApprovalBtnDisabled();
            // controller.getSaveBtnDisabled();
            // controller.getPrintBtnDisabled();
            // controller.getcontactBtnDisabled();
            // controller.getPageDisabled();
            // controller.savePrintFlg();
            // System.assertEquals(10, controller.productCount);
            // controller.unCheckedAssetsView[0][0].rec_CheckBox_c = true;
            // controller.exchangeAsset();
            // System.assertEquals(11, controller.productCount);
            // System.assertEquals(1, controller.productCount3);
            // controller.productIdx = 1;
            // controller.refreshProductData();
            // controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            // controller.estimate.Contract_Range__c = 2;
            // controller.save();
            // List<Maintenance_Contract_Asset__c> mcaList = [select Id, Asset__r.Name from Maintenance_Contract_Asset__c where Maintenance_Contract__c = :contract.Id];
            // System.assertEquals(1, mcaList.size());
            // System.assertEquals('asset01', mcaList[0].Asset__r.Name);
            // controller.print();
            // 维修合同报价2の決定ロジック
            Apexpages.currentPage().getParameters().put('id', contactEsti2.Id);
            SelectAssetEstimateURFController controller2 = new SelectAssetEstimateURFController();
            controller2.init();
            controller2.unCheckedAssetsView[0][1].rec_CheckBox_c = true;
            controller2.unCheckedAssetsView[0][3].rec_CheckBox_c = true;
            System.assertEquals(10, controller2.productCount);
            controller2.exchangeAsset();
            System.assertEquals(12, controller2.productCount);
            System.assertEquals(2, controller2.productCount3);
            // contactEsti1 = [select IsSyncing__c from Maintenance_Contract_Estimate__c where Id = :contactEsti1.Id];
            // System.assertEquals(true, contactEsti1.IsSyncing__c);
            controller2.checkedAssets[0].mcae.Check_Result__c = 'test0';
            controller2.checkedAssets[1].mcae.Check_Result__c = 'test1';
            controller2.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller2.estimate.Contract_Range__c = 2;
            controller2.estimate.Process_Status__c = '批准';
            controller2.decide();
            // contactEsti1 = [select IsSyncing__c from Maintenance_Contract_Estimate__c where Id = :contactEsti1.Id];
            // System.assertEquals(false, contactEsti1.IsSyncing__c);
            // contactEsti2 = [select IsSyncing__c from Maintenance_Contract_Estimate__c where Id = :contactEsti2.Id];
            // System.assertEquals(true, contactEsti2.IsSyncing__c);
            controller2.undecide();
            //mcaList = [select Id, Asset__r.Name from Maintenance_Contract_Asset__c where Maintenance_Contract__c = :contract.Id order by Asset__r.Name];
            //System.assertEquals(2, mcaList.size());
            //System.assertEquals('asset02', mcaList[0].Asset__r.Name);
            //System.assertEquals('asset04', mcaList[1].Asset__r.Name);
            System.Test.stopTest();
        }
    }
    static testMethod void testcopyid_01() {
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        insert u3;
        system.runAs(u3) {
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
               ProductURF__c purf = new ProductURF__c(UFR_MaxRepairCount__c = 2,URFLimitSerial__c = 'URF-P',Maintenance_Price_Year_URF__c = 1200);
            insert purf;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false,ProductURF__c = purf.Id);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'主机');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'耗材');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Not_Upper_limit_reason__c = 'tect contract';
            contract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            contract.URF_Contract__c = true;
            contract.agree_Upper_limit__c = true;
            insert contract;
            // 维修合同报价を作成する
            Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
                RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
                Name = 'contract estimate 1',
                Maintenance_Contract__c = contract.Id,
                Request_quotation_Amount__c = 1,
                EndUserType__c = '既有用户',
                mainTalksTime__c = 1,
                talksStartDate__c = Date.today(),
                Discount_reason__c = 'test',
                Improve_ConsumptionRate_Idea__c = 'test'
            );
            insert contactEsti1;
            Apexpages.currentPage().getParameters().put('copyid', contactEsti1.Id);
            SelectAssetEstimateURFController controller = new SelectAssetEstimateURFController();
            controller.init();
            controller.lastFriYearsPriceSum  =3322;
            controller.lastSecYearsPriceSum = 1222;
            controller.alertString ='';
            controller.alertString2 ='';
            controller.alertString3 ='';
            controller.getSaveBtnDisabled();
            controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller.estimate.Contract_Range__c = 2;
            controller.save();
            SelectAssetEstimateURFController.pageDecide(contactEsti1.Id);
            SelectAssetEstimateURFController.pageUndecide(contactEsti1.Id);
//            controller.ComputeLTYRepair();
            controller.ShowLTYRepair();
        }
    }
    static testMethod void testInit_01() {
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        insert u3;
        system.runAs(u3) {
            try {
                SelectAssetEstimateURFController controller001 = new SelectAssetEstimateURFController();
                controller001.init();
            } catch (Exception e) {
            }
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            hospital.Is_Active__c = '有效';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            ProductURF__c purf = new ProductURF__c(UFR_MaxRepairCount__c = 2,URFLimitSerial__c = 'URF-P',Maintenance_Price_Year_URF__c = 1200);
            insert purf;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false,ProductURF__c = purf.Id);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'耗材');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'耗材');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'主机');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Not_Upper_limit_reason__c = 'tect contract';
            contract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            contract.URF_Contract__c = true;
            contract.agree_Upper_limit__c = true;
            insert contract;
            // 维修合同/保有设备を作成する
            Maintenance_Contract_Asset__c mca1 = new Maintenance_Contract_Asset__c();
            mca1.Asset__c = asset01.Id;
            mca1.Estimate_List_Price__c = 100;
            mca1.Maintenance_Contract__c = contract.Id;
            Maintenance_Contract_Asset__c mca2 = new Maintenance_Contract_Asset__c();
            mca2.Asset__c = asset01.Id;
            mca2.Estimate_List_Price__c = 100;
            mca2.Maintenance_Contract__c = contract.Id;
            insert new Maintenance_Contract_Asset__c[] {mca1, mca2};
            Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
                RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
                Name = 'contract estimate 1',
                Maintenance_Contract__c = contract.Id,
                Contract_Esti_Start_Date__c = Date.today().addDays(1),
                Request_quotation_Amount__c = 1,
                EndUserType__c = '既有用户',
                mainTalksTime__c = 1,
                talksStartDate__c = Date.today(),
                Discount_reason__c = 'test',
                Improve_ConsumptionRate_Idea__c = 'test'
            );
            insert contactEsti1;
            Maintenance_Contract_Asset_Estimate__c mcae1 = new Maintenance_Contract_Asset_Estimate__c();
            mcae1.Asset__c = asset01.Id;
            mcae1.Adjustment_Upper_price__c = 1;
            mcae1.Adjustment_Lower_price__c = 1;
            mcae1.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae1.Estimate_List_Price__c = 1000;
            mcae1.Check_Result__c = 'OK';
            Maintenance_Contract_Asset_Estimate__c mcae2 = new Maintenance_Contract_Asset_Estimate__c();
            mcae2.Asset__c = asset01.Id;
            mcae2.Adjustment_Upper_price__c = 1;
            mcae2.Adjustment_Lower_price__c = 1;
            mcae2.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae2.Estimate_List_Price__c = 1000;
            mcae2.Check_Result__c = 'OK';
            insert new Maintenance_Contract_Asset_Estimate__c[] {mcae1, mcae2};
            Apexpages.currentPage().getParameters().put('mcid', contract.Id);
            Apexpages.currentPage().getParameters().put('completion', '1');
            SelectAssetEstimateURFController controller = new SelectAssetEstimateURFController();
            controller.init();
            controller.firstPage();
            controller.currPage = 3;
            controller.previousPage();
            controller.endPage();
            controller.currPage = 200;
            controller.nextPage();
            controller.recordNumChange();
            controller.getSaveBtnDisabled();
            //controller.ComputeLTYRepair();
            controller.cancel();
            controller.saveAndCancel();
        }
    }
    static testMethod void testInit_02() {
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        insert u3;
        system.runAs(u3) {
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            ProductURF__c purf = new ProductURF__c(UFR_MaxRepairCount__c = 2,URFLimitSerial__c = 'URF-P',Maintenance_Price_Year_URF__c = 1200);
            insert purf;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false,ProductURF__c = purf.Id);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'主机');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'耗材');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
            // 修理を作成する01
            Repair__c repair01 = new Repair__c();
            repair01.Account__c = dep.Id;
            repair01.Department_Class__c = strategicDep[0].Id;
            repair01.Hospital__c = hospital.Id;
            repair01.Delivered_Product__c = asset01.Id;
            repair01.SERVICE_CONTRACT_JUDEGE_DAY__C = Date.today().addDays(0);  // 维修合同判断日がサービス契約の中間辺りの日付
            repair01.FSE_Work_Location__c = '上海';
            repair01.Agreed_Date__c = Date.today().addDays(-1);
            insert repair01;
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Not_Upper_limit_reason__c = 'tect contract';
            contract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            contract.URF_Contract__c = true;
            contract.agree_Upper_limit__c = true;
            insert contract;
            // 维修合同报价を作成する
            Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 1',
                RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
                Maintenance_Contract__c = contract.Id,
                Contract_Esti_Start_Date__c = Date.today().addDays(1),
                Request_quotation_Amount__c = 1,
                EndUserType__c = '既有用户',
                mainTalksTime__c = 1,
                talksStartDate__c = Date.today(),
                Discount_reason__c = 'test',
                Improve_ConsumptionRate_Idea__c = 'test'
            );
            insert contactEsti1;
            Maintenance_Contract_Asset_Estimate__c mcae1 = new Maintenance_Contract_Asset_Estimate__c();
            mcae1.Asset__c = asset01.Id;
            mcae1.Adjustment_Upper_price__c = 1;
            mcae1.Adjustment_Lower_price__c = 1;
            mcae1.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae1.Estimate_List_Price__c = 1000;
            mcae1.Check_Result__c = 'OK';
            Maintenance_Contract_Asset_Estimate__c mcae2 = new Maintenance_Contract_Asset_Estimate__c();
            mcae2.Asset__c = asset01.Id;
            mcae2.Adjustment_Upper_price__c = 1;
            mcae2.Adjustment_Lower_price__c = 1;
            mcae2.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae2.Estimate_List_Price__c = 1000;
            mcae2.Check_Result__c = 'OK';
            insert new Maintenance_Contract_Asset_Estimate__c[] {mcae1, mcae2};
            Apexpages.currentPage().getParameters().put('id', contactEsti1.Id);
            SelectAssetEstimateURFController controller = new SelectAssetEstimateURFController();
            controller.init();
            controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller.estimate.Contract_Range__c = 2;
            controller.save();
            Test.startTest();
            controller.ComputeLTYRepair();
            controller.saveAndCancel();
            SelectAssetEstimateURFController.ComputeLTYRepair(controller.targetEstimateId);
            Test.stopTest();
        }
    }
    static testMethod void testInit_03() {
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        insert u3;
        system.runAs(u3) {
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            ProductURF__c purf = new ProductURF__c(UFR_MaxRepairCount__c = 2,URFLimitSerial__c = 'URF-P',Maintenance_Price_Year_URF__c = 1200);
            insert purf;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false,ProductURF__c = purf.Id);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'主机');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'耗材');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Not_Upper_limit_reason__c = 'tect contract';
            contract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            contract.URF_Contract__c = true;
            contract.agree_Upper_limit__c = true;
            insert contract;
            // 维修合同报价を作成する
            Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 1',
                RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
                Maintenance_Contract__c = contract.Id,
                Request_quotation_Amount__c = 1,
                EndUserType__c = '既有用户',
                mainTalksTime__c = 1,
                talksStartDate__c = Date.today(),
                Discount_reason__c = 'test',
                Improve_ConsumptionRate_Idea__c = 'test'
            );
            insert contactEsti1;
            Maintenance_Contract_Asset_Estimate__c mcae1 = new Maintenance_Contract_Asset_Estimate__c();
            mcae1.Asset__c = asset01.Id;
            mcae1.Adjustment_Upper_price__c = 1;
            mcae1.Adjustment_Lower_price__c = 1;
            mcae1.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae1.Estimate_List_Price__c = 1000;
            mcae1.Check_Result__c = 'OK';
            Maintenance_Contract_Asset_Estimate__c mcae2 = new Maintenance_Contract_Asset_Estimate__c();
            mcae2.Product_Manual__c = productA.Id;
            mcae2.Adjustment_Upper_price__c = 1;
            mcae2.Adjustment_Lower_price__c = 1;
            mcae2.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae2.Estimate_List_Price__c = 1000;
            mcae2.Check_Result__c = 'OK';
            insert new Maintenance_Contract_Asset_Estimate__c[] {mcae1, mcae2};
            Apexpages.currentPage().getParameters().put('copyid', contactEsti1.Id);
            Apexpages.currentPage().getParameters().put('completion', '3');
            SelectAssetEstimateURFController controller = new SelectAssetEstimateURFController();
            controller.init();
            controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller.estimate.Contract_Range__c = 2;
            controller.save();
        }
    }
    static testMethod void testApprovalProcess_01() {
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        insert u3;
        system.runAs(u3) {
        ControllerUtil.EscapeNFM001Trigger = true;
        // 病院を作る
        Account hospital = new Account();
        hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
        hospital.Name = 'test hospital';
        insert hospital;
        // 戦略科室を得る
        List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
        // 診療科を作る
        Account dep = new Account();
        dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
        dep.Name = 'test dep';
        dep.ParentId = strategicDep[0].Id;
        dep.Department_Class__c = strategicDep[0].Id;
        dep.Hospital__c = hospital.Id;
        insert dep;
        ProductURF__c purf = new ProductURF__c(UFR_MaxRepairCount__c = 2,URFLimitSerial__c = 'URF-P',Maintenance_Price_Year_URF__c = 1200);
        insert purf;
        // 製品を作る
        Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false,ProductURF__c = purf.Id);
        insert productA;
        // 価格表エントリを作成する
        PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
        entry.UnitPrice = 0;
        entry.IsActive = true;
        entry.UseStandardPrice = false;
        entry.CurrencyIsoCode = 'CNY';
        entry.Product2Id = productA.Id;
        insert entry;
        // 納入機器を作成する
        Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
        Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'耗材');
        Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'主机');
        Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'耗材');
        Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
        // 维修合同を作成する
        Maintenance_Contract__c contract = new Maintenance_Contract__c();
        contract.Name = 'tect contract';
        contract.Not_Upper_limit_reason__c = 'tect contract';
        contract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
        contract.Hospital__c = hospital.Id;
        contract.Department_Class__c = strategicDep[0].Id;
        contract.Department__c = dep.Id;
        contract.Service_Contract_Staff__c = u3.Id;
        contract.Payment_Plan_Sum_First__c = 1;
        contract.URF_Contract__c = true;
        contract.agree_Upper_limit__c = true;
        insert contract;
        // 维修合同报价を作成する
        Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
            Name = 'contract estimate 1',
            RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
            Contract_Esti_Start_Date__c = Date.today(),
            Contract_Range__c = 2,
            Maintenance_Contract__c = contract.Id,
            Request_quotation_Amount__c = 1,
            EndUserType__c = '既有用户',
            mainTalksTime__c = 1,
            talksStartDate__c = Date.today(),
            Discount_reason__c = 'test',
            Improve_ConsumptionRate_Idea__c = 'test'
        );
        insert new Maintenance_Contract_Estimate__c[] {contactEsti1};
        Maintenance_Contract_Asset_Estimate__c mcae1 = new Maintenance_Contract_Asset_Estimate__c();
            mcae1.Asset__c = asset01.Id;
            mcae1.Adjustment_Upper_price__c = 1;
            mcae1.Adjustment_Lower_price__c = 1;
            mcae1.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae1.Estimate_List_Price__c = 1000;
            mcae1.Check_Result__c = 'OK';
            Maintenance_Contract_Asset_Estimate__c mcae2 = new Maintenance_Contract_Asset_Estimate__c();
            mcae2.Asset__c = asset01.Id;
            mcae2.Adjustment_Upper_price__c = 1;
            mcae2.Adjustment_Lower_price__c = 1;
            mcae2.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae2.Estimate_List_Price__c = 1000;
            mcae2.Check_Result__c = 'OK';
            insert new Maintenance_Contract_Asset_Estimate__c[] {mcae1, mcae2};
        // 新規
        Apexpages.currentPage().getParameters().put('id', contactEsti1.Id);
        SelectAssetEstimateURFController controller = new SelectAssetEstimateURFController();
        controller.init();
        controller.estimate.Contract_Esti_Start_Date__c = Date.today();
        controller.estimate.Contract_Range__c = 2;
        controller.unCheckedAssetsView[0][0].rec_CheckBox_c = true;
        controller.exchangeAsset();
        controller.checkedAssets[0].mcae.Check_Result__c = 'OK';
        controller.approvalProcess();
        // 提交待审批时,更新已填写申请状态
        List<Maintenance_Contract_Estimate__c> mcenew = [select id,ApprovalProcess_Status__c from Maintenance_Contract_Estimate__c where id = :contactEsti1.Id];
        //System.assertEquals('已填写完并申请', mcenew[0].ApprovalProcess_Status__c);
        }
    }
    static testMethod void EditUnitTest() {
        //Test.startTest();
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        insert u3;
        system.runAs(u3) {
            ControllerUtil.EscapeNFM001Trigger = true;
            //SelectAssetEstimateURFController controller = new SelectAssetEstimateURFController();
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            ProductURF__c purf = new ProductURF__c(UFR_MaxRepairCount__c = 2,URFLimitSerial__c = 'URF-P',Maintenance_Price_Year_URF__c = 1200);
            insert purf;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false,ProductURF__c = purf.Id);
            insert productA;
            //// 価格表エントリを作成する
            //PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            //entry.UnitPrice = 0;
            //entry.IsActive = true;
            //entry.UseStandardPrice = false;
            //entry.CurrencyIsoCode = 'CNY';
            //entry.Product2Id = productA.Id;
            //insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'耗材');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'主机');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'耗材');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Not_Upper_limit_reason__c = 'tect contract';
            contract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            contract.Payment_Plan_Sum_First__c = 1;
            contract.URF_Contract__c = true;
            contract.agree_Upper_limit__c = true;
            insert contract;
            // 维修合同报价を作成する
            Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 1',
                RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
                Contract_Esti_Start_Date__c = Date.today(),
                Contract_Range__c = 2,
                Maintenance_Contract__c = contract.Id,
                Request_quotation_Amount__c = 1,
                EndUserType__c = '既有用户',
                mainTalksTime__c = 1,
                talksStartDate__c = Date.today(),
                Discount_reason__c = 'test',
                Improve_ConsumptionRate_Idea__c = 'test'
            );
            Maintenance_Contract_Estimate__c contactEsti2 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 2',
                RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
                Contract_Esti_Start_Date__c = Date.today().addMonths(6),
                Contract_Range__c = 3,
                Maintenance_Contract__c = contract.Id,
                Request_quotation_Amount__c = 1,
                EndUserType__c = '既有用户',
                mainTalksTime__c = 1,
                talksStartDate__c = Date.today(),
                Discount_reason__c = 'test',
                Improve_ConsumptionRate_Idea__c = 'test'
            );
            insert new Maintenance_Contract_Estimate__c[] {contactEsti1, contactEsti2};
            System.Test.startTest();
            Apexpages.currentPage().getParameters().put('id', contactEsti1.Id);
            SelectAssetEstimateURFController controller = new SelectAssetEstimateURFController();
            controller.init();
            controller.text1 = 'S:Name';
            controller.cond1 = 'equals';
            controller.val1 = 'asset01,asset02';
            controller.searchBtn();
            controller.cond1 = 'equals';
            controller.val1 = 'asset02';
            controller.searchBtn();
            controller.cond1 = 'contains';
            controller.val1 = ' asset02';
            controller.searchBtn();
            controller.cond1 = 'notequals';
            controller.searchBtn();
            controller.cond1 = 'starts with';
            controller.searchBtn();
            Test.stopTest();
        }
    }
    // 补充test 实际联动
    static testMethod void testInit_04() {
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        insert u3;
        system.runAs(u3) {
            Achievement_linkage__c oppMapping = new Achievement_linkage__c();
            oppMapping.Name = '01';
            oppMapping.Consumption_rate_Lower__c = 0;
            oppMapping.Consumption_rate_Upper__c = 50;                           // 重複してもエラーにはならない
            oppMapping.PriceCount_Lower__c  = -40;
            oppMapping.PriceCount_Upper__c  = -30;
            insert oppMapping;
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            ProductURF__c purf = new ProductURF__c(UFR_MaxRepairCount__c = 2,URFLimitSerial__c = 'URF-P',Maintenance_Price_Year_URF__c = 1200);
            insert purf;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false,ProductURF__c = purf.Id);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'耗材');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'主机');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Not_Upper_limit_reason__c = 'tect contract';
            contract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            contract.URF_Contract__c = true;
            contract.agree_Upper_limit__c = true;
            insert contract;
            // 维修合同报价を作成する
            Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 1',
                RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
                Maintenance_Contract__c = contract.Id,
                Request_quotation_Amount__c = 1,
                EndUserType__c = '既有用户',
                mainTalksTime__c = 1,
                talksStartDate__c = Date.today(),
                Discount_reason__c = 'test',
                Improve_ConsumptionRate_Idea__c = 'test'
            );
            insert contactEsti1;
            Maintenance_Contract_Asset_Estimate__c mcae1 = new Maintenance_Contract_Asset_Estimate__c();
            mcae1.Asset__c = asset01.Id;
            mcae1.Adjustment_Upper_price__c = 1;
            mcae1.Adjustment_Lower_price__c = 1;
            mcae1.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae1.Estimate_List_Price__c = 1000;
            mcae1.Check_Result__c = 'OK';
            Maintenance_Contract_Asset_Estimate__c mcae2 = new Maintenance_Contract_Asset_Estimate__c();
            mcae2.Product_Manual__c = productA.Id;
            mcae2.Adjustment_Upper_price__c = 1;
            mcae2.Adjustment_Lower_price__c = 1;
            mcae2.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae2.Estimate_List_Price__c = 1000;
            mcae2.Check_Result__c = 'OK';
            insert new Maintenance_Contract_Asset_Estimate__c[] {mcae1, mcae2};
            Apexpages.currentPage().getParameters().put('id', contactEsti1.Id);
            SelectAssetEstimateURFController controller = new SelectAssetEstimateURFController();
            controller.init();
            controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller.estimate.Contract_Range__c = 2;
            controller.priceChangeReset();
            //controller.getChartData();
            //System.assertEquals(1, controller.dataList.size());
            controller.save();
            controller.changedAfterPrint = true;
            controller.checkChangedAfterPrint();
        }
    }
    static testMethod void testnotargetEstimateId_dataList() {
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        insert u3;
        system.runAs(u3) {
            try {
                SelectAssetEstimateURFController controller001 = new SelectAssetEstimateURFController();
                controller001.init();
            } catch (Exception e) {
            }
            Achievement_linkage__c oppMapping = new Achievement_linkage__c();
            oppMapping.Name = '01';
            oppMapping.Consumption_rate_Lower__c = 0;
            oppMapping.Consumption_rate_Upper__c = 50;                           // 重複してもエラーにはならない
            oppMapping.PriceCount_Lower__c  = -40;
            oppMapping.PriceCount_Upper__c  = -30;
            insert oppMapping;
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            ProductURF__c purf = new ProductURF__c(UFR_MaxRepairCount__c = 2,URFLimitSerial__c = 'URF-P',Maintenance_Price_Year_URF__c = 1200);
            insert purf;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false,ProductURF__c = purf.Id);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'耗材');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'主机');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
            // 上一期维修合同
            Maintenance_Contract__c lastcontract = new Maintenance_Contract__c();
            lastcontract.Name = 'tect contract';
            lastcontract.Not_Upper_limit_reason__c = 'tect contract';
            lastcontract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
            lastcontract.Hospital__c = hospital.Id;
            lastcontract.Department_Class__c = strategicDep[0].Id;
            lastcontract.Department__c = dep.Id;
            lastcontract.Contract_Start_Date__c = Date.today().addMonths(-11);
            lastcontract.Contract_End_Date__c = Date.today().addMonths(1);
            lastcontract.Service_Contract_Staff__c = u3.Id;
            lastcontract.First_Estimate_Date__c = Date.today().addMonths(-1);
            lastcontract.First_contract_usage_Rate__c = 110;
            lastcontract.URF_Contract__c = true;
            lastcontract.agree_Upper_limit__c = true;
            insert lastcontract;
            // 维修合同/保有设备を作成する
            Maintenance_Contract_Asset__c lastmca1 = new Maintenance_Contract_Asset__c();
            lastmca1.Asset__c = asset01.Id;
            lastmca1.Estimate_List_Price__c = 100;
            lastmca1.Estimate_Cost__c = 100;
            lastmca1.Maintenance_Contract__c = lastcontract.Id;
            insert new Maintenance_Contract_Asset__c[] {lastmca1};
            asset01.CurrentContract_F__c = lastcontract.Id;
            asset01.CurrentContract_F_asset__c = lastmca1.Id;
            update asset01;
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Not_Upper_limit_reason__c = 'tect contract';
            contract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            contract.URF_Contract__c = true;
            contract.agree_Upper_limit__c = true;
            insert contract;
            // 维修合同/保有设备を作成する
            Maintenance_Contract_Asset__c mca1 = new Maintenance_Contract_Asset__c();
            mca1.Asset__c = asset01.Id;
            mca1.Estimate_List_Price__c = 100;
            mca1.Maintenance_Contract__c = contract.Id;
            Maintenance_Contract_Asset__c mca2 = new Maintenance_Contract_Asset__c();
            mca2.Asset__c = asset01.Id;
            mca2.Estimate_List_Price__c = 100;
            mca2.Maintenance_Contract__c = contract.Id;
            insert new Maintenance_Contract_Asset__c[] {mca1, mca2};
            // Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
            //     RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
            //     Name = 'contract estimate 1',
            //     Maintenance_Contract__c = contract.Id,
            //     Contract_Esti_Start_Date__c = Date.today().addDays(1),
            //     Request_quotation_Amount__c = 1,
            //     EndUserType__c = '既有用户',
            //     mainTalksTime__c = 1,
            //     talksStartDate__c = Date.today(),
            //     Discount_reason__c = 'test',
            //     Improve_ConsumptionRate_Idea__c = 'test'
            // );
            // insert contactEsti1;
            // Maintenance_Contract_Asset_Estimate__c mcae1 = new Maintenance_Contract_Asset_Estimate__c();
            // mcae1.Asset__c = asset01.Id;
            // mcae1.Adjustment_Upper_price__c = 1;
            // mcae1.Adjustment_Lower_price__c = 1;
            // mcae1.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            // mcae1.Estimate_List_Price__c = 1000;
            // mcae1.Check_Result__c = 'OK';
            // Maintenance_Contract_Asset_Estimate__c mcae2 = new Maintenance_Contract_Asset_Estimate__c();
            // mcae2.Asset__c = asset01.Id;
            // mcae2.Adjustment_Upper_price__c = 1;
            // mcae2.Adjustment_Lower_price__c = 1;
            // mcae2.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            // mcae2.Estimate_List_Price__c = 1000;
            // mcae2.Check_Result__c = 'OK';
            // insert new Maintenance_Contract_Asset_Estimate__c[] {mcae1, mcae2};
            Apexpages.currentPage().getParameters().put('mcid', contract.Id);
            SelectAssetEstimateURFController controller = new SelectAssetEstimateURFController();
            controller.init();
            // controller.firstPage();
            // controller.currPage = 3;
            // controller.previousPage();
            // controller.endPage();
            // controller.currPage = 200;
            // controller.nextPage();
            // controller.recordNumChange();
            // controller.getSaveBtnDisabled();
            // //controller.ComputeLTYRepair();
            // controller.cancel();
            // controller.saveAndCancel();
        }
    }
    static testMethod void testSyncEstimate() {
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        insert u3;
        system.runAs(u3) {
            Achievement_linkage__c oppMapping = new Achievement_linkage__c();
            oppMapping.Name = '01';
            oppMapping.Consumption_rate_Lower__c = 0;
            oppMapping.Consumption_rate_Upper__c = 50;                           // 重複してもエラーにはならない
            oppMapping.PriceCount_Lower__c  = -40;
            oppMapping.PriceCount_Upper__c  = -30;
            insert oppMapping;
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            ProductURF__c purf = new ProductURF__c(UFR_MaxRepairCount__c = 2,URFLimitSerial__c = 'URF-P',Maintenance_Price_Year_URF__c = 1200);
            insert purf;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false,ProductURF__c = purf.Id);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'耗材');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'耗材');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Not_Upper_limit_reason__c = 'tect contract';
            contract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            contract.URF_Contract__c = true;
            contract.agree_Upper_limit__c = true;
            insert contract;
            // 维修合同报价を作成する
            Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 1',
                RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
                Maintenance_Contract__c = contract.Id,
                Request_quotation_Amount__c = 2,
                EndUserType__c = '既有用户',
                mainTalksTime__c = 1,
                talksStartDate__c = Date.today(),
                Discount_reason__c = 'test',
                Improve_ConsumptionRate_Idea__c = 'test',
                GuidePrice_Up__c = 1
            );
            insert contactEsti1;
            Maintenance_Contract_Asset_Estimate__c mcae1 = new Maintenance_Contract_Asset_Estimate__c();
            mcae1.Asset__c = asset01.Id;
            mcae1.Adjustment_Upper_price__c = 1;
            mcae1.Adjustment_Lower_price__c = 1;
            mcae1.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae1.Estimate_List_Price__c = 1000;
            mcae1.Check_Result__c = 'OK';
            Maintenance_Contract_Asset_Estimate__c mcae2 = new Maintenance_Contract_Asset_Estimate__c();
            mcae2.Product_Manual__c = productA.Id;
            mcae2.Adjustment_Upper_price__c = 1;
            mcae2.Adjustment_Lower_price__c = 1;
            mcae2.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae2.Estimate_List_Price__c = 1000;
            mcae2.Check_Result__c = 'OK';
            insert new Maintenance_Contract_Asset_Estimate__c[] {mcae1, mcae2};
            Apexpages.currentPage().getParameters().put('id', contactEsti1.Id);
            SelectAssetEstimateURFController controller = new SelectAssetEstimateURFController();
            controller.init();
            controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller.estimate.Contract_Range__c = 2;
            controller.priceChangeReset();
            // controller.getChartData();
            // System.assertEquals(1, controller.dataList.size());
            controller.save();
            controller.changedAfterPrint = true;
            controller.syncEstimate(true,true);
        }
    }
}
force-app/main/default/classes/SelectAssetEstimateURFControllerTest.cls-meta.xml
New file
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>41.0</apiVersion>
    <status>Active</status>
</ApexClass>
force-app/main/default/classes/SelectAssetEstimateVMController.cls
New file
Diff too large
force-app/main/default/classes/SelectAssetEstimateVMController.cls-meta.xml
New file
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>44.0</apiVersion>
    <status>Active</status>
</ApexClass>
force-app/main/default/classes/SelectAssetEstimateVMControllerTest.cls
New file
@@ -0,0 +1,1614 @@
@isTest
private class SelectAssetEstimateVMControllerTest {
    private static Id pricebookId = ControllerUtil.getStandardPricebook().Id;
    static Asset createAsset(String input, String accountid, String dcId, String hpId, String serialNo, String prId, String mark ) {
        Asset asset = new Asset();
        asset.Name = input;
        asset.AccountId = accountid;
        asset.Department_Class__c = dcId;
        asset.Hospital__c = hpId;
        asset.SerialNumber = serialNo;
        asset.Product2Id = prId;
        asset.InstallDate = Date.today();
        //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start
        //在接收参数的时候新增了String类型的Mark字段,以及在调用该方法时传递了String类型的Mark字段
        asset.AssetMark__c = mark;
        //JZHG-BSDUT4 ---20200825---update By rentongxiao---End
        insert asset;
        return asset;
    }
    public class AssetInfo {
        public Integer lineNo {get; private set;}
        public Boolean rec_checkBox_c {get; set;}
        public Asset rec { get; set; }
        public Maintenance_Contract_Asset_Estimate__c mcae { get; set; }
        public Boolean isManual { get; set; }
        public Decimal orgPrice {get; private set;}
        public Id getRecId() {
            Id rtn = null;
            if (rec != null) {
                rtn = rec.Id;
            }
            return rtn;
        }
        public void setRecId(Id value) {
            // なにもしない
        }
        // Manual専用
        public AssetInfo(Integer lineNo) {
            this.lineNo = lineNo;
            this.rec = null;
            this.mcae = new Maintenance_Contract_Asset_Estimate__c(
                isNew__c = true
            );
            this.isManual = true;
            this.rec_checkBox_c = false;
            this.orgPrice = 0;
        }
    }
    // 2つ見積もりがあり、親のサビコンと同期するのテスト
    static testMethod void testDecide_01() {
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        u3.HR_Post__c='总裁';
        insert u3;
        system.runAs(u3) {
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            StaticParameter.EscapeSyncProduct2Trigger = true;
            StaticParameter.EscapeAccountTrigger = true;
            StaticParameter.EscapeMaintenanceContractAfterUpdateTrigger = true;
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            // Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            // Asset asset01 = intProCommonMethodController.buildAssetHost('asset01',dep.Id, hospital.Id, strategicDep[0].Id,'使用中');
            Product2 pro = new Product2(
                Name = 'proName',
                // ProductCode='pro001',
                Asset_Model_No__c = 'pro001',
                SFDA_Status__c = '有効',
                Dealer_special_Object__c = true,
                Packing_list_manual__c = 1,
                Family='GI',
                Fixture_Model_No__c='n01',
                Serial_Lot_No__c='S/N tracing',
                Fixture_Model_No_T__c = 'n01',
                ProductCode_Ext__c='pc01',
                Manual_Entry__c=false
            );
            insert pro;
            Asset asset01 = new Asset(
                Name = 'asset01',
                Product2Id = pro.Id,
                Hospital__c = hospital.Id,
                Department_Class__c = strategicDep[0].Id,
                AccountId = dep.Id,
                Status = '使用中',
                Asset_Owner__c = '病院資産',
                IsCompetitorProduct = True,
                AssetMark__c = '主机',
                RecordTypeId = System.Label.Asset_RecordType,
                SerialNumber = 'asset1',
                Quantity = 1,
                Manage_type__c = '个体管理',
                Loaner_accsessary__c = false,
                Out_of_wh__c = 0,
                Salesdepartment__c = '1.华北营业本部',
                Internal_asset_location__c = '北京 备品中心',
                Product_category__c = 'GI',
                Equipment_Type__c = '产品试用',
                SalesProvince__c = '大连',
                CompanyOfEquipment__c = '北京',
                Internal_Asset_number__c = '0001',
                Rental_Count__c = 0,
                Asset_loaner_category__c = '固定资产',
                Consumable_Guaranteen_end__c = System.Today() + 1,
                WH_location__c = '货架号1'
            );
            insert asset01;
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'耗材');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'耗材');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Not_Upper_limit_reason__c = 'tect contract';
            contract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            insert contract;
            Maintenance_Contract_Asset__c mca1 = new Maintenance_Contract_Asset__c();
            mca1.Asset__c = asset01.Id;
            mca1.Estimate_List_Price__c = 100;
            mca1.Maintenance_Contract__c = contract.Id;
            insert new Maintenance_Contract_Asset__c[] {mca1};
            // 维修合同报价を作成する
            Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 1',
                RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
                Contract_Esti_Start_Date__c = Date.today(),
                Contract_Range__c = 2,
                Maintenance_Contract__c = contract.Id,
                Request_quotation_Amount__c = 1,
                EndUserType__c = '既有用户',
                mainTalksTime__c = 1,
                talksStartDate__c = Date.today(),
                Discount_reason__c = 'test',
                Improve_ConsumptionRate_Idea__c = 'test'
            );
            insert contactEsti1;
            System.Test.startTest();
            // 新規
            Apexpages.currentPage().getParameters().put('mcid', contract.Id);
            SelectAssetEstimateVMController controller = new SelectAssetEstimateVMController();
            controller.init();
            controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller.estimate.Contract_Range__c = 2;
            controller.unCheckedAssetsView[0][0].rec_CheckBox_c = true;
            controller.exchangeAsset();
            controller.save();
            controller.approvalProcess();
            // 维修合同报价1
            Apexpages.currentPage().getParameters().put('id', contactEsti1.Id);
            controller = new SelectAssetEstimateVMController();
            controller.init();
             //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start
            // System.assertEquals(5, controller.productCount2);
            //因为默认查询的保有设备类型为主机
            System.assertEquals(2,controller.productCount2);
             //JZHG-BSDUT4 ---20200825---update By rentongxiao---End
            controller.getEnablePrintContract();
            controller.getUnDecideBtnDisabled();
            controller.getDecideBtnDisabled();
            controller.getApprovalBtnDisabled();
            controller.getSaveBtnDisabled();
            controller.getPrintBtnDisabled();
            controller.getPageDisabled();
            controller.savePrintFlg();
            System.assertEquals(10, controller.productCount);
            controller.unCheckedAssetsView[0][0].rec_CheckBox_c = true;
            controller.exchangeAsset();
            System.assertEquals(11, controller.productCount);
            System.assertEquals(1, controller.productCount3);
            controller.productIdx = 1;
            controller.refreshProductData();
            controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller.estimate.Contract_Range__c = 2;
            controller.save();
            List<Maintenance_Contract_Asset__c> mcaList = [select Id, Asset__r.Name from Maintenance_Contract_Asset__c where Maintenance_Contract__c = :contract.Id];
            System.assertEquals(1, mcaList.size());
            System.assertEquals('asset01', mcaList[0].Asset__r.Name);
            controller.print();
            System.Test.stopTest();
        }
    }
    // 2つ見積もりがあり、親のサビコンと同期するのテスト
    static testMethod void testDecide_02() {
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        u3.HR_Post__c='总裁';
        insert u3;
        system.runAs(u3) {
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            StaticParameter.EscapeSyncProduct2Trigger = true;
            StaticParameter.EscapeAccountTrigger = true;
            StaticParameter.EscapeMaintenanceContractAfterUpdateTrigger = true;
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'主机');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'主机');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'主机');
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Not_Upper_limit_reason__c = 'tect contract';
            contract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            insert contract;
            // // 维修合同报价を作成する
            // Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
            //     Name = 'contract estimate 1',
            //     RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
            //     Contract_Esti_Start_Date__c = Date.today(),
            //     Contract_Range__c = 2,
            //     Maintenance_Contract__c = contract.Id
            // );
            Maintenance_Contract_Estimate__c contactEsti2 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 2',
                RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
                Contract_Esti_Start_Date__c = Date.today().addMonths(6),
                Contract_Range__c = 3,
                Maintenance_Contract__c = contract.Id,
                Request_quotation_Amount__c = 1,
                EndUserType__c = '既有用户',
                mainTalksTime__c = 1,
                talksStartDate__c = Date.today(),
                Discount_reason__c = 'test',
                Improve_ConsumptionRate_Idea__c = 'test'
            );
            insert  contactEsti2;
            System.Test.startTest();
            // 新規
            Apexpages.currentPage().getParameters().put('mcid', contract.Id);
            SelectAssetEstimateVMController controller = new SelectAssetEstimateVMController();
            controller.init();
            controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller.estimate.Contract_Range__c = 2;
            controller.unCheckedAssetsView[0][0].rec_CheckBox_c = true;
            controller.exchangeAsset();
            controller.save();
            controller.approvalProcess();
            // // 维修合同报价1
            // Apexpages.currentPage().getParameters().put('id', contactEsti1.Id);
            // controller = new SelectAssetEstimateVMController();
            // controller.init();
            // System.assertEquals(5, controller.productCount2);
            // controller.getEnablePrintContract();
            // controller.getUnDecideBtnDisabled();
            // controller.getDecideBtnDisabled();
            // controller.getApprovalBtnDisabled();
            // controller.getSaveBtnDisabled();
            // controller.getPrintBtnDisabled();
            // controller.getcontactBtnDisabled();
            // controller.getPageDisabled();
            // controller.savePrintFlg();
            // System.assertEquals(10, controller.productCount);
            // controller.unCheckedAssetsView[0][0].rec_CheckBox_c = true;
            // controller.exchangeAsset();
            // System.assertEquals(11, controller.productCount);
            // System.assertEquals(1, controller.productCount3);
            // controller.productIdx = 1;
            // controller.refreshProductData();
            // controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            // controller.estimate.Contract_Range__c = 2;
            // controller.save();
            // List<Maintenance_Contract_Asset__c> mcaList = [select Id, Asset__r.Name from Maintenance_Contract_Asset__c where Maintenance_Contract__c = :contract.Id];
            // System.assertEquals(1, mcaList.size());
            // System.assertEquals('asset01', mcaList[0].Asset__r.Name);
            // controller.print();
            // 维修合同报价2の決定ロジック
            Apexpages.currentPage().getParameters().put('id', contactEsti2.Id);
            SelectAssetEstimateVMController controller2 = new SelectAssetEstimateVMController();
            controller2.init();
            controller2.unCheckedAssetsView[0][1].rec_CheckBox_c = true;
            controller2.unCheckedAssetsView[0][3].rec_CheckBox_c = true;
            System.assertEquals(10, controller2.productCount);
            controller2.exchangeAsset();
            System.assertEquals(12, controller2.productCount);
            System.assertEquals(2, controller2.productCount3);
            // contactEsti1 = [select IsSyncing__c from Maintenance_Contract_Estimate__c where Id = :contactEsti1.Id];
            // System.assertEquals(true, contactEsti1.IsSyncing__c);
            controller2.checkedAssets[0].mcae.Check_Result__c = 'test0';
            controller2.checkedAssets[1].mcae.Check_Result__c = 'test1';
            controller2.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller2.estimate.Contract_Range__c = 2;
            controller2.estimate.Process_Status__c = '批准';
            controller2.decide();
            // contactEsti1 = [select IsSyncing__c from Maintenance_Contract_Estimate__c where Id = :contactEsti1.Id];
            // System.assertEquals(false, contactEsti1.IsSyncing__c);
            // contactEsti2 = [select IsSyncing__c from Maintenance_Contract_Estimate__c where Id = :contactEsti2.Id];
            // System.assertEquals(true, contactEsti2.IsSyncing__c);
            controller2.undecide();
            //mcaList = [select Id, Asset__r.Name from Maintenance_Contract_Asset__c where Maintenance_Contract__c = :contract.Id order by Asset__r.Name];
            //System.assertEquals(2, mcaList.size());
            //System.assertEquals('asset02', mcaList[0].Asset__r.Name);
            //System.assertEquals('asset04', mcaList[1].Asset__r.Name);
            System.Test.stopTest();
        }
    }
    static testMethod void testcopyid_01() {
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        u3.HR_Post__c='总裁';
        insert u3;
        system.runAs(u3) {
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'主机');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'耗材');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Not_Upper_limit_reason__c = 'tect contract';
            contract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            insert contract;
            // 维修合同报价を作成する
            Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
                RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
                Name = 'contract estimate 1',
                Maintenance_Contract__c = contract.Id,
                Request_quotation_Amount__c = 1,
                EndUserType__c = '既有用户',
                mainTalksTime__c = 1,
                talksStartDate__c = Date.today(),
                Discount_reason__c = 'test',
                Improve_ConsumptionRate_Idea__c = 'test'
            );
            insert contactEsti1;
            Apexpages.currentPage().getParameters().put('copyid', contactEsti1.Id);
            SelectAssetEstimateVMController controller = new SelectAssetEstimateVMController();
            controller.init();
            controller.lastFriYearsPriceSum  =3322;
            controller.lastSecYearsPriceSum = 1222;
            controller.alertString ='';
            controller.alertString2 ='';
            controller.alertString3 ='';
            controller.getSaveBtnDisabled();
            controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller.estimate.Contract_Range__c = 2;
            controller.save();
            SelectAssetEstimateVMController.pageDecide(contactEsti1.Id);
            SelectAssetEstimateVMController.pageUndecide(contactEsti1.Id);
//            controller.ComputeLTYRepair();
            controller.ShowLTYRepair();
        }
    }
    static testMethod void testInit_01() {
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        u3.HR_Post__c='总裁';
        insert u3;
        system.runAs(u3) {
            try {
                SelectAssetEstimateVMController controller001 = new SelectAssetEstimateVMController();
                controller001.init();
            } catch (Exception e) {
            }
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            hospital.Is_Active__c = '有效';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'耗材');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'耗材');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'主机');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Not_Upper_limit_reason__c = 'tect contract';
            contract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            insert contract;
            // 维修合同/保有设备を作成する
            Maintenance_Contract_Asset__c mca1 = new Maintenance_Contract_Asset__c();
            mca1.Asset__c = asset01.Id;
            mca1.Estimate_List_Price__c = 100;
            mca1.Maintenance_Contract__c = contract.Id;
            Maintenance_Contract_Asset__c mca2 = new Maintenance_Contract_Asset__c();
            mca2.Asset__c = asset01.Id;
            mca2.Estimate_List_Price__c = 100;
            mca2.Maintenance_Contract__c = contract.Id;
            insert new Maintenance_Contract_Asset__c[] {mca1, mca2};
            Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
                RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
                Name = 'contract estimate 1',
                Maintenance_Contract__c = contract.Id,
                Contract_Esti_Start_Date__c = Date.today().addDays(1),
                Request_quotation_Amount__c = 1,
                EndUserType__c = '既有用户',
                mainTalksTime__c = 1,
                talksStartDate__c = Date.today(),
                Discount_reason__c = 'test',
                Improve_ConsumptionRate_Idea__c = 'test'
            );
            insert contactEsti1;
            Maintenance_Contract_Asset_Estimate__c mcae1 = new Maintenance_Contract_Asset_Estimate__c();
            mcae1.Asset__c = asset01.Id;
            mcae1.Adjustment_Upper_price__c = 1;
            mcae1.Adjustment_Lower_price__c = 1;
            mcae1.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae1.Estimate_List_Price__c = 1000;
            mcae1.Check_Result__c = 'OK';
            Maintenance_Contract_Asset_Estimate__c mcae2 = new Maintenance_Contract_Asset_Estimate__c();
            mcae2.Asset__c = asset01.Id;
            mcae2.Adjustment_Upper_price__c = 1;
            mcae2.Adjustment_Lower_price__c = 1;
            mcae2.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae2.Estimate_List_Price__c = 1000;
            mcae2.Check_Result__c = 'OK';
            insert new Maintenance_Contract_Asset_Estimate__c[] {mcae1, mcae2};
            Apexpages.currentPage().getParameters().put('mcid', contract.Id);
            Apexpages.currentPage().getParameters().put('completion', '1');
            SelectAssetEstimateVMController controller = new SelectAssetEstimateVMController();
            controller.init();
            controller.firstPage();
            controller.currPage = 3;
            controller.previousPage();
            controller.endPage();
            controller.currPage = 200;
            controller.nextPage();
            controller.recordNumChange();
            controller.getSaveBtnDisabled();
            //controller.ComputeLTYRepair();
            controller.cancel();
            controller.saveAndCancel();
            controller.onChDealerUpdate();
            controller.checkDealerId = mcae2.Id;
            controller.onChDealerUpdate();
            controller.checkDealerId = hospital.Id;
            controller.onChDealerUpdate();
        }
    }
    static testMethod void testInit_02() {
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        u3.HR_Post__c='总裁';
        insert u3;
        system.runAs(u3) {
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'主机');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'耗材');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
            // 修理を作成する01
            Repair__c repair01 = new Repair__c();
            repair01.Account__c = dep.Id;
            repair01.Department_Class__c = strategicDep[0].Id;
            repair01.Hospital__c = hospital.Id;
            repair01.Delivered_Product__c = asset01.Id;
            repair01.SERVICE_CONTRACT_JUDEGE_DAY__C = Date.today().addDays(0);  // 维修合同判断日がサービス契約の中間辺りの日付
            repair01.FSE_Work_Location__c = '上海';
            repair01.Agreed_Date__c = Date.today().addDays(-1);
            insert repair01;
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Not_Upper_limit_reason__c = 'tect contract';
            contract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            insert contract;
            // 维修合同报价を作成する
            Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 1',
                RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
                Maintenance_Contract__c = contract.Id,
                Contract_Esti_Start_Date__c = Date.today().addDays(1),
                Request_quotation_Amount__c = 1,
                EndUserType__c = '既有用户',
                mainTalksTime__c = 1,
                talksStartDate__c = Date.today(),
                Discount_reason__c = 'test',
                Improve_ConsumptionRate_Idea__c = 'test'
            );
            insert contactEsti1;
            Maintenance_Contract_Asset_Estimate__c mcae1 = new Maintenance_Contract_Asset_Estimate__c();
            mcae1.Asset__c = asset01.Id;
            mcae1.Adjustment_Upper_price__c = 1;
            mcae1.Adjustment_Lower_price__c = 1;
            mcae1.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae1.Estimate_List_Price__c = 1000;
            mcae1.Check_Result__c = 'OK';
            Maintenance_Contract_Asset_Estimate__c mcae2 = new Maintenance_Contract_Asset_Estimate__c();
            mcae2.Asset__c = asset01.Id;
            mcae2.Adjustment_Upper_price__c = 1;
            mcae2.Adjustment_Lower_price__c = 1;
            mcae2.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae2.Estimate_List_Price__c = 1000;
            mcae2.Check_Result__c = 'OK';
            insert new Maintenance_Contract_Asset_Estimate__c[] {mcae1, mcae2};
            Apexpages.currentPage().getParameters().put('id', contactEsti1.Id);
            SelectAssetEstimateVMController controller = new SelectAssetEstimateVMController();
            controller.init();
            controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller.estimate.Contract_Range__c = 2;
            controller.save();
            Test.startTest();
            controller.ComputeLTYRepair();
            controller.saveAndCancel();
            SelectAssetEstimateVMController.ComputeLTYRepair(controller.targetEstimateId);
            Test.stopTest();
        }
    }
    static testMethod void testInit_03() {
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        u3.HR_Post__c='总裁';
        insert u3;
        system.runAs(u3) {
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'主机');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'耗材');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Not_Upper_limit_reason__c = 'tect contract';
            contract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            insert contract;
            // 维修合同报价を作成する
            Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 1',
                RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
                Maintenance_Contract__c = contract.Id,
                Request_quotation_Amount__c = 1,
                EndUserType__c = '既有用户',
                mainTalksTime__c = 1,
                talksStartDate__c = Date.today(),
                Discount_reason__c = 'test',
                Improve_ConsumptionRate_Idea__c = 'test'
            );
            insert contactEsti1;
            Maintenance_Contract_Asset_Estimate__c mcae1 = new Maintenance_Contract_Asset_Estimate__c();
            mcae1.Asset__c = asset01.Id;
            mcae1.Adjustment_Upper_price__c = 1;
            mcae1.Adjustment_Lower_price__c = 1;
            mcae1.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae1.Estimate_List_Price__c = 1000;
            mcae1.Check_Result__c = 'OK';
            Maintenance_Contract_Asset_Estimate__c mcae2 = new Maintenance_Contract_Asset_Estimate__c();
            mcae2.Product_Manual__c = productA.Id;
            mcae2.Adjustment_Upper_price__c = 1;
            mcae2.Adjustment_Lower_price__c = 1;
            mcae2.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae2.Estimate_List_Price__c = 1000;
            mcae2.Check_Result__c = 'OK';
            insert new Maintenance_Contract_Asset_Estimate__c[] {mcae1, mcae2};
            Apexpages.currentPage().getParameters().put('copyid', contactEsti1.Id);
            Apexpages.currentPage().getParameters().put('completion', '3');
            SelectAssetEstimateVMController controller = new SelectAssetEstimateVMController();
            controller.init();
            controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller.estimate.Contract_Range__c = 2;
            controller.save();
        }
    }
    static testMethod void testApprovalProcess_01() {
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        u3.HR_Post__c='总裁';
        insert u3;
        system.runAs(u3) {
        ControllerUtil.EscapeNFM001Trigger = true;
        // 病院を作る
        Account hospital = new Account();
        hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
        hospital.Name = 'test hospital';
        insert hospital;
        // 戦略科室を得る
        List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
        // 診療科を作る
        Account dep = new Account();
        dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
        dep.Name = 'test dep';
        dep.ParentId = strategicDep[0].Id;
        dep.Department_Class__c = strategicDep[0].Id;
        dep.Hospital__c = hospital.Id;
        insert dep;
        // 製品を作る
        Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false);
        insert productA;
        // 価格表エントリを作成する
        PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
        entry.UnitPrice = 0;
        entry.IsActive = true;
        entry.UseStandardPrice = false;
        entry.CurrencyIsoCode = 'CNY';
        entry.Product2Id = productA.Id;
        insert entry;
        // 納入機器を作成する
        Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
        Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'耗材');
        Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'主机');
        Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'耗材');
        Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
        // 维修合同を作成する
        Maintenance_Contract__c contract = new Maintenance_Contract__c();
        contract.Name = 'tect contract';
        contract.Not_Upper_limit_reason__c = 'tect contract';
        contract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
        contract.Hospital__c = hospital.Id;
        contract.Department_Class__c = strategicDep[0].Id;
        contract.Department__c = dep.Id;
        contract.Service_Contract_Staff__c = u3.Id;
        contract.Payment_Plan_Sum_First__c = 1;
        insert contract;
        // 维修合同报价を作成する
        Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
            Name = 'contract estimate 1',
            RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
            Contract_Esti_Start_Date__c = Date.today(),
            Contract_Range__c = 2,
            Maintenance_Contract__c = contract.Id,
            Request_quotation_Amount__c = 1,
            EndUserType__c = '既有用户',
            mainTalksTime__c = 1,
            talksStartDate__c = Date.today(),
            Discount_reason__c = 'test',
            Improve_ConsumptionRate_Idea__c = 'test'
        );
        insert new Maintenance_Contract_Estimate__c[] {contactEsti1};
        Maintenance_Contract_Asset_Estimate__c mcae1 = new Maintenance_Contract_Asset_Estimate__c();
            mcae1.Asset__c = asset01.Id;
            mcae1.Adjustment_Upper_price__c = 1;
            mcae1.Adjustment_Lower_price__c = 1;
            mcae1.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae1.Estimate_List_Price__c = 1000;
            mcae1.Check_Result__c = 'OK';
            Maintenance_Contract_Asset_Estimate__c mcae2 = new Maintenance_Contract_Asset_Estimate__c();
            mcae2.Asset__c = asset01.Id;
            mcae2.Adjustment_Upper_price__c = 1;
            mcae2.Adjustment_Lower_price__c = 1;
            mcae2.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae2.Estimate_List_Price__c = 1000;
            mcae2.Check_Result__c = 'OK';
            insert new Maintenance_Contract_Asset_Estimate__c[] {mcae1, mcae2};
        // 新規
        Apexpages.currentPage().getParameters().put('id', contactEsti1.Id);
        SelectAssetEstimateVMController controller = new SelectAssetEstimateVMController();
        controller.init();
        controller.estimate.Contract_Esti_Start_Date__c = Date.today();
        controller.estimate.Contract_Range__c = 2;
        controller.unCheckedAssetsView[0][0].rec_CheckBox_c = true;
        controller.exchangeAsset();
        controller.checkedAssets[0].mcae.Check_Result__c = 'OK';
        controller.approvalProcess();
        // 提交待审批时,更新已填写申请状态
        List<Maintenance_Contract_Estimate__c> mcenew = [select id,ApprovalProcess_Status__c from Maintenance_Contract_Estimate__c where id = :contactEsti1.Id];
        System.assertEquals('已填写完并申请', mcenew[0].ApprovalProcess_Status__c);
        }
    }
    static testMethod void EditUnitTest() {
        //Test.startTest();
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        u3.HR_Post__c='总裁';
        insert u3;
        system.runAs(u3) {
            ControllerUtil.EscapeNFM001Trigger = true;
            //SelectAssetEstimateVMController controller = new SelectAssetEstimateVMController();
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false);
            insert productA;
            //// 価格表エントリを作成する
            //PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            //entry.UnitPrice = 0;
            //entry.IsActive = true;
            //entry.UseStandardPrice = false;
            //entry.CurrencyIsoCode = 'CNY';
            //entry.Product2Id = productA.Id;
            //insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'耗材');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'主机');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'耗材');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Not_Upper_limit_reason__c = 'tect contract';
            contract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            contract.Payment_Plan_Sum_First__c = 1;
            insert contract;
            // 维修合同报价を作成する
            Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 1',
                RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
                Contract_Esti_Start_Date__c = Date.today(),
                Contract_Range__c = 2,
                Maintenance_Contract__c = contract.Id,
                Request_quotation_Amount__c = 1,
                EndUserType__c = '既有用户',
                mainTalksTime__c = 1,
                talksStartDate__c = Date.today(),
                Discount_reason__c = 'test',
                Improve_ConsumptionRate_Idea__c = 'test'
            );
            Maintenance_Contract_Estimate__c contactEsti2 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 2',
                RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
                Contract_Esti_Start_Date__c = Date.today().addMonths(6),
                Contract_Range__c = 3,
                Maintenance_Contract__c = contract.Id,
                Request_quotation_Amount__c = 1,
                EndUserType__c = '既有用户',
                mainTalksTime__c = 1,
                talksStartDate__c = Date.today(),
                Discount_reason__c = 'test',
                Improve_ConsumptionRate_Idea__c = 'test'
            );
            insert new Maintenance_Contract_Estimate__c[] {contactEsti1, contactEsti2};
            System.Test.startTest();
            Apexpages.currentPage().getParameters().put('id', contactEsti1.Id);
            SelectAssetEstimateVMController controller = new SelectAssetEstimateVMController();
            controller.init();
            controller.text1 = 'S:Name';
            controller.cond1 = 'equals';
            controller.val1 = 'asset01,asset02';
            controller.searchBtn();
            controller.cond1 = 'equals';
            controller.val1 = 'asset02';
            controller.searchBtn();
            controller.cond1 = 'contains';
            controller.val1 = ' asset02';
            controller.searchBtn();
            controller.cond1 = 'notequals';
            controller.searchBtn();
            controller.cond1 = 'starts with';
            controller.searchBtn();
            Test.stopTest();
        }
    }
    // 补充test 实际联动
    static testMethod void testInit_04() {
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        u3.HR_Post__c='总裁';
        insert u3;
        system.runAs(u3) {
            Achievement_linkage__c oppMapping = new Achievement_linkage__c();
            oppMapping.Name = '01';
            oppMapping.Consumption_rate_Lower__c = 0;
            oppMapping.Consumption_rate_Upper__c = 50;                           // 重複してもエラーにはならない
            oppMapping.PriceCount_Lower__c  = -40;
            oppMapping.PriceCount_Upper__c  = -30;
            insert oppMapping;
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'耗材');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'主机');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Not_Upper_limit_reason__c = 'tect contract';
            contract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            insert contract;
            // 维修合同报价を作成する
            Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 1',
                RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
                Maintenance_Contract__c = contract.Id,
                Request_quotation_Amount__c = 1,
                EndUserType__c = '既有用户',
                mainTalksTime__c = 1,
                talksStartDate__c = Date.today(),
                Discount_reason__c = 'test',
                Improve_ConsumptionRate_Idea__c = 'test'
            );
            insert contactEsti1;
            Maintenance_Contract_Asset_Estimate__c mcae1 = new Maintenance_Contract_Asset_Estimate__c();
            mcae1.Asset__c = asset01.Id;
            mcae1.Adjustment_Upper_price__c = 1;
            mcae1.Adjustment_Lower_price__c = 1;
            mcae1.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae1.Estimate_List_Price__c = 1000;
            mcae1.Check_Result__c = 'OK';
            Maintenance_Contract_Asset_Estimate__c mcae2 = new Maintenance_Contract_Asset_Estimate__c();
            mcae2.Product_Manual__c = productA.Id;
            mcae2.Adjustment_Upper_price__c = 1;
            mcae2.Adjustment_Lower_price__c = 1;
            mcae2.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae2.Estimate_List_Price__c = 1000;
            mcae2.Check_Result__c = 'OK';
            insert new Maintenance_Contract_Asset_Estimate__c[] {mcae1, mcae2};
            Apexpages.currentPage().getParameters().put('id', contactEsti1.Id);
            SelectAssetEstimateVMController controller = new SelectAssetEstimateVMController();
            controller.init();
            controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller.estimate.Contract_Range__c = 2;
            controller.priceChangeReset();
            //controller.getChartData();
            //System.assertEquals(1, controller.dataList.size());
            controller.save();
            controller.changedAfterPrint = true;
            controller.checkChangedAfterPrint();
        }
    }
    static testMethod void testnotargetEstimateId_dataList() {
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        u3.HR_Post__c='总裁';
        insert u3;
        system.runAs(u3) {
            try {
                SelectAssetEstimateVMController controller001 = new SelectAssetEstimateVMController();
                controller001.init();
            } catch (Exception e) {
            }
            Achievement_linkage__c oppMapping = new Achievement_linkage__c();
            oppMapping.Name = '01';
            oppMapping.Consumption_rate_Lower__c = 0;
            oppMapping.Consumption_rate_Upper__c = 50;                           // 重複してもエラーにはならない
            oppMapping.PriceCount_Lower__c  = -40;
            oppMapping.PriceCount_Upper__c  = -30;
            insert oppMapping;
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'耗材');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'主机');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
            // 上一期维修合同
            Maintenance_Contract__c lastcontract = new Maintenance_Contract__c();
            lastcontract.Name = 'tect contract';
            lastcontract.Not_Upper_limit_reason__c = 'tect contract';
            lastcontract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
            lastcontract.Hospital__c = hospital.Id;
            lastcontract.Department_Class__c = strategicDep[0].Id;
            lastcontract.Department__c = dep.Id;
            lastcontract.Contract_Start_Date__c = Date.today().addMonths(-365);
            lastcontract.Contract_End_Date__c = Date.today().addMonths(1);
            lastcontract.Service_Contract_Staff__c = u3.Id;
            lastcontract.First_Estimate_Date__c = Date.today().addMonths(-1);
            lastcontract.First_contract_usage_Rate__c = 110;
            insert lastcontract;
            // 维修合同/保有设备を作成する
            Maintenance_Contract_Asset__c lastmca1 = new Maintenance_Contract_Asset__c();
            lastmca1.Asset__c = asset01.Id;
            lastmca1.Estimate_List_Price__c = 100;
            lastmca1.Estimate_Cost__c = 100;
            lastmca1.Maintenance_Contract__c = lastcontract.Id;
            insert new Maintenance_Contract_Asset__c[] {lastmca1};
            asset01.CurrentContract_F__c = lastcontract.Id;
            asset01.CurrentContract_F_asset__c = lastmca1.Id;
            update asset01;
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Not_Upper_limit_reason__c = 'tect contract';
            contract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            insert contract;
            // 维修合同/保有设备を作成する
            Maintenance_Contract_Asset__c mca1 = new Maintenance_Contract_Asset__c();
            mca1.Asset__c = asset01.Id;
            mca1.Estimate_List_Price__c = 100;
            mca1.Maintenance_Contract__c = contract.Id;
            Maintenance_Contract_Asset__c mca2 = new Maintenance_Contract_Asset__c();
            mca2.Asset__c = asset01.Id;
            mca2.Estimate_List_Price__c = 100;
            mca2.Maintenance_Contract__c = contract.Id;
            insert new Maintenance_Contract_Asset__c[] {mca1, mca2};
            // Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
            //     RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
            //     Name = 'contract estimate 1',
            //     Maintenance_Contract__c = contract.Id,
            //     Contract_Esti_Start_Date__c = Date.today().addDays(1),
            //     Request_quotation_Amount__c = 1,
            //     EndUserType__c = '既有用户',
            //     mainTalksTime__c = 1,
            //     talksStartDate__c = Date.today(),
            //     Discount_reason__c = 'test',
            //     Improve_ConsumptionRate_Idea__c = 'test'
            // );
            // insert contactEsti1;
            // Maintenance_Contract_Asset_Estimate__c mcae1 = new Maintenance_Contract_Asset_Estimate__c();
            // mcae1.Asset__c = asset01.Id;
            // mcae1.Adjustment_Upper_price__c = 1;
            // mcae1.Adjustment_Lower_price__c = 1;
            // mcae1.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            // mcae1.Estimate_List_Price__c = 1000;
            // mcae1.Check_Result__c = 'OK';
            // Maintenance_Contract_Asset_Estimate__c mcae2 = new Maintenance_Contract_Asset_Estimate__c();
            // mcae2.Asset__c = asset01.Id;
            // mcae2.Adjustment_Upper_price__c = 1;
            // mcae2.Adjustment_Lower_price__c = 1;
            // mcae2.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            // mcae2.Estimate_List_Price__c = 1000;
            // mcae2.Check_Result__c = 'OK';
            // insert new Maintenance_Contract_Asset_Estimate__c[] {mcae1, mcae2};
            Apexpages.currentPage().getParameters().put('mcid', contract.Id);
            SelectAssetEstimateVMController controller = new SelectAssetEstimateVMController();
            controller.init();
            // controller.firstPage();
            // controller.currPage = 3;
            // controller.previousPage();
            // controller.endPage();
            // controller.currPage = 200;
            // controller.nextPage();
            // controller.recordNumChange();
            // controller.getSaveBtnDisabled();
            // //controller.ComputeLTYRepair();
            // controller.cancel();
            // controller.saveAndCancel();
        }
    }
    static testMethod void testSyncEstimate() {
        ControllerUtil.EscapeNFM001Trigger = true;
        User u3 = new User();
        u3.LastName = '_サンブリッジ';
        u3.FirstName = 'う';
        u3.Alias = 'う';
        u3.Email = 'olympusTest03@sunbridge.com';
        u3.Username = 'olympusTest03@sunbridge.com';
        u3.CommunityNickname = 'う';
        u3.IsActive = true;
        u3.EmailEncodingKey = 'ISO-2022-JP';
        u3.TimeZoneSidKey = 'Asia/Tokyo';
        u3.LocaleSidKey = 'ja_JP';
        u3.LanguageLocaleKey = 'ja';
        u3.ProfileId = System.Label.ProfileId_SystemAdmin;
        u3.Job_Category__c = '销售服务';
        u3.Province__c = '北京市';
        u3.Use_Start_Date__c = Date.today().addMonths(-6);
        u3.HR_Post__c='总裁';
        insert u3;
        system.runAs(u3) {
            Achievement_linkage__c oppMapping = new Achievement_linkage__c();
            oppMapping.Name = '01';
            oppMapping.Consumption_rate_Lower__c = 0;
            oppMapping.Consumption_rate_Upper__c = 50;                           // 重複してもエラーにはならない
            oppMapping.PriceCount_Lower__c  = -40;
            oppMapping.PriceCount_Upper__c  = -30;
            insert oppMapping;
            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;
            // 戦略科室を得る
            List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;
            // 製品を作る
            Product2 productA = new Product2( Name='テスト商品', Maintenance_Price_Year__c = 12000, Manual_Entry__c = false);
            insert productA;
            // 価格表エントリを作成する
            PricebookEntry entry = new PricebookEntry( Pricebook2Id=pricebookId, Product2Id=productA.Id);
            entry.UnitPrice = 0;
            entry.IsActive = true;
            entry.UseStandardPrice = false;
            entry.CurrencyIsoCode = 'CNY';
            entry.Product2Id = productA.Id;
            insert entry;
            // 納入機器を作成する
            Asset asset01 = createAsset('asset01', dep.Id, strategicDep[0].Id, hospital.Id, '00001', productA.Id,'主机');
            Asset asset02 = createAsset('asset02', dep.Id, strategicDep[0].Id, hospital.Id, '00002', productA.Id,'主机');
            Asset asset03 = createAsset('asset03', dep.Id, strategicDep[0].Id, hospital.Id, '00003', productA.Id,'耗材');
            Asset asset04 = createAsset('asset04', dep.Id, strategicDep[0].Id, hospital.Id, '00004', productA.Id,'耗材');
            Asset asset05 = createAsset('asset05', dep.Id, strategicDep[0].Id, hospital.Id, '00005', productA.Id,'耗材');
            // 维修合同を作成する
            Maintenance_Contract__c contract = new Maintenance_Contract__c();
            contract.Name = 'tect contract';
            contract.Not_Upper_limit_reason__c = 'tect contract';
            contract.RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract__c' and DeveloperName = 'NewMaintenance_Contract'].id;
            contract.Hospital__c = hospital.Id;
            contract.Department_Class__c = strategicDep[0].Id;
            contract.Department__c = dep.Id;
            contract.Service_Contract_Staff__c = u3.Id;
            insert contract;
            // 维修合同报价を作成する
            Maintenance_Contract_Estimate__c contactEsti1 = new Maintenance_Contract_Estimate__c(
                Name = 'contract estimate 1',
                RecordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Maintenance_Contract_Estimate__c' and DeveloperName = 'NewMaintenance_Quote'].id,
                Maintenance_Contract__c = contract.Id,
                Request_quotation_Amount__c = 2,
                EndUserType__c = '既有用户',
                mainTalksTime__c = 1,
                talksStartDate__c = Date.today(),
                Discount_reason__c = 'test',
                Improve_ConsumptionRate_Idea__c = 'test',
                GuidePrice_Up__c = 1
            );
            insert contactEsti1;
            Maintenance_Contract_Asset_Estimate__c mcae1 = new Maintenance_Contract_Asset_Estimate__c();
            mcae1.Asset__c = asset01.Id;
            mcae1.Adjustment_Upper_price__c = 1;
            mcae1.Adjustment_Lower_price__c = 1;
            mcae1.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae1.Estimate_List_Price__c = 1000;
            mcae1.Check_Result__c = 'OK';
            Maintenance_Contract_Asset_Estimate__c mcae2 = new Maintenance_Contract_Asset_Estimate__c();
            mcae2.Product_Manual__c = productA.Id;
            mcae2.Adjustment_Upper_price__c = 1;
            mcae2.Adjustment_Lower_price__c = 1;
            mcae2.Maintenance_Contract_Estimate__c = contactEsti1.Id;
            mcae2.Estimate_List_Price__c = 1000;
            mcae2.Check_Result__c = 'OK';
            insert new Maintenance_Contract_Asset_Estimate__c[] {mcae1, mcae2};
            Apexpages.currentPage().getParameters().put('id', contactEsti1.Id);
            SelectAssetEstimateVMController controller = new SelectAssetEstimateVMController();
            controller.init();
            controller.estimate.Contract_Esti_Start_Date__c = Date.today();
            controller.estimate.Contract_Range__c = 2;
            controller.priceChangeReset();
            // controller.getChartData();
            // System.assertEquals(1, controller.dataList.size());
            controller.save();
            controller.changedAfterPrint = true;
            Test.StartTest();
            controller.syncEstimate(true,true);
            Test.stopTest();
        }
    }
}
force-app/main/default/classes/SelectAssetEstimateVMControllerTest.cls-meta.xml
New file
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>41.0</apiVersion>
    <status>Active</status>
</ApexClass>
force-app/main/default/pages/ChangeDealerApproval.page
New file
@@ -0,0 +1,119 @@
<apex:page controller="ChangeDealerApprovalController" showHeader="false" sidebar="false" id="allPage" action="{!init}" title="变更报价提交对象申请" lightningStylesheets="true">
    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
    <script type="text/javascript">
        window.onload = function initCheckValue() {
            resetDealer();
        }
        function resetDealer() {
            var target = j$(escapeVfId('allPage:allForm:changedInput:estimateTarget')).val();
            var obj = document.getElementById('allPage:allForm:changedInput:changedDealer');
            var obj_lkwgt = document.getElementById('allPage:allForm:changedInput:changedDealer_lkwgt');
            var lbObj = document.getElementById('changedLabel');
            if (target == '医院') {
                obj.style.display = "none";
                obj_lkwgt.style.display = "none";
                lbObj.style.display = "none";
            } else {
                obj.style.display = "block";
                obj_lkwgt.style.display = "block";
                lbObj.style.display = "block";
            }
        }
        function requiredCheck() {
            var target = j$(escapeVfId('allPage:allForm:changedInput:estimateTarget')).val();
            var etTarget = j$(escapeVfId('allPage:allForm:etTarget')).val();
            var dealer = j$(escapeVfId('allPage:allForm:dealer')).val();
            if (target != '医院') {
                var obj = j$(escapeVfId('allPage:allForm:changedInput:changedDealer')).val();
                if (obj == null || obj == '') {
                    alert('请输入变更后经销商名');
                    return false;
                }
                if (etTarget == target && obj == dealer) {
                    alert('报价提交对象没有变更!');
                    return false;
                }
            } else {
                if (etTarget == '医院') {
                    alert('报价提交对象没有变更!');
                    return false;
                }
            }
            if (confirm('一旦提交此记录,您将不能再编辑或调回,请确认是否继续?')) {
                submitApproval();
            } else {
                return false;
            }
        }
        function closedWin(isClosed) {
            if (isClosed == 1) {
                if (!confirm("请确认是否取消修改?")) {
                    return false;
                }
                window.opener.closeWin(1);
            } else {
                var errMsg = '{!submitErrorMsg}';
                if (errMsg == 'false') {
                    if (!confirm("已经提交待审批,是否关闭?")) {
                        return false;
                    }
                    window.opener.closeWin(2);
                } else {
                    return false;
                }
            }
        }
    </script>
    <apex:form id="allForm">
        <apex:inputHidden id="etTarget" value="{!estimate.Estimate_Target__c}"/>
        <apex:inputHidden id="dealer" value="{!estimate.Dealer__c}"/>
        <apex:actionFunction name="submitApproval" action="{!submitApproval}" rerender="allForm" oncomplete="closedWin();"/>
        <apex:pageBlock id="changedInput" title="" mode="edit" >
            <apex:pageMessages id="submitErrorMsg"/>
            <apex:pageBlockButtons >
                <!-- 取引の開始 -->
                <apex:commandButton value="提交待审批" onclick="requiredCheck(); return false;" disabled="{!ApprovalButDisabled}"/>
                <!-- キャンセル -->
                <apex:commandButton value="取消" onclick="closedWin(1); return false;" />
            </apex:pageBlockButtons>
            <div class="pbSubheader first tertiaryPalette">
                <h3>报价提交对象变更</h3>
            </div>
            <table style="padding-top:10px" width="100%">
                <tr>
                    <td width="5%"></td>
                    <td width="15%" style="text-align: right;">
                        <label>报价提交对象</label>
                    </td>
                    <td width="80%" style="text-align: left;">
                        <apex:selectList value="{!estimate.Changed_Estimate_Target__c}" multiselect="false" size="1" id="estimateTarget" onchange="resetDealer()" style="margin-left:15px;">
                            <apex:selectOptions value="{!etSelectOptions}" ></apex:selectOptions>
                            <!-- <apex:actionSupport event="onchange" onsubmit="" onbeforedomupdate="" action="{!depChange}" rerender="idCon">
                                <apex:param name="sltD" value="{!sltDep}"/>
                            </apex:actionSupport> -->
                        </apex:selectList>
                    </td>
                </tr>
                <tr>
                    <td width="5%"></td>
                    <td width="15%" style="text-align: right;">
                        <div id="changedLabel">经销商名</div>
                    </td>
                    <td width="80%" style="text-align: left;">
                        <apex:inputField value="{!estimate.Changed_Dealer__c}" id="changedDealer" style="margin-left:15px;"/>
                    </td>
                </tr>
            </table>
        </apex:pageBlock>
    </apex:form>
</apex:page>
force-app/main/default/pages/ChangeDealerApproval.page-meta.xml
New file
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>36.0</apiVersion>
    <availableInTouch>false</availableInTouch>
    <confirmationTokenRequired>false</confirmationTokenRequired>
    <label>ChangeDealerApproval</label>
</ApexPage>
force-app/main/default/pages/EquipmentRentalExtend.page
New file
@@ -0,0 +1,573 @@
<apex:page standardController="Rental_Apply__c" extensions="EquipmentRentalExtendController" showHeader="false" sidebar="false" id="allPage" action="{!init}" lightningStylesheets="true">
<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
<style>
    .dateFormat  {
        display: none;
    }
    .requiredBlock  {
        display: none;
    }
    .message {
      width: 1184px;
    }
    div#out_Div_R {
      position:relative;
      overflow: hidden;
      width: 1200px;
      margin-left: 915px;
    }
    div#in_Div_R {
      position:relative;
      overflow: auto;
      width: 754px;
      height: 451px;
      margin-left: 915px;
      margin-top: -451px;
    }
     div#out_Div_L {
      position:relative;
      overflow: hidden;
      width: 915px;
    }
    div#in_Div_L {
      position:relative;
      width: 915px;
      height: 451px;
    }
    div#in_Div_L td.dataCellBorder1 {
      border-width: 0px 0px 1px 1px;
      white-space: pre-line;
      word-break: break-all;
      word-wrap: break-word;
    }
    div#in_Div_L td.tdRed {
      background-color:red;
    }
    div#in_Div_L td.tdYellow {
      background-color:yellow;
    }
    div#in_Div_L td.tdGray {
      background-color:gray;
    }
    div#in_Div_L td.tdBlue {
      background-color:Cyan;
    }
    div#in_Div_L td.tdNormal {
      background-color:none;
    }
    div#in_Div_R td.dataCellBorder1 {
      border-width: 0px 0px 1px 1px;
      white-space: pre-line;
      word-break: break-all;
      word-wrap: break-word;
    }
    div#in_Div_R td.tdRed {
      background-color:red;
    }
    div#in_Div_R td.tdYellow {
      background-color:yellow;
    }
    div#in_Div_R td.tdGray {
      background-color:gray;
    }
    div#in_Div_R td.tdBlue {
      background-color:Cyan;
    }
    div#in_Div_R td.tdNormal {
      background-color:none;
    }
</style>
<script>
function searchJs() {
    blockme();
    searchfunc();
}
function searchsp1Js() {
    blockme();
    searchsp1func();
}
function searchsp2Js() {
    blockme();
    searchsp2func();
}
function searchsp3Js() {
    blockme();
    searchsp3func();
}
function searchsp4Js() {
    blockme();
    searchsp4func();
}
function setDatejs() {
    blockme();
    setDatefunc();
}
function closePage(){
    window.opener = window;
   var win = window.open("","_self");
   win.close();
}
function saveJs() {
    blockme();
    var flgReturn = j$(escapeVfId('allPage:allForm:returnIMFupdate')).value();
    if(flgReturn == 'Changed'){
        var rg=confirm("注意整单归还备品,否则将按现场转借记违规3点");
        if(rg){
            savefunc();
        }else{
            unblockUI();
        }
    }else{
        savefunc();
    }
}
//bp2
// function extendJs() {
//     blockme();
//     extendfunc();
// }
function sortTableJs(key) {
    blockme();
    sortTablefunc(key);
}
//bp2
// function setDisabled() {
//     var count = j$('input#count_hidden').value();
//     for (var i = 0; i < count; i++) {
//         var canChange = j$(escapeVfId('allPage:allForm:dataBlock:dataline:'+ i + ':canChange')).value();
//         if (canChange == 'false') {
//              j$(escapeVfId('allPage:allForm:dataBlock:dataline:'+ i + ':extend_day')).attr('disabled',true);
//              j$(escapeVfId('allPage:allForm:dataBlock:dataline:'+ i + ':extend_reason')).attr('disabled',true);
//         }
//     }
// }
function submitListener(e){
    var keynum = 0;
    if (window.event){
        keynum = window.event.keyCode;
    }
    else if (e.which){
        keynum = e.which;
    }
    // Here we check whether the Enter button was pressed
  // if (keynum == 13){
      // searchJs();
  // }
}
function ShowDetails(argument) {
    // body...
        var flgReturn = j$(escapeVfId('allPage:allForm:returnIMFupdate')).value();
        if(flgReturn == 'None'){
            j$(escapeVfId('allPage:allForm:returnIMFupdate')).val('Changed');
        }
}
var heightAjustment = 120;
var widthAjustment = 30;
function windowResize() {
    blockHeight = j$(window).innerHeight() - j$(escapeVfId('allPage:allForm:searchBlock')).height() - j$(escapeVfId('allPage:allForm:dataBlock:pageBlockButton1')).height() - j$('table#msgtable').height() - heightAjustment;
    sbwidth = scrollbarWidth();
    R_width = j$(escapeVfId('allPage:allForm:dataBlock')).width();
    blockWidth = 745;
    j$(escapeVfId('allPage:allForm:dataBlock')).css('height', blockHeight + 78 + 'px');
    j$('div#in_Div_L').css('width', blockWidth+170 + 'px');
    j$('div#out_Div_L').css('width', blockWidth+170 + 'px');
    j$('div#in_Div_L').css('height', blockHeight + 'px');
    //**************************************************************
    j$('div#in_Div_R').css('width', R_width-blockWidth- 190 + 'px');
    j$('div#out_Div_R').css('width', R_width-blockWidth-190  + 'px');
    j$('div#in_Div_R').css('height', blockHeight+ 20 + 'px');
    var titleHeight_L = j$('div#out_Div_L').height();
    var titleHeight_R = j$('div#out_Div_R').height();
    if(titleHeight_L >= titleHeight_R){
        j$('div#out_Div_R').css('height',(titleHeight_L)+'px');
        j$('div#out_Div_R').css('margin-top',(-titleHeight_L)+'px');
        j$('table#table_out_Div_R').css('height',(titleHeight_L)+'px');
    }else{
        j$('div#out_Div_L').css('height',titleHeight_R+'px');
    }
    // j$('div#in_Div_L').css('width', (745) + 'px');
    // j$('div#in_Div_R').css('width', (770) + 'px');
    j$('div#in_Div_R').css('margin-top', (-j$('div#in_Div_L').height()) + 'px');
    var number = j$('table#tableData_L').find('tr').length;
    if(number>0){
        for(var i = 0 ; i <number ;i++){
//bp2  EquipmentSetSRList2ページでやる
//             j$(escapeVfId('allPage:allForm:dataBlock:dataline_R:'+ i +':received_staff_mlktp')).attr('hidden','hidden');
            if(j$('tr#tableData_R_'+i).height() > j$('tr#tableData_L_'+i).height()){
                j$('tr#tableData_L_'+i).css('height',j$('tr#tableData_R_'+i).height());
            }else{
                j$('tr#tableData_R_'+i).css('height',j$('tr#tableData_L_'+i).height());
            }
        }
    }
    if (j$('table#tableData_R').height() > j$('div#in_Div_R').height()) {
        j$('div#in_Div_R').css('width', (R_width-blockWidth-190 + sbwidth) + 'px');
    } else {
       j$('div#out_Div_R').css('width', (R_width-blockWidth-190 + sbwidth) + 'px');
        j$('div#in_Div_R').css('width', (R_width-blockWidth-190 + sbwidth) + 'px');
    }
}
function checkAll() {
    j$(escapeVfId('checker')).prop('disabled', true);
    var productCount = j$('input#count_hidden').value();
    //var productCount = j$(escapeVfId('allPage:allForm:allBlock:equipmentSetDetailSection:equipmentSetDetailCnt')).value();
    if (j$(escapeVfId('checker')).attr('checked') == 'checked') {
        for (var i = 0; i < productCount; i++) {
            var disabled = j$(escapeVfId('allPage:allForm:dataBlock:dataline_L:'+ i + ':rowCheck')).prop('disabled');
            if (disabled == false) {
                j$(escapeVfId('allPage:allForm:dataBlock:dataline_L:'+ i + ':rowCheck')).attr('checked',true);
            }
        }
    } else {
        for (var i = 0; i < productCount; i++) {
            var disabled = j$(escapeVfId('allPage:allForm:dataBlock:dataline_L:'+ i + ':rowCheck')).prop('disabled');
            if (disabled == false) {
                j$(escapeVfId('allPage:allForm:dataBlock:dataline_L:'+ i + ':rowCheck')).attr('checked',false);
            }
        }
    }
    j$(escapeVfId('checker')).prop('disabled', false);
}
/*bp2  EquipmentSetSRList2ページでやる
// onComplete="unblockUI();hiddenBtn();" で使う
function hiddenBtn(){
    var cut =  j$('input#count_hidden').value();
    for(var i = 0;i<cut;i++){
        if( document.getElementById('allPage:allForm:dataBlock:dataline:'+i+':received_staff_mlktp')){
            document.getElementById('allPage:allForm:dataBlock:dataline:'+i+':received_staff_mlktp').style.display="none";
            document.getElementById('allPage:allForm:dataBlock:dataline:'+i+':received_staff_mlktp').style.width="75px";
            document.getElementById('allPage:allForm:dataBlock:dataline:'+i+':received_staff').style.width="75px";
        }
        if(document.getElementById('allPage:allForm:dataBlock:dataline:'+i+':Delivery_staff_mlktp')){
            document.getElementById('allPage:allForm:dataBlock:dataline:'+i+':Delivery_staff_mlktp').style.display="none";
            document.getElementById('allPage:allForm:dataBlock:dataline:'+i+':Delivery_staff_mlktp').style.width="75px";
            document.getElementById('allPage:allForm:dataBlock:dataline:'+i+':Delivery_staff').style.width="75px";
        }
    }
}
window.onload = function hiddenBtninit(){
     var cut =  j$('input#count_hidden').value();
    for(var i = 0;i<cut;i++){
        if( document.getElementById('allPage:allForm:dataBlock:dataline:'+i+':received_staff_mlktp')){
            document.getElementById('allPage:allForm:dataBlock:dataline:'+i+':received_staff_mlktp').style.display="none";
            document.getElementById('allPage:allForm:dataBlock:dataline:'+i+':received_staff_mlktp').style.width="75px";
            document.getElementById('allPage:allForm:dataBlock:dataline:'+i+':received_staff').style.width="75px";
        }
    if(document.getElementById('allPage:allForm:dataBlock:dataline:'+i+':Delivery_staff_mlktp')){
            document.getElementById('allPage:allForm:dataBlock:dataline:'+i+':Delivery_staff_mlktp').style.display="none";
            document.getElementById('allPage:allForm:dataBlock:dataline:'+i+':Delivery_staff_mlktp').style.width="75px";
            document.getElementById('allPage:allForm:dataBlock:dataline:'+i+':Delivery_staff').style.width="75px";
        }
    }
}
*/
window.onresize = windowResize;
</script>
    <apex:form id="allForm" onkeyup="submitListener(event);">
        <apex:actionFunction name="searchfunc" action="{!searchBtn}" rerender="allForm" onComplete="unblockUI();"></apex:actionFunction>
        <apex:actionFunction name="searchsp1func" action="{!searchsp1Btn}" rerender="allForm" onComplete="unblockUI();"></apex:actionFunction>
        <apex:actionFunction name="searchsp2func" action="{!searchsp2Btn}" rerender="allForm" onComplete="unblockUI();"></apex:actionFunction>
        <apex:actionFunction name="searchsp3func" action="{!searchsp3Btn}" rerender="allForm" onComplete="unblockUI();"></apex:actionFunction>
        <apex:actionFunction name="searchsp4func" action="{!searchsp4Btn}" rerender="allForm" onComplete="unblockUI();"></apex:actionFunction>
        <apex:actionFunction name="setDatefunc" action="{!setDate}" rerender="allForm" onComplete="unblockUI();"></apex:actionFunction>
        <apex:actionFunction name="savefunc" action="{!saveBtn}" rerender="allForm" onComplete="unblockUI();"></apex:actionFunction>
        <!-- 分页用 SWAG-B9UBDP start -->
        <apex:actionFunction name="recordNumChangeAction" action="{!recordNumChange}" rerender="allForm" oncomplete="unblockUI();">
        </apex:actionFunction>
        <!-- 分页用 SWAG-B9UBDP end -->
<!-- //bp2
        <apex:actionFunction name="extendfunc" action="{!extendBtn}" rerender="allForm" onComplete="unblockUI();"></apex:actionFunction>
-->
        <apex:actionFunction name="sortTablefunc" action="{!sortTable}" rerender="allForm" onComplete="unblockUI();">
            <apex:param name="firstParam" assignTo="{!sortKey}" value="" />
        </apex:actionFunction>
        <apex:inputHidden value="{!returnIMFupdate}" id="returnIMFupdate" />
        <apex:pageBlock id="searchBlock" title="检索">
            <apex:pageBlockButtons location="top">
                <table>
                    <tr>
                        <td align="right" style="padding-left: 1000px"><input type="button" value="关闭" onclick="closePage()" style="width:70px;"/></td>
                    </tr>
                </table>
            </apex:pageBlockButtons>
            <table style='width:1150px;'>
                <tr style="height:55px">
                    <td style="width:85px" align="right">选择条件</td>
                    <td style="width:85px" align="right"><apex:selectList value="{!text1}" id="text1" size="1" style="width:80px"><apex:selectOptions value="{!textOpts}"/></apex:selectList></td>
                    <td style="width:85px" align="center"><apex:selectList value="{!cond1}" id="cond1" size="1" style="width:80px"><apex:selectOptions value="{!equalOpts}"/></apex:selectList></td>
                    <td style="width:95px" align="left"><apex:inputText value="{!val1}" id="val1" style="width:100px;"/></td>
                    <td style="width:85px" align="right">所有者</td>
                    <td style="width:120px" align="left"><apex:inputText value="{!ownerSearch}" style="width:100px;" /></td>
                    <td style="width:135px" align="center"><input type="button" value="借出中全部" onclick="searchsp1Js();" style="width:130px"/></td>
                    <td style="width:135px" align="center"><input type="button" value="超过中" onclick="searchsp2Js();" style="width:130px"/></td>
                    <td style="width:135px" align="center"><input type="button" value="1周以内回收预定" onclick="searchsp3Js();" style="width:130px"/></td>
                    <td style="width:135px" align="center"><input type="button" value="全部" onclick="searchsp4Js();" style="width:130px"/></td>
                </tr>
                <tr>
                    <td align="right" colspan="2">{!$ObjectType.Rental_Apply__c.fields.Demo_purpose1__c.label}&nbsp;<apex:inputField value="{!searchCondition.Demo_purpose1__c}"/></td>
                    <td align="center" colspan="4">
                        {!$ObjectType.Rental_Apply_Equipment_Set__c.fields.Final_reply_day__c.label}
                        &nbsp;<apex:inputField style="width:115px" value="{!finalDayFrom.Birth_Date__c}"/>
                        &nbsp;~
                        &nbsp;<apex:inputField style="width:115px" value="{!finalDayTo.Birth_Date__c}"/>
                    </td>
                    <td align="center"><input type="button" value="检索" onclick="searchJs();" style="width:130px;font-weight:bold"/></td>
                    <td></td>
                    <td></td>
                    <!-- 20210628 ljh update SFDC-C4BBFH  -->
                    <td style="width:135px" align="center"><!-- <input type="button" value="PDF" onclick="alert('开发中');" style="width:130px"/> --></td>
                </tr>
            </table>
        </apex:pageBlock>
        <apex:pageBlock id="dataBlock" title="结果">
            <apex:pageBlockButtons location="top" id="pageBlockButton1">
                <input type="button" value="保存" onclick="saveJs();" style="width:80px;background-color:red;height:22px;margin-right: 20px;margin-top: 5px;"/>
                     <!-- 分页用 SWAG-B9UBDP start -->
                    <table align="right" style="width: 700px;">
                        <tr>
                            <td>{!(currPage-1)*selctRecordNum}&nbsp;-&nbsp;{!IF(currPage*selctRecordNum > totalRecords, totalRecords, currPage*selctRecordNum)}</td>
                            <td>&nbsp;&nbsp;共{!totalRecords}个</td>
                            <td align="right" width="150px">显示
                                <apex:selectList value="{!selRecordOption}" id="selRecordOption" size="1" onchange="blockme();recordNumChangeAction();" disabled="{!IF(totalRecords<10,true,false)}"><apex:selectOptions value="{!recordNum}"/></apex:selectList>条记录
                            </td>
                            <td align="right" width="55px">第{!currPage}页</td>
                            <td align="right" width="45px">
                                <apex:commandLink action="{!firstPage}" value="首页" id="firstPg" onclick="blockme();" oncomplete="unblockUI();" reRender="allForm" style="{!IF(currPage==1,'display: none;','')}color: blue;"/>
                                <apex:outputText value="首页" style="{!IF(currPage!=1,'display: none;','')}color: gray;"></apex:outputText>
                            </td>
                            <td align="right" width="55px">
                                <apex:commandLink action="{!previousPage}" value="上一页" id="previous" onclick="blockme();" oncomplete="unblockUI();" reRender="allForm" style="{!IF(currPage==1,'display: none;','')}color: blue;"/>
                                <apex:outputText value="上一页" style="{!IF(currPage!=1,'display: none;','')}color: gray;"></apex:outputText>
                            </td>
                            <td width="3px"></td>
                            <td align="left" width="55px">
                                <!-- HWAG-B4R3SS  START 20181026-->
                                <apex:commandLink action="{!nextPage}" value="下一页" id="next" onclick="blockme();" oncomplete="unblockUI();" reRender="allForm" style="{!IF(totalPage==currPage ||totalPage == 0,'display: none;','')}color: blue;"/>
                                <apex:outputText value="下一页" style="{!IF(totalPage!=currPage && totalPage != 0,'display: none;','')}color: gray;"></apex:outputText>
                            </td>
                            <td align="left" width="45px">
                                <apex:commandLink action="{!endPage}" value="尾页" id="endPg" onclick="blockme();" oncomplete="unblockUI();" reRender="allForm" style="{!IF(totalPage==currPage||totalPage == 0,'display: none;','')}color: blue;"/>
                                <apex:outputText value="尾页" style="{!IF(totalPage!=currPage
                                    && totalPage != 0,'display: none;','')}color: gray;"></apex:outputText>
                            </td>
                            <!-- HWAG-B4R3SS  END 20181026-->
                            <td align="left">共{!totalPage}页</td>
                        </tr>
                    </table>
                     <!-- 分页用 SWAG-B9UBDP end -->
               <!--  <input type="button" value="延长申请" onclick="extendJs();" style="width:80px;background-color:red;height:22px"/> -->
            </apex:pageBlockButtons>
            <input type="hidden" id="count_hidden" value="{!raesInfoListSize}"/>
<!--             <table>
                <tr>
                    <td style="width:20px"></td>
                    <td style="width:100px" align="right">{!$ObjectType.Rental_Apply_Equipment_Set__c.fields.Request_extend_day__c.label}</td>
                    <td style="width:100px" align="left"><apex:inputField value="{!finalDayFrom.Request_extend_day__c}"/></td>
                    <td style="width:100px" align="right">{!$ObjectType.Rental_Apply_Equipment_Set__c.fields.Extend_request_reason__c.label}</td>
                    <td style="width:100px" align="left"><apex:inputField value="{!finalDayFrom.Extend_request_reason__c}"/></td>
                    <td style="width:50px"></td>
                    <td style="width:100px" align="right"><input type="button" value="适用" onclick="setDatejs();" style="width:80px"/></td>
                    <td style="width:100px" align="left"><input type="button" value="保存" onclick="saveJs();" style="width:80px;background-color: red"/></td>
                </tr>
            </table> -->
            <table id="msgtable">
                <tr>
                    <td>
                        <apex:outputPanel id="message">
                            <apex:pageMessages />
                        </apex:outputPanel>
                    </td>
                </tr>
            </table>
            <div id="out_Div_L">
                <table class="list" border="1" style="border-collapse: collapse;table-layout:fixed;border-bottom-width: 0px;border-spacing:0;width:915px;">
                    <tr style="background-color:#DCDCDC;height: 50px;" class="headerRow">
                        <td style="width:20px" align="center">
                            <input type='checkbox' onClick='checkAll()' id='checker'/>
                        </td>
                        <td style="width:110px" align="center">
                            <a href="#" onclick="sortTableJs('0');return false;" style="text-decoration: underline;">{!$ObjectType.Rental_Apply__c.fields.Name.label}</a> {!sortOrder[0]}
                        </td>
                        <td style="width:60px;white-space:pre-line;word-break:break-all;word-wrap:break-word;" align="center">
                            <a href="#" onclick="sortTableJs('1');return false;" style="text-decoration: underline;">{!$ObjectType.Rental_Apply_Equipment_Set__c.fields.RAES_Status__c.label}</a> {!sortOrder[1]}
                        </td>
                        <!-- 备品出借担当 -->
                        <td style="width:110px" align="center">{!$ObjectType.Rental_Apply__c.fields.Person_In_Charge__c.label}</td>
                        <!-- 医院名 -->
                        <td style="width:100px" align="center">
                            <a href="#" onclick="sortTableJs('4');return false;" style="text-decoration: underline;">{!$ObjectType.Account.fields.Hospital_Name__c.label}</a> {!sortOrder[4]}
                        </td>
                        <td style="width:110px" align="center">{!$ObjectType.Fixture_Set__c.fields.Name.label}</td>
                        <td style="width:100px" align="center">
                            <a href="#" onclick="sortTableJs('3');return false;" style="text-decoration: underline;">{!$ObjectType.Rental_Apply_Equipment_Set__c.fields.First_RAESD_Model_No_F__c.label}</a> {!sortOrder[3]}
                        </td>
                        <td style="width:85px" align="center">{!$ObjectType.Rental_Apply_Equipment_Set__c.fields.SerialNumber_F__c.label}</td>
                        <td style="width:85px" align="center">记录类型</td>
                    </tr>
                </table>
            </div>
            <div id="out_Div_R" >
                <table class="list" border="1" style="border-collapse: collapse;table-layout:fixed;border-bottom-width: 0px;border-spacing:0;width:660px;" id="table_out_Div_R">
                    <tr style="background-color:#DCDCDC;" class="headerRow">
                        <td style="width:85px" align="center">
                            <a href="#" onclick="sortTableJs('6');return false;" style="text-decoration: underline;">{!$ObjectType.Rental_Apply_Equipment_Set__c.fields.Demo_purpose1__c.label}</a> {!sortOrder[6]}
                        </td>
                        <td style="width:90px" align="center">
                            <a href="#" onclick="sortTableJs('2');return false;" style="text-decoration: underline;">{!$ObjectType.Rental_Apply_Equipment_Set__c.fields.Demo_purpose2__c.label}</a> {!sortOrder[2]}
                        </td>
                        <td style="width:100px" align="center">{!$ObjectType.Fixture_Set__c.fields.Loaner_name__c.label}</td>
                        <td style="width:164px" align="center">附属品明细</td>
                        <!-- <td style="width:80px" align="center">{!$ObjectType.Rental_Apply__c.fields.Rental_Start_Date__c.label}</td>
                        <td style="width:80px" align="center">{!$ObjectType.Rental_Apply__c.fields.Rental_End_Date__c.label}</td> -->
<!-- *************************insert 20160720 增加发货信息 趙徳芳 End*************************** -->
                        <td style="width:120px" align="center">{!$ObjectType.Rental_Apply_Equipment_Set__c.fields.Received_Confirm__c.label}</td>
                        <td style="width:140px" align="center">{!$ObjectType.Rental_Apply_Equipment_Set__c.fields.Received_ng_detail__c.label}</td>
                        <td style="width:80px" align="center">
                            <a href="#" onclick="sortTableJs('5');return false;" style="text-decoration: underline;">{!$ObjectType.Rental_Apply_Equipment_Set__c.fields.Final_reply_day__c.label}</a> {!sortOrder[5]}
                        </td>
                        <td style="width:80px" align="center">{!$ObjectType.Rental_Apply_Equipment_Set__c.fields.Bollow_Date__c.label}</td>
                        <td style="width:80px" align="center">违规理由</td>
<!-- *************************Delete 20160602 No.153 趙徳芳 Start************************* -->
                        <!-- <td style="width:90px" align="center">{!$ObjectType.Rental_Apply_Equipment_Set__c.fields.Request_extend_day__c.label}</td> -->
                       <!--  <td style="width:140px" align="center">{!$ObjectType.Rental_Apply_Equipment_Set__c.fields.Extend_request_reason__c.label}</td> -->
<!-- *************************Delete 20160602 No.153 趙徳芳 End*************************** -->
<!-- //bp2  EquipmentSetSRList2ページでやる                 <td style="width:80px" align="center">{!$ObjectType.Rental_Apply_Equipment_Set__c.fields.Return_delivery_company2__c.label}</td>
                        <td style="width:80px" align="center">{!$ObjectType.Rental_Apply_Equipment_Set__c.fields.Return_Fedex_number2__c.label}</td>
                        <td style="width:80px" align="center">{!$ObjectType.Rental_Apply_Equipment_Set__c.fields.Return_Distributor_method2__c.label}</td>
                        <td style="width:195px" align="center">{!$ObjectType.Rental_Apply_Equipment_Set__c.fields.Received_confirmation_staff2__c.label}</td>
-->
                        <!-- *************************insert 20160720 增加发货信息 趙徳芳 Start************************* -->
                        <!-- <td style="width:110px" align="center"> -->
                            <!-- <a href="#" onclick="sortTableJs('7');return false;" style="text-decoration: underline;">{!$ObjectType.Rental_Apply_Equipment_Set__c.fields.Bollow_Date__c.label}</a> {!sortOrder[7]} -->
                        <!-- </td> -->
                        <!-- 发货运输单 -->
                        <td style="width:110px" align="center">
                            <a href="#" onclick="sortTableJs('7');return false;" style="text-decoration: underline;">{!$ObjectType.Rental_Apply_Equipment_Set_Detail__c.fields.DeliverySlip__c.label}</a> {!sortOrder[7]}
                        </td>
                        <!-- 回寄运输单 -->
                        <td style="width:110px" align="center">
                            <a href="#" onclick="sortTableJs('7');return false;" style="text-decoration: underline;">{!$ObjectType.Rental_Apply_Equipment_Set_Detail__c.fields.Return_DeliverySlip__c.label}</a> {!sortOrder[7]}
                        </td>
<!-- //bp2
                        <td style="width:110px" align="center">{!$ObjectType.Rental_Apply_Equipment_Set__c.fields.delivery_company__c.label}</td>
                        <td style="width:80px" align="center">{!$ObjectType.Rental_Apply_Equipment_Set__c.fields.Fedex_number__c.label}</td>
                        <td style="width:110px" align="center">{!$ObjectType.Rental_Apply_Equipment_Set__c.fields.Distributor_method__c.label}</td>
                        <td style="width:100px" align="center">{!$ObjectType.Rental_Apply_Equipment_Set__c.fields.Return_to_wh_staff__c.label}</td>
-->
                    </tr>
                </table>
            </div>
            <div id="in_Div_L" style="overflow:hidden">
                <table class="list" border="1" style="border-collapse: collapse;table-layout:fixed;border-bottom-width: 0px;border-spacing:0;width:915px;" id="tableData_L">
                    <apex:variable value="{!0}" var="Cnt" />
                    <apex:repeat id="dataline_L" value="{!raesInfoListList[currPage-1]}" var="info">
                    <tr class="dataRow" id="tableData_L_{!Cnt}" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
                        <td class="dataCellBorder1" style="width:20px" align="center"><apex:inputCheckbox value="{!info.check}" id="rowCheck" disabled="{!!info.canChange}"/><apex:inputHidden id="canChange" value="{!info.canChange}"/></td>
                        <td class="dataCellBorder1 td{!info.status}" style="width:110px;" align="left"><apex:outputField value="{!info.raes.Rental_Apply__c}"/></td>
                        <td class="dataCellBorder1" style="width:60px" align="left"><apex:outputField value="{!info.raes.RAES_Status__c}"/></td>
                        <td class="dataCellBorder1" align="left" style="width:110px"><apex:outputText value="{!info.rentalPerson}"/></td>
                        <td class="dataCellBorder1" align="left" style="width:100px"><apex:outputText value="{!info.hpName}"/></td>
                        <td class="dataCellBorder1" style="width:110px" align="left"><apex:outputField value="{!info.raes.Fixture_Set__c}"/></td>
                        <td class="dataCellBorder1" style="width:100px" align="left"><apex:outputText value="{!info.esCode}"/></td>
                        <td class="dataCellBorder1" style="width:85px" align="left"><apex:outputText value="{!info.serialNumber}"/></td>
                        <td class="dataCellBorder1" style="width:85px" align="left"><apex:outputText value="{!info.recordTypeName}"/></td>
                        </tr>
                        <apex:variable value="{!Cnt+1}" var="Cnt" />
                        </apex:repeat>
                    </table>
                </div>
                <div id="in_Div_R" style="overflow:auto;">
                <table class="list" border="1" style="border-collapse: collapse;table-layout:fixed;border-bottom-width: 0px;border-spacing:0;width:660px;" id="tableData_R">
                    <apex:variable value="{!0}" var="Cnt_R" />
                    <apex:repeat id="dataline_R" value="{!raesInfoListList[currPage-1]}" var="info">
                    <tr id="tableData_R_{!Cnt_R}" class="dataRow" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}" >
                        <td class="dataCellBorder1" style="width:85px" align="left"><apex:outputField value="{!info.raes.Demo_purpose1__c}"/></td>
                        <td class="dataCellBorder1" style="width:90px" align="left"><apex:outputField value="{!info.raes.Demo_purpose2__c}"/></td>
                        <td class="dataCellBorder1" style="width:100px" align="left"><apex:outputText value="{!info.esName}"/></td>
                        <!-- <td class="dataCellBorder1" style="width:80px" align="left"><apex:outputField value="{!info.raes.Rental_Apply__r.Rental_Start_Date__c}"/></td>
                        <td class="dataCellBorder1" style="width:80px" align="left"><apex:outputField value="{!info.raes.Rental_Apply__r.Rental_End_Date__c}"/></td> -->
                        <td class="dataCellBorder1" style="width:164px" align="left"><apex:outputText value="{!info.DetailsLine}"/></td>
                        <td class="dataCellBorder1" style="width:120px" align="left">
                        <apex:inputField rendered="{!IF(((info.raes.Received_Confirm__c=='默认签收-OK'&&isStockUser)||info.raes.Received_Confirm__c!='默认签收-OK') && info.raes.Wei_loaner_arranged__c = 0,true,false)}" value="{!info.raes.Received_Confirm__c}"/>
                        <apex:outputField rendered="{!IF((info.raes.Received_Confirm__c=='默认签收-OK'&&isStockUser==false) || info.raes.Wei_loaner_arranged__c > 0,true,false)}" value="{!info.raes.Received_Confirm__c}"/>
                        </td>
                        <td class="dataCellBorder1" style="width:140px" align="left">
                        <apex:inputField style="width:95%" rendered="{!IF(((info.raes.Received_Confirm__c=='默认签收-OK'&&isStockUser)||info.raes.Received_Confirm__c!='默认签收-OK') && info.raes.Wei_loaner_arranged__c = 0,true,false)}" value="{!info.raes.Received_ng_detail__c}"/>
                        <apex:outputField style="width:95%" rendered="{!IF((info.raes.Received_Confirm__c=='默认签收-OK'&&isStockUser==false) || info.raes.Wei_loaner_arranged__c > 0,true,false)}" value="{!info.raes.Received_ng_detail__c}"/>
                        <!-- <apex:inputField value="{!info.raes.Received_ng_detail__c}" style="width:95%"/> -->
                        </td>
                        <td class="dataCellBorder1" style="width:80px" align="left"><apex:outputField value="{!info.raes.Final_reply_day__c}"/></td>
                        <td class="dataCellBorder1" style="width:80px" align="left"><apex:outputField value="{!info.raes.Bollow_Date__c}"/></td>
                        <td class="dataCellBorder1" style="width:80px" align="left"><apex:outputText value="{!info.FoulReasonStr}"/></td>
<!-- *************************Delete 20160602 No.153 趙徳芳 Start************************* -->
                        <!-- <td class="dataCellBorder1" style="width:90px" align="left"><apex:inputField id="extend_day" value="{!info.raes.Request_extend_day__c}"/></td> -->
                        <!-- <td class="dataCellBorder1" style="width:140px" align="left"><apex:inputField id="extend_reason" value="{!info.raes.Extend_request_reason__c}" style="width:95%"/></td> -->
<!-- *************************Delete 20160602 No.153 趙徳芳 End*************************** -->
<!-- //bp2  EquipmentSetSRList2ページでやる
                        <td class="dataCellBorder1" style="width:80px" align="left"><apex:inputField onchange="ShowDetails(this)" id="return_company" value="{!info.raes.Return_delivery_company2__c}" /></td>
                        <td class="dataCellBorder1" style="width:80px" align="left"><apex:inputField onchange="ShowDetails(this)" id="return_Fedex" value="{!info.raes.Return_Fedex_number2__c}" style="width:95%"/></td>
                        <td class="dataCellBorder1" style="width:80px" align="left"><apex:inputField onchange="ShowDetails(this)" id="return_method" value="{!info.raes.Return_Distributor_method2__c}"/></td>
                        <td class="dataCellBorder1" style="width:200px" align="left"><apex:inputField id="received_staff" value="{!info.raes.Received_confirmation_staff2__c}" style="width:75%"/></td>
 -->
                        <script type="text/javascript">
                        </script>
                        <!-- <td class="dataCellBorder1" style="width:110px" align="left"><apex:outputField value="{!info.raes.Bollow_Date__c}"/></td> -->
                        <td class="dataCellBorder1" style="width:110px" align="left"><apex:outputField value="{!info.raes.First_RAESD__r.DeliverySlip__c}"/></td>
                        <td class="dataCellBorder1" style="width:110px" align="left"><apex:outputField value="{!info.raes.First_RAESD__r.Return_DeliverySlip__c}"/></td>
<!-- //bp2
                        <td class="dataCellBorder1" style="width:110px" align="left"><apex:outputField id="Delivery_company" value="{!info.raes.delivery_company__c}" style="width:95%"/></td>
                        <td class="dataCellBorder1" style="width:80px" align="left"><apex:outputField id="Delivery_Fedex" value="{!info.raes.Fedex_number__c}" style="width:95%"/></td>
                        <td class="dataCellBorder1" style="width:110px" align="left"><apex:outputField id="Delivery_method" value="{!info.raes.Distributor_method__c}" style="width:95%"/></td>
                        <td class="dataCellBorder1" style="width:100px" align="left"><apex:outputField id="Delivery_staff" value="{!info.raes.Return_to_wh_staff__c}" style="width:75%"/></td>
-->
                    </tr>
                    <apex:variable value="{!Cnt_R+1}" var="Cnt_R" />
                    </apex:repeat>
                </table>
            </div>
            <script>
            j$('div#in_Div_R').scroll(function() {
        j$('div#out_Div_R').scrollLeft(j$(this).scrollLeft());
    });
           j$('div#in_Div_R').scroll(function() {
            j$('div#in_Div_L').scrollTop(j$(this).scrollTop());
    });
//bp2                setDisabled();
                windowResize();
            </script>
        </apex:pageBlock>
    </apex:form>
</apex:page>
force-app/main/default/pages/EquipmentRentalExtend.page-meta.xml
New file
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>40.0</apiVersion>
    <availableInTouch>false</availableInTouch>
    <confirmationTokenRequired>false</confirmationTokenRequired>
    <label>EquipmentRentalExtend</label>
</ApexPage>
force-app/main/default/pages/ListShip.page
New file
@@ -0,0 +1,315 @@
<apex:page standardController="Account" extensions="ListShipController" showHeader="false" sidebar="false" action="{!init}" id="Page" readOnly="true" lightningStylesheets="true">
<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
<apex:includeScript value="{!URLFOR($Resource.jqueryTableFix)}"/>
<script type='text/javascript'>
function searchJs() {
    blockme();
    searchBtn();
}
function submitListener(e){
    var keynum = 0;
    if (window.event){
        keynum = window.event.keyCode;
    }
    else if (e.which){
        keynum = e.which;
    }
    // Here we check whether the Enter button was pressed
    if (keynum == 13){
        searchJs();
    }
}
</script>
<style>
.dateFormat  {
    display: none;
}
</style>
    <apex:pageBlock id="searchAsset">
        <apex:form id="Form" onkeyup="submitListener(event)">
            <apex:actionFunction name="searchBtn" action="{!searchBtn}" rerender="searchAsset" onComplete="unblockUI();"></apex:actionFunction>
            <apex:pageMessages />
            <table style="border: 0; border-collapse: collapse;" id="searchTbl1">
                <tr>
                    <th style="text-align:right; width:50px;">条件:</th>
                    <th style="text-align:right; width:60px;">本部</th>
                    <td style="text-align:left; width:75px;"><apex:selectList value="{!salesDept}" size="1" style="width:95%"><apex:selectOptions value="{!salesDeptOpts}"/></apex:selectList></td>
                    <th style="text-align:right; width:60px;">省</th>
                    <td style="text-align:left; width:75px;"><apex:selectList value="{!area}" size="1" style="width:95%"><apex:selectOptions value="{!areaOpts}"/></apex:selectList></td>
                    <th style="text-align:right; width:60px;">医院</th>
                    <td style="text-align:left; width:75px;"><apex:inputText value="{!enduser}" style="width:95%;"/></td>
                    <th style="text-align:right; width:60px;">{!$ObjectType.Ship__c.fields.Shipping_date__c.Label}</th>
                    <td style="text-align:left; width:75px;"><apex:inputField value="{!dateFrom.Birth_Date__c}" style="width:95%;"/></td>
                    <td style="text-align:left; width:10px;">~</td>
                    <td style="text-align:left; width:75px;"><apex:inputField value="{!dateTo.Birth_Date__c}" style="width:95%;"/></td>
                </tr>
            </table>
            <table style="width:100%; border: 0; border-collapse: collapse; margin: 10px 0 10px 0; " id="searchTbl2">
                <tr>
                    <th style="width:50px;">&nbsp;</th>
                    <th style="text-align:right; width:60px;">{!$ObjectType.Ship__c.fields.Category2__c.Label}</th>
                    <td style="text-align:left; width:75px;"><apex:selectList value="{!category2}" size="1" style="width:95%"><apex:selectOptions value="{!category2Opts}"/></apex:selectList></td>
                    <th style="text-align:right; width:60px;">{!$ObjectType.Ship__c.fields.Category3__c.Label}</th>
                    <td style="text-align:left; width:75px;"><apex:inputText value="{!category3}" style="width:95%;"/></td>
                    <th style="text-align:right; width:60px;">{!$ObjectType.Ship__c.fields.Category4__c.Label}</th>
                    <td style="text-align:left; width:75px;"><apex:inputText value="{!category4}" style="width:95%;"/></td>
                    <th style="text-align:right; width:60px;">{!$ObjectType.Ship__c.fields.Category5__c.Label}</th>
                    <td style="text-align:left; width:75px;"><apex:inputText value="{!category5}" style="width:95%;"/></td>
                    <th style="text-align:right; width:60px;">产品型号</th>
                    <td style="text-align:left; width:75px;"><apex:inputText value="{!modelNo}" style="width:95%;"/></td>
                    <td style="width:40px;">&nbsp;</td>
                    <td style="text-align:left;"><apex:commandButton value="适用" style="width:60px;" reRender="Page" onclick="searchJs();"/></td>
                </tr>
            </table>
            <table style="border: 0; border-collapse: collapse;margin-bottom: 10px;" id="groupbyTbl">
                <tr>
                    <th style="text-align:right; width:60px;">行项目:</th>
                    <td style="text-align:left;"><apex:inputCheckbox id="isSalesDept" value="{!isSalesDept}" disabled="true"></apex:inputCheckbox><apex:outputLabel value="本部" for="isSalesDept"/></td>
                    <td style="text-align:left;"><apex:inputCheckbox id="isArea" value="{!isArea}"></apex:inputCheckbox><apex:outputLabel value="省" for="isArea"/></td>
                    <td style="text-align:left;"><apex:inputCheckbox id="isEnduser" value="{!isEnduser}"></apex:inputCheckbox><apex:outputLabel value="医院" for="isEnduser"/></td>
                    <td style="text-align:left;"><apex:inputCheckbox id="isCategory2" value="{!isCategory2}"></apex:inputCheckbox><apex:outputLabel value="{!$ObjectType.Product2.fields.Category2__c.Label}" for="isCategory2"/></td>
                    <td style="text-align:left;"><apex:inputCheckbox id="isCategory3" value="{!isCategory3}"></apex:inputCheckbox><apex:outputLabel value="{!$ObjectType.Product2.fields.Category3__c.Label}" for="isCategory3"/></td>
                    <td style="text-align:left;"><apex:inputCheckbox id="isCategory4" value="{!isCategory4}"></apex:inputCheckbox><apex:outputLabel value="{!$ObjectType.Product2.fields.Category4__c.Label}" for="isCategory4"/></td>
                    <td style="text-align:left;"><apex:inputCheckbox id="isCategory5" value="{!isCategory5}"></apex:inputCheckbox><apex:outputLabel value="{!$ObjectType.Product2.fields.Category5__c.Label}" for="isCategory5"/></td>
                    <td style="text-align:left;"><apex:inputCheckbox id="isProductCode" value="{!isProductCode}"></apex:inputCheckbox><apex:outputLabel value="产品型号" for="isProductCode"/></td><!-- {!$ObjectType.Product2.fields.Asset_Model_No__c.Label} -->
                    <th style="text-align:right; width:70px;">列项目:</th>
                    <td style="text-align:left;"><apex:inputCheckbox id="isShowMonth" value="{!isShowMonth}"></apex:inputCheckbox><apex:outputLabel value="年度月" for="isShowMonth"/></td>
                    <td style="text-align:left;"><apex:inputCheckbox id="isShowWeek" value="{!isShowWeek}"></apex:inputCheckbox><apex:outputLabel value="周" for="isShowWeek"/></td>
                    <th style="text-align:right; width:80px;">汇总字段:</th>
                    <td style="text-align:left;"><apex:inputCheckbox id="isShowSumQty" value="{!isShowSumQty}"></apex:inputCheckbox><apex:outputLabel value="数量" for="isShowSumQty"/></td>
                    <td style="text-align:left;"><apex:inputCheckbox id="isShowSumAmount" value="{!isShowSumAmount}"></apex:inputCheckbox><apex:outputLabel value="売上金額" for="isShowSumAmount"/></td>
                </tr>
            </table>
        </apex:form>
        <table style="border-collapse: collapse;" id="detailtbl">
<apex:outputPanel rendered="{!isShowMonth}" layout="none">
            <tr>
    <apex:outputPanel rendered="{!IF(totalLine.ttlColspan > 1, true, false)}" layout="none">
                <th colspan="{!totalLine.ttlColspan - 1}"></th>
    </apex:outputPanel>
                <th style="text-align:center;border: solid 1px;">年度月</th>
    <apex:repeat value="{!headerYrCols}" var="yr">
                <th colspan="{!headerYrColspan[yr]}" style="text-align:center;border: solid 1px;">{!yr}</th>
    </apex:repeat>
    <apex:outputPanel rendered="{!Not(isShowWeek)}" layout="none">
                <th colspan="{!aggregateColspan}" style="text-align:center;border: solid 1px;">合计</th>
    </apex:outputPanel>
            </tr>
</apex:outputPanel>
<apex:outputPanel rendered="{!isShowWeek}" layout="none">
            <tr>
    <apex:outputPanel rendered="{!IF(totalLine.ttlColspan > 1, true, false)}" layout="none">
                <th colspan="{!totalLine.ttlColspan - 1}"></th>
    </apex:outputPanel>
                <th style="text-align:center;border: solid 1px;">周</th>
    <apex:repeat value="{!headerYrCols}" var="yr">
        <apex:repeat value="{!headerDcCols[yr]}" var="dc">
                <th colspan="{!aggregateColspan}" style="text-align:center;border: solid 1px;">{!dc}</th>
        </apex:repeat>
    </apex:repeat>
                <th colspan="{!aggregateColspan}" style="text-align:center;border: solid 1px;">合计</th>
            </tr>
</apex:outputPanel>
            <tr>
    <apex:outputPanel rendered="{!isSalesDept}" layout="none">
                <th width="100px" style="text-align:center;border: solid 1px;">本部</th>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!isArea}" layout="none">
                <th width="100px" style="text-align:center;border: solid 1px;">省</th>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!isEnduser}" layout="none">
                <th width="100px" style="text-align:center;border: solid 1px;">医院</th>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!isCategory2}" layout="none">
                <th width="100px" style="text-align:center;border: solid 1px;">{!$ObjectType.Product2.fields.Category2__c.Label}</th>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!isCategory3}" layout="none">
                <th width="100px" style="text-align:center;border: solid 1px;">{!$ObjectType.Product2.fields.Category3__c.Label}</th>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!isCategory4}" layout="none">
                <th width="100px" style="text-align:center;border: solid 1px;">{!$ObjectType.Product2.fields.Category4__c.Label}</th>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!isCategory5}" layout="none">
                <th width="100px" style="text-align:center;border: solid 1px;">{!$ObjectType.Product2.fields.Category5__c.Label}</th>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!isProductCode}" layout="none">
                <th width="100px" style="text-align:center;border: solid 1px;">产品型号</th><!-- {!$ObjectType.Product2.fields.Asset_Model_No__c.Label} -->
    </apex:outputPanel>
    <apex:outputPanel rendered="{!IF(totalLine.ttlColspan == 0, true, false)}" layout="none">
                <th style="text-align:center;border: solid 1px; width:100px;">汇总字段</th>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!isShowMonth || isShowWeek}" layout="none">
        <apex:repeat value="{!headerYrCols}" var="yr"><apex:repeat value="{!headerDcCols[yr]}" var="dc">
            <apex:outputPanel rendered="{!isShowSumQty}" layout="none">
                <th width="100px" style="text-align:center;border: solid 1px;">数量</th>
            </apex:outputPanel>
            <apex:outputPanel rendered="{!isShowSumAmount}" layout="none">
                <th width="100px" style="text-align:center;border: solid 1px;">売上金額</th>
            </apex:outputPanel>
        </apex:repeat></apex:repeat>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!isShowSumQty}" layout="none">
                <th width="100px" style="text-align:center;border: solid 1px;">数量</th>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!isShowSumAmount}" layout="none">
                <th width="100px" style="text-align:center;border: solid 1px;">売上金額</th>
    </apex:outputPanel>
            </tr>
<apex:variable value="{!0}" var="line" />
<apex:repeat value="{!pageLines}" var="pl">
            <tr>
    <apex:outputPanel rendered="{!isSalesDept}" layout="none">
                <td style="text-align:center;border: solid 1px;"><apex:outputText value="{!pl.salesDept}"></apex:outputText></td>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!isArea}" layout="none">
                <td style="text-align:center;border: solid 1px;"><apex:outputText value="{!pl.area}"></apex:outputText></td>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!isEnduser}" layout="none">
                <td style="text-align:center;border: solid 1px;"><apex:outputText value="{!pl.enduser}"></apex:outputText></td>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!isCategory2}" layout="none">
                <td style="text-align:center;border: solid 1px;"><apex:outputText value="{!pl.category2}"></apex:outputText></td>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!isCategory3}" layout="none">
                <td style="text-align:center;border: solid 1px;"><apex:outputText value="{!pl.category3}"></apex:outputText></td>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!isCategory4}" layout="none">
                <td style="text-align:center;border: solid 1px;"><apex:outputText value="{!pl.category4}"></apex:outputText></td>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!isCategory5}" layout="none">
                <td style="text-align:center;border: solid 1px;"><apex:outputText value="{!pl.category5}"></apex:outputText></td>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!isProductCode}" layout="none">
                <td style="text-align:center;border: solid 1px;">
                    <apex:outputText value="{!pl.productCode}" />
                </td>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!IF(totalLine.ttlColspan == 0, true, false)}" layout="none">
                <th style="text-align:center;border: solid 1px; width:100px;">合计</th>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!isShowMonth || isShowWeek}" layout="none">
        <apex:repeat value="{!headerYrCols}" var="yr"><apex:repeat value="{!headerDcCols[yr]}" var="dc">
            <apex:outputPanel rendered="{!isShowSumQty}" layout="none">
                <td style="text-align:right;border: solid 1px;">
                    <apex:outputText value="{0,number,#,##0}">
                        <apex:param value="{!pl.cntMap[yr & '|' & dc & '|' & Text(line)]}" />
                    </apex:outputText>
                </td>
            </apex:outputPanel>
            <apex:outputPanel rendered="{!isShowSumAmount}" layout="none">
                <td style="text-align:right;border: solid 1px;">
                    <apex:outputText value="{0,number,#,##0}">
                        <apex:param value="{!pl.sumRepairMap[yr & '|' & dc & '|' & Text(line)]}" />
                    </apex:outputText>
                </td>
            </apex:outputPanel>
        </apex:repeat></apex:repeat>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!isShowSumQty}" layout="none">
                <td style="text-align:right;border: solid 1px;">
                    <apex:outputText value="{0,number,#,##0}">
                        <apex:param value="{!pl.allCnt}" />
                    </apex:outputText>
                </td>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!isShowSumAmount}" layout="none">
                <td style="text-align:right;border: solid 1px;">
                    <apex:outputText value="{0,number,#,##0}">
                        <apex:param value="{!pl.allSumRepair}" />
                    </apex:outputText>
                </td>
    </apex:outputPanel>
            </tr>
    <apex:variable value="{!line + 1}" var="line" />
</apex:repeat>
<apex:outputPanel rendered="{!IF(totalLine.ttlColspan > 0, true, false)}" layout="none">
            <!-- 最後行:{!line}、合計行 -->
            <tr>
    <apex:outputPanel rendered="{!IF(totalLine.ttlColspan > 1, true, false)}" layout="none">
                <td colspan="{!totalLine.ttlColspan - 1}"></td>
    </apex:outputPanel>
                <th style="text-align:center;border: solid 1px;">合计</th>
    <apex:outputPanel rendered="{!isShowMonth || isShowWeek}" layout="none">
        <apex:repeat value="{!headerYrCols}" var="yr"><apex:repeat value="{!headerDcCols[yr]}" var="dc">
            <apex:outputPanel rendered="{!isShowSumQty}" layout="none">
                <td style="text-align:right;border: solid 1px;">
                    <apex:outputText value="{0,number,#,##0}">
                        <apex:param value="{!totalLine.cntMap[yr & '|' & dc & '|' & Text(line)]}" />
                    </apex:outputText>
                </td>
            </apex:outputPanel>
            <apex:outputPanel rendered="{!isShowSumAmount}" layout="none">
                <td style="text-align:right;border: solid 1px;">
                    <apex:outputText value="{0,number,#,##0}">
                        <apex:param value="{!totalLine.sumRepairMap[yr & '|' & dc & '|' & Text(line)]}" />
                    </apex:outputText>
                </td>
            </apex:outputPanel>
        </apex:repeat></apex:repeat>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!isShowSumQty}" layout="none">
                <td style="text-align:right;border: solid 1px;">
                    <apex:outputText value="{0,number,#,##0}">
                        <apex:param value="{!totalLine.allCnt}" />
                    </apex:outputText>
                </td>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!isShowSumAmount}" layout="none">
                <td style="text-align:right;border: solid 1px;">
                    <apex:outputText value="{0,number,#,##0}">
                        <apex:param value="{!totalLine.allSumRepair}" />
                    </apex:outputText>
                </td>
    </apex:outputPanel>
            </tr>
</apex:outputPanel>
        </table>
<script type="text/javascript">
//    var blockHeight = j$(window).innerHeight() - j$(escapeVfId('Page:searchAsset:Form')).height() - 30;
<apex:outputPanel rendered="{!isShowMonth && isShowWeek}" layout="none">
//    j$(escapeVfId('detailtbl')).tablefix({height: blockHeight, fixRows: 3, fixCols: 0});
</apex:outputPanel>
<apex:outputPanel rendered="{!isShowMonth || isShowWeek}" layout="none">
//    j$(escapeVfId('detailtbl')).tablefix({height: blockHeight, fixRows: 2, fixCols: 0});
</apex:outputPanel>
<apex:outputPanel rendered="{!Not(isShowMonth) && Not(isShowWeek)}" layout="none">
//    j$(escapeVfId('detailtbl')).tablefix({height: blockHeight, fixRows: 1, fixCols: 0});
</apex:outputPanel>
</script>
    </apex:pageBlock>
<script type="text/javascript">
j$(function() {
    // http://techbrij.com/html-table-row-grouping-jquery
    function groupTable(rows, startIndex, total){
        if (total === 0){
            return;
        }
        var i , currentIndex = startIndex, count=1, lst=[];
        var tds = rows.find('td:eq('+ currentIndex +')');
        var ctrl = j$(tds[0]);
        lst.push(rows[0]);
        for (i=1;i<=tds.length;i++){
            if (ctrl.text() ==  j$(tds[i]).text()){
                count++;
                j$(tds[i]).addClass('deleted');
                lst.push(rows[i]);
            } else{
                if (count>1){
                    ctrl.attr('rowspan',count);
                    groupTable(j$(lst),startIndex+1,total-1)
                }
                count=1;
                lst = [];
                ctrl=j$(tds[i]);
                lst.push(rows[i]);
            }
        }
    }
    groupTable(j$('#detailtbl tr:has(td)'),0,7);
    j$('#detailtbl .deleted').remove();
});
</script>
</apex:page>
force-app/main/default/pages/ListShip.page-meta.xml
New file
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>29.0</apiVersion>
    <availableInTouch>false</availableInTouch>
    <confirmationTokenRequired>false</confirmationTokenRequired>
    <label>ListShip</label>
</ApexPage>
force-app/main/default/pages/NewOnCall.page
New file
@@ -0,0 +1,427 @@
<apex:page standardController="On_Call__c" extensions="OnCallController" id="page" lightningStylesheets="true">
    <apex:includeScript value="{! URLFOR($Resource.AWSService, 'AWSService.js') }" />
    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
    <style>
        .disabledbutton {
            pointer-events: none;
            opacity: 0.4;
        }
    </style>
    <script>
        //Initial Required Information
        AWSService.sfSessionId = '{!GETSESSIONID()}';
        var staticResources = JSON.parse('{!staticResource}');
        //zhj MEBG新方案改造 2022-11-29 start
        var staticResourcesV2 = JSON.parse('{!staticResourceV2}');
        //zhj MEBG新方案改造 2022-11-29 end
        var requiredFieldAPIList = JSON.parse('{!requiredFieldAPIListStr}');
        var fieldAPIToLabelMap = JSON.parse('{!fieldAPIToLabelMapStr}');
        var VLookUpFields = new Set(['segment__c','Hospital__c','Oncall_Equipment__c','OwnerId']);
        var redirectMode = 'Save';
        //Redirect Required Parameter
        var redirectCallBack = function redirectCallBack(sfId, errorMessage) {
            if (sfId) {
                if (redirectMode == 'Save') {
                    window.open('/' + sfId, '_self');
                } else if (redirectMode == 'SaveAndNew') {
                    window.open('/setup/ui/recordtypeselect.jsp?ent=' + '{!sobjecttypeForFrontEnd}' + '&retURL=/' + '{!sobjectPrefix}' + '/o&save_new_url=/' + '{!sobjectPrefix}' + '/e?retURL=%2F' + '{!sobjectPrefix}' + '%2Fo', '_self');
                }
            } else {
                // alert(errorMessage);
                alertErrorMessage(errorMessage);
            }
        }
        //Query Required Parameter
        var queryBack = function queryBack(data) {
            console.log('data = ' + data);
            //document.querySelector("[id='page:form:pageBlock:pageBlockSection:j_id1:0:j_id2']").value = data.object.callerPhone;
            if(document.getElementById(api_id_map['Caller_phone__c']))
                document.getElementById(api_id_map['Caller_phone__c']).value = data.object.callerPhone;    //20220404  By Chen Yanan
            if(document.querySelector("[data-id='Responsible_Person_HP__c']"))
                document.querySelector("[data-id='Responsible_Person_HP__c']").value = data.object.responsiblePersonHP;
            unblockUI();
        };
        //Check If Insert Or Update
        var insertOrUpdateBack = function insertOrUpdateBack(payloadJson, result, isNewMode) {
            debugger
            console.log(result);
            let r = result;
            console.log('Result from AWS' + JSON.stringify(r));
            console.log('payloadJson=' + JSON.stringify(payloadJson));
            payloadJson.Caller_phone__c = r.object[0].callerPhone;
            payloadJson.Responsible_Person_HP__c = r.object[0].responsiblePersonHP;
            //zhj MEBG新方案改造 2022-11-29 start
            // payloadJson.Caller_Phone_Encrypt__c = r.object[0].callerPhoneEncrypt;
            // payloadJson.Responsible_PersonHP_Encrypt__c = r.object[0].responsiblePersonHPEncrypt;
            //zhj MEBG新方案改造 2022-11-29 end
            payloadJson.AWS_Data_Id__c = '{!AWSDataId}';
            if (isNewMode|| {!isCloneMode} ||!'{!AWSDataId}') {//Add by Li Jun for PIPL 20220413
                payloadJson.AWS_Data_Id__c = r.object[0].dataId;
                delete payloadJson.OwnerId;
            } else {
                payloadJson.AWS_Data_Id__c = '{!AWSDataId}';
            }
            if('{!sfRecordIdForEdit}'){
                payloadJson.Id = '{!sfRecordIdForEdit}';
            }
            if('{!rtTypeId}'){
                payloadJson.RecordTypeId = '{!rtTypeId}';//Add by zhj for Record Type Issue 20220421
            }
            return payloadJson;
        }
        // New Or Edit
        function ProcessPI(onCallJson, payloadForNewPI) {
            blockme();
            if ({!isNewMode} || {!isCloneMode} ||!'{!AWSDataId}') {//Add by Li Jun for PIPL 20220413
                NewPIToAWS(onCallJson, payloadForNewPI)
            }else {
                UpdatePIToAWS(onCallJson, payloadForNewPI)
            }
        }
        //Get Sensitive Information
        function getPIPayload(onCallJson) {
            let onCallPayloadList = [];
            let callerPhone = onCallJson.Caller_phone__c;
            let responsiblePersonHP = onCallJson.Responsible_Person_HP__c;
            let onCallPIData = new Object();
            onCallPIData.callerPhone = callerPhone;
            onCallPIData.responsiblePersonHP = responsiblePersonHP;
            onCallPIData.sfRecordId = '';
            console.log('onCall PI Data:' + JSON.stringify(onCallPIData));
            onCallPayloadList.push(onCallPIData);
            console.log(JSON.stringify(onCallPayloadList));
            return JSON.stringify(onCallPayloadList);
        }
        //Check Validate Field Value
        function validateFieldValueFormate() {
            return true;
        }
        //Get Page Information
        function getOnCallInformation() {
            let nodelist = document.querySelectorAll("[data-id]");
            let result = {}
            for (let index = 0; index < nodelist.length; index++) {
                if (VLookUpFields.has(nodelist[index].getAttribute("data-id"))) {
                    console.log(nodelist[index].id.indexOf('lkwgt'));
                    if (nodelist[index].id.indexOf('lkwgt') == -1) {
                        let vlookUpNodeId = nodelist[index].id + '_lkid';
                        let vlookUpNodeValue = document.getElementById(vlookUpNodeId);
                        let v = '';
                        if(vlookUpNodeValue){
                            v = vlookUpNodeValue.value;
                        }else{
                            v = nodelist[index].value;
                        }
                        result[nodelist[index].getAttribute("data-id")] = v;
                    }
                } else if (nodelist[index].type == 'checkbox') {
                    result[nodelist[index].getAttribute("data-id")] = nodelist[index].checked;
                } else if (nodelist[index].type == 'select-multiple') {
                    //nodelist[index].getAttribute("data-id")
                    let multiple = nodelist[index].getAttribute("data-id");
                    let targets = document.querySelector("[data-id=" + multiple + "]").parentNode.children[1].children[0].children[1].children[2].children[0].innerText;
                    targets = targets.replace(/\n/g, ";");
                    console.log('targets = ' + targets);
                    result[nodelist[index].getAttribute("data-id")] = targets;
                } else {
                    result[nodelist[index].getAttribute("data-id")] = nodelist[index].value;
                }
                let x = index + 1;
                if (x <= nodelist.length - 1 && (nodelist[x].getAttribute("data-id") == nodelist[index].getAttribute("data-id"))) {
                    index++;
                }
            }
            console.log(JSON.stringify(result));
            return result;
        }
        //Query from AWS
        function QueryOnCallFromAWS() {
            AWSService.query(staticResources.queryUrl, '{!AWSDataId}', queryBack, staticResources.token);
        }
        //Update Sensitive Information to AWS
        function UpdatePIToAWS(onCallJson, payloadForNewPI) {
            let controllerSaveMethod = '{!$RemoteAction.OnCallController.saveOnCall}';
            let obj = JSON.parse(payloadForNewPI);
            obj[0].dataId = '{!AWSDataId}';
            let payloadForNewPIJson = JSON.stringify(obj);
            //zhj MEBG新方案改造 2022-11-29 start
            //AWSService.update(staticResources.updateUrl, onCallJson, payloadForNewPIJson, controllerSaveMethod, staticResources.token, staticResources.transactionUrl, false, insertOrUpdateBack, redirectCallBack);
            AWSService.update(staticResourcesV2.updateUrl, onCallJson, payloadForNewPIJson, controllerSaveMethod, staticResources.token, staticResourcesV2.transactionUrl, false, insertOrUpdateBack, redirectCallBack);
            //zhj MEBG新方案改造 2022-11-29 end
        }
        //Insert Sensitive Information to AWS
        function NewPIToAWS(onCallJson, payloadForNewPI) {
            let controllerSaveMethod = '{!$RemoteAction.OnCallController.saveOnCall}';
            //zhj MEBG新方案改造 2022-11-29 start
            //AWSService.insert(staticResources.newUrl, onCallJson, payloadForNewPI, controllerSaveMethod, staticResources.token, staticResources.transactionUrl,{!isNewMode}, insertOrUpdateBack, redirectCallBack);
            AWSService.insert(staticResourcesV2.newUrl, onCallJson, payloadForNewPI, controllerSaveMethod, staticResourcesV2.token, staticResources.transactionUrl,{!isNewMode}, insertOrUpdateBack, redirectCallBack);
            //zhj MEBG新方案改造 2022-11-29 end
        }
        //Check Required Fields
        function checkRequiredFieldMsg(formData) {
            let blankRequiredFields = '';
            for (i = 0; i < requiredFieldAPIList.length; i++) {
                if (formData[requiredFieldAPIList[i]] && !VLookUpFields.has(requiredFieldAPIList[i])) {
                    continue;
                }else if(VLookUpFields.has(requiredFieldAPIList[i]) && formData[requiredFieldAPIList[i]] != '000000000000000'){
                    continue;
                } else {
                    if (blankRequiredFields == '') {
                        blankRequiredFields = blankRequiredFields + fieldAPIToLabelMap[requiredFieldAPIList[i]];
                    } else {
                        blankRequiredFields = blankRequiredFields + ',' + fieldAPIToLabelMap[requiredFieldAPIList[i]];
                    }
                }
            }
            return blankRequiredFields;
        }
        function EditButton(isDisabled){
            var topele = document.getElementById('topButtonRow');
            var bottomele = document.getElementById('bottomButtonRow');
            if (isDisabled) {
                topele.classList.add("disabledbutton");
                bottomele.classList.add("disabledbutton");
            }else {
                topele.classList.remove("disabledbutton");
                bottomele.classList.remove("disabledbutton");
            }
        }
        //Base Process
        function saveOnCallProcess(saveMode) {
            EditButton(true);
            redirectMode = saveMode;
            console.log('redirectMode' + redirectMode);
            hiddenErrorMsgNode();
            //1. Get onCall Information from Form
            let onCallJson = getOnCallInformation();
            //2. Validate the onCall field value formate, for example the email formate or phone formate
            let validationResultMessage = validateFieldValueFormate();
            console.log(validationResultMessage);
            if (!validationResultMessage) {
                //Popup error message.  - To Do After POC
                alertErrorMessage('邮箱格式输入有误,请重新输入!');
                return
            }
            // Check Required Field
            let checkRequiredFieldMsgResult = checkRequiredFieldMsg(onCallJson);
            if (checkRequiredFieldMsgResult) {
                alertErrorMessage('{!Input_Required_Field_Msg}' + checkRequiredFieldMsgResult);
                return
            }
            //3. Prepare the payload for New PI API To AWS - To Do
            let payloadForNewPI = getPIPayload(onCallJson);
            //4. onCall to AWS
            ProcessPI(onCallJson, payloadForNewPI);
        }
        //Alert Error Message
        function alertErrorMessage(errorMsg) {
            let errorMsgNode = document.getElementById("page:form:block:msgContent");
            errorMsg = '错误:无效数据。' + '\n' + errorMsg;
            errorMsgNode.innerText = errorMsg;
            errorMsgNode.className = 'pbError';
            unblockUI();
            EditButton(false);
        }
        //Hide Error Message
        function hiddenErrorMsgNode() {
            let errorMsgNode = document.getElementById("page:form:block:msgContent");
            errorMsgNode.innerText = '';
            errorMsgNode.className = '';
        }
        var GetEleApiName = function(ele){
            for(let ci in ele.classList){
                let c = ele.classList[ci];
                if(c.indexOf('PIBackApi'+'_')>-1){
                    return c.replace('PIBackApi'+'_','');
                }
            }
            return '';
        }
        function IsFormTag(tag_name){
            if (!tag_name) {
                return false;
            }
            return ['input','select','textarea'].indexOf(tag_name.toLowerCase())>-1;
        }
        function IsFormElement(e){
            return IsFormTag(e.tagName);
        }
    </script>
    <div class="bPageTitle">
        <div class="ptBody">
            <div class="content">
                <img src="/img/s.gif" alt="OnCall" class="pageTitleIcon" title="OnCall" />
                <h1 class="pageType">OnCall编辑
                    <span class="titleSeparatingColon">:</span>
                </h1>
                <h2 class="pageDescription">新建OnCall</h2>
                <div class="blank">&nbsp;</div>
            </div>
            <div class="links">
                <a href="javascript:openPopupFocusEscapePounds(%27https://help.salesforce.com/apex/htdoor?loc=help&amp;target=onCalls_edit.htm&amp;section=onCalls&amp;language=zh_CN&amp;release=234.18.8&amp;instance=CS117&amp;showSplash=true%27, %27Help%27, 700, 600, %27width=700,height=600,resizable=yes,toolbar=yes,status=no,scrollbars=yes,menubar=yes,directories=no,location=no,dependant=no%27, false, false);"
                    title="此页面的帮助 (新窗口)">
                    <span class="helpLink">此页面的帮助</span>
                    <img src="/img/s.gif" alt="" class="helpIcon" />
                </a>
            </div>
        </div>
        <div class="ptBreadcrumb"></div>
    </div>
    <apex:form id="form">
        <apex:pageblock id="block" >
            <div class="pbHeader">
                <table cellspacing="0" cellpadding="0" border="0">
                    <tbody>
                        <tr>
                            <td class="pbTitle">
                                <img src="/img/s.gif" alt="" class="minWidth" title="" width="1" height="1" />
                                <h2 class="mainTitle">OnCall编辑</h2>
                            </td>
                            <td class="pbButton" id="topButtonRow" style="pointer-events: none; opacity: 0.4;">
                                <input class="btn" type="Button" value="保存" onclick="saveOnCallProcess('Save')" />
                                <input class="btn" type="Button" value="保存并新建" onclick="saveOnCallProcess('SaveAndNew')" />
                                <apex:commandButton action="{!cancel}" value="取消" />
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <!-- Error Msg-->
            <div style="text-align: center;">
                <apex:outputPanel id="errorMsg">
                    <apex:pageMessages id="msgContent" escape="false" />
                </apex:outputPanel>
            </div>
            <!-- Iterate the layoutSections, which is a list of sections -->
            <apex:repeat value="{!layoutSections}" var="layoutSection">
                <apex:pageBlockSection title="{!layoutSection.name}" collapsible="{!layoutSection.allowCollapse}" columns="{!layoutSection.columns}">
                    <!--Each section has layoutFields, let's iterate them as well-->
                    <apex:repeat value="{!layoutSection.layoutFields}" var="layoutField">
                       <apex:inputField styleClass="PIBackApi PIBackApi_{!layoutField.fieldAPI}" html-data-id="{!layoutField.fieldAPI}" value="{!On_Call__c[layoutField.fieldAPI]}" rendered="{!not(layoutField.isPlaceHOlder)&&isNewMode}"
                            required="{!layoutField.isRequired}" />
                        <apex:inputField styleClass="PIBackApi PIBackApi_{!layoutField.fieldAPI}" html-data-id="{!layoutField.fieldAPI}" value="{!On_Call__c[layoutField.fieldAPI]}" rendered="{!not(layoutField.isPlaceHOlder)&&not(isNewMode)&&layoutField.fieldAPI!='RecordTypeId'}"
                            required="{!layoutField.isRequired}" />
                        <apex:outputField styleClass="PIBackApi PIBackApi_{!layoutField.fieldAPI}" html-data-id="{!layoutField.fieldAPI}" value="{!On_Call__c[layoutField.fieldAPI]}" rendered="{!not(layoutField.isPlaceHOlder)&&not(isNewMode)&&layoutField.fieldAPI=='RecordTypeId'}"
                       />
                        <apex:pageblocksectionitem rendered="{!layoutField.isPlaceHolder}">
                        </apex:pageblocksectionitem>
                    </apex:repeat>
                </apex:pageBlockSection>
            </apex:repeat>
            <script>
                var init_nodes = document.getElementsByClassName("PIBackApi");
                var api_id_map={};
                for(let ei in init_nodes){
                    let e = init_nodes[ei];
                    if(IsFormElement(e)){
                        if(e.getAttribute("multiple") != 'multiple' || e.style.display == 'none' && e.id.indexOf('selected') < 0){
                            api_id_map[GetEleApiName(e)] = e.id;
                        }
                    }
                }
                //Append Page
                sfdcPage.appendToOnloadQueue(function () {
                    var layoutSections = JSON.parse('{!layoutSectionsStr}');
                    for (let m = 0; m < layoutSections.length; m++) {
                        let layoutSection = layoutSections[m].layoutFields;
                        for (let n = 0; n < layoutSection.length; n++) {
                            let layoutField = layoutSection[n];
                            if (layoutField.fieldAPI != '' && document.querySelector("[data-id='"+layoutField.fieldAPI+"']") != null) {
                                let e = document.querySelector("[data-id='"+layoutField.fieldAPI+"']");
                                e.disabled = !(layoutField.editableField);
                                if (!(layoutField.editableField)) {
                                    if (e.getAttribute("multiple") && e.getAttribute("multiple") == 'multiple') {
                                        e.parentNode.classList.add("disabledbutton");
                                    }
                                    if (e.tagName == 'DIV') {
                                        e.classList.add("disabledbutton");
                                    }
                                }
                            }
                        }
                    }
                    //2. Query AWS Data by dataId
                    console.log('Mode for onCall Page:' + {!isNewMode});
                    if (!{!isNewMode}) {
                        blockme();
                        QueryOnCallFromAWS();
                    };
                    document.querySelector("[data-id='OwnerId']").classList.add("disabledbutton");
                    document.getElementById('topButtonRow').style = '';
               document.getElementById('bottomButtonRow').style = '';
                    jQuery(".lookupInput").each(function(i,e){
                        let je =jQuery(e).find('input');
                        je.attr("readonly","");
                        je.css("background","unset");
                        let dataid = je.attr('data-id');
                        if(['Hospital_Name__c','Department_Class__c','OwnerId'].indexOf(dataid) > -1) return;
                        jQuery(e).children(":last-child").before('<img class="closeIcon" data-id="'+dataid+'" generate="" alt="Clear" src="/s.gif" style="display: inline-block;">');
                    })
                    jQuery(".lookupInput").on("mouseenter","img[generate]",function(e){
                        this.className = "closeIconOn";
                    });
                    jQuery(".lookupInput").on("mouseleave","img[generate]",function(e){
                        this.className = "closeIcon"
                    });
                    jQuery(".lookupInput").on("click","img[generate]",function(e){
                        let id = jQuery("input[data-id='"+jQuery(this).attr("data-id")+ "']").attr("id");
                        let input = document.getElementById(id);
                        if(input){
                            input.value = '';
                            let hidden = document.getElementById(id+'_lkid');
                            if(hidden){
                                hidden.value = '';
                            }
                        }
                    });
                });
            </script>
            <div class="pbBottomButtons">
                <table cellspacing="0" cellpadding="0" border="0">
                    <tbody>
                        <tr>
                            <td class="pbTitle">
                                <img src="/img/s.gif" alt="" class="minWidth" title="" width="1" height="1" />&nbsp;</td>
                            <td class="pbButtonb" id="bottomButtonRow" style="pointer-events: none; opacity: 0.4;">
                                <input class="btn" type="Button" value="保存" onclick="saveOnCallProcess('Save')" />
                                <input class="btn" type="Button" value="保存并新建" onclick="saveOnCallProcess('SaveAndNew')" />
                                <apex:commandButton action="{!cancel}" value="取消" />
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </apex:pageblock>
    </apex:form>
</apex:page>
force-app/main/default/pages/NewOnCall.page-meta.xml
New file
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>54.0</apiVersion>
    <availableInTouch>false</availableInTouch>
    <confirmationTokenRequired>false</confirmationTokenRequired>
    <label>NewOnCall</label>
</ApexPage>
force-app/main/default/pages/NewPaymentPlanLoad.page
New file
@@ -0,0 +1,676 @@
<apex:page Controller="NewPaymentPlanLoadController"  showHeader="false" sidebar="false" action="{!init}" id="allPage" title="维修合同文本信息录入页面" pageStyle="PageStyleCss" lightningStylesheets="true">
<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
<style type="text/css">
    .BlockSytle{
        width: 1000px;
    }
    .PageStyleCss{
        width: 980px;
        height: 340px;
    }
    .align-save-button {
        vertical-align: top;
        margin-top: 0.0rem;
         margin-bottom: 0.125rem;
    }
    input{
        disabled: false;
    }
</style>
<script type="text/javascript">
    j$(escapeVfId('allPage:allForm:allBlock:TextInformation:Contract_Limit_Times__c')).attr('disabled',true);
    function init() {
        Convert_All_Amount();
        // 新增点检总次数(只在页面中显示)fxk 2021/9/2 Star
        AllChecktime();
        // 新增点检总次数(只在页面中显示)fxk 2021/9/2 ENd
        Initdisabled();
    }
    function Convert_All_Amount() {
        var Total_Contract_Amount = j$(escapeVfId('allPage:allForm:Contract_Amount_Hidden')).val();
        var Total_Contract_Amount_In_Words = j$(escapeVfId('allPage:allForm:Total_Contract_Amount_In_Words_Hidden')).val();
        if( Total_Contract_Amount !=null && Total_Contract_Amount!=undefined && Total_Contract_Amount.length > 0 ){
            Convert_Contract_Amount();
            Amount_Warranty_Coverage();
            for(var i=1; i<7; i++){
            Convert_Amount(i);
            }
        }
    }
    function Initdisabled() {
        var Status = '{!PageMCEElement.Status__c}';
        if(Status != '引合中'){
        j$(escapeVfId('allPage:allForm:allBlock:Is_Standard_Contract')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Term_Of_Payment__c')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:one_off_payment_agreed_period__c')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Total_Contract_Amount_In_Words')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Total_Payment_Time__c')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Date_First')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Date_Second')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Date_Third')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Date_Forth')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Date_Fifth')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Date_Sixth')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Sum_1')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Sum_2')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Sum_3')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Sum_4')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Sum_5')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Sum_6')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Sum_6')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Small_Repair_Time__c')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Live_Technical_Support_Time__c')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Tour_Check__c')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Engineer_Name__c')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Phone_Number__c')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Inspection_Time__c')).attr("disabled", true);
        // 新增点检总次数(只在页面中显示)fxk 2021/9/2 Star
        j$(escapeVfId('allPage:allForm:allBlock:Contract_Limit_Times__c')).attr("disabled", true);
        // 新增点检总次数(只在页面中显示)fxk 2021/9/2 End
        j$(escapeVfId('allPage:allForm:allBlock:Dedust__c')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:First_Party_Contract_Number__c')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Second_Party_Contract_Number__c')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Negotiate_Mean__c')).attr("disabled", true);
        }
        //XLIU-CEP8WW LY 20220905 start
        var saveBT = '{!PageMCEElement.old_Is_RecognitionModel__c}';
        var payment = j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Term_Of_Payment__c')).val();
        if (saveBT =='true' && payment=='多次付款'){
            j$(escapeVfId('allPage:allForm:allBlock:allButtons:bottom:PrintButton')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:allButtons:bottom:PrintButton')).attr("class", true);
            j$(escapeVfId('allPage:allForm:allBlock:allButtons:PrintButton')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:allButtons:PrintButton')).attr("class", true);
        }
        //XLIU-CEP8WW LY 20220905 end
    }
    function Convert_Contract_Amount() {
        var Total_Contract_Amount = j$(escapeVfId('allPage:allForm:Contract_Amount_Hidden')).val();
        var Total_Contract_Amount_In_Words = smalltoBIG(Total_Contract_Amount);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Total_Contract_Amount_In_Words')).text(Total_Contract_Amount_In_Words);
        j$(escapeVfId('allPage:allForm:Total_Contract_Amount_In_Words_Hidden')).val(Total_Contract_Amount_In_Words);
    }
    //HWAG-BHT7XX 2019/11/26 START
  //   function paytime(status){
        // console.log('1'+status);
        // switch(status){
        //     case '1':
        //         document.getElementById('paytime1').style.display= "inline";
        //         document.getElementById('paytime2').style.display= "none";
        //         document.getElementById('paytime3').style.display= "none";
        //         document.getElementById('paytime4').style.display= "none";
        //         document.getElementById('paytime5').style.display= "none";
        //         document.getElementById('paytime6').style.display= "none";
        //         break;
        //     case '2':
        //         document.getElementById('paytime2').style.display= "inline";
        //         document.getElementById('paytime1').style.display= "inline";
        //         document.getElementById('paytime3').style.display= "none";
        //         document.getElementById('paytime4').style.display= "none";
        //         document.getElementById('paytime5').style.display= "none";
        //         document.getElementById('paytime6').style.display= "none";
        //         break;
        //     case '3':
        //         document.getElementById('paytime3').style.display= "inline";
        //         document.getElementById('paytime2').style.display= "inline";
        //         document.getElementById('paytime1').style.display= "inline";
        //         document.getElementById('paytime4').style.display= "none";
        //         document.getElementById('paytime5').style.display= "none";
        //         document.getElementById('paytime6').style.display= "none";
        //         break;
        //     case '4':
        //         document.getElementById('paytime4').style.display= "inline";
        //         document.getElementById('paytime2').style.display= "inline";
        //         document.getElementById('paytime3').style.display= "inline";
        //         document.getElementById('paytime1').style.display= "inline";
        //         document.getElementById('paytime5').style.display= "none";
        //         document.getElementById('paytime6').style.display= "none";
        //         break;
        //     case '5':
        //         document.getElementById('paytime5').style.display= "inline";
        //         document.getElementById('paytime2').style.display= "inline";
        //         document.getElementById('paytime3').style.display= "inline";
        //         document.getElementById('paytime4').style.display= "inline";
        //         document.getElementById('paytime1').style.display= "inline";
        //         document.getElementById('paytime6').style.display= "none";
        //         break;
        //     case '6':
        //         document.getElementById('paytime6').style.display= "inline";
        //         document.getElementById('paytime2').style.display= "inline";
        //         document.getElementById('paytime3').style.display= "inline";
        //         document.getElementById('paytime4').style.display= "inline";
        //         document.getElementById('paytime5').style.display= "inline";
        //         document.getElementById('paytime1').style.display= "inline";
        //         break;
        //     default:
        //         break;
        // }
  //   }
    function Amount_Warranty_Coverage(){
        var Total_Contract_Amount = j$(escapeVfId('allPage:allForm:Contract_Amount_Hidden')).val();
        var Amount_Warranty_Coverage = (Total_Contract_Amount*1.3).toString();
        console.log(Amount_Warranty_Coverage+'======');
        var Amount_Warranty_Coverage_In_Words = smalltoBIG(Amount_Warranty_Coverage);
        console.log(Amount_Warranty_Coverage_In_Words+'======');
        // j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Total_Contract_Amount_In_Words')).text(Amount_Warranty_Coverage_In_Words);
        j$(escapeVfId('allPage:allForm:Amount_Warranty_Coverage_In_Word_Hidden')).val(Amount_Warranty_Coverage_In_Words);
        j$(escapeVfId('allPage:allForm:Amount_Warranty_Coverage_Hidden')).val(Amount_Warranty_Coverage);
    }
    //HWAG-BHT7XX 2019/11/26 END
    function Convert_Amount(number) {
        var Amount = j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Sum_'+number)).val();
        if(Amount == null || Amount== undefined || Amount.length == 0)
            return;
        var Amount_In_Words = smalltoBIG(Amount);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Sum_' + number + '_in_Word')).text(Amount_In_Words);
        j$(escapeVfId('allPage:allForm:Payment_Plan_Sum_' + number + '_in_Word_Hidden')).val(Amount_In_Words);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Sum_'+number)).val(toNumComma(Amount));
    }
    /** 数字金额大写转换(可以处理整数,小数,负数) */
    function smalltoBIG(n)
    {
        var fraction = ['角', '分'];
        var digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
        var unit = [ ['元', '万', '亿'], ['', '拾', '佰', '仟']  ];
        var head = n < 0? '欠': '';
        n = n.replace(/\,/g,"");
        n = Math.abs(n);
        var s = '';
        for (var i = 0; i < fraction.length; i++){
            s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
        }
        s = s || '整';
        n = Math.floor(n);
        for (var i = 0; i < unit[0].length && n > 0; i++)     {
            var p = '';
            for (var j = 0; j < unit[1].length && n > 0; j++)     {
                p = digit[n % 10] + unit[1][j] + p;
                n = Math.floor(n / 10);
            }
            s = p.replace(/(零.)*零$/, '').replace(/^$/, '零')  + unit[0][i] + s;
        }
        return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
    }
    function CloseJs() {
        // body...
        var Rs = j$(escapeVfId('allPage:allForm:statusSave')).value();
        // alert(Rs);
        // fxk 2021/8/31 点检次数必须填 end
        // var saveErrorflag = j$(escapeVfId('saveErrorflag')).value();
        if(Rs == 'Fin'){
        // fxk 2021/8/31 点检次数必须填 end
            // window.opener.top.location.href = '/{!PageMCEElement.id}';
   //          top.window.close();
            window.close();
            unblockUI();
        }else{
            unblockUI();
        }
    }
    function ChangeTermofPaymentPlanJS(){
        //XLIU-CEP8WW LY 20220905 start
        var saveBT = '{!PageMCEElement.old_Is_RecognitionModel__c}';
        var payment = j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Term_Of_Payment__c')).val();
        if (saveBT =='true' && payment=='多次付款'){
            j$(escapeVfId('allPage:allForm:allBlock:allButtons:bottom:PrintButton')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:allButtons:bottom:PrintButton')).attr("class", true);
            j$(escapeVfId('allPage:allForm:allBlock:allButtons:PrintButton')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:allButtons:PrintButton')).attr("class", true);
        }
        if (saveBT =='true' && payment=='一次性付款') {
            j$(escapeVfId('allPage:allForm:allBlock:allButtons:bottom:PrintButton')).attr("disabled", false);
            j$(escapeVfId('allPage:allForm:allBlock:allButtons:bottom:PrintButton')).attr("class", false);
            j$(escapeVfId('allPage:allForm:allBlock:allButtons:PrintButton')).attr("disabled", false);
            j$(escapeVfId('allPage:allForm:allBlock:allButtons:PrintButton')).attr("class", false);
        }
        //XLIU-CEP8WW LY 20220905 end
        ChangeTermofPaymentPlan();
    }
    // 新增点检总次数(只在页面中显示)fxk 2021/9/2 Star
    function AllChecktime(){
        var Allchecks;
        // gzw fix 20210929 追加非标准合同判断
        var ContractAllMonth = '{!Contract_validMonth}';//j$(escapeVfId('allPage:allForm:Contract_validMonth')).value();
        // alert(ContractAllMonth);
        var contractType = j$(escapeVfId('allPage:allForm:allBlock:Is_Standard_Contract')).val();
        var checks;
        if(contractType == '是'){
            checks= j$(escapeVfId('allPage:allForm:allBlock:TextInformation:Inspection_Time__c')).val();
        }else{
            checks= j$(escapeVfId('allPage:allForm:allBlock:TextInformation:Inspection_Time__cno')).val();
        }
        //  = j$(escapeVfId('allPage:allForm:allBlock:TextInformation:Inspection_Time__c')).val();
        // alert(checks);
        // add 一年内点检区间不够生成一次点检计划,默认生成一个点检计划,计划区间为合同开始日-结束日 2021/10/25 fxk Star
        if((checks == 1 && ContractAllMonth < 9)
            || (checks == 2 && ContractAllMonth < 6)
            || (checks == 3 && ContractAllMonth < 4)
            || (checks == 4 && ContractAllMonth < 3)){
            Allchecks = 1;
        }else{
        // add 一年内点检区间不够生成一次点检计划,默认生成一个点检计划,计划区间为合同开始日-结束日 2021/10/25 fxk End
            if (ContractAllMonth - parseInt(ContractAllMonth / 12) * 12 >= 6 && checks == 1){
                Allchecks = parseInt((ContractAllMonth * checks)/12+1);
            }else{
                Allchecks = parseInt((ContractAllMonth * checks)/12);
                // alert(Allchecks);
            }
        }
        // alert(Allchecks);
        if(contractType == '是'){
            j$(escapeVfId('allPage:allForm:allBlock:TextInformation:Contract_Limit_Times__c')).text(Allchecks);
        }else{
            j$(escapeVfId('allPage:allForm:allBlock:TextInformation:Contract_Limit_Times__cno')).text(Allchecks);
        }
    }
    // 新增点检总次数(只在页面中显示)fxk 2021/9/2 End
</script>
<apex:form styleClass="BlockSytle" id="allForm">
    <body onload="init()">
    <apex:actionFunction name="ChangeTermofPaymentPlan" action="{!Dummy}" rerender="paymentPlan"></apex:actionFunction>
    <apex:actionFunction name="RerenderallpageBlockJS" action="{!Dummy}" rerender="TextInformation" oncomplete="AllChecktime();"></apex:actionFunction>
    <!-- <apex:actionFunction name="RerenderallpageBlockJS"  rerender="TextInformation"></apex:actionFunction> -->
    <apex:outputPanel id="hiddenInput">
    <apex:inputHidden value="{!statusSave}" id="statusSave"/>
    <!-- // fxk 2021/8/31 点检次数必须填 end -->
    <!-- <input type="hidden" value="{!saveErrorflag}" id="saveErrorflag"/> -->
    <!-- // fxk 2021/8/31 点检次数必须填 end -->
    <apex:inputHidden value="{!PageMCEElement.Contract_Amount__c}" id="Contract_Amount_Hidden"/>
    <!-- HWAG-BHT7XX 2019/11/26 START -->
    <apex:inputHidden value="{!PageMCEElement.Amount_Warranty_Coverage__c}" id="Amount_Warranty_Coverage_Hidden" />
    <apex:inputHidden value="{!PageMCEElement.Amount_Warranty_Coverage_In_Word__c}" id="Amount_Warranty_Coverage_In_Word_Hidden"/>
    <!-- HWAG-BHT7XX 2019/11/26 END -->
    <apex:inputHidden value="{!PageMCEElement.Total_Contract_Amount_In_Words__c}" id="Total_Contract_Amount_In_Words_Hidden"/>
    <apex:inputHidden value="{!PageMCEElement.Payment_Plan_Sum_First_in_Word__c}" id="Payment_Plan_Sum_1_in_Word_Hidden"/>
    <apex:inputHidden value="{!PageMCEElement.Payment_Plan_Sum_Second_in_Word__c}" id="Payment_Plan_Sum_2_in_Word_Hidden"/>
    <apex:inputHidden value="{!PageMCEElement.Payment_Plan_Sum_Third_in_Word__c}" id="Payment_Plan_Sum_3_in_Word_Hidden"/>
    <apex:inputHidden value="{!PageMCEElement.Payment_Plan_Sum_Forth_in_Word__c}" id="Payment_Plan_Sum_4_in_Word_Hidden"/>
    <apex:inputHidden value="{!PageMCEElement.Payment_Plan_Sum_Fifth_in_Word__c}" id="Payment_Plan_Sum_5_in_Word_Hidden"/>
    <apex:inputHidden value="{!PageMCEElement.Payment_Plan_Sum_Sixth_in_Word__c}" id="Payment_Plan_Sum_6_in_Word_Hidden"/>
    </apex:outputPanel>
    <apex:pageBlock id="allBlock" >
    <apex:outputPanel id="Messages" style="color:red">
        <apex:messages />
    </apex:outputPanel>
    <table border="0" >
        <colgroup>
            <col width="25%"/>
            <col width="25%"/>
            <col width="25%"/>
            <col width="25%"/>
        </colgroup>
        <tr>
            <td style ="text-align: right;">
                <apex:outputText value="是否为标准合同:"  /> &nbsp;&nbsp;
            </td>
            <td style ="text-align: left;">
                <div class="requiredInput"><div class="requiredBlock"></div>
                     <apex:inputField id="Is_Standard_Contract" value="{!PageMCEElement.Is_Standard_Contract__c}" onchange="RerenderallpageBlockJS(); "/>
                        (必填项,所有合同均必须勾选)
                </div>
            </td>
            <td/>
            <td/>
        </tr>
    </table>
    <br/>
    <apex:pageBlockSection id="paymentPlan" title="付款计划(必填内容):" columns="1">
        <apex:selectList label="付款方式:" style="margin-right:3px" size="1" id="Term_Of_Payment__c" value="{!PageMCEElement.Term_Of_Payment__c}" onchange="ChangeTermofPaymentPlanJS();">
            <apex:selectOptions value="{!Term_Of_Payment}"/>
        </apex:selectList>
        <apex:outputPanel style="display: {!IF(Check_Of_Payment, '', 'none')}" >
            <h2 style="margin-left:4%;">一次性付款:</h2>
            <p style="margin-left:4%;">
                本合同正式签订之日起
                <apex:selectList style="margin-right:3px;margin-left:3px" size="1" id="one_off_payment_agreed_period__c" value="{!PageMCEElement.one_off_payment_agreed_period__c}">
                    <apex:selectOptions value="{!one_off_payment_agreed_period}"/>
                </apex:selectList>
                 日内,甲方向乙方支付全部合同款人民币
                 <apex:outputText style="margin-right:3px;margin-left:3px" value="{!PageMCEElement.Contract_Amount__c}"/>元,大写<apex:outputText id="Total_Contract_Amount_In_Words" style="margin-right:1px;margin-left:1px" value="{!PageMCEElement.Total_Contract_Amount_In_Words__c}"/>。
            </p>
        </apex:outputPanel>
        <apex:outputPanel style="display: {!IF(Not(Check_Of_Payment), '', 'none')}">
            <h2 style="margin-left:4%;" >多次付款:</h2>
            <div style="margin-left:4%;line-height:22px">
                本合同款项分&nbsp;&nbsp;
                <apex:selectList style="margin-right:3px" size="1" id="Total_Payment_Time__c" value="{!PageMCEElement.Total_Payment_Time__c}" onchange="paytime(this.value)">
                    <apex:selectOptions value="{!Total_Payment_Time}"/>
                </apex:selectList>&nbsp;期付出,详细如下:
                <br/>
                <!-- <div id="paytime1" style="display:{!IF((PageMCEElement.Total_Payment_Time__c='6' || PageMCEElement.Total_Payment_Time__c='5' || PageMCEElement.Total_Payment_Time__c='4' || PageMCEElement.Total_Payment_Time__c='3' || PageMCEElement.Total_Payment_Time__c='2' || PageMCEElement.Total_Payment_Time__c='1'),'block','none')};"> -->
                    第一期款项付款时间为&nbsp;
                    <apex:inputField id="Payment_Plan_Date_First" value="{!PageMCEElement.Payment_Plan_Date_First__c}" />
                    &nbsp;前,甲方向乙方支付人民币&nbsp;
                    <apex:inputField id="Payment_Plan_Sum_1" value="{!PageMCEElement.Payment_Plan_Sum_First__c}" onchange="Convert_Amount('1');" />
                    &nbsp;元,大写
                    <apex:outputText id="Payment_Plan_Sum_1_in_Word" style="margin-right:1px;margin-left:1px" value="{!PageMCEElement.Payment_Plan_Sum_First_in_Word__c}"/>;
                    <br/>
                <!-- </div>
                <div id="paytime2" style="display:{!IF((PageMCEElement.Total_Payment_Time__c='6' || PageMCEElement.Total_Payment_Time__c='5' || PageMCEElement.Total_Payment_Time__c='4' || PageMCEElement.Total_Payment_Time__c='3' || PageMCEElement.Total_Payment_Time__c='2'),'block','none')};"> -->
                    第二期款项付款时间为&nbsp;
                    <apex:inputField id="Payment_Plan_Date_Second" value="{!PageMCEElement.Payment_Plan_Date_Second__c}" />
                    &nbsp;前,甲方向乙方支付人民币&nbsp;
                    <apex:inputField id="Payment_Plan_Sum_2" value="{!PageMCEElement.Payment_Plan_Sum_Second__c}" onchange="Convert_Amount('2');"/>
                    &nbsp;元,大写
                    <apex:outputText id="Payment_Plan_Sum_2_in_Word" style="margin-right:1px;margin-left:1px" value="{!PageMCEElement.Payment_Plan_Sum_Second_in_Word__c}"/>;
                    <br/>
                <!-- </div>
                <div id="paytime3" style="display:{!IF((PageMCEElement.Total_Payment_Time__c='6' || PageMCEElement.Total_Payment_Time__c='5' || PageMCEElement.Total_Payment_Time__c='4' || PageMCEElement.Total_Payment_Time__c='3'),'block','none')};"> -->
                    第三期款项付款时间为&nbsp;
                    <apex:inputField id="Payment_Plan_Date_Third" value="{!PageMCEElement.Payment_Plan_Date_Third__c}" />
                    &nbsp;前,甲方向乙方支付人民币&nbsp;
                    <apex:inputField id="Payment_Plan_Sum_3" value="{!PageMCEElement.Payment_Plan_Sum_Third__c}" onchange="Convert_Amount('3');"/>
                    &nbsp;元,大写
                    <apex:outputText id="Payment_Plan_Sum_3_in_Word" style="margin-right:1px;margin-left:1px" value="{!PageMCEElement.Payment_Plan_Sum_Third_in_Word__c}"/>;
                    <br/>
                <!-- </div>
                <div id="paytime4" style="display:{!IF((PageMCEElement.Total_Payment_Time__c='6' || PageMCEElement.Total_Payment_Time__c='5' || PageMCEElement.Total_Payment_Time__c='4'),'block','none')};"> -->
                    第四期款项付款时间为&nbsp;
                    <apex:inputField id="Payment_Plan_Date_Forth" value="{!PageMCEElement.Payment_Plan_Date_Forth__c}" />
                    &nbsp;前,甲方向乙方支付人民币&nbsp;
                    <apex:inputField id="Payment_Plan_Sum_4" value="{!PageMCEElement.Payment_Plan_Sum_Forth__c} " onchange="Convert_Amount('4');"/>
                    &nbsp;元,大写
                    <apex:outputText id="Payment_Plan_Sum_4_in_Word" style="margin-right:1px;margin-left:1px" value="{!PageMCEElement.Payment_Plan_Sum_Forth_in_Word__c}"/>;
                    <br/>
                <!-- </div>
                <div id="paytime5" style="display:{!IF((PageMCEElement.Total_Payment_Time__c='6' || PageMCEElement.Total_Payment_Time__c='5'),'block','none')};"> -->
                    第五期款项付款时间为&nbsp;
                    <apex:inputField id="Payment_Plan_Date_Fifth" value="{!PageMCEElement.Payment_Plan_Date_Fifth__c}" />
                    &nbsp;前,甲方向乙方支付人民币&nbsp;
                    <apex:inputField id="Payment_Plan_Sum_5" value="{!PageMCEElement.Payment_Plan_Sum_Fifth__c}" onchange="Convert_Amount('5');"/>
                    &nbsp;元,大写
                    <apex:outputText id="Payment_Plan_Sum_5_in_Word" style="margin-right:1px;margin-left:1px" value="{!PageMCEElement.Payment_Plan_Sum_Fifth_in_Word__c}"/>;
                    <br/>
                <!-- </div>
                <div id="paytime6" style="display:{!IF(PageMCEElement.Total_Payment_Time__c='6','block','none')};"> -->
                    第六期款项付款时间为&nbsp;
                    <apex:inputField id="Payment_Plan_Date_Sixth" value="{!PageMCEElement.Payment_Plan_Date_Sixth__c}" />
                    &nbsp;前,甲方向乙方支付人民币&nbsp;
                    <apex:inputField id="Payment_Plan_Sum_6" value="{!PageMCEElement.Payment_Plan_Sum_Sixth__c}" onchange="Convert_Amount('6');" />
                    &nbsp;元,大写
                    <apex:outputText id="Payment_Plan_Sum_6_in_Word" style="margin-right:1px;margin-left:1px" value="{!PageMCEElement.Payment_Plan_Sum_Sixth_in_Word__c}"/>。
                <!-- </div> -->
            </div>
        </apex:outputPanel>
    </apex:pageBlockSection>
    <br/>
    <h2>
        <div style="margin-left:5%; color:Blue">
            <apex:outputText >提示信息:标准合同下述内容需要全部填写。</apex:outputText>
        </div>
    </h2>
    <br/>
    <apex:pageBlockSection id="TextInformation" title="文本信息:" columns="1">
        <apex:outputPanel id="StandardContractContextno" rendered="{!IF(PageMCEElement.Is_Standard_Contract__c == '否', 'true', 'false')}">
            <table border="" style="width:90%" >
                <colgroup>
                    <col width="25%"/>
                    <col width="25%"/>
                    <col width="25%"/>
                    <col width="25%"/>
                </colgroup>
                <tr>
                    <td style =" text-align:left;">
                    </td>
                    <td style ="text-align: left;">
                    </td>
                    <td style ="text-align: left;">
                    </td>
                    <td style ="text-align: left;">
                    </td>
                </tr>
                <tr>
                    <td style ="text-align: left;">
                        <apex:outputText style="margin-left:20%;" value="点检:"  /> &nbsp;&nbsp;&nbsp;&nbsp;
                    </td>
                    <td style ="text-align: left;">
                        <div class="requiredInput"><div class="requiredBlock"></div>
                            每年
                            <apex:selectList style="margin-left:3px;margin-right:3px" size="1" id="Inspection_Time__cno" value="{!PageMCEElement.Inspection_Time__c}" onchange="AllChecktime();">
                                <apex:selectOptions value="{!Tour_Check}"/>
                            </apex:selectList>次
                            (必填项)
                        </div>
                    </td>
                    <td style ="text-align: left;">
                    </td>
                    <td style ="text-align: left;">
                    </td>
                </tr>
                <!-- fxk 2021、9、2 新加点检总次数 star-->
                <tr>
                    <td style ="text-align: left;">
                        <apex:outputText style="margin-left:20%;" value="点检总次数:"  /> &nbsp;&nbsp;&nbsp;&nbsp;
                    </td>
                    <td style ="text-align: left;">
                        共
                        <apex:outputText style="margin-left:3px;margin-right:3px;width:25px" id="Contract_Limit_Times__cno" value="{!PageMCEElement.Contract_Limit_Times__c}">
                        </apex:outputText>次
                    </td>
                    <td style ="text-align: left;">
                    </td>
                    <td style ="text-align: left;">
                    </td>
                </tr>
                <!-- fxk 2021、9、2 新加点检总次数 end-->
            </table>
        </apex:outputPanel>
    <apex:outputPanel id="StandardContractContext" rendered="{!IF(PageMCEElement.Is_Standard_Contract__c == '是', 'true', 'false')}">
    <table border="0" style="width:90%" >
        <colgroup>
            <col width="25%"/>
            <col width="25%"/>
            <col width="25%"/>
            <col width="25%"/>
        </colgroup>
        <tr>
            <td style ="text-align: left;">
                <apex:outputText style="margin-left:20%;" value="小修理时限:"  /> &nbsp;&nbsp;&nbsp;&nbsp;
            </td>
            <td style ="text-align: left;">
                <apex:selectList style="margin-right:3px" size="1" id="Small_Repair_Time__c" value="{!PageMCEElement.Small_Repair_Time__c}">
                    <apex:selectOptions value="{!Small_Repair_Time}"/>
                </apex:selectList>
            <!-- XLIU-CEP8WW 【委托】合同文本更新/新增 LY 20220524 start-->
            工作日
            <!-- XLIU-CEP8WW 【委托】合同文本更新/新增 LY 20220524 end-->
            </td>
            <td style ="text-align: left;">
                <apex:outputText style="margin-left:20%;" value="大修理时限:"  /> &nbsp;&nbsp;&nbsp;&nbsp;
            </td>
            <td style ="text-align: left;">
                <apex:selectList style="margin-right:3px" size="1" id="Big_Repair_Time__c" value="{!PageMCEElement.Big_Repair_Time__c}">
                    <apex:selectOptions value="{!Big_Repair_Time}"/>
                </apex:selectList>
            工作日
            </td>
        </tr>
        <tr>
            <td style ="text-align: left;">
                <apex:outputText style="margin-left:20%;" value="现场技术支持时限:"  /> &nbsp;&nbsp;&nbsp;&nbsp;
            </td>
            <td style ="text-align: left;">
                <apex:selectList style="margin-right:3px" size="1" id="Live_Technical_Support_Time__c" value="{!PageMCEElement.Live_Technical_Support_Time__c}">
                    <!-- XLIU-CEP8WW 【委托】合同文本更新/新增 LY 20220524 start-->
                    <!--<apex:selectOptions value="{!Small_Repair_Time}"/>-->
                    <apex:selectOptions value="{!Live_Technical_Support_Time}"/>
                    <!-- XLIU-CEP8WW 【委托】合同文本更新/新增 LY 20220524 end-->
                </apex:selectList>
            小时
            </td>
            <td style ="text-align: left;">
                <apex:outputText style="margin-left:20%;" value="巡回:"  /> &nbsp;&nbsp;&nbsp;&nbsp;
            </td>
            <td style ="text-align: left;">
                每年
                <apex:selectList style="margin-left:3px;margin-right:3px" size="1" id="Tour_Check__c" value="{!PageMCEElement.Tour_Check__c}">
                    <apex:selectOptions value="{!Tour_Check}"/>
                </apex:selectList>次
            </td>
        </tr>
        <tr>
            <td style =" text-align:left;">
                <apex:outputText style="margin-left:20%;" value="工程师姓名:"  /> &nbsp;&nbsp;&nbsp;&nbsp;
            </td>
            <td style ="text-align: left;">
                 <apex:inputTextarea id="Engineer_Name__c" value="{!PageMCEElement.Engineer_Name__c}"/>
            </td>
            <td style ="text-align: left;">
                <apex:outputText style="margin-left:20%;" value="手机号码:"  /> &nbsp;&nbsp;&nbsp;&nbsp;
            </td>
            <td style ="text-align: left;">
                 <apex:inputTextarea id="Phone_Number__c" value="{!PageMCEElement.Phone_Number__c}"/>
            </td>
        </tr>
        <tr>
            <td style ="text-align: left;">
                <apex:outputText style="margin-left:20%;" value="点检:"  /> &nbsp;&nbsp;&nbsp;&nbsp;
            </td>
            <td style ="text-align: left;">
                <div class="requiredInput"><div class="requiredBlock"></div>
                    每年
                    <apex:selectList style="margin-left:3px;margin-right:3px" size="1" id="Inspection_Time__c" value="{!PageMCEElement.Inspection_Time__c}" onchange="AllChecktime();">
                        <apex:selectOptions value="{!Tour_Check}"/>
                    </apex:selectList>次
                    (必填项)
                </div>
            </td>
            <td style ="text-align: left;">
                <apex:outputText style="margin-left:20%;" value="除尘:"  /> &nbsp;&nbsp;&nbsp;&nbsp;
            </td>
            <td style ="text-align: left;">
                每年
                <apex:selectList style="margin-left:3px;margin-right:3px" size="1" id="Dedust__c" value="{!PageMCEElement.Dedust__c}">
                    <apex:selectOptions value="{!Dedust}"/>
                </apex:selectList>次
            </td>
        </tr>
        <!-- fxk 2021、9、2 新加点检总次数 star-->
        <tr>
            <td style ="text-align: left;">
                <apex:outputText style="margin-left:20%;" value="点检总次数:"  /> &nbsp;&nbsp;&nbsp;&nbsp;
            </td>
            <td style ="text-align: left;">
                共
                <apex:outputText style="margin-left:3px;margin-right:3px;width:25px" id="Contract_Limit_Times__c" value="{!PageMCEElement.Contract_Limit_Times__c}">
                </apex:outputText>次
            </td>
        </tr>
        <!-- fxk 2021、9、2 新加点检总次数 end-->
        <tr>
            <td style ="text-align: left;">
                <apex:outputText value="合同份数:甲方:" style="margin-left:20%" />
            </td>
            <td style ="text-align: left;">
                <apex:selectList style="margin-left:3px;margin-right:3px" size="1" id="First_Party_Contract_Number__c" value="{!PageMCEElement.First_Party_Contract_Number__c}">
                    <apex:selectOptions value="{!First_Party_Contract_Number}"/>
                        </apex:selectList>份
               </td>
            <td style ="text-align: left;">
                <apex:outputText value="乙方:" style="margin-left:20%" />
            </td>
            <td>
                <apex:selectList style="margin-left:3px;margin-right:3px" size="1" id="Second_Party_Contract_Number__c" value="{!PageMCEElement.Second_Party_Contract_Number__c}">
                    <apex:selectOptions value="{!First_Party_Contract_Number}"/>
                </apex:selectList>
                份
           </td>
        </tr>
    </table>
    <div style="margin-left:5%;">
        <apex:outputText >
           协商方式:<apex:selectList style="margin-left:1px;margin-right:10px" size="1" id="Negotiate_Mean__c" value="{!PageMCEElement.Negotiate_Mean__c}">
                 <apex:selectOptions value="{!Negotiate_Mean}"/>
            </apex:selectList>提示信息:(1)任何一方有权向设在北京的中国国际经济贸易仲裁委员会申请仲裁,仲裁的裁决是终局性的,对双方均有约束力。(2)向甲方所在地有管辖权的人民法院提起诉讼。(3)向乙方所在地有管辖权的人民法院提起诉讼。
        </apex:outputText>
    </div>
    </apex:outputPanel>
    </apex:pageBlockSection>
        <apex:pageBlockButtons id="allButtons">
        <apex:outputPanel rendered="{!IF(PageMCEElement.Status__c != '引合中', 'true', 'false')}">
            <apex:commandButton styleClass="align-save-button" disabled="true" id="SaveButton1" value="保存"  action="{!save}" onclick="blockme();" reRender="hiddenInput,Messages"  oncomplete="CloseJs();"/>
            <apex:commandButton disabled="true" id="CancelButton1" value="取消" onclick="CloseJs(); return false;"/>
            <apex:commandButton disabled="true" id="PrintButton1" value="打印" action="{!print}" onclick="blockme();" rerender="hiddenInput,Messages,pdfPrint"  oncomplete="PrintJs();" />
        </apex:outputPanel>
        <apex:outputPanel id="bottom" rendered="{!IF(PageMCEElement.Status__c == '引合中', 'true', 'false')}">
            <apex:commandButton id="SaveButton" value="保存"  action="{!save}" onclick="blockme();" reRender="hiddenInput,Messages"  oncomplete="CloseJs();"/>
            <apex:commandButton id="CancelButton" value="取消" onclick="CloseJs(); return false;"/>
            <apex:commandButton id="PrintButton" value="打印" action="{!print}" onclick="blockme();" rerender="hiddenInput,Messages,pdfPrint"  oncomplete="PrintJs();" />
        </apex:outputPanel>
        </apex:pageBlockButtons>
    </apex:pageBlock>
    </body>
    </apex:form>
<apex:outputPanel id="pdfPrint">
<script type="text/javascript">
    function PrintJs() {
        var Rs = j$(escapeVfId('allPage:allForm:statusSave')).value();
        if(Rs == 'Fin'){
            unblockUI();
            if ('{!printContract}' == 'true') {
                //HWAG-BHT7XX 2019/11/26 START
                if('{!agreeUpperLimit}' == 'true'){
                // 打印医院限次合同配置
                window.open('/apex/NewMCHPDFLimit?id={!PageMCEElement.id}', 'MCHLimitPDF');
                window.close();
                }else{
                // 打印医院合同配置
                window.open('/apex/NewMCHPDF?id={!PageMCEElement.id}', 'MCHPDF');
                window.close();
                }
                //HWAG-BHT7XX 2019/11/26 END
             }else if ('{!printAgent}' == 'true') {
                 if('{!agreeUpperLimit}' == 'true'){
                //打印经销商限次合同
                window.open('/apex/NewMCAgentPDFLimit?id={!PageMCEElement.id}', 'MCAgentLimitPDF');
                window.close()
                }else{
                //打印经销商合同
                window.open('/apex/NewMCAgentPDF?id={!PageMCEElement.id}', 'MCHPDF');
                window.close();
                }
            }else {
                alert('1');
            }
        }else{
            unblockUI();
        }
    }
</script>
</apex:outputPanel>
</apex:page>
force-app/main/default/pages/NewPaymentPlanLoad.page-meta.xml
New file
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>35.0</apiVersion>
    <availableInTouch>false</availableInTouch>
    <confirmationTokenRequired>false</confirmationTokenRequired>
    <label>NewPaymentPlanLoad</label>
</ApexPage>
force-app/main/default/pages/NewRentalApply.page
New file
@@ -0,0 +1,661 @@
<apex:page standardController="Rental_Apply__c" extensions="RentalApplyController" id="page"
lightningStylesheets="true">
    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
    <apex:includeScript value="{! URLFOR($Resource.AWSService, 'AWSService.js') }" />
    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
    <!-- <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/> -->
    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
    <style>
        .disabledbutton {
            pointer-events: none;
            opacity: 0.4;
        }
    </style>
    <script>
        //Initial Required Information
        var staticResources = JSON.parse('{!staticResource}');
        //zhj MEBG新方案改造 2022-11-29 start
        var staticResourcesV2 = JSON.parse('{!staticResourceV2}');
        var isEdit = JSON.parse('{!isEdit}');
        var phoneNumber = '';
        var directShippmentAddress = '';
        //zhj MEBG新方案改造 2022-11-29 end
        var staticResourcesContact = JSON.parse('{!staticResourceContact}');
        var requiredFieldAPIList = JSON.parse('{!requiredFieldAPIListStr}');
        var fieldAPIToLabelMap = JSON.parse('{!fieldAPIToLabelMapStr}');
        var VLookUpFields = new Set(['OwnerId','OPDPlan__c','Zsq_Rental_Apply__c','Loaner_medical_Staff__c','Hospital__c','Strategic_dept__c','Account__c','Repair__c','Campaign__c','QIS_number__c','QISRepair__c','NewRepair__c','Follow_UP_Opp__c','Statu_Achievements__c','Shipment_address__c','Dealer__c','Old_Rental_Apply__c','OPD__c']);
        var userVLookUpFields = ['Person_In_Charge__c','Return_Trake_Staff__c','applyUser__c','Rental_Assistant__c','Assign_Person__c','ZongjianApprovalManager__c','BuchangApprovalManager__c','JingliApprovalManager__c','BuchangApprovalManagerSales__c','SalesManager__c'];
        var redirectMode = 'Save';
        //Redirect Required Parameter
        var redirectCallBack = function redirectCallBack(sfId,errorMessage) {
            if(sfId){
                if (redirectMode == 'Save') {
                window.open('/' + sfId, '_self');
            } else if (redirectMode == 'SaveAndNew') {
                window.open('/a3i/e', '_self');
            }
            }else{
                // alert(errorMessage);
                alertErrorMessage(errorMessage);
            }
        }
        //Query Required Parameter
        var queryBack = function queryBack(data) {
            console.log('data = ' + data);
            // document.querySelector("[data-id='Phone_number__c']").value = data.object.phoneNumber;
            // document.querySelector("[data-id='direct_shippment_address__c']").value = data.object.directShippmentAddress;
            //zhj MEBG新方案改造 2022-11-29 start
            if(document.querySelector("[data-id='Phone_number__c']")){
                document.querySelector("[data-id='Phone_number__c']").value = data.object.phoneNumber;
                phoneNumber = data.object.phoneNumber;
            }
            if(document.querySelector("[data-id='direct_shippment_address__c']")){
                document.querySelector("[data-id='direct_shippment_address__c']").value = data.object.directShippmentAddress;
                directShippmentAddress = data.object.directShippmentAddress;
            }
            //zhj MEBG新方案改造 2022-11-29 end
            unblockUI();
            enableButtonStatus();//Add by Li Jun 20220418
        };
        //Check If Insert Or Update
        var insertOrUpdateBack = function insertOrUpdateBack(payloadJson, result, isNewMode) {
            debugger
            console.log(result);
            let r = result;
            console.log('Result from AWS' + JSON.stringify(r));
            console.log('payloadJson=' + JSON.stringify(payloadJson));
            payloadJson.Phone_number__c = r.object[0].phoneNumber;
            payloadJson.direct_shippment_address__c = r.object[0].directShippmentAddress;
            //zhj MEBG新方案改造 2022-11-29 start
            // payloadJson.Phone_Number_Encrypt__c = r.object[0].phoneNumberEncrypt;
            // payloadJson.Direct_Shippment_Address_Encrypt__c = r.object[0].directShippmentAddressEncrypt;
            //zhj MEBG新方案改造 2022-11-29 end
            payloadJson.AWS_Data_Id__c = '{!AWSDataId}';
            if('{!rtTypeId}'){
                payloadJson.RecordTypeId = '{!rtTypeId}';//Add by Li Jun for Record Type Issue 20220419
            }
            if (isNewMode || {!isCloneMode}) {
                payloadJson.AWS_Data_Id__c = r.object[0].dataId;
                delete payloadJson.OwnerId;
            } else {
                payloadJson.AWS_Data_Id__c = '{!AWSDataId}';
            }
            if('{!rtTypeId}'){
                payloadJson.RecordTypeId = '{!rtTypeId}';//Add by zhj for Record Type Issue 20220421
            }
            return payloadJson;
        }
        //Add Button status start 20220418
        function enableButton(obj) {
            obj.classList.remove("btnDisabled");
        }
        function disableButton(obj) {
            obj.classList.add("btnDisabled");
        }
        function disableButtonStatus() {
            let btnList = document.getElementsByClassName('btn');
            for (let i = 0; i < btnList.length; i++) {
                disableButton(btnList[i]);
            }
        }
        function enableButtonStatus() {
            let btnList = document.getElementsByClassName('btn');
            for (let i = 0; i < btnList.length; i++) {
                enableButton(btnList[i]);
            }
        }
        disableButtonStatus();
        //Add Button status end 20220418
        // New Or Edit
        function EditButton(isDisabled){
            var topele = document.getElementById('topButtonRow');
            var bottomele = document.getElementById('bottomButtonRow');
            if (isDisabled) {
                topele.classList.add("disabledbutton");
                bottomele.classList.add("disabledbutton");
            }else {
                topele.classList.remove("disabledbutton");
                bottomele.classList.remove("disabledbutton");
            }
        }
        function ProcessPI(rentalApplyJson, payloadForNewPI) {
            blockme();
            if ({!isNewMode} || {!isCloneMode}) {
                NewPIToAWS(rentalApplyJson, payloadForNewPI)
            }else {
                UpdatePIToAWS(rentalApplyJson, payloadForNewPI)
            }
        }
        var GetEleByClass = function(class_name){
            let eles = document.getElementsByClassName(class_name);
            if(eles.length > 0) return eles[0];
            return null;
        }
        function GetEleApiName(ele){
            for(let ci in ele.classList){
                let c = ele.classList[ci];
                if(c.indexOf('PIBackApi_')>-1){
                    return c.replace('PIBackApi_','');
                }
            }
            return '';
        }
        function IsFormTag(tag_name){
            if (!tag_name) {
                return false;
            }
            return ['input','select','textarea'].indexOf(tag_name.toLowerCase())>-1;
        }
        function IsFormElement(e){
            return IsFormTag(e.tagName);
        }
        //Get Sensitive Information
        function getPIPayload(rentalApplyJson) {
            let rentalApplyPayloadList = [];
            let phoneNumber = rentalApplyJson.Phone_number__c;
            let directShippmentAddress = rentalApplyJson.direct_shippment_address__c;
            let rentalApplyPIData = new Object();
            rentalApplyPIData.phoneNumber = phoneNumber;
            rentalApplyPIData.directShippmentAddress = directShippmentAddress;
            rentalApplyPIData.sfRecordId = '';
            console.log('rentalApply PI Data:' + JSON.stringify(rentalApplyPIData));
            rentalApplyPayloadList.push(rentalApplyPIData);
            console.log(JSON.stringify(rentalApplyPayloadList));
            return JSON.stringify(rentalApplyPayloadList);
        }
        //Check Validate Field Value
        function validateFieldValueFormate() {
            return true;
        }
        function getCKEinstance(api_name){
            let t = jQuery("label[for$='textAreaDelegate_"+api_name+"']").closest("tr").find("textarea")[0];
            if(t && t.id){
                return CKEDITOR.instances[t.id]
            }
            return null;
        }
        //Get Page Information
        function getRentalApplyInformation() {
            let nodelist = document.querySelectorAll("[data-id]");
            let result = {}
            //富文本
            // if(document.querySelector("[aria-describedby = 'cke_38']")){
            //     result.HP_received_sign_rich__c = document.querySelector("[aria-describedby = 'cke_38']").contentWindow.document.getElementsByTagName('body')[0].innerHTML
            // }
            // result.HP_received_sign_rich__c = CKEDITOR.instances["page:form:block:j_id34:12:j_id35:j_id36:1:j_id37:textAreaDelegate_HP_received_sign_rich__c"].getData();
            // if(document.querySelector("[aria-describedby = 'cke_71']")){
            //     result.  Extension_List_RentalApply__c = document.querySelector("[aria-describedby = 'cke_71']").contentWindow.document.getElementsByTagName('body')[0].innerHTML
            // }
            for (let index = 0; index < nodelist.length; index++) {
                if (VLookUpFields.has(nodelist[index].getAttribute("data-id"))) {
                    console.log(nodelist[index].id.indexOf('lkwgt'));
                    if (nodelist[index].id.indexOf('lkwgt') == -1) {
                        let vlookUpNodeId = nodelist[index].id + '_lkid';
                        if(document.getElementById(vlookUpNodeId)){
                            let vlookUpNodeValue = document.getElementById(vlookUpNodeId).value;
                            result[nodelist[index].getAttribute("data-id")] = vlookUpNodeValue;
                        }
                    }
                } else if (nodelist[index].type == 'checkbox') {
                    result[nodelist[index].getAttribute("data-id")] = nodelist[index].checked;
                } else if (nodelist[index].type == 'select-multiple') {
                    //nodelist[index].getAttribute("data-id")
                    let multiple = nodelist[index].getAttribute("data-id");
                    let targets = document.querySelector("[data-id=" + multiple + "]").parentNode.children[1].children[0].children[1].children[2].children[0].innerText;
                    targets = targets.replace(/\n/g, ";");
                    console.log('targets = ' + targets);
                    result[nodelist[index].getAttribute("data-id")] = targets;
                } else {
                    result[nodelist[index].getAttribute("data-id")] = nodelist[index].value;
                }
                let x = index + 1;
                if (x <= nodelist.length - 1 && (nodelist[x].getAttribute("data-id") == nodelist[index].getAttribute("data-id"))) {
                    index++;
                }
            }
            for (let i = 0; i < userVLookUpFields.length; i++) {
                if(document.querySelector("[data-id='" + userVLookUpFields[i] + "']")!=null){
                    let userVlookUpNodeValue = document.querySelector("[data-id='" + userVLookUpFields[i] + "']").children[1].value;
                    console.log('userVlookUpNodeValue:'+userVlookUpNodeValue);
                    if(userVlookUpNodeValue!='000000000000000'){
                        result[userVLookUpFields[i]] = userVlookUpNodeValue;
                    }
                }
            }
            if(api_id_map['demo_purpose2__c']){
                result.demo_purpose2__c = document.getElementById(api_id_map['demo_purpose2__c']).value!='_\x01_'?document.getElementById(api_id_map['demo_purpose2__c']).value:'';
            }
            if(api_id_map['ToAgency__c']){
                result.ToAgency__c = document.getElementById(api_id_map['ToAgency__c']).value!='_\x01_'?document.getElementById(api_id_map['ToAgency__c']).value:'';
            }
            //document.querySelector("[id='page:form:block:j_id34:0:j_id35:j_id36:18:j_id37']").disabled =true; // Commented By Li Jun 20220304
            if(api_id_map['Loaner_cancel_reason__c']){
                result.Loaner_cancel_reason__c = document.getElementById(api_id_map['Loaner_cancel_reason__c']).value!='_\x01_'?document.getElementById(api_id_map['Loaner_cancel_reason__c']).value:'';
            }
            // else{
            //     if(document.querySelector("[id='page:form:block:j_id34:11:j_id35:j_id36:1:j_id37']")!=null){
            //         result.Loaner_cancel_reason__c = document.querySelector("[id='page:form:block:j_id34:11:j_id35:j_id36:1:j_id37']").value;
            //     }
            // }
            // //格式化时间
            // if(result.HP_received_sign_day__c){
            //     result.HP_received_sign_day__c = result.HP_received_sign_day__c.replace(/\//g, '-')+':00';
            // }
            let e = getCKEinstance('HP_received_sign_rich__c');
            if(e){
                    result.HP_received_sign_rich__c = e.getData();
                }
                e = getCKEinstance('Extension_List_RentalApply__c');
            if(e){
                    result.Extension_List_RentalApply__c = e.getData();
                }
            if(document.getElementById(api_id_map['Office_Assistant1__c'] + '_lkid')!=null){
                // result.ToAgency__c = document.getElementById('page:form:block:j_id34:0:j_id35:j_id36:18:j_id37').value;
                result.Office_Assistant1__c = document.getElementById(api_id_map['Office_Assistant1__c'] + '_lkid').value;
            }
            if(document.getElementById(api_id_map['Office_Assistant2__c'] + '_lkid')!=null){
                // result.ToAgency__c = document.getElementById('page:form:block:j_id34:0:j_id35:j_id36:18:j_id37').value;
                result.Office_Assistant2__c = document.getElementById(api_id_map['Office_Assistant2__c'] + '_lkid').value;
            }
            console.log(JSON.stringify(result));
            return result;
        }
        //Query from AWS
        function QueryRentalApplyFromAWS() {
            AWSService.query(staticResources.queryUrl, '{!AWSDataId}', queryBack, staticResources.token);
        }
        //Update Sensitive Information to AWS
        function UpdatePIToAWS(rentalApplyJson, payloadForNewPI) {
            let controllerSaveMethod = '{!$RemoteAction.RentalApplyController.saveRentalApply}';
            let obj = JSON.parse(payloadForNewPI);
            obj[0].dataId = '{!AWSDataId}';
            let payloadForNewPIJson = JSON.stringify(obj);
            //zhj MEBG新方案改造 2022-11-29 start
            //AWSService.update(staticResources.updateUrl, rentalApplyJson, payloadForNewPIJson, controllerSaveMethod, staticResources.token, staticResources.transactionUrl, false, insertOrUpdateBack, redirectCallBack);
            AWSService.update(staticResourcesV2.updateUrl, rentalApplyJson, payloadForNewPIJson, controllerSaveMethod, staticResources.token, staticResourcesV2.transactionUrl, false, insertOrUpdateBack, redirectCallBack);
            //zhj MEBG新方案改造 2022-11-29 end
        }
        //Insert Sensitive Information to AWS
        function NewPIToAWS(rentalApplyJson, payloadForNewPI) {
            let controllerSaveMethod = '{!$RemoteAction.RentalApplyController.saveRentalApply}';
            //zhj MEBG新方案改造 2022-11-29 start
            //AWSService.insert(staticResources.newUrl, rentalApplyJson, payloadForNewPI, controllerSaveMethod, staticResources.token, staticResources.transactionUrl, true, insertOrUpdateBack, redirectCallBack);
            debugger
            console.log('staticResourcesV2.newUrl = ' + staticResourcesV2.newUrl);
            AWSService.insert(staticResourcesV2.newUrl, rentalApplyJson, payloadForNewPI, controllerSaveMethod, staticResources.token, staticResourcesV2.transactionUrl, true, insertOrUpdateBack, redirectCallBack);
            //zhj MEBG新方案改造 2022-11-29 end
        }
        //Check Required Fields
        function checkRequiredFieldMsg(formData) {
            let blankRequiredFields = '';
            for (i = 0; i < requiredFieldAPIList.length; i++) {
                if (formData[requiredFieldAPIList[i]] && !VLookUpFields.has(requiredFieldAPIList[i])) {
                    continue;
                }else if(VLookUpFields.has(requiredFieldAPIList[i]) && formData[requiredFieldAPIList[i]] != '000000000000000'){
                    continue;
                } else {
                    if (blankRequiredFields == '') {
                        blankRequiredFields = blankRequiredFields + fieldAPIToLabelMap[requiredFieldAPIList[i]];
                    } else {
                        blankRequiredFields = blankRequiredFields + ',' + fieldAPIToLabelMap[requiredFieldAPIList[i]];
                    }
                }
            }
            return blankRequiredFields;
        }
        //Base Process
        function saveRentalApplyProcess(saveMode) {
            EditButton(true);
            redirectMode = saveMode;
            console.log('redirectMode' + redirectMode);
            hiddenErrorMsgNode();
            //1. Get rentalApply Information from Form
            let rentalApplyJson = getRentalApplyInformation();
            //2. Validate the rentalApply field value formate, for example the email formate or phone formate
            let validationResultMessage = validateFieldValueFormate();
            console.log(validationResultMessage);
            if (!validationResultMessage) {
                //Popup error message.  - To Do After POC
                alertErrorMessage('邮箱格式输入有误,请重新输入!');
                return
            }
            // Check Required Field
            let checkRequiredFieldMsgResult = checkRequiredFieldMsg(rentalApplyJson);
            if (checkRequiredFieldMsgResult) {
                alertErrorMessage('{!Input_Required_Field_Msg}' + checkRequiredFieldMsgResult);
                return
            }
            //3. Prepare the payload for New PI API To AWS - To Do
            let payloadForNewPI = getPIPayload(rentalApplyJson);
            //zhj MEBG新方案改造 2022-11-29 start
            debugger
            if(isEdit == true && (rentalApplyJson.Phone_number__c != phoneNumber || rentalApplyJson.direct_shippment_address__c != directShippmentAddress)){
                alertErrorMessage('申请单批准后,不能编辑备品借用信息');
                return
            }
            //zhj MEBG新方案改造 2022-11-29 end
            //4. rentalApply to AWS
            ProcessPI(rentalApplyJson, payloadForNewPI);
        }
        //Alert Error Message
        function alertErrorMessage(errorMsg) {
            let errorMsgNode = document.getElementById("page:form:block:msgContent");
            errorMsg = '错误:无效数据。' + '\n' + errorMsg;
            errorMsgNode.innerText = errorMsg;
            errorMsgNode.className = 'pbError';
            unblockUI();
            EditButton(false);
        }
        //Hide Error Message
        function hiddenErrorMsgNode() {
            let errorMsgNode = document.getElementById("page:form:block:msgContent");
            errorMsgNode.innerText = '';
            errorMsgNode.className = '';
        }
        //替换vlookup
        function replaceSearchContactLookup() {
            let lookUpNode = htmlToElement(contactHtmlString);
            console.log(lookUpNode);
            if (!{!isNewMode}) {
                queryContactName();
            }
            let parentNode = document.querySelector("[data-id='Loaner_medical_Staff__c']").parentNode;
            document.querySelector("[data-id='Loaner_medical_Staff__c']").removeAttribute("onchange");
            parentNode.replaceChild(lookUpNode, document.querySelector("[data-id='Loaner_medical_Staff__c']").parentNode.children[2]);
        }
        var newSearchContactWindow = null;
        var contactHtmlString = '<img src="/img/s.gif" onclick="searchContact(\'page:form:contactId\')" alt="Reference Document Number Lookup" class="lookupIcon"  title="Reference Document Number Lookup (New Window)"/>';
        function htmlToElement(html) {
            var template = document.createElement('template');
            html = html.trim(); // Never return a text node of whitespace as the result
            template.innerHTML = html;
            return template.content.firstChild;
        }
        function queryContactName() {
            let sfId = document.getElementById(document.querySelector("[data-id='Loaner_medical_Staff__c']").id + '_lkid').value;
            let dataId = '';
            if ('{!contactsInfo}' != '') {
                let contactsInfo = JSON.parse('{!contactsInfo}');
                dataId = contactsInfo[sfId];
            } else if ('{!AWSDataId}' != '') {
                dataId = '{!AWSDataId}';
            }
            let queryBackContactName = function queryBackContactName(result){
                document.querySelector("[data-id='Loaner_medical_Staff__c']").value = result.object.lastName;
            };
            AWSService.query(staticResourcesContact.queryUrl, dataId, queryBackContactName, staticResourcesContact.token);
        }
        //自定义lookup查询
        function searchContact(contactNodeId){
            let accountValue = "";
            if (document.querySelector("[data-id='Account__c']")) {
                let accountNodeId = document.querySelector("[data-id='Account__c']").id + '_lkid';
                accountValue = document.getElementById(accountNodeId).value;
            }
            let searchContactKeyWord = document.querySelector("[data-id='Loaner_medical_Staff__c']").value;
            console.log(accountValue);
            if(accountValue !='000000000000000'){
                let baseUrl = "/apex/SearchContactPage";
                let suffixUrl = "?contactId="+contactNodeId+"&accountId="+accountValue+"&searchContactKeyWord=" + searchContactKeyWord;
                let newSearchContactParam = 'height=600,width=800,left=100,top=100,dialogHide=true,resizable=no,scrollbars=yes,toolbar=no,status=no';
                newSearchContactWindow = window.open(baseUrl+suffixUrl, 'Popup', newSearchContactParam);
                if (window.focus) {
                    newSearchContactWindow.focus();
                }
                return false;
            }else{
                alertErrorMessage('{!PIPL_Input_Account_Error_Msg}');
            }
        }
        //窗口关闭时发生
        function closePopupWindow() {
            if (null != newSearchContactWindow) {
                newSearchContactWindow.close();
            }
            let contactInfoStr = document.getElementById('page:form:contactId').value;
            console.log('closePopup:'+contactInfoStr);
            let contactInfo = JSON.parse(contactInfoStr);
            let contactNodeId = document.querySelector("[data-id='Loaner_medical_Staff__c']").id + '_lkid';
            document.getElementById(contactNodeId).value = contactInfo.ContactId;
            document.querySelector("[data-id='Loaner_medical_Staff__c']").value = contactInfo.Name;
        }
    </script>
    <div class="bPageTitle">
        <div class="ptBody">
            <div class="content">
                <img src="/img/s.gif" alt="备品借出申请" class="pageTitleIcon" title="备品借出申请" />
                <h1 class="pageType">备品借出申请编辑
                    <span class="titleSeparatingColon">:</span>
                </h1>
                <h2 class="pageDescription"> 新建备品借出申请</h2>
                <div class="blank">&nbsp;</div>
            </div>
            <div class="links">
                <a href="javascript:openPopupFocusEscapePounds(%27https://help.salesforce.com/apex/htdoor?loc=help&amp;target=rentalApplys_edit.htm&amp;section=rentalApplys&amp;language=zh_CN&amp;release=234.18.8&amp;instance=CS117&amp;showSplash=true%27, %27Help%27, 700, 600, %27width=700,height=600,resizable=yes,toolbar=yes,status=no,scrollbars=yes,menubar=yes,directories=no,location=no,dependant=no%27, false, false);"
                    title="此页面的帮助 (新窗口)">
                    <span class="helpLink">此页面的帮助</span>
                    <img src="/img/s.gif" alt="" class="helpIcon" />
                </a>
            </div>
        </div>
        <div class="ptBreadcrumb"></div>
    </div>
    <apex:form id="form">
        <apex:inputHidden value="{!contactId}" id="contactId"/>
        <apex:pageblock id="block">
            <div class="pbHeader">
                <table cellspacing="0" cellpadding="0" border="0">
                    <tbody>
                        <tr>
                            <td class="pbTitle">
                                <img src="/img/s.gif" alt="" class="minWidth" title="" width="1" height="1" />
                                <h2 class="mainTitle">备品借出申请编辑</h2>
                            </td>
                            <td class="pbButton" id="topButtonRow" style="pointer-events: none; opacity: 0.4;">
                                <input class="btn" type="Button" value="保存" onclick="saveRentalApplyProcess('Save')" />
                                <input class="btn" type="Button" value="保存并新建" onclick="saveRentalApplyProcess('SaveAndNew')" />
                                <apex:commandButton action="{!cancel}" value="取消" />
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <!-- Error Msg-->
            <div style="text-align: center;">
                <apex:outputPanel id="errorMsg">
                    <apex:pageMessages id="msgContent" escape="false" />
                </apex:outputPanel>
            </div>
            <!-- Iterate the layoutSections, which is a list of sections -->
            <apex:repeat value="{!layoutSections}" var="layoutSection">
                <apex:pageBlockSection title="{!layoutSection.name}" collapsible="{!layoutSection.allowCollapse}" columns="{!layoutSection.columns}">
                    <!--Each section has layoutFields, let's iterate them as well-->
                    <apex:repeat value="{!layoutSection.layoutFields}" var="layoutField">
                        <apex:inputField styleClass="PIBackApi PIBackApi_{!layoutField.fieldAPI}" html-data-id="{!layoutField.fieldAPI}" value="{!Rental_Apply__c[layoutField.fieldAPI]}" style="width:50px" rendered="{!not(layoutField.isPlaceHOlder)&&isNewMode}"
                            required="{!layoutField.isRequired}" />
                        <apex:inputField styleClass="PIBackApi PIBackApi_{!layoutField.fieldAPI}" html-data-id="{!layoutField.fieldAPI}" value="{!Rental_Apply__c[layoutField.fieldAPI]}" rendered="{!not(layoutField.isPlaceHOlder)&&not(isNewMode)&&layoutField.fieldAPI!='RecordTypeId'}"
                            required="{!layoutField.isRequired}" />
                        <apex:outputField styleClass="PIBackApi PIBackApi_{!layoutField.fieldAPI}" html-data-id="{!layoutField.fieldAPI}" value="{!Rental_Apply__c[layoutField.fieldAPI]}" rendered="{!not(layoutField.isPlaceHOlder)&&not(isNewMode)&&layoutField.fieldAPI=='RecordTypeId'}"
                       />
                        <apex:pageblocksectionitem rendered="{!layoutField.isPlaceHolder}">
                        </apex:pageblocksectionitem>
                    </apex:repeat>
                </apex:pageBlockSection>
            </apex:repeat>
            <script>
                blockme(); //zhj 2022-12-28 improve
               var init_nodes = document.getElementsByClassName("PIBackApi");
                var api_id_map={};
                for(let ei in init_nodes){
                    let e = init_nodes[ei];
                    if(IsFormElement(e)){
                        if(e.getAttribute("multiple") != 'multiple' || e.style.display == 'none' && e.id.indexOf('selected') < 0){
                            api_id_map[GetEleApiName(e)] = e.id;
                        }
                    }else{
                        let eid = jQuery(e).find(".lookupInput input").attr("id")
                        if(eid){
                            eid += '_lkid';
                            if(document.getElementById(eid)){
                                api_id_map[GetEleApiName(e)] = eid;
                            }
                        }
                    }
                }
                console.log(api_id_map);
                //Append Page
                sfdcPage.appendToOnloadQueue(function () {
                    var layoutSections = JSON.parse('{!layoutSectionsStr}');
                    for (let m = 0; m < layoutSections.length; m++) {
                        let layoutSection = layoutSections[m].layoutFields;
                        for (let n = 0; n < layoutSection.length; n++) {
                            let layoutField = layoutSection[n];
                            if (layoutField.fieldAPI != '' && document.querySelector("[data-id='"+layoutField.fieldAPI+"']") != null) {
                                let e = document.querySelector("[data-id='"+layoutField.fieldAPI+"']");
                                console.log('layoutField.fieldAPI= ' + layoutField.fieldAPI);
                                e.disabled = !(layoutField.editableField);
                                if (!(layoutField.editableField)) {
                                    if (e.getAttribute("multiple") && e.getAttribute("multiple") == 'multiple') {
                                        e.parentNode.classList.add("disabledbutton");
                                    }
                                    if (e.tagName == 'DIV') {
                                        e.classList.add("disabledbutton");
                                    }
                                    if(document.querySelector('[data-id=Old_Rental_Apply__c] .lookupIcon')){
                                        document.querySelector('[data-id=Old_Rental_Apply__c] .lookupIcon').classList.add("disabledbutton");
                                    }
                                }
                            }
                        }
                    }
                    var onlyReadFields = ['ExtensionStatus__c','ExtensionApplicationTime_Initial__c','ExtensionApprovalTime_Initial__c','ExtensionApplicationTime_Final__c','ExtensionApprovalTime_Final__c','ExtensionSuccessTimes__c','ZongjianApprovalManager__c','BuchangApprovalManager__c','JingliApprovalManager__c','BuchangApprovalManagerSales__c','SalesManager__c'];
                    console.log(onlyReadFields);
                    for(let i=0;i<onlyReadFields.length;i++){
                        if(document.querySelector('[data-id='+onlyReadFields[i]+']')){
                            document.querySelector('[data-id='+onlyReadFields[i]+']').parentNode.remove();
                        }
                    }
                    //2. Query AWS Data by dataId
                    console.log('Mode for rentalApply Page:' + {!isNewMode});
                    if (!{!isNewMode}) {
                        QueryRentalApplyFromAWS();
                    }else{
                        enableButtonStatus();//Add by Li Jun 20220418
                    };
                    //Replace Vlookup Field
                    replaceSearchContactLookup();
                    document.querySelector("[data-id='OwnerId']").classList.add("disabledbutton");
                    document.getElementById('topButtonRow').style = '';
             document.getElementById('bottomButtonRow').style = '';
                    let previous_value = {};
                    jQuery(".lookupInput input").each(function(i,e){
                        let je =jQuery(e);
                        let dataid = je.attr('data-id');
                        if(['Loaner_medical_Staff__c'].indexOf(dataid) < 0) return;
                        jQuery(e).focus(function(){
                            previous_value[this.id] = this.value;
                        })
                        jQuery(e).change(function(){
                            if (previous_value[this.id] != jQuery(this).val()) {
                                document.getElementById(this.id+'_lkid').value = '';
                            }
                        })
                    });
                    unblockUI();
                    // jQuery(".lookupInput").each(function(i,e){
                    //     let je =jQuery(e).find('input');
                    //     je.attr("readonly","");
                    //     je.css("background","unset");
                    //     let dataid = je.attr('data-id');
                    //     if(['Hospital_Name__c','Department_Class__c','OwnerId'].indexOf(dataid) > -1) return;
                    //     jQuery(e).children(":last-child").before('<img class="closeIcon" data-id="'+dataid+'" generate="" alt="Clear" src="/s.gif" style="display: inline-block;">');
                    // })
                    // jQuery(".lookupInput").on("mouseenter","img[generate]",function(e){
                    //     this.className = "closeIconOn";
                    // });
                    // jQuery(".lookupInput").on("mouseleave","img[generate]",function(e){
                    //     this.className = "closeIcon"
                    // });
                    // jQuery(".lookupInput").on("click","img[generate]",function(e){
                    //     let id = jQuery("input[data-id='"+jQuery(this).attr("data-id")+ "']").attr("id");
                    //     let input = document.getElementById(id);
                    //     if(input){
                    //         input.value = '';
                    //         let hidden = document.getElementById(id+'_lkid');
                    //         if(hidden){
                    //             hidden.value = '';
                    //         }
                    //     }
                    // });
                });
            </script>
            <div class="pbBottomButtons">
                <table cellspacing="0" cellpadding="0" border="0">
                    <tbody>
                        <tr>
                            <td class="pbTitle">
                                <img src="/img/s.gif" alt="" class="minWidth" title="" width="1" height="1" />&nbsp;</td>
                            <td class="pbButtonb" id="bottomButtonRow" style="pointer-events: none; opacity: 0.4;">
                                <input class="btn" type="Button" value="保存" onclick="saveRentalApplyProcess('Save')" />
                                <input class="btn" type="Button" value="保存并新建" onclick="saveRentalApplyProcess('SaveAndNew')" />
                                <apex:commandButton action="{!cancel}" value="取消" />
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </apex:pageblock>
    </apex:form>
</apex:page>
force-app/main/default/pages/NewRentalApply.page-meta.xml
New file
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>54.0</apiVersion>
    <availableInTouch>false</availableInTouch>
    <confirmationTokenRequired>false</confirmationTokenRequired>
    <label>NewRentalApply</label>
</ApexPage>
force-app/main/default/pages/PaymentPlanLoad.page
New file
@@ -0,0 +1,468 @@
<apex:page Controller="PaymentPlanLoadController"  showHeader="false" sidebar="false" action="{!init}" id="allPage" title="维修合同文本信息录入页面" pageStyle="PageStyleCss" lightningStylesheets="true" >
<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
<style type="text/css">
    .BlockSytle{
        width: 1000px;
    }
    .PageStyleCss{
        width: 980px;
        height: 340px;
    }
    input{
        disabled: false;
    }
</style>
<script type="text/javascript">
    function init() {
        Convert_All_Amount();
        // 新增点检总次数(只在页面中显示)fxk 2021/9/2 Star
        AllChecktime();
        // 新增点检总次数(只在页面中显示)fxk 2021/9/2 ENd
        Initdisabled();
    }
    function Convert_All_Amount() {
        var Total_Contract_Amount = j$(escapeVfId('allPage:allForm:Contract_Amount_Hidden')).val();
        var Total_Contract_Amount_In_Words = j$(escapeVfId('allPage:allForm:Total_Contract_Amount_In_Words_Hidden')).val();
        if( Total_Contract_Amount !=null && Total_Contract_Amount!=undefined && Total_Contract_Amount.length > 0 ){
            Convert_Contract_Amount();
            for(var i=1; i<7; i++){
            Convert_Amount(i);
            }
        }
    }
    function Initdisabled() {
        var Status = '{!PageMCEElement.Status__c}';
        if(Status != '引合中'){
        j$(escapeVfId('allPage:allForm:allBlock:Is_Standard_Contract')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Term_Of_Payment__c')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:one_off_payment_agreed_period__c')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Total_Contract_Amount_In_Words')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Total_Payment_Time__c')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Date_First')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Date_Second')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Date_Third')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Date_Forth')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Date_Fifth')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Date_Sixth')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Sum_1')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Sum_2')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Sum_3')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Sum_4')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Sum_5')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Sum_6')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Sum_6')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Small_Repair_Time__c')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Live_Technical_Support_Time__c')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Tour_Check__c')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Engineer_Name__c')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Phone_Number__c')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Inspection_Time__c')).attr("disabled", true);
        // 新增点检总次数(只在页面中显示)fxk 2021/9/2 Star
        j$(escapeVfId('allPage:allForm:allBlock:Contract_Limit_Times__c')).attr("disabled", true);
        // 新增点检总次数(只在页面中显示)fxk 2021/9/2 End
        j$(escapeVfId('allPage:allForm:allBlock:Dedust__c')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:First_Party_Contract_Number__c')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Second_Party_Contract_Number__c')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Negotiate_Mean__c')).attr("disabled", true);
        }
    }
    function Convert_Contract_Amount() {
        var Total_Contract_Amount = j$(escapeVfId('allPage:allForm:Contract_Amount_Hidden')).val();
        var Total_Contract_Amount_In_Words = smalltoBIG(Total_Contract_Amount);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Total_Contract_Amount_In_Words')).text(Total_Contract_Amount_In_Words);
        j$(escapeVfId('allPage:allForm:Total_Contract_Amount_In_Words_Hidden')).val(Total_Contract_Amount_In_Words);
    }
    function Convert_Amount(number) {
        var Amount = j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Sum_'+number)).val();
        if(Amount == null || Amount== undefined || Amount.length == 0)
            return;
        var Amount_In_Words = smalltoBIG(Amount);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Sum_' + number + '_in_Word')).text(Amount_In_Words);
        j$(escapeVfId('allPage:allForm:Payment_Plan_Sum_' + number + '_in_Word_Hidden')).val(Amount_In_Words);
        j$(escapeVfId('allPage:allForm:allBlock:paymentPlan:Payment_Plan_Sum_'+number)).val(toNumComma(Amount));
    }
    /** 数字金额大写转换(可以处理整数,小数,负数) */
    function smalltoBIG(n)
    {
        var fraction = ['角', '分'];
        var digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
        var unit = [ ['元', '万', '亿'], ['', '拾', '佰', '仟']  ];
        var head = n < 0? '欠': '';
        n = n.replace(/\,/g,"");
        n = Math.abs(n);
        var s = '';
        for (var i = 0; i < fraction.length; i++){
            s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
        }
        s = s || '整';
        n = Math.floor(n);
        for (var i = 0; i < unit[0].length && n > 0; i++)     {
            var p = '';
            for (var j = 0; j < unit[1].length && n > 0; j++)     {
                p = digit[n % 10] + unit[1][j] + p;
                n = Math.floor(n / 10);
            }
            s = p.replace(/(零.)*零$/, '').replace(/^$/, '零')  + unit[0][i] + s;
        }
        return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
    }
    function CloseJs() {
        // body...
        var Rs = j$(escapeVfId('allPage:allForm:statusSave')).value();
        // fxk 2021/8/31 点检次数必须填 end
        // var saveErrorflag = j$(escapeVfId('saveErrorflag')).value();
        if(Rs == 'Fin'){
            // fxk 2021/8/31 点检次数必须填 end
            // zzm 2023/4/24 classic 改版为lightning
            // window.opener.top.location.href = '/{!PageMCEElement.id}';
            // window.close();
            window.location.href = '/{!PageMCEElement.id}';
   //          top.window.close();
            unblockUI();
        }else{
            unblockUI();
        }
    }
    function ChangeTermofPaymentPlanJS(){
        ChangeTermofPaymentPlan();
    }
    // 新增点检总次数(只在页面中显示)fxk 2021/9/2 Star
    function AllChecktime(){
        var Allchecks;
        var ContractAllMonth = '{!Contract_validMonth}';//j$(escapeVfId('allPage:allForm:Contract_validMonth')).value();
        // alert(ContractAllMonth);
        var checks = j$(escapeVfId('allPage:allForm:allBlock:TextInformation:Inspection_Time__c')).val();
        // alert(checks);
        // add 一年内点检区间不够生成一次点检计划,默认生成一个点检计划,计划区间为合同开始日-结束日 2021/10/25 fxk Star
        if((checks == 1 && ContractAllMonth < 9)
            || (checks == 2 && ContractAllMonth < 6)
            || (checks == 3 && ContractAllMonth < 4)
            || (checks == 4 && ContractAllMonth < 3)){
            Allchecks = 1;
        }else{
        // add 一年内点检区间不够生成一次点检计划,默认生成一个点检计划,计划区间为合同开始日-结束日 2021/10/25 fxk End
            if (ContractAllMonth - parseInt(ContractAllMonth / 12) * 12 >= 6 && checks == 1){
                Allchecks = parseInt((ContractAllMonth * checks)/12+1);
            }else{
                Allchecks = parseInt((ContractAllMonth * checks)/12);
            }
        }
        // alert(Allchecks);
        // var EndDate = '{!PageMCEElement.Contract_End_Date__c}';
        j$(escapeVfId('allPage:allForm:allBlock:TextInformation:Contract_Limit_Times__c')).text(Allchecks);
    }
    // 新增点检总次数(只在页面中显示)fxk 2021/9/2 End
</script>
<apex:form styleClass="BlockSytle" id="allForm">
    <body onload="init()">
    <apex:actionFunction name="ChangeTermofPaymentPlan" action="{!Dummy}" rerender="paymentPlan"></apex:actionFunction>
    <apex:actionFunction name="RerenderallpageBlockJS" action="{!Dummy}" rerender="TextInformation"></apex:actionFunction>
    <apex:outputPanel id="hiddenInput">
    <apex:inputHidden value="{!statusSave}" id="statusSave"/>
    <apex:inputHidden value="{!Contract_validMonth}" id="Contract_validMonth"/>
    <apex:inputHidden value="{!PageMCEElement.Contract_Amount__c}" id="Contract_Amount_Hidden"/>
    <apex:inputHidden value="{!PageMCEElement.Total_Contract_Amount_In_Words__c}" id="Total_Contract_Amount_In_Words_Hidden"/>
    <apex:inputHidden value="{!PageMCEElement.Payment_Plan_Sum_First_in_Word__c}" id="Payment_Plan_Sum_1_in_Word_Hidden"/>
    <apex:inputHidden value="{!PageMCEElement.Payment_Plan_Sum_Second_in_Word__c}" id="Payment_Plan_Sum_2_in_Word_Hidden"/>
    <apex:inputHidden value="{!PageMCEElement.Payment_Plan_Sum_Third_in_Word__c}" id="Payment_Plan_Sum_3_in_Word_Hidden"/>
    <apex:inputHidden value="{!PageMCEElement.Payment_Plan_Sum_Forth_in_Word__c}" id="Payment_Plan_Sum_4_in_Word_Hidden"/>
    <apex:inputHidden value="{!PageMCEElement.Payment_Plan_Sum_Fifth_in_Word__c}" id="Payment_Plan_Sum_5_in_Word_Hidden"/>
    <apex:inputHidden value="{!PageMCEElement.Payment_Plan_Sum_Sixth_in_Word__c}" id="Payment_Plan_Sum_6_in_Word_Hidden"/>
    </apex:outputPanel>
    <apex:pageBlock id="allBlock" >
    <apex:outputPanel id="Messages" style="color:red">
        <apex:messages />
    </apex:outputPanel>
    <table border="0" >
        <colgroup>
            <col width="25%"/>
            <col width="25%"/>
            <col width="25%"/>
            <col width="25%"/>
        </colgroup>
        <tr>
            <td style ="text-align: right;">
                <apex:outputText value="是否为标准合同:"  /> &nbsp;&nbsp;
            </td>
            <td style ="text-align: left;">
                <div class="requiredInput"><div class="requiredBlock"></div>
                     <apex:inputField required id="Is_Standard_Contract" value="{!PageMCEElement.Is_Standard_Contract__c}" onchange="RerenderallpageBlockJS(); "/>
                        (必填项,所有合同均必须勾选)
                </div>
            </td>
            <td/>
            <td/>
        </tr>
    </table>
    <br/>
    <apex:pageBlockSection id="paymentPlan" title="付款计划(必填内容):" columns="1">
        <apex:selectList label="付款方式:" style="margin-right:3px" size="1" id="Term_Of_Payment__c" value="{!PageMCEElement.Term_Of_Payment__c}" onchange="ChangeTermofPaymentPlanJS();">
            <apex:selectOptions value="{!Term_Of_Payment}"/>
        </apex:selectList>
        <apex:outputPanel style="display: {!IF(Check_Of_Payment, '', 'none')}" >
            <h2 style="margin-left:4%;">一次性付款:</h2>
            <p style="margin-left:4%;">
                本合同正式签订之日起
                <apex:selectList style="margin-right:3px;margin-left:3px" size="1" id="one_off_payment_agreed_period__c" value="{!PageMCEElement.one_off_payment_agreed_period__c}">
                    <apex:selectOptions value="{!one_off_payment_agreed_period}"/>
                </apex:selectList>
                 日内,甲方向乙方支付全部合同款人民币
                 <apex:outputText style="margin-right:3px;margin-left:3px" value="{!PageMCEElement.Contract_Amount__c}"/>元,大写<apex:outputText id="Total_Contract_Amount_In_Words" style="margin-right:1px;margin-left:1px" value="{!PageMCEElement.Total_Contract_Amount_In_Words__c}"/>。
            </p>
        </apex:outputPanel>
        <apex:outputPanel style="display: {!IF(Not(Check_Of_Payment), '', 'none')}">
            <h2 style="margin-left:4%;" >多次付款:</h2>
            <div style="margin-left:4%;line-height:22px">
                本合同款项分&nbsp;&nbsp;
                <apex:selectList style="margin-right:3px" size="1" id="Total_Payment_Time__c" value="{!PageMCEElement.Total_Payment_Time__c}">
                    <apex:selectOptions value="{!Total_Payment_Time}"/>
                </apex:selectList>&nbsp;期付出,详细如下:
                <br/>
                第一期款项付款时间为&nbsp;
                <apex:inputField id="Payment_Plan_Date_First" value="{!PageMCEElement.Payment_Plan_Date_First__c}" />
                &nbsp;前,甲方向乙方支付人民币&nbsp;
                <apex:inputField id="Payment_Plan_Sum_1" value="{!PageMCEElement.Payment_Plan_Sum_First__c}" onchange="Convert_Amount('1');" />
                &nbsp;元,大写
                <apex:outputText id="Payment_Plan_Sum_1_in_Word" style="margin-right:1px;margin-left:1px" value="{!PageMCEElement.Payment_Plan_Sum_First_in_Word__c}"/>;
                <br/>
                第二期款项付款时间为&nbsp;
                <apex:inputField id="Payment_Plan_Date_Second" value="{!PageMCEElement.Payment_Plan_Date_Second__c}" />
                &nbsp;前,甲方向乙方支付人民币&nbsp;
                <apex:inputField id="Payment_Plan_Sum_2" value="{!PageMCEElement.Payment_Plan_Sum_Second__c}" onchange="Convert_Amount('2');"/>
                &nbsp;元,大写
                <apex:outputText id="Payment_Plan_Sum_2_in_Word" style="margin-right:1px;margin-left:1px" value="{!PageMCEElement.Payment_Plan_Sum_Second_in_Word__c}"/>;
                <br/>
                第三期款项付款时间为&nbsp;
                <apex:inputField id="Payment_Plan_Date_Third" value="{!PageMCEElement.Payment_Plan_Date_Third__c}" />
                &nbsp;前,甲方向乙方支付人民币&nbsp;
                <apex:inputField id="Payment_Plan_Sum_3" value="{!PageMCEElement.Payment_Plan_Sum_Third__c}" onchange="Convert_Amount('3');"/>
                &nbsp;元,大写
                <apex:outputText id="Payment_Plan_Sum_3_in_Word" style="margin-right:1px;margin-left:1px" value="{!PageMCEElement.Payment_Plan_Sum_Third_in_Word__c}"/>;
                <br/>
                第四期款项付款时间为&nbsp;
                <apex:inputField id="Payment_Plan_Date_Forth" value="{!PageMCEElement.Payment_Plan_Date_Forth__c}" />
                &nbsp;前,甲方向乙方支付人民币&nbsp;
                <apex:inputField id="Payment_Plan_Sum_4" value="{!PageMCEElement.Payment_Plan_Sum_Forth__c} " onchange="Convert_Amount('4');"/>
                &nbsp;元,大写
                <apex:outputText id="Payment_Plan_Sum_4_in_Word" style="margin-right:1px;margin-left:1px" value="{!PageMCEElement.Payment_Plan_Sum_Forth_in_Word__c}"/>;
                <br/>
                第五期款项付款时间为&nbsp;
                <apex:inputField id="Payment_Plan_Date_Fifth" value="{!PageMCEElement.Payment_Plan_Date_Fifth__c}" />
                &nbsp;前,甲方向乙方支付人民币&nbsp;
                <apex:inputField id="Payment_Plan_Sum_5" value="{!PageMCEElement.Payment_Plan_Sum_Fifth__c}" onchange="Convert_Amount('5');"/>
                &nbsp;元,大写
                <apex:outputText id="Payment_Plan_Sum_5_in_Word" style="margin-right:1px;margin-left:1px" value="{!PageMCEElement.Payment_Plan_Sum_Fifth_in_Word__c}"/>;
                <br/>
                第六期款项付款时间为&nbsp;
                <apex:inputField id="Payment_Plan_Date_Sixth" value="{!PageMCEElement.Payment_Plan_Date_Sixth__c}" />
                &nbsp;前,甲方向乙方支付人民币&nbsp;
                <apex:inputField id="Payment_Plan_Sum_6" value="{!PageMCEElement.Payment_Plan_Sum_Sixth__c}" onchange="Convert_Amount('6');" />
                &nbsp;元,大写
                <apex:outputText id="Payment_Plan_Sum_6_in_Word" style="margin-right:1px;margin-left:1px" value="{!PageMCEElement.Payment_Plan_Sum_Sixth_in_Word__c}"/>。
            </div>
        </apex:outputPanel>
    </apex:pageBlockSection>
    <br/>
    <h2>
        <div style="margin-left:5%; color:Blue">
            <apex:outputText >提示信息:标准合同下述内容需要全部填写。</apex:outputText>
        </div>
    </h2>
    <br/>
    <apex:pageBlockSection id="TextInformation" title="文本信息:" columns="1">
    <apex:outputPanel id="StandardContractContext" rendered="{!IF(PageMCEElement.Is_Standard_Contract__c == '是', 'true', 'false')}">
    <table border="0" style="width:90%" >
        <colgroup>
            <col width="25%"/>
            <col width="25%"/>
            <col width="25%"/>
            <col width="25%"/>
        </colgroup>
        <tr>
            <td style ="text-align: left;">
                <apex:outputText style="margin-left:20%;" value="小修理时限:"  /> &nbsp;&nbsp;&nbsp;&nbsp;
            </td>
            <td style ="text-align: left;">
                <apex:selectList style="margin-right:3px" size="1" id="Small_Repair_Time__c" value="{!PageMCEElement.Small_Repair_Time__c}">
                    <apex:selectOptions value="{!Small_Repair_Time}"/>
                </apex:selectList>
            小时
            </td>
            <td style ="text-align: left;">
                <apex:outputText style="margin-left:20%;" value="大修理时限:"  /> &nbsp;&nbsp;&nbsp;&nbsp;
            </td>
            <td style ="text-align: left;">
                <apex:selectList style="margin-right:3px" size="1" id="Big_Repair_Time__c" value="{!PageMCEElement.Big_Repair_Time__c}">
                    <apex:selectOptions value="{!Big_Repair_Time}"/>
                </apex:selectList>
            工作日
            </td>
        </tr>
        <tr>
            <td style ="text-align: left;">
                <apex:outputText style="margin-left:20%;" value="现场技术支持时限:"  /> &nbsp;&nbsp;&nbsp;&nbsp;
            </td>
            <td style ="text-align: left;">
                <apex:selectList style="margin-right:3px" size="1" id="Live_Technical_Support_Time__c" value="{!PageMCEElement.Live_Technical_Support_Time__c}">
                    <apex:selectOptions value="{!Small_Repair_Time}"/>
                </apex:selectList>
            小时
            </td>
            <td style ="text-align: left;">
                <apex:outputText style="margin-left:20%;" value="巡回:"  /> &nbsp;&nbsp;&nbsp;&nbsp;
            </td>
            <td style ="text-align: left;">
                每年
                <apex:selectList style="margin-left:3px;margin-right:3px" size="1" id="Tour_Check__c" value="{!PageMCEElement.Tour_Check__c}">
                    <apex:selectOptions value="{!Tour_Check}"/>
                </apex:selectList>次
            </td>
        </tr>
        <tr>
            <td style =" text-align:left;">
                <apex:outputText style="margin-left:20%;" value="工程师姓名:"  /> &nbsp;&nbsp;&nbsp;&nbsp;
            </td>
            <td style ="text-align: left;">
                 <apex:inputTextarea id="Engineer_Name__c" value="{!PageMCEElement.Engineer_Name__c}"/>
            </td>
            <td style ="text-align: left;">
                <apex:outputText style="margin-left:20%;" value="手机号码:"  /> &nbsp;&nbsp;&nbsp;&nbsp;
            </td>
            <td style ="text-align: left;">
                 <apex:inputTextarea id="Phone_Number__c" value="{!PageMCEElement.Phone_Number__c}"/>
            </td>
        </tr>
        <tr>
            <td style ="text-align: left;">
                <apex:outputText style="margin-left:20%;" value="点检:"  /> &nbsp;&nbsp;&nbsp;&nbsp;
            </td>
            <td style ="text-align: left;">
                <div class="requiredInput"><div class="requiredBlock"></div>
                    每年
                    <apex:selectList style="margin-left:3px;margin-right:3px" size="1" id="Inspection_Time__c" value="{!PageMCEElement.Inspection_Time__c}" onchange="AllChecktime();">
                        <apex:selectOptions value="{!Tour_Check}"/>
                    </apex:selectList>次
                    (必填项)
                </div>
            </td>
            <td style ="text-align: left;">
                <apex:outputText style="margin-left:20%;" value="除尘:"  /> &nbsp;&nbsp;&nbsp;&nbsp;
            </td>
            <td style ="text-align: left;">
                每年
                <apex:selectList style="margin-left:3px;margin-right:3px" size="1" id="Dedust__c" value="{!PageMCEElement.Dedust__c}">
                    <apex:selectOptions value="{!Dedust}"/>
                </apex:selectList>次
            </td>
        </tr>
        <!-- fxk 2021、9、2 新加点检总次数 star-->
        <tr>
            <td style ="text-align: left;">
                <apex:outputText style="margin-left:20%;" value="点检总次数:"  /> &nbsp;&nbsp;&nbsp;&nbsp;
            </td>
            <td style ="text-align: left;">
                共
                <apex:outputText style="margin-left:3px;margin-right:3px;width: 25px" id="Contract_Limit_Times__c" value="{!PageMCEElement.Contract_Limit_Times__c}">
                </apex:outputText>次
            </td>
        </tr>
        <!-- fxk 2021、9、2 新加点检总次数 end-->
        <tr>
            <td style ="text-align: left;">
                <apex:outputText value="合同份数:甲方:" style="margin-left:20%" />
            </td>
            <td style ="text-align: left;">
                <apex:selectList style="margin-left:3px;margin-right:3px" size="1" id="First_Party_Contract_Number__c" value="{!PageMCEElement.First_Party_Contract_Number__c}">
                    <apex:selectOptions value="{!First_Party_Contract_Number}"/>
                        </apex:selectList>份
               </td>
            <td style ="text-align: left;">
                <apex:outputText value="乙方:" style="margin-left:20%" />
            </td>
            <td>
                <apex:selectList style="margin-left:3px;margin-right:3px" size="1" id="Second_Party_Contract_Number__c" value="{!PageMCEElement.Second_Party_Contract_Number__c}">
                    <apex:selectOptions value="{!First_Party_Contract_Number}"/>
                </apex:selectList>
                份
           </td>
        </tr>
    </table>
    <div style="margin-left:5%;">
        <apex:outputText >
           协商方式:<apex:selectList style="margin-left:1px;margin-right:10px" size="1" id="Negotiate_Mean__c" value="{!PageMCEElement.Negotiate_Mean__c}">
                 <apex:selectOptions value="{!Negotiate_Mean}"/>
            </apex:selectList>提示信息:(1)向设在北京的中国国际经济贸易仲裁委员会申请仲裁。(2)向有管辖权的人民法院提起诉讼。
        </apex:outputText>
    </div>
    </apex:outputPanel>
    </apex:pageBlockSection>
        <apex:pageBlockButtons >
        <apex:outputPanel rendered="{!IF(PageMCEElement.Status__c != '引合中', 'true', 'false')}">
            <apex:commandButton disabled="true" id="SaveButton1" value="保存"  action="{!save}" onclick="blockme();" reRender="hiddenInput,Messages"  oncomplete="CloseJs();"/>
            <apex:commandButton disabled="true" id="CancelButton1" value="取消" onclick="CloseJs(); return false;"/>
            <apex:commandButton disabled="true" id="PrintButton1" value="打印" action="{!print}" onclick="blockme();" rerender="hiddenInput,Messages,pdfPrint"  oncomplete="PrintJs();" />
        </apex:outputPanel>
        <apex:outputPanel rendered="{!IF(PageMCEElement.Status__c == '引合中', 'true', 'false')}">
            <apex:commandButton id="SaveButton" value="保存"  action="{!save}" onclick="blockme();" reRender="hiddenInput,Messages"  oncomplete="CloseJs();"/>
            <apex:commandButton id="CancelButton" value="取消" onclick="CloseJs(); return false;"/>
            <apex:commandButton id="PrintButton" value="打印" action="{!print}" onclick="blockme();" rerender="hiddenInput,Messages,pdfPrint"  oncomplete="PrintJs();" />
        </apex:outputPanel>
        </apex:pageBlockButtons>
    </apex:pageBlock>
    </body>
    </apex:form>
<apex:outputPanel id="pdfPrint">
<script type="text/javascript">
    function PrintJs() {
        var Rs = j$(escapeVfId('allPage:allForm:statusSave')).value();
        if(Rs == 'Fin'){
            unblockUI();
            if ('{!printContract}' == 'true') {
            // 打印医院合同配置
                window.open('/apex/MCHPDF?id={!PageMCEElement.id}', 'MCHPDF');
             }else if ('{!printAgent}' == 'true') {
            //打印经销商合同
            window.open('/apex/MCAgentPDF?id={!PageMCEElement.id}', 'MCHPDF');
            }else {
                alert('1');
            }
        }else{
            unblockUI();
        }
    }
</script>
</apex:outputPanel>
</apex:page>
force-app/main/default/pages/PaymentPlanLoad.page-meta.xml
New file
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>36.0</apiVersion>
    <availableInTouch>false</availableInTouch>
    <confirmationTokenRequired>false</confirmationTokenRequired>
    <label>PaymentPlanLoad</label>
</ApexPage>
force-app/main/default/pages/PrintInspectupReport.page
New file
@@ -0,0 +1,400 @@
<apex:page id="allPage" showHeader="false" sidebar="false" controller="PrintInspectupReportController" applyBodyTag="false" applyHtmlTag="false" action="{!init}" pageStyle="PageStyleCss" lightningStylesheets="true">
<html>
<head>
    <title>打印筛选条件</title>
    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
<!-- css -->
<style type="text/css">
    /*以下是下拉复选框的样式  start*/
    * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            position: relative;
        }
        ul,
        li {
            list-style: none;
        }
        .nav_1st {
            width: 300px;
            height: 32px;
            line-height: 32px;
            padding: 5px 30px 5px 5px;
            border: 1px solid #c9c9c9;
            background-size: 5%;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
            margin: 0 auto;
        }
        .nav {
            width: 300px;
            line-height: 20px;
            border: 1px solid #c9c9c9;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
            position: absolute;
            top: 30px;
            right: 0;
            left: 0;
            margin: 10px 0 0 94px;
            z-index: 9999;
            display: none;
        }
        .nav_close {
            position: fixed;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            z-index: 9990;
            display: none;
        }
        .nav li input {
            margin: 0px 3px 0px 3px;
        }
        .nav li p:hover {
            background: #1e90ff;
            color: #fff;
        }
        #classification {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    /*以下是下拉复选框的样式  start*/
</style>
<!-- js -->
<script type="text/javascript">
    //下拉多选框  strat
     window.onload = () => {
           j$(".nav_1st").click(function () {
                j$(".nav,.nav_close").toggle();
            });
            j$(".nav_close").click(function () {
                j$(".nav,.nav_close").hide();
            });
            j$(".li-input").click(function () {
                var checked2 = j$(this).prop("checked");
                if (checked2 == true) {
                    j$(this).prop("checked", false);
                } else {
                    j$(this).prop("checked", true);
                }
            });
            j$(".ul-nav").click(function () {
                var checked1 = j$(this).children("input").prop("checked");
                if (checked1 == false) {
                    j$("#classification").children("#initial").remove();
                    j$(this).children("input").prop("checked", true);
                    j$("#classification").append("<span class='valClass' id='" + (j$(this).children("input")[0].value.trim()) + "'>" + (j$(this)
                        .text().trim() + ",") + "</span>");
                } else {
                    j$(this).children("input").prop("checked", false);
                    j$("#classification").children("#" + (j$(this).children("input")[0].value.trim())).remove();
                    var length = j$("#classification").html().length;
                    if (length === 0) {
                        j$("#classification").append("<span class='valClass' id='initial'>--无--</span>");
                    }
                }
                var optioncheck = j$(".valClass");
                var hint = '';
                for(var i = 0;i<optioncheck.length;i++){
                    hint +=optioncheck[i].innerText;
                }
                j$("#valId").attr("title",hint);
            });
        }
    //生成pdf
    function createPDFJs(){
        //blockme();
        //计数使用,用于判断选择的点检是否超过4个
        var index = 0;
        var strId = '';
        var lawtable = document.getElementById("tableHeader_L");//获取id为tableHeader_L的table
        var rows = lawtable.rows;//获取所有行
        //循环获取所有选中的点检
        for(var i=1; i < rows.length; i++){
            var row = rows[i];//获取每一行
            var getChecked = row.cells[2].getElementsByTagName("input")[0].checked;//获取复选框是否选中
            if(getChecked){
                //不能超过4条数据
                if(index < 4){
                    index++;
                    if(strId == ''){
                        strId = row.cells[2].getElementsByTagName("input")[0].id;//获取选中的复选框id
                    }else{
                        strId += ','+row.cells[2].getElementsByTagName("input")[0].id;//获取选中的复选框id
                    }
                }else{
                    alert('选择的点检不能超过4条!');
                    return;
                }
            }
        }
        var parameter = '';
        //加生成类型条件
        var produceTypeVal = document.getElementById('allPage:allForm:allBlock:paymentPlan1:isResultShow').value;
        parameter = produceTypeVal;
        //保有设备的类型
        var assetType = document.getElementById('allPage:allForm:allBlock:paymentPlan1:selectAssetType').value;
        parameter += ',,'+assetType;
        //保有设备 内容
        var assetStr = '';
        var assetList = j$("#classification").children();
        if(j$("#classification").children().text().trim() != '--无--'){
            for(var i = 0;i < assetList.length;i++){
                if(j$("#classification").children()[i].id != '' && j$("#classification").children()[i].id != null){
                    if(assetStr == ''){
                        assetStr = assetList[i].id;
                    }else{
                        assetStr += ','+assetList[i].id;
                    }
                }
            }
        }
        parameter += ',,'+assetStr;
        //是否分页
        var isPaging = document.getElementById('allPage:allForm:allBlock:paymentPlan1:isPaging').checked;
        parameter += ',,'+isPaging;
        //+  洗消信息条件
        var falg = document.getElementById("allPage:allForm:allBlock:paymentPlan2:activeOnId").checked;
        parameter += ',,'+falg;
        //+  点检对象
        if(strId != ''){
            parameter += ',,'+strId;
        }else{
            alert('请选择点检计划!');
            return false;
        }
        //+  合id
        parameter += ',,' + '{!maintenanceContractId}';
        // 打印医院合同配置
        window.open('/apex/PrintInspectupReportPDF?parameter=' + parameter);
        window.close();
        //createPDF(parameter);
    }
    //全选
    function onCheckAllJS(Obj){
        if(!Obj.checked){
            Obj.checked = false;
            var lawtable = document.getElementById("tableHeader_L");//获取id为tableHeader_L的table
            var rows = lawtable.rows;//获取所有行
            for(var i=1; i < rows.length; i++){
                var row = rows[i];//获取每一行
                var getChecked = row.cells[3].getElementsByTagName("input")[0].checked;//获取复选框是否选中
                if(getChecked){
                    row.cells[3].getElementsByTagName("input")[0].checked = false;
                }
            }
        }else{
            Obj.checked = true;
            var lawtable = document.getElementById("tableHeader_L");//获取id为tableHeader_L的table
            var rows = lawtable.rows;//获取所有行
            for(var i=1; i < rows.length; i++){
                var row = rows[i];//获取每一行
                var getChecked = row.cells[3].getElementsByTagName("input")[0].checked;//获取复选框是否选中
                if(!getChecked){
                    row.cells[3].getElementsByTagName("input")[0].checked = true;
                }
            }
        }
    }
    //选择下拉框值有变动以后触发
    function selectAssetTypeJs(Obj){
        var selectId = Obj.value;
        //如果保有设备选择无
        if(selectId == '' || selectId == null){
            j$("#isPagingId").hide();
            j$("#selectCheckId").hide();
        }else{
            //消除选择的其他选项
            if(j$("#classification").children().text() != "--无--"){
                j$("#classification").children().remove();
                j$("#classification").append("<span class='valClass' id='initial'>--无--</span>");
            }
            var inputObj = j$(".li-input");
            if(inputObj != null){
                for(var i = 0; i < inputObj.length;i++){
                    if(inputObj[i].checked){
                        inputObj[i].checked = false;
                    }
                }
            }
            //是否分页设置成不勾选状态
            document.getElementById('allPage:allForm:allBlock:paymentPlan1:isPaging').checked = false;
            if(selectId == "4" || selectId == "0"){
                j$("#selectCheckId").hide();
                j$("#isPagingId").hide();
            }else{
                j$("#selectCheckId").show();
                j$("#isPagingId").show();
                if(selectId == "1"){
                    j$("#divId1").show();
                    j$("#divId2").hide();
                    j$("#divId3").hide();
                }
                if(selectId == "2"){
                    j$("#divId1").hide();
                    j$("#divId2").show();
                    j$("#divId3").hide();
                }
                if(selectId == "3"){
                    j$("#divId1").hide();
                    j$("#divId2").hide();
                    j$("#divId3").show();
                }
            }
        }
    }
</script>
</head>
<body>
    <apex:form styleClass="BlockSytle" id="allForm">
    <!-- 页面数据初始化方法 -->
    <apex:actionFunction name="init" action="{!init}" rerender="oppBlock1,message,checEventFrame" onComplete="unblockUI();"></apex:actionFunction>
    <div>
        <apex:pageBlock id="allBlock" >
            <apex:pageBlockSection id="paymentPlan1" title="选择条件1" columns="2">
                <apex:outputPanel >
               <table style="width:1000px;">
                    <tr style="">
                        <td style="width: 76px;float: left;line-height: 40px;">
                            <font>是否空白</font>&nbsp;
                        </td>
                        <td style="float: left;">
                            <apex:selectList value="{!isResultShow}" id="isResultShow" size="1" style="width:85px;min-width: 80px;">
                                <apex:selectOptions value="{!isResultShowLOption}"/>
                                &nbsp;
                            </apex:selectList>
                        </td>
                        <td style="width: 76px;float: left;line-height: 40px;">
                            <font>保有设备</font>&nbsp;
                        </td>
                        <td style="min-width: 400px;float: left;">
                            <apex:selectList value="{!selectAssetType}" id="selectAssetType" size="1" style="width:85px;min-width: 80px;float: left;" onchange="selectAssetTypeJs(this);return false;">
                                <apex:selectOptions value="{!selectAssetTypeOption}"/>
                            </apex:selectList>
                            &nbsp;&nbsp;
                            <div style="float: left;display: none;line-height: 32px;" id="selectCheckId">
                                <div class="nav_1st" id="valId" title="">
                                    <p id="classification" style="margin-top: -7px;"><span id="initial">--无--</span></p>
                                </div>
                                <ul class="nav" style="background-color: #FFFFFF;">
                                    <div id="divId1" style="display:">
                                        <!-- 战略科室下拉框 -->
                                        <apex:repeat value="{!strategyDepartment}" var="orr" id="selSD">
                                            <li class="sdclass" style="margin-left:0px">
                                                <p class="ul-nav" name="cate_id[]" >
                                                    <input type="checkbox" value="{!orr.parameterName}" class="li-input" style="display: inline-block;vertical-align: middle;" />
                                                    <font style="">{!orr.parameterName}</font>
                                                </p>
                                            </li>
                                        </apex:repeat>
                                    </div>
                                    <div id="divId2" style="display:">
                                        <!-- 科室下拉框 -->
                                        <apex:repeat value="{!department}" var="orrr" id="selD">
                                            <li class="dclass" style="margin-left:0px">
                                                <p class="ul-nav" name="cate_id[]" >
                                                    <input type="checkbox" value="{!orrr.parameterName}" class="li-input" style="display: inline-block;vertical-align: middle;"/>
                                                    <font style="">{!orrr.parameterName}</font></p>
                                            </li>
                                        </apex:repeat>
                                    </div>
                                    <div id="divId3" style="display:;">
                                        <apex:repeat value="{!installationSite}" var="orrrr" id="seliD">
                                            <li class="iclass" style="margin-left:0px">
                                                <p class="ul-nav" name="cate_id[]" >
                                                    <input type="checkbox" value="{!orrrr.parameterName}" class="li-input" style="display: inline-block;vertical-align: middle;"/><font style="">{!orrrr.parameterName}</font>
                                                </p>
                                            </li>
                                        </apex:repeat>
                                    </div>
                                </ul>
                                <div class="nav_close"></div>
                            </div>
                        </td>
                        <td style="float: left;display: none;line-height: 40px;" id="isPagingId">
                            <font>是否分页</font>&nbsp;
                            <apex:inputCheckBox value="{!isPaging}" id="isPaging" style="display: inline-block;vertical-align: middle;"/>
                        </td>
                    </tr>
                </table>
                </apex:outputPanel>
            </apex:pageBlockSection>
            <apex:pageBlockSection id="paymentPlan2" title="筛选条件2" columns="2">
                <apex:outputPanel >
                <table style="width:800px;">
                    <tr>
                         <td>
                            <span style="vertical-align: text-bottom;float: left;">
                                <font>洗消信息&nbsp;&nbsp;</font>
                                <apex:inputCheckBox value="{!activeOn}" id="activeOnId" style="display: inline-block;vertical-align: middle;"/>
                            </span>
                        </td>
                    </tr>
                </table>
                </apex:outputPanel>
            </apex:pageBlockSection>
            <apex:pageBlockSection id="paymentPlan3" title="筛选条件3" columns="1">
                <apex:outputPanel >
                <table class="list" style="font-size:11px;width: 100%;" border="" id="tableHeader_L" >
                    <thead>
                        <tr class="headerRow" height="30px"  align="center">
                            <!--标题 -->
                            <td style="">信息对象</td>
                            <td style="">最后点检日</td>
                            <td style="width:100px" colspan="1">
                                <!-- <input type="checkbox" name="reading" onchange="onCheckAllJS(this);return false;" id="checkAll"/> -->
                                勾选
                            </td>
                        </tr>
                    </thead>
                    <tbody>
                        <apex:variable value="{!0}" var="cnt" />
                            <apex:repeat value="{!inspectupPlanList}" var="or" id="oppTable">
                                <tr class="dataRow {!IF(MOD(cnt, 2)==0, 'odd', 'even')} {!IF(cnt==1, 'first', '')}" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} "  onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
                                    <td style="border-width: 0 0 0px 0;" align="center" >
                                        <apex:outputText value="{!or.Chack_Plan_NO__c}次点检" />
                                    </td>
                                    <td style="border-width: 0 0 0px 0;" align="center">
                                        <apex:outputfield value="{!or.Execution_End_Date__c}" />
                                    </td>
                                    <td align="center" style="border-width: 0 0 0px 0;" colspan="1">
                                        <input type="checkbox" name="reading" id="{!or.id}"/>
                                    </td>
                                </tr>
                            <apex:variable value="{!cnt + 1}" var="cnt" />
                        </apex:repeat>
                    </tbody>
                </table>
                </apex:outputPanel>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <div style="width: 98%;">
            <apex:commandButton onclick="createPDFJs();return false;"  rendered="true" value="生成PDF" style="width:80px;float: right;"/>
        </div>
    </div>
    </apex:form>
</body>
</html>
</apex:page>
force-app/main/default/pages/PrintInspectupReport.page-meta.xml
New file
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>45.0</apiVersion>
    <availableInTouch>false</availableInTouch>
    <confirmationTokenRequired>false</confirmationTokenRequired>
    <label>PrintInspectupReport</label>
</ApexPage>
force-app/main/default/pages/RepPAEDecisionRecord.page
New file
@@ -0,0 +1,402 @@
<apex:page standardController="PAE_DecisionRecord__c" extensions="RepPAEDecisionRecordController" showHeader="false" sidebar="false" id="allPage" action="{!init}" title="PAE判定记录" lightningStylesheets="true">
<apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
<apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
<apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
<apex:includeScript value="{!URLFOR($Resource.CommonUtilJs)}"/>
<style  type="text/css">.bPageBlock .pbTitle{width:100%;text-align:center;}</style>
<script>
//插入行
function InsertRows(){
    //解除不可写状态
    blockme();
    InsertRow();
}
// 保存并关闭
function SaveAndCloses(onlySave){
   //  精琢科技   zxk   2021-11-17    start
            var productCount = "{!paedRecordDetailView}";
            //新值
            var PAEJudgeIdStr = '';
            //旧值
            var strJudgejsIdStr = '';
            var falsg = 0;
            //  + ':PAEJudge'
            for (var i = 0; i < productCount.length; i++) {
                var PAEJudgeId = 'allPage:allForm:allBlock:unEditable:ConsumableorderdetailsTable:' + i + ':PAEJudge';
                var strJudgejsId = 'allPage:allForm:allBlock:unEditable:ConsumableorderdetailsTable:' + i + ':strJudgejs';
                PAEJudgeIdStr = j$(escapeVfId(PAEJudgeId)).value();
                strJudgejsIdStr = j$(escapeVfId(strJudgejsId)).value();
                if (PAEJudgeIdStr != '' && PAEJudgeIdStr != strJudgejsIdStr) {
                    falsg = 1;
                    break;
                }
            }
            if (falsg == 1) {
                if (confirm('存在未知或者修改过PAE判定的code  确认保存?')) {
                    blockme();
                    SaveAndClose(onlySave);
                }
            } else {
                blockme();
                SaveAndClose(onlySave);
            }
            //  精琢科技   zxk   2021-11-17    end
        }
//20200107
function toIntake(){
    blockme();
    toIntake();
}
//20191209 ljh
function InsertMoreRowsJs(productIdx){
    blockme();
    InsertMoreRows(productIdx);
}
var selectedSize = 0;
var pageLimit = {!pageLimit};
function CheckSize(j){
    var a = j.id;
    var productCount = j$(escapeVfId(a)).attr('checked');
    if (productCount == 'checked') {
        if(selectedSize >= pageLimit){
            window.alert("页面所选数据不能超过500条");
            j$(escapeVfId(a)).attr('checked',false);
            return;
        }
        selectedSize ++;
    } else {
        selectedSize --;
    }
    //alert(selectedSize);
}
// 2021-12-08  zxk   精琢科技  手动赋值逻辑  start
        function checkBoxTf() {
            // alert(lineNumberStr);
            var productCountStr = "{!paedRecordDetailView}";
            var PAEJudgeIdStr = '';
            var strJudgejsIdStr = '';
            var PaeIsSaveIdStr = '';
            var  MonitorPAE = '';
            var falsg = 0;
            for (var i = 0; i < productCountStr.length; i++) {
                var PAEJudgeId = 'allPage:allForm:allBlock:unEditable:ConsumableorderdetailsTable:' + i + ':PAEJudge';
                var strJudgejsId = 'allPage:allForm:allBlock:unEditable:ConsumableorderdetailsTable:' + i + ':strJudgejs';
                var PaeIsSaveId = 'allPage:allForm:allBlock:unEditable:ConsumableorderdetailsTable:' + i + ':PaeIsSave';
                var MonitorPAEId = 'allPage:allForm:allBlock:unEditable:ConsumableorderdetailsTable:' + i + ':MonitorPAE';
                PAEJudgeIdStr = j$(escapeVfId(PAEJudgeId)).value();
                strJudgejsIdStr = j$(escapeVfId(strJudgejsId)).value();
                PaeIsSaveIdStr = j$(escapeVfId(PaeIsSaveId)).value();
                MonitorPAE = j$(escapeVfId(MonitorPAEId)).value();
                 if(PaeIsSaveIdStr != '1'){
                        if (strJudgejsIdStr != PAEJudgeIdStr || (strJudgejsIdStr == '' || strJudgejsIdStr == null)) {
                           j$(escapeVfId('allPage:allForm:allBlock:unEditable:ConsumableorderdetailsTable:' + i + ':MonitorPAE')).attr('checked',true);
                        }else{
                           j$(escapeVfId('allPage:allForm:allBlock:unEditable:ConsumableorderdetailsTable:' + i + ':MonitorPAE')).attr('checked',false);
                        }
                }
            }
        }
        // 2021-12-08  zxk   精琢科技  手动赋值逻辑  end
function checkAll() {
    selectedSize = 0;
    var productCount = "{!paedRecordDetailViewCount}";
    if (j$(escapeVfId('checker')).attr('checked') == 'checked') {
        for (var i = 0; i < productCount; i++) {
            var checkId = 'allPage:allForm:allBlock:unEditable:ConsumableorderdetailsTable:' + i + ':variableinfo' + ':consumablesCountproRowCheckbox';
            if (!j$(escapeVfId(checkId)).attr('disabled')){
                j$(escapeVfId(checkId)).attr('checked',true);
                selectedSize ++;
            }
        }
    } else {
        for (var i = 0; i < productCount; i++) {
            j$(escapeVfId('allPage:allForm:allBlock:unEditable:ConsumableorderdetailsTable:' + i + ':variableinfo' + ':consumablesCountproRowCheckbox')).attr('checked',false);
        }
    }
}
</script>
<style>
    .dateFormat  {
        display: none;
    }
    td.columuslowercolour {
        background-color:red;
        text-align: right;
    }
    td.columuscuperolour {
        background-color: yellow;
        text-align: right;
    }
</style>
    <apex:form id="allForm">
        <apex:actionFunction name="InsertRow" action="{!InsertRow}" rerender="unEditable" onComplete="unblockUI();" >
        </apex:actionFunction>
        <apex:actionFunction name="InsertMoreRows" action="{!InsertMoreRows}" rerender="unEditable,message" onComplete="unblockUI();" >
            <!-- // 2021-12-08  zxk   精琢科技  手动赋值逻辑  start -->
            <apex:param assignto="{!productIdx}" name="productIdx" value="">
            </apex:param>
        <!-- // 2021-12-08  zxk   精琢科技  手动赋值逻辑  end -->
        </apex:actionFunction>
        <apex:actionFunction name="SaveAndClose" action="{!SaveAndClose}" rerender="unEditable,message" onComplete="unblockUI();" >
            <apex:param name="firstParam" assignTo="{!CancelineFlag}" value="" />
        </apex:actionFunction>
        <apex:actionFunction name="toIntake" action="{!toIntake}" rerender="unEditable" onComplete="unblockUI();" >
        </apex:actionFunction>
        <apex:actionFunction name="ReturnReportInterface" action="{!ReturnReportInterface}" rerender="unEditable" onComplete="unblockUI();" >
        </apex:actionFunction>
        <apex:outputPanel id="allPanel">
            <apex:pageBlock id="allBlock" >
                <apex:pageBlock title="{!IF(RecordTypeName = 'ASRCDecision' , 'Intake universal code 编辑画面', 'Final universal code 编辑画面')}" id="unEditable" rendered="{!editAble}">
                     <table cellspacing="10">
                        <colgroup>
                            <col width="15%"/>
                            <col width="15%"/>
                            <col width="15%"/>
                            <col width="15%"/>
                            <col width="15%"/>
                            <col width="5%"/>
                            <col width="15%"/>
                            <col width="15%"/>
                            <col width="15%"/>
                            <col width="15%"/>
                            <col width="15%"/>
                            <apex:outputPanel layout="none" rendered="{!IF(RecordTypeName = 'ASACDecision' , true, false)}">
                            <col width="15%"/>
                            <col width="15%"/>
                            </apex:outputPanel>
                        </colgroup>
                        <tr>
                            <td align="left" ><apex:outputText id="OrderCode_out"  value="{!$Label.PAE}" /></td>
                            <!-- 2020/07/28 taoqz start -->
                            <!-- PAE判定结果 由选项列表改为经过工作流更新后的文本 -->
                            <td align="left" ><apex:inputField id="OrderStatus_out" value="{!rdRecord.PAEDetail_DetermineResults__c}"/></td>
                            <!-- 2020/07/28 taoqz end -->
                            <apex:outputPanel layout="none" rendered="{!IF(RecordTypeName = 'ASRCDecision' , true, false)}">
                                <!-- <th>AS-RC</th> -->
                                <td ><span> {!$ObjectType.Report__c.fields.Repair_ConfirmationDate__c.label}:</span></td>
                            </apex:outputPanel>
                            <apex:outputPanel layout="none" rendered="{!IF(RecordTypeName = 'ASACDecision' , true, false)}">
                                <td align="right"> {!$ObjectType.Report__c.fields.OCSM_RC_CordingDate__c.label}:</td>
                            </apex:outputPanel>
                            <td align="left" ><apex:outputField value="{!rdRecord.PAE_ConfirmationDate__c}"/></td>
                            <apex:outputPanel layout="none" rendered="{!IF(RecordTypeName = 'ASRCDecision' , true, false)}">
                                <!-- <th>AS-RC</th> -->
                                <td align="right" > {!$ObjectType.Report__c.fields.Repair_Authenticator__c.label}:</td>
                            </apex:outputPanel>
                            <apex:outputPanel layout="none" rendered="{!IF(RecordTypeName = 'ASACDecision' , true, false)}">
                                <!-- <th>AS-AC</th> -->
                                <td align="right" >{!$ObjectType.Report__c.fields.OCSM_RC_CordingUser__c.label}:</td>
                            </apex:outputPanel>
                            <td align="left" ><apex:outputField value="{!rdRecord.PAE_Authenticator__c}"/></td>
                            <apex:outputPanel layout="none" rendered="{!IF(RecordTypeName = 'ASACDecision' , true, false)}">
                                <td align="right" >再现结果确认:</td>
                                <td align="left" style="{!IF(rdRecord.PAE_reappear_confirm__c = '未确认' , 'color: red;font-weight: 800;', '')}" ><apex:outputField value="{!rdRecord.PAE_reappear_confirm__c}"/></td>
                                 <input type="button" value="Intake universal code 编辑
" style="margin-left:30px;float:right;{!IF(rdRecord.PAE_reappear_confirm__c = '未确认','color: red;','')}"  onclick="toIntake();return false;"  class="btn" />
                            </apex:outputPanel>
                        </tr>
                    </table>
                    <apex:outputPanel layout="none" rendered="{!IF(RecordTypeName = 'ASACDecision'&& rdRecord.PAE_reappear_confirm__c = '未确认',false , true)}">
                    <table style="width:100%; {!IF(RecordTypeName = 'ASACDecision'&& rdRecord.PAE_reappear_confirm__c = '未确认', 'display: none;', '')}" >
                        <tr>
                            <td>
                            <apex:commandButton value="关闭"  style="margin-left:30px;width:80px;float:right"  onclick="ReturnReportInterface();return false;"  rerender="unEditable,message" oncomplete="unblockUI();"/>
                            <apex:commandButton value="保存"  disabled="{!IF((editFlag) && savebuton == false && !(RecordTypeName='ASRCDecision'&&OCSM_QARA='1'),true,false)}" style="margin-left:30px;width:80px;float:right"  onclick="SaveAndCloses(1);return false;"  rerender="unEditable,message" oncomplete="unblockUI();"/>
                            <apex:commandButton value="保存并关闭" disabled="{!editFlag}"  rendered="{!IF(repa != null && RecordTypeName = 'ASACDecision',true,false)}" style="margin-left:30px;width:80px;float:right"  onclick="SaveAndCloses(2);return false;"  rerender="unEditable,message" oncomplete="unblockUI();" />
                            <!-- OCSM QARA screen  [确定并关闭] -->
                            <!-- update by rentx 2020-10-26 start -->
                            <apex:commandButton rendered="{!IF((OCSM_QARA == '1' && RecordTypeName = 'ASRCDecision' && repa != null) || (RecordTypeName = 'ASRCDecision' && ReportId != null),true,false)}" value="确定并关闭"  disabled="{!editFlag}" style="margin-left:30px;width:100px;float:right"  onclick="SaveAndCloses(2);return false;"  rerender="unEditable,message" oncomplete="unblockUI();" />
                            <!-- update by rentx 2020-10-26 start -->
                            <apex:commandButton value="插入行" disabled="{!IF((RecordTypeName = 'ASRCDecision' && OCSM_QARA = '0') && ((RecordTypeName='ASACDecision'&&OCSM_Cording='0')||(editFlag)),true,false)}" style="margin-left:30px;width:100px;float:right" onclick="InsertRows();return false;" rerender="unEditable,message" oncomplete="unblockUI();"/>
                            <apex:commandButton value="取消行" disabled="{!IF((RecordTypeName = 'ASRCDecision' && OCSM_QARA = '0') && ((RecordTypeName='ASACDecision'&&OCSM_Cording='0')||(editFlag)),true,false)}" style="margin-left:30px;width:100px;float:right" onclick="SaveAndCloses(3);return false;"  rerender="unEditable,message" oncomplete="unblockUI();"/>
                            <!-- update by rentx 2020-10-26 end -->
                            </td>
                        </tr>
                    </table>
                    </apex:outputPanel>
                    <apex:outputPanel layout="none" rendered="{!IF(RecordTypeName = 'ASACDecision'&& rdRecord.PAE_reappear_confirm__c = '未确认',true , false)}">
                    <p style="text-align: center;padding-bottom: 10px;width:100%;font-weight: 800;">再现结果未确认,请点击Intake universal code 编辑 按钮前去确认</p>
                    </apex:outputPanel>
                        <apex:outputPanel id="message">
                            <apex:pageMessages />
                        </apex:outputPanel>
                    <table class="list" border="0" cellpadding="0" cellspacing="0">
                        <tr class="headerRow">
                            <apex:variable var="v" value="" rendered="{!editAble}">
                                <th><input type='checkbox' onClick='checkAll()' id='checker'/>选择</th>
                            </apex:variable>
                            <apex:outputPanel layout="none" rendered="{!IF(RecordTypeName = 'ASACDecision' , true, false)}">
                                <th>Location Group </th>
                                <th>Location </th>
                                <th>Final universal description / Phenomenon </th>
                            </apex:outputPanel>
                            <apex:outputPanel layout="none" rendered="{!IF(RecordTypeName = 'ASRCDecision' , true, false)}">
                                <th>Intake universal description</th>
                            </apex:outputPanel>
                            <apex:outputPanel layout="none" rendered="{!IF(RecordTypeName = 'ASRCDecision' , true, false)}">
                                <th>Intake universal code</th>
                            </apex:outputPanel>
                            <apex:outputPanel layout="none" rendered="{!IF(RecordTypeName = 'ASACDecision' , true, false)}">
                                <th>Final universal code </th>
                            </apex:outputPanel>
                            <!-- <th>AS-RC</th> -->
                            <!-- <th width="7%">PAE判定</th> -->
                            <th width="7%">{!$ObjectType.PAE_DecisionRecordDetail__c.fields.PAE_Judge__c.label}</th>
                            <apex:outputPanel layout="none" rendered="{!IF(RecordTypeName = 'ASRCDecision' , true, false)}">
                            <!-- <th width="7%">再现結果</th> -->
                            <th width="7%">{!$ObjectType.PAE_DecisionRecordDetail__c.fields.PAED_Reappear_Result__c.label}</th>
                            <!-- <th width="15%">intake 页面 Final universal Code</th> -->
                            <th width="15%">{!$ObjectType.PAE_DecisionRecordDetail__c.fields.Final_universal_code__c.label}</th>
                            </apex:outputPanel>
                            <!-- <th width="7%">状态</th> -->
                            <th width="7%">{!$ObjectType.PAE_DecisionRecordDetail__c.fields.PAED_Status__c.label}</th>
                            <!-- <th width="7%">确认日</th> -->
                            <th width="7%">{!$ObjectType.PAE_DecisionRecordDetail__c.fields.PAED_ConfirmationDate__c.label}</th>
                            <!-- <th width="7%">确认者</th> -->
                            <th width="7%">{!$ObjectType.PAE_DecisionRecordDetail__c.fields.PAED_Affirmant__c.label}</th>
                            <!-- <th width="7%">取消日</th> -->
                            <th width="7%">{!$ObjectType.PAE_DecisionRecordDetail__c.fields.PAED_CancellationDate__c.label}</th>
                            <!-- <th width="7%">取消者</th> -->
                            <th width="7%">{!$ObjectType.PAE_DecisionRecordDetail__c.fields.PAED_Nullifier__c.label}</th>
                            <apex:outputPanel layout="none" rendered="{!IF(RecordTypeName = 'ASRCDecision' , true, false)}">
                            <!-- <th width="7%">不再現結果確認日</th> -->
                            <th width="7%">{!$ObjectType.PAE_DecisionRecordDetail__c.fields.PAED_ResultConfirmationDate__c.label}</th>
                            <!-- <th width="7%">不再現結果確認者</th> -->
                            <th width="7%">{!$ObjectType.PAE_DecisionRecordDetail__c.fields.PAED_ResultAffirmant__c.label}</th>
                            </apex:outputPanel>
                            <!-- <th width="7%">手动修改</th> -->
                            <th width="7%">
                                {!$ObjectType.PAE_DecisionRecordDetail__c.fields.Monitor_PAE__c.label}
                            </th>
                        </tr>
                        <apex:repeat value="{!paedRecordDetailView}" var="paedRdV" id="ConsumableorderdetailsTable">
                            <tr class="dataRow">
                                <!-- //复选框 -->
                                <apex:variable var="v" value="" rendered="{!editAble}" id="variableinfo">
                                    <td>
                                        <apex:inputCheckbox value="{!paedRdV.check}" onclick="CheckSize(this);" id="consumablesCountproRowCheckbox" disabled="{!paedRdV.canSelect}"/>
                                            <apex:inputCheckbox value="{!paedRdV.oldCheck}" id="proRowOldCheckbox" style="display:none"/>
                                        <apex:inputCheckbox id="isReadOnly" value="{!paedRdV.canSelect}" style="display:none" />
                                    </td>
                                 </apex:variable>
                                <!-- QIS read only; always blank-->
                                <apex:outputPanel layout="none" rendered="{!IF(RecordTypeName = 'ASRCDecision' && repa != null , true, false)}">
                                    <td class="dataCell"></td>
                                </apex:outputPanel>
                                <apex:outputPanel layout="none" rendered="{!IF(RecordTypeName = 'ASACDecision' && repa != null, true, false)}">
                                    <td class="dataCell"></td>
                                    <td class="dataCell"></td>
                                    <td class="dataCell"></td>
                                </apex:outputPanel>
                                <td class="dataCell">
                                    <apex:outputPanel layout="none" rendered="{!IF(paedRdV.paedrdd.PAE_is_save__c !='1' || paedRdV.paedrdd.isedit__c = true, true,false)}">
                                        <apex:outputPanel layout="none" rendered="{!IF((RecordTypeName = 'ASACDecision'&& rdRecord.PAE_reappear_confirm__c = '未确认')||(OCSM_QARA='0' &&RecordTypeName = 'ASRCDecision'), false, true)}">
                                        <apex:InputField id="PAEDManagementCode" value="{!paedRdV.paedrdd.PAED_ManagementCode__c}" onblur="InsertMoreRowsJs(this.value);return false;"/>
                                        </apex:outputPanel>
                                    </apex:outputPanel>
                                    <apex:outputPanel layout="none" rendered="{!IF(!(paedRdV.paedrdd.PAE_is_save__c !='1' || paedRdV.paedrdd.isedit__c = true),true , false)}">
                                        <apex:outputField value="{!paedRdV.paedrdd.PAED_ManagementCode__c}" />
                                    </apex:outputPanel>
                                </td>
                                <td class="dataCell">
                                 <apex:outputPanel layout="none" rendered="{!IF(paedRdV.paedrdd.PAE_is_save__c ='1',false, true)}">
                                    <apex:outputPanel layout="none" rendered="{!IF((RecordTypeName = 'ASACDecision'&& rdRecord.PAE_reappear_confirm__c = '未确认')||(OCSM_QARA='0'&&RecordTypeName = 'ASRCDecision'), false, true)}">
                                        <apex:InputField id="PAEJudge" onchange="checkBoxTf();" value="{!paedRdV.paedrdd.PAE_Judge__c}"/>
                                    </apex:outputPanel>
                                    </apex:outputPanel>
                                        <apex:outputPanel layout="none" rendered="{!IF(paedRdV.paedrdd.PAE_is_save__c ='1',true , false)}">
                                        <apex:outputField id="PAEJudge1" value="{!paedRdV.paedrdd.PAE_Judge__c}"/>
                                    </apex:outputPanel>
                                     <!-- // 2021-12-08  zxk   精琢科技  手动赋值逻辑  start -->
                                    <apex:inputhidden id="strJudgejs" value="{!paedRdV.strJudge}">
                                    </apex:inputhidden>
                                    <apex:inputhidden id="Monitor_PAE__c" value="{!paedRdV.paedrdd.Monitor_PAE__c}">
                                    </apex:inputhidden>
                                    <apex:inputhidden id="PaeIsSave" value="{!paedRdV.paedrdd.PAE_is_save__c }">
                                    </apex:inputhidden>
                                    <!-- // 2021-12-08  zxk   精琢科技  手动赋值逻辑  end -->
                                </td>
                                <apex:outputPanel layout="none" rendered="{!IF(RecordTypeName = 'ASRCDecision' , true, false)}">
                                <td class="dataCell">
                                    <apex:outputPanel layout="none" rendered="{!IF(OCSM_Cording != '1', true, false)}">
                                    <apex:outputField value="{!paedRdV.paedrdd.PAED_Reappear_Result__c}"/>
                                    </apex:outputPanel>
                                    <apex:outputPanel layout="none" rendered="{!IF(OCSM_Cording='1', true, false)}">
                                    <apex:InputField value="{!paedRdV.paedrdd.PAED_Reappear_Result__c}"/>
                                    </apex:outputPanel>
                                </td>
                                <td class="dataCell">
                                    <apex:outputField value="{!paedRdV.paedrdd.Final_universal_code__c}"/>
                                </td>
                                </apex:outputPanel>
                                <td class="dataCell">
                                    <apex:OutputField value="{!paedRdV.paedrdd.PAED_Status__c}"/>
                                </td>
                                <td class="dataCell">
                                    <!-- Gzw 20200826 修改 Final 信息没有时,显示修理上内容 -->
                                    <apex:OutputField value="{!paedRdV.paedrdd.PAED_ConfirmationDate_F__c}"/>
                                </td>
                                <td class="dataCell">
                                    <apex:OutputField value="{!paedRdV.paedrdd.PAED_Affirmant_F__c}"/>
                                </td>
                                <td class="dataCell">
                                    <apex:OutputField value="{!paedRdV.paedrdd.PAED_CancellationDate__c}" rendered="{!IF(paedRdV.paedrdd.PAED_CancellationDate__c != null, true, false)}"/>
                                </td>
                                <td class="dataCell">
                                    <apex:OutputField value="{!paedRdV.paedrdd.PAED_Nullifier__r.Name}"/>
                                </td>
                                <apex:outputPanel layout="none" rendered="{!IF(RecordTypeName = 'ASRCDecision' , true, false)}">
                                <td class="dataCell">
                                    <apex:OutputField value="{!paedRdV.paedrdd.PAED_ResultConfirmationDate__c}"/>
                                </td>
                                <td class="dataCell">
                                    <apex:OutputField value="{!paedRdV.paedrdd.PAED_ResultAffirmant_new__c}"/>
                                </td>
                                </apex:outputPanel>
                                <!-- // 2021-12-08  zxk   精琢科技  手动赋值逻辑  start -->
                                    <td class="dataCell">
                                        <apex:inputcheckbox id="MonitorPAE" value="{!paedRdV.monitorPAE}" disabled="true">
                                        </apex:inputcheckbox>
                                        <apex:inputhidden id="MonitorPAEhidden" value="{!paedRdV.monitorPAE}">
                                        </apex:inputhidden>
                                    </td>
                                    <!-- // 2021-12-08  zxk   精琢科技  手动赋值逻辑  end -->
                            </tr>
                        </apex:repeat>
                    </table>
                </apex:pageBlock>
            </apex:pageBlock>
        </apex:outputPanel>
    </apex:form>
</apex:page>
force-app/main/default/pages/RepPAEDecisionRecord.page-meta.xml
New file
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <availableInTouch>false</availableInTouch>
    <confirmationTokenRequired>false</confirmationTokenRequired>
    <label>RepPAEDecisionRecord</label>
</ApexPage>
force-app/main/default/pages/SelectAssetEstimate.page
New file
@@ -0,0 +1,1713 @@
<!--<apex:page standardcontroller="Maintenance_Contract_Estimate__c" extensions="SelectAssetEstimateController" sidebar="false" showHeader="true" id="allPage" action="{!init}"> -->
<apex:page controller="SelectAssetEstimateController" tabStyle="Maintenance_Contract_Estimate__c" lightningStylesheets="true" sidebar="false" showHeader="true" id="allPage" action="{!init}">
    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
<style type="text/css">
    table { border-collapse: collapse; }
    .container {
        overflow:auto;
        width:100%;
        height:304px;
    }
    .container2 {
        overflow:auto;
        width:100%;
        height:404px;
    }
    .btntable .dateFormat  {
        display: none;
    }
</style>
<script type="text/javascript">
var oxygenPriceAdj = {!oxygenPriceAdj};
var Session_ID = '{!$Api.Session_ID}';
var Confirm_ChangedAfterPrint = '打印后行信息有变化,是否继续操作(报价编码会变新)?';
var isNewAddMonth = {!isNewAddMonth};
var Confirm_EstimateRefresh = '已超过创建日3个月,是否更新报价?';
window.sfdcPage.appendToOnloadQueue(function() { calonLoad() });
function unblockUI(){
    // 2021、8、26 合同报价页面的优化,无保有设备点检对象选择框变黑 fxk star
    // disable1();
    // 2021、8、26 合同报价页面的优化,无保有设备点检对象选择框变黑 fxk end
    pageSetDisabled();
    var isChange = j$(escapeVfId('allPage:allForm:changedSubmitPrice')).value();
    if (isChange=='true') {
        j$(escapeVfId('allPage:allForm:changedSubmitPrice')).val('false');
        var rowCnt = j$(escapeVfId('allPage:allForm:allBlock:assetSection:productCnt')).val();
        refreshAsset(rowCnt);
    }
    j$("#sbArea").fadeOut(500, function(){
        j$("#sbArea").remove();
    });
}
//<!-- HWAG-B4R3SS  START 20181026-->
function clearAndSearch() {
    document.getElementById("allPage:allForm:allBlock:text1").value = "";
    document.getElementById("allPage:allForm:allBlock:cond1").value = "equals";
    document.getElementById("allPage:allForm:allBlock:val1").value = "";
    blockme();
    searchfunc();
}
function searchJs() {
    blockme();
    searchfunc();
}
//<!-- HWAG-B4R3SS  END 20181026-->
// 初始化设定画面项目不可用
function pageSetDisabled(){
    var isDisabled = {!PageDisabled};
    if (isDisabled) {
        j$(escapeVfId('allPage:allForm:allBlock:contract:depart')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contract:startdate')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contract:monthRange')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contract:estimateTarget')).attr("disabled", true);
        var rowCnt = {!productCount};
        for (var i = 0; i < rowCnt; i++) {
            var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
            if (isManual == 'true') {
                var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Assert'));
                a.attr("disabled", true);
            }
            j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetCheck')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':comment')).attr("disabled", true);
        }
        j$(escapeVfId('allPage:allForm:allBlock:appendCondition:Examination_Count')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disPercent')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disMoney')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:discountReason')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:improveConsumptionRateIdea')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:contractstartdate')).attr("disabled", true);
        var target = j$(escapeVfId('allPage:allForm:allBlock:contract:estimateTarget')).val();
        if (target != '医院') {
            j$(escapeVfId('allPage:allForm:allBlock:contract:dealer')).attr("disabled", true);
        }
    }
    if ('{!DecideBtnDisabled}' == 'false') {
        j$(escapeVfId('allPage:allForm:contractstartdate')).attr("disabled", false);
    }
}
// 2021、8、26 合同报价页面的优化,无保有设备点检对象选择框变黑 fxk star
// function disable1(){
//     var isDisabled ;
//     if(isDisabled){
//         var rowCnt = {!productCount};
//         for (var i = 0; i < rowCnt; i++) {
//             // 保有设备名
//             var assN = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:'+ i +':assetName')).text();
//             var assN1 = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:'+ i +':Assert')).val();
//             // alert('1234567'+assN +'----'+assN1);
//             if(!assN1 && !assN){
//                 // alert('23456789'+assN);
//                 j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetCheck'   )).attr("disabled", true);
//             }else{
//                 j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetCheck'   )).attr("disabled", false);
//             }
//         }
//     }
// }
// 2021、8、26 合同报价页面的优化,无保有设备点检对象选择框变黑 fxk end
var winOpenObj;
function closeWin(flg) {
    winOpenObj.close();
    if (flg==2) {
        window.location.href="/{!URLENCODE(estimate.Id)}/e?completion=2";
    }
}
function controlDisabled() {
    winOpenObj = window.open("/apex/ChangeDealerApproval?eid=" + '{!URLENCODE(estimate.Id)}','ChangeDealerApproval','height=300,width=700,toolbar=no,menubar=no,left=20%,top=30%,scrollbars=yes,resizable=no,location=no,status=no');
}
// 見積もり作成後、3ヶ月以内であれば見積もりの内容を継続使用可能
function calonLoad() {
    // 2021、8、26 合同报价页面的优化,无保有设备点检对象选择框变黑 fxk star
    // disable1();
    // 2021、8、26 合同报价页面的优化,无保有设备点检对象选择框变黑 fxk end
    pageSetDisabled();
    var createdDate = new Date('{!estimate.CreatedDate}');
    // 20201103 gzw bug 对应 没有 nowDate JS出现问题
    var nowDate = new Date();
    // 报价中设备的机身编码为空时的新品合同有效期延长 20200710 gzw
    var aLLManual = 'true';
    var cntWithKara = {!productCount};
    for (var i = 0; i < cntWithKara; i++) {
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        if (isManual != 'true') {
            aLLManual = 'false';
            break;
        }
    }
    if (aLLManual == 'false') {
        createdDate = createdDate.setMonth(createdDate.getMonth() + 3);
        // FIX liang JSの時間って addMonthsないですか? そかも 1/1 なら、 4/1もだめですよ。
        if (createdDate < Date.parse(nowDate)) {
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:savebtntop')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:saveAndCancelBtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:approvalbtntop')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:savebtntop')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:saveAndCancelBtn')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:approvalbtntop')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:savebtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:approvalbtn')).attr("disabled", true);
            // 最初は、Decideの同時に保存もあります、それを防ぐため、保存とDecideを同時に無効にする
            // 考えてみると、クラスにDecideの判断があり、Decideの時明細変更チェックもあります、3ヶ月のチェックもあります、ここで無効にする意味がありません
            //j$(escapeVfId('allPage:allForm:decidebtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:savebtn')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:approvalbtn')).attr("class", 'btnDisabled');
            //j$(escapeVfId('allPage:allForm:decidebtn')).attr("class", 'btnDisabled');
            if (confirm(Confirm_EstimateRefresh)) {
                window.location.href="/apex/SelectAssetEstimate?copyid={!URLENCODE(targetEstimateId)}";
                return true;
            } else {
                if ('{!DecideBtnDisabled}' == 'false') {
                    // decide可能の場合、別途decideのチェックが必要、
                    // チェック後再度画面refreshされるため、decide可能の場合、decideボタンが使えるようになります。
                    changeContractStartdate('{!estimate.Contract_Start_Date__c}');
                }
                return false;
            }
        }
    }else{
        createdDate = createdDate.setMonth(createdDate.getMonth() + 6);
        // FIX liang JSの時間って addMonthsないですか? そかも 1/1 なら、 4/1もだめですよ。
        if (createdDate < Date.parse(nowDate)) {
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:savebtntop')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:saveAndCancelBtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:approvalbtntop')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:savebtntop')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:saveAndCancelBtn')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:approvalbtntop')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:savebtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:approvalbtn')).attr("disabled", true);
            // 最初は、Decideの同時に保存もあります、それを防ぐため、保存とDecideを同時に無効にする
            // 考えてみると、クラスにDecideの判断があり、Decideの時明細変更チェックもあります、3ヶ月のチェックもあります、ここで無効にする意味がありません
            //j$(escapeVfId('allPage:allForm:decidebtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:savebtn')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:approvalbtn')).attr("class", 'btnDisabled');
            //j$(escapeVfId('allPage:allForm:decidebtn')).attr("class", 'btnDisabled');
            if (confirm('已超过创建日6个月,是否更新报价?')) {
                window.location.href="/apex/SelectAssetEstimate?copyid={!URLENCODE(targetEstimateId)}";
                return true;
            } else {
                if ('{!DecideBtnDisabled}' == 'false') {
                    // decide可能の場合、別途decideのチェックが必要、
                    // チェック後再度画面refreshされるため、decide可能の場合、decideボタンが使えるようになります。
                    changeContractStartdate('{!estimate.Contract_Start_Date__c}');
                }
                return false;
            }
        }
    }
    if ('{!DecideBtnDisabled}' == 'false') {
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:oldMainteReal')).val(j$(escapeVfId('allPage:allForm:allBlock:contractInfo:mainteReal')).text());
    }
}
function checkAll(checker) {
    var cnt = j$(escapeVfId('allPage:allForm:allBlock:assetSection:productCnt')).val();
    for (var i = 0; i < cnt; i++) {
        if (j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetRowCheckbox')).size() == 0) {
            break;
        }
        document.getElementById('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetRowCheckbox').checked = checker.checked;
    }
}
function checkAll2(checker) {
    var cnt2 = j$(escapeVfId('allPage:allForm:allBlock:assetSection2:productCnt2')).val();
    var outer = 0;
    for (var i = 0; i < cnt2; i++) {
        outer = Math.floor(i / 1000);
        if (document.getElementById('allPage:allForm:allBlock:assetSection2:outassetTable2:' + outer +':assetTable2:' + (i-(1000*outer)) + ':assetRowCheckbox2').disabled == false) {
            document.getElementById('allPage:allForm:allBlock:assetSection2:outassetTable2:' + outer +':assetTable2:' + (i-(1000*outer)) + ':assetRowCheckbox2').checked = checker.checked;
        }
    }
}
function checkPercentage(val) {
    if (val == null || val == "") {
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disPercent')).val(0.00);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disMoney')).val(0.00);
        return;
    }
    if (isNaN(parseInt(val))) {
        alert("请输入数值");
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disPercent')).val(0.00);
        return;
    }
    val = localParseFloat(val);
    val = Math.round(val * 100) / 100;
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disPercent')).val(toNumComma(val));
    //if (val> 100.00 || val < 0) {
    //    alert("请输入0.00到99.99之间的数值");
    //    j$(escapeVfId('allPage:allForm:allBlock:disBlock:disPercent')).val("");
    //    return;
    //}
    makeRealPrice();
}
function checkDiscount(val) {
    if (val == null || val == "") {
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disPercent')).val(0.00);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disMoney')).val(0.00);
        return;
    }
    if (isNaN(parseInt(val))) {
        alert("请输入数值");
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disMoney')).val(0.00);
        return;
    }
    val = localParseFloat(val);
    val = Math.round(val * 100) / 100;
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disMoney')).val(toNumComma(val));
    //if (val < 0) {
    //    alert("优惠价格不能低于0元");
    //    j$(escapeVfId('allPage:allForm:allBlock:disBlock:disMoney')).val("");
    //    return;
    //}
   makeRealPrice(1);
}
function checkContractRange(val, cnt) {
    if (isNaN(parseInt(val))) {
        alert("请输入数值");
        j$(escapeVfId('allPage:allForm:allBlock:contract:monthRange')).val("");
        return;
    }
    if (val <= 0) {
        alert("合同月数必须大于0");
        j$(escapeVfId('allPage:allForm:allBlock:contract:monthRange')).val("");
        return;
    }
    // HWAG-BA73ZP
    contractStartDateChange();
    refreshAsset(cnt);
}
function checkContractEstiStartDate(val, cnt) {
    if (val == null || val == "") {
        return;
    }
    for (var i = 0; i < cnt; i++) {
        var instaldate = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':InstallDate')).text();
        if (instaldate != null && instaldate != '') {
            var listprice = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val();
            var isnew = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNewHidden')).val();
            if (isnew == "true") {
                listprice = listprice / {!isNewPriceAdj};
            }
            var startdate = new Date(val);
            startdate.setMonth(startdate.getMonth() + isNewAddMonth);
            instaldate = new Date(instaldate);
            if (startdate < instaldate) {
                listprice = listprice * {!isNewPriceAdj};
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPrice')).text(toNumComma(listprice));
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val(listprice);
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPricePageHidden')).val(listprice);
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNew')).attr('checked',true);
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNewHidden')).val('true');
            } else {
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPrice')).text(toNumComma(listprice));
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val(listprice);
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPricePageHidden')).val(listprice);
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNew')).attr('checked',false);
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNewHidden')).val('false');
            }
        }
    }
    refreshAsset(cnt);
}
function refreshAsset(cnt) {
    // row金額合計
    var repairSum = 0;
    var listSum = 0;
    // 合同月数乗算
    var month = j$(escapeVfId('allPage:allForm:allBlock:contract:monthRange')).val();
    if (month == undefined || month == "") {
        month = 1;
    }
    var month2 = 0;
    if (month > 12) {
        month2 = month - 12;
        month = 12;
    }
    for (var i = 0; i < cnt; i++) {
        var strMoney = 0;
        var repairMoney = 0;
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        var isnew = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNewHidden')).val();
        if (isManual == 'true') {
            var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Assert')).value();
            if (a != '') {
                strMoney = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val();
                if (isnew == 'true') {
                    strMoney = month * strMoney + month2 * strMoney / {!isNewPriceAdj};
                } else {
                    strMoney = month * strMoney + month2 * strMoney;
                }
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPrice')).text(toNumComma(strMoney));
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPricePageHidden')).val(strMoney);
                repairMoney = j$.trim(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).value());
            } else {
                // TODO 一時的な対応、なんで別行の金額リフレッシュされた?
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPrice')).text("");
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPricePageHidden')).val();
            }
        }
        else {
            strMoney = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val();
            if (isnew == 'true') {
                strMoney = month * strMoney + month2 * strMoney / {!isNewPriceAdj};
            } else {
                strMoney = month * strMoney + month2 * strMoney;
            }
            j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPrice')).text(toNumComma(strMoney));
            j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPricePageHidden')).val(strMoney);
            repairMoney = j$.trim(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).value());
        }
        repairSum = repairSum + localParseFloat(repairMoney);
        listSum = listSum + localParseFloat(toNum(strMoney));
    }
    j$(escapeVfId('allPage:allForm:allBlock:assetRepairSumNum')).text(toNumComma(repairSum));
    j$(escapeVfId('allPage:allForm:allBlock:assetListSumNum')).text(toNumComma(listSum));
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetSumPrice')).text(toNumComma(listSum));
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetSumPriceHidden')).val(toNum(listSum));
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetRepairSumPrice')).text(toNumComma(repairSum));
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetRepairSumPriceHidden')).val(toNum(repairSum));
    NotUseOxygenatedWaterAmount(1);
    examinationPriceCal(cnt);
}
function NotUseOxygenatedWaterAmount(t) {
    var sum = 1 * localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetSumPrice')).text());
    var sumAdj = 0;
    if (document.getElementById('allPage:allForm:allBlock:appendCondition:notUseOxygen').checked == true) {
        sumAdj = -1 * sum * oxygenPriceAdj;
    }
    j$(escapeVfId('allPage:allForm:allBlock:NotUseOxygenatedWaterAmount')).text(toNumComma(sumAdj));
    // 付加条件総額欄
    var examPrice = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:appendCondition:examinationReal')).text());
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:appendPrice')).text(toNumComma(sumAdj + examPrice));
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:appendPriceHidden')).val(toNum(sumAdj + examPrice));
    makeRealPrice(1);
}
function examinationPriceCal(cntWithKara) {
    var examinationCount = localParseInt(j$(escapeVfId('allPage:allForm:allBlock:appendCondition:Examination_Count')).val());
    var examinationCountStr = number_format_common(examinationCount, 0, ".", ",");
    j$(escapeVfId('allPage:allForm:allBlock:appendCondition:Examination_Count')).val(examinationCountStr);
    var cnt = 0;
    for (var i = 0; i < cntWithKara; i++) {
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        if (isManual == 'true') {
            var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Assert')).value();
            if (a != '') {
                cnt++;
            }
        }
        else {
            cnt++;
        }
    }
    var examinationPrice = 0;
// 今後復活かも
//    var cntLot = Math.ceil(cnt / 20);
//    if (cntLot == 0) {
//        examinationPrice = 0;
//    }
//    else if (cntLot == 1) {
//        examinationPrice = 2000;
//    }
//    else if (cntLot == 2) {
//        examinationPrice = 3800;
//    }
//    else if (cntLot == 3) {
//        examinationPrice = 5400;
//    }
//    else if (cntLot == 4) {
//        examinationPrice = 6800;
//    }
//    else if (cntLot == 5) {
//        examinationPrice = 8000;
//    }
//    else if (cntLot >= 6) {
//        examinationPrice = 1600 * cntLot;
//    }
    j$(escapeVfId('allPage:allForm:allBlock:appendCondition:examinationReal')).text(toNumComma(examinationPrice * examinationCount));
    j$(escapeVfId('allPage:allForm:allBlock:appendCondition:examinationRealHidden')).val(toNum(examinationPrice * examinationCount));
    // 付加条件総額欄
    var oxygenPrice = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:NotUseOxygenatedWaterAmount')).text());
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:appendPrice')).text(toNumComma(oxygenPrice + examinationPrice * examinationCount));
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:appendPriceHidden')).val(toNum(oxygenPrice + examinationPrice * examinationCount));
    makeRealPrice(1);
}
/*
 * @param t   1: 金額により割引
 */
function makeRealPrice(t) {
    // 実際金額合計
    var sum1 = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetSumPrice')).text();
    var sum2 = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetRepairSumPrice')).text();
    var append = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:appendPrice')).text();
    var sum = localParseFloat(sum1) + localParseFloat(append);
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetSum2')).text(toNumComma(sum));
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetSum2Hidden')).val(toNum(sum));
    var disM = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disMoney')).val());
    var disMP = toNum(disM / sum * 100);
    // 割引金額から割引率を計算
    if (t == 1) {
        var disP = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disPercent')).val();
        if (disMP != disP) {
            j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disPercent')).val(disMP);
        }
    }
    // 割引率から割引金額を計算
    else {
        var disP = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disPercent')).val();
        if (disMP != disP) {
            disM = sum * disP / 100;
            j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disMoney')).val(toNum(disM));
        }
    }
    sum = sum - disM;
    // 修理総額を計上
    sum = sum + localParseFloat(sum2);
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:mainteReal')).text(toNumComma(sum));
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:mainteRealHidden')).val(toNum(sum));
}
function resetDealer() {
    var target = j$(escapeVfId('allPage:allForm:allBlock:contract:estimateTarget')).val();
    var obj = document.getElementById('allPage:allForm:allBlock:contract:dealer');
    var obj_lkwgt = document.getElementById('allPage:allForm:allBlock:contract:dealer_lkwgt');
    if (target == '医院') {
        obj.style.display = "none";
        obj_lkwgt.style.display = "none";
    } else {
        obj.style.display = "block";
        obj_lkwgt.style.display = "block";
    }
}
function changeAllCheckResult(val) {
    var cnt = j$(escapeVfId('allPage:allForm:allBlock:assetSection:productCnt')).val();
    for (var i = 0; i < cnt; i++) {
        if (val == ' ') {
            document.getElementById('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':checkResult').value = '';
        } else {
            document.getElementById('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':checkResult').value = val;
        }
    }
}
function alertMsg() {
    // body...
    if('{!isPaymentSet}' == 'false'){
        alert('请填写付款计划');
        return false;
    }else if('{!isPaymentSet}' == 'Denied'){
        alert('付款计划金额与实际不符,请重新填写');
        return false;
    }else{
        return true;
    }
}
function onclickCheckchangedAfterPrint(saveBtnDisabled, saveOrApproval) {
    if(saveBtnDisabled == 'Pttrue'){
        var rs = alertMsg();
        if(rs){
        }else {
            return false;
        }
    }
    var cntWithKara = {!productCount};
    var alerts = 0;
    var today = new Date();
    today.setMonth(today.getMonth() - 3);
    for (var i = 0; i < cntWithKara; i++) {
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        if (isManual == 'true') {
            var plkid = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Assert_lkid'));
            var pid = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':ProductId'));
            if (plkid.size() > 0 && pid.size() > 0) {
                if (pid.value() != '' && plkid.value() != pid.value().substring(0, 15)) {
                    alert('请使用产品放大镜按钮设定手动产品');
                    return false;
                }
            }
        }
        if (isManual == 'false') {
            var strDate = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':finalExaminationDate')).value();
            strDate = strDate.replace(/(^\s*)|(\s*$)/g, "");
            if (strDate == "" || Date.parse(strDate) < Date.parse(today)) {
                alerts = 1;
            }
        }
    }
    if (alerts == 1) {
        if (confirm("选择的保有设备[最后点检日]为空或已经超过三个月之前,是否继续?")) {
        } else {
            return false;
        }
    }
    blockme();
    if (saveOrApproval == "true") {
        if (saveBeforeCheckPriceChange()) {
            if (confirm("行信息有变化(维修合同价格),是否更新报价?")) {
                j$(escapeVfId('allPage:allForm:changedSubmitPrice')).val('true');
            } else {
                j$(escapeVfId('allPage:allForm:changedSubmitPrice')).val('fasle');
                unblockUI();
                return false;
            }
        }
        j$(escapeVfId('allPage:allForm:isSaveOrApproval')).val('true');
    }
    return true;
    // if ((saveBtnDisabled == "true"||saveBtnDisabled == "Pttrue" )&& checkchangedAfterPrint()) {
    //     if (confirm(Confirm_ChangedAfterPrint)) {
    //         if (saveOrApproval == "true") {
    //             j$(escapeVfId('allPage:allForm:isSaveOrApproval')).val('true');
    //         }
    //         return true;
    //     } else {
    //         unblockUI();
    //         return false;
    //     }
    // } else {
    //     if (saveOrApproval == "true") {
    //         j$(escapeVfId('allPage:allForm:isSaveOrApproval')).val('true');
    //     }
    //     return true;
    // }
}
function changeEstiStartdate(val) {
    if ('{!SaveBtnDisabled}' == 'false') {
        j$(escapeVfId('allPage:allForm:contractstartdate')).val(val);
        changeContractStartdate(val);
    }
}
function changeContractStartdate(val) {
    var oldDateStr = j$('#oldContractDate').value();
    var oldDate = new Date();
    if (oldDateStr != null && oldDateStr != '') {
        oldDate = new Date(oldDateStr);
    }
    if ('{!DecideBtnDisabled}' == 'false') {
        var monthStr = '00' + (oldDate.getMonth()+1);
        monthStr = monthStr.substring(monthStr.length-2, monthStr.length);
        var dayStr = '00' + oldDate.getDate();
        dayStr = dayStr.substring(dayStr.length-2, dayStr.length);
        var oldDateVal = oldDate.getFullYear() + '/' + monthStr + '/' + dayStr;
        j$(escapeVfId('allPage:allForm:oldDecideContractDate')).val(oldDateVal);
        if (saveBeforeCheckPriceChange()) {
            blockme();
            contractStartDateChange();
        }
    } else {
        var cntWithKara = {!productCount};
        var haveLine = 'false';
        for (var i = 0; i < cntWithKara; i++) {
            var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
            if (isManual == 'true') {
                var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Assert_lkid'));
                if (a.size() > 0 && a.val() != "000000000000000") {
                    haveLine = 'true';
                }
            } else {
                haveLine = 'true';
            }
        }
        if (haveLine == 'false') {
            return false;
        }
        var contractStartDate = new Date(val);
        var strCreatedDate = '{!estimate.CreatedDate}';
        var createDate = new Date();
        if (strCreatedDate != '') {
            createDate = new Date(strCreatedDate);
        }
        createDate = new Date(createDate.toDateString());
        var threeMA = new Date(createDate.setMonth(createDate.getMonth() + 3));
        var isnewMA = new Date(createDate.setMonth(createDate.getMonth() - 3 - isNewAddMonth));
        if (oldDate >= isnewMA && contractStartDate >= isnewMA) {
            return false;
        }
        if (oldDate < threeMA && contractStartDate < threeMA) {
            return false;
        }
        if (contractStartDate >= isnewMA) {
            alert('合同开始预定日或合同开始日发生变化并且大于创建日6个月,所有合同对象设备不适用新品价格。\n请在画面刷新后确认维修合同价格,再继续其他操作。');
        } else if (contractStartDate >= threeMA) {
            alert('合同开始预定日或合同开始日发生变化并且大于创建日3个月,所有合同对象设备使用【合同开始日】重新计算维修合同价格。\n请在画面刷新后确认维修合同价格,再继续其他操作。');
        } else {
            alert('合同开始预定日或合同开始日发生变化并且在创建日3个月以内,所有合同对象设备使用【创建日】重新计算维修合同价格。\n请在画面刷新后确认维修合同价格,再继续其他操作。');
        }
        j$('oldContractDate').val(val);
        blockme();
        contractStartDateChange();
    }
}
function AlertPriceBtnJs(){
    var  VarAlert  = j$(escapeVfId('allPage:allForm:alertStringValue')).val();
    var  VarAlert2 = j$(escapeVfId('allPage:allForm:alertStringValue2')).val();
    var  VarAlert3 = j$(escapeVfId('allPage:allForm:alertStringValue3')).val();
    var  PStatus   = j$(escapeVfId('allPage:allForm:PriceStatus')).val();
    blockme();
    if(PStatus!='申请中'&&PStatus!='批准'){
        ComputeLTYRepair();
        //ShowLTYRepair();
    }else if(PStatus == '申请中'||PStatus == '批准'){
        ShowLTYRepair();
    }
}
function ComputeLTY() {
    var  urlNameJs = j$(escapeVfId('allPage:allForm:urlName')).val();
    urlNameJs = '{!$Label.ID_of_SelectAssetEstimate}'+urlNameJs ;
    var w = window.open(encodeURI(urlNameJs),'过去两年修理实绩','menubar=no,height=720,width=986');
    w.focus();
}
function recordNumChangeJs() {
    recordNumChangeAction();
}
function checkDecideDate() {
    var strSubmitDate = '{!estimate.Submit_quotation_day__c}';
    var submitDate = new Date();
    var nowDate = new Date();
    /// 报价中设备的机身编码为空时的新品合同有效期延长 20200710 gzw
    // 默认为3月,全是产品为6月;
    var monthGap = 6;
    var cntWithKara = {!productCount};
    for (var i = 0; i < cntWithKara; i++) {
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        if (isManual != 'true') {
            monthGap = 3;
            break;
        }
    }
    if (strSubmitDate != '') {
        submitDate = new Date(strSubmitDate);
        submitDate = new Date(submitDate.setMonth(submitDate.getMonth() + monthGap));
    }
    if (strSubmitDate != '' && nowDate > submitDate) {
        alert('已超出报价申请日' + monthGap + '个月,不允许DECIDE。');
        return false;
    }
    return true;
}
function decideJs() {
    if (checkDecideDate() == true) {
        if (onclickCheckchangedAfterPrint('true','false') == true) {
            var oldDate = j$(escapeVfId('allPage:allForm:oldDecideContractDate')).value();
            var contractDate = new Date(j$(escapeVfId('allPage:allForm:contractstartdate')).value());
            //var olDt = oldDate.getFullYear() + oldDate.getMonth() + oldDate.getDate();
            var monthStr = '00' + (contractDate.getMonth()+1);
            monthStr = monthStr.substring(monthStr.length-2, monthStr.length);
            var dayStr = '00' + contractDate.getDate();
            dayStr = dayStr.substring(dayStr.length-2, dayStr.length);
            var contractDateStr = contractDate.getFullYear() + '/' + monthStr + '/' + dayStr;
            //var neDt = contractDate.getFullYear() + contractDate.getMonth() + contractDate.getDate();
            //monthStr = '00' + (oldDate.getMonth()+1);
            //monthStr = monthStr.substring(monthStr.length-2, monthStr.length);
            //dayStr = '00' + oldDate.getDate();
            //dayStr = dayStr.substring(dayStr.length-2, dayStr.length);
            //oldDateVal = oldDate.getFullYear() + '/' + monthStr + '/' + dayStr;
            if (oldDate == contractDateStr) {
                j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
                decide();
            } else {
                var oldp = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:oldMainteReal')).value();
                var newp = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:mainteReal')).text();
                if (oldp != newp) {
                    j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
                    if (confirm('本次合同开始日的修改将导致合同金额发生变化,请您确认是否修改?')) {
                        decide();
                    } else {
                        alert('合同开始日未进行变更,请确认全部内容后点击Decide。');
                        j$(escapeVfId('allPage:allForm:contractstartdate')).val(oldDate);
                        j$(escapeVfId('allPage:allForm:oldDecideContractDate')).val('');
                        j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
                        decideCancle();
                    }
                } else {
                    j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
                    if (confirm('本次合同开始日的修改不会导致合同金额发生变化,请您确认是否修改?')) {
                        decide();
                    } else {
                        j$(escapeVfId('allPage:allForm:contractstartdate')).val(oldDate);
                        alert('合同开始日未进行变更,请确认全部内容后点击Decide。');
                        unblockUI();
                    }
                }
            }
        }
    }
}
</script>
<apex:form id="allForm">
    <apex:inputHidden id="alertStringValue" value="{!alertString}" />
    <apex:inputHidden id="alertStringValue2" value="{!alertString2}" />
    <apex:inputHidden id="alertStringValue3" value="{!alertString3}" />
    <apex:inputHidden id="PriceStatus" value="{!estimate.Process_Status__c}"/>
    <apex:inputHidden id="urlName" value="{!estimate.Name}"/>
    <apex:inputHidden id="changedAfterPrint" value="{!changedAfterPrint}"/>
    <apex:inputHidden id="changedSubmitPrice" value="{!changedSubmitPrice}"/>
    <apex:inputHidden id="isSaveOrApproval" value="{!isSaveOrApproval}"/>
    <!-- HWAG-B4R3SS  START 20181026-->
    <apex:actionFunction name="searchfunc" action="{!searchBtn}" rerender="Form,Block,assetSection2,pageMessages,allBlock" onComplete="unblockUI();"></apex:actionFunction>
    <!-- HWAG-B4R3SS  END 20181026-->
    <apex:actionFunction name="ComputeLTYRepair" action="{!ComputeLTYRepair}"  oncomplete="unblockUI();ComputeLTY();"/>
    <apex:actionFunction name="ShowLTYRepair" action="{!ShowLTYRepair}"  oncomplete="unblockUI();ComputeLTY();"/>
    <apex:actionFunction name="decide" action="{!decide}" rerender="allForm" oncomplete="unblockUI();"/>
    <apex:actionFunction name="decideCancle" action="{!decideCancle}" rerender="allForm" oncomplete="unblockUI();"/>
    <apex:inputHidden id="oldDecideContractDate" value="{!OldContractStartDate}" />
    <input type="hidden" id="oldContractDate" value="{!estimate.Contract_Start_Date__c}" />
<script type="text/javascript">
//j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
</script>
    <apex:pageBlock title="维修合同报价" id="allBlock">
        <apex:pageBlockButtons id="blocktop" location="top">
            <apex:commandButton id="savebtntop" action="{!save}" value="{!$Label.Save_Button}" disabled="{!SaveBtnDisabled}" rerender="allForm" onclick="if (!onclickCheckchangedAfterPrint('true','true')) return false;" oncomplete="unblockUI();"/>
           <!--  <apex:commandButton id="LastTwoYearRepairShow" value="过去两年维修实绩Repaort"  action="{!ShowLTYRepair}" rerender="alertStringValue,alertStringValue2,alertStringValue3" oncomplete="AlertPrice();"/> -->
            <apex:commandButton id="LastTwoYearRepairComp" value="过去三年维修实绩计算" rerender="PriceStatus" onclick="AlertPriceBtnJs()"/>
            <apex:commandButton id="approvalbtntop" action="{!approvalProcess}" value="提交待审批" disabled="{!ApprovalBtnDisabled}" rerender="allForm" onclick="if (!onclickCheckchangedAfterPrint('true','true')) return false;" oncomplete="unblockUI();ComputeLTYRepair();"/>
            <!-- HWAG-B399Q8 2018/08/20 新增请提交待审批 提示字段 start-->
            &nbsp; <apex:outputText style="color:red;font-size:20px" value="请提交待审批" rendered="{!IS_Clone_After_Decide}"/>
            <!-- HWAG-B399Q8 2018/08/20 新增请提交待审批 提示字段 end-->
            <apex:commandButton action="{!cancel}" value="不保存(返回)" style="float:right;" rerender="allForm" onclick="blockme();" oncomplete="unblockUI();"/>
            <apex:commandButton id="saveAndCancelBtn" action="{!saveAndCancel}" value="保存(返回)" style="float:right;" rerender="allForm" oncomplete="unblockUI();" onclick="if (!onclickCheckchangedAfterPrint('true','true')) return false;" disabled="{!SaveBtnDisabled}"/>
        </apex:pageBlockButtons>
        <apex:pageMessages id="pageMessages"></apex:pageMessages>
        <!-- update 合同报价页面的优化 添加‘assetSection’ fxk 2021/9/10 Star-->
        <apex:actionFunction name="refreshProductData" action="{!refreshProductData}" rerender="pageMessages, assetListPrice, assetListPriceHidden, productCount3, assetSection" oncomplete="refreshAsset({!productCount});unblockUI();">
            <apex:param assignTo="{!productIdx}" name="productIdx" value=""/>
        </apex:actionFunction>
        <!-- update 合同报价页面的优化 添加‘assetSection’ fxk 2021/9/10 End-->
        <apex:actionFunction name="contractStartDateChange" action="{!contractStartDateChange}" rerender="allForm" oncomplete="unblockUI();">
        </apex:actionFunction>
        <apex:actionFunction name="recordNumChangeAction" action="{!recordNumChange}" rerender="allForm" oncomplete="unblockUI();">
        </apex:actionFunction>
        <apex:pageblocksection title="{!$ObjectType.Maintenance_Contract__c.label}" id="contract">
            <apex:outputField value="{!estimate.Name}"/>
            <apex:outputField value="{!contract.Management_Code__c}" />
            <apex:outputField value="{!estimate.Process_Status__c}"/>
            <apex:outputField value="{!contract.Status__c}"/>
            <apex:outputField value="{!contract.Hospital__c}" />
            <apex:inputField value="{!estimate.Department__c}" id="depart"/>
            <apex:inputField value="{!estimate.Contract_Esti_Start_Date__c}" required="true" id="startdate" onchange="changeEstiStartdate(this.value);"/><!-- onchange="checkContractEstiStartDate(this.value, {!productCount})" -->
            <apex:inputField value="{!estimate.Contract_Range__c}" required="true" id="monthRange" onchange="checkContractRange(this.value, {!productCount})"/>
            <apex:outputField value="{!estimate.Contract_Esti_End_Date__c}"/>
            <apex:outputField label="制定日" value="{!estimate.CreatedDate}" id="createDateShow"/>
            <apex:outputPanel >
                <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">报价提交对象</label>
                <apex:inputField value="{!estimate.Estimate_Target__c}" id="estimateTarget" onchange="resetDealer()" style="margin-left:5px"/>
                <apex:outputPanel rendered="{!DecideBtnDisabled==false}">
                    <input type="button" class="btn" value="变更" onclick="controlDisabled()" style="margin-left:20px;width:40px;padding:0 0;"/>
                </apex:outputPanel>
                <apex:outputPanel rendered="{!DecideBtnDisabled==true}">
                    <input type="button" class="btnDisabled" value="变更" disabled="true" onclick="controlDisabled()" style="margin-left:20px;width:40px;padding:0 0;"/>
                </apex:outputPanel>
            </apex:outputPanel>
            <apex:inputField value="{!estimate.Dealer__c}" id="dealer" />
            <script type="text/javascript">
                j$(escapeVfId('allPage:allForm:allBlock:contract:estimateTarget')).children('option[value=]').remove();
                resetDealer();
            </script>
        </apex:pageblocksection>
        <apex:pageblocksection columns="1" title="合同对象设备" id="assetSection" >
            <apex:outputLabel />
            <apex:outputPanel >
                <input type="hidden" id="allPage:allForm:allBlock:assetSection:productCnt" value="{!productCount}" />
                <table width="100%">
                    <tr>
                        <td>&nbsp;</td>
                        <td width="100px"><span>全</span>
                            <select style="vertical-align:text-bottom" id="allCheckResult" size="1" onchange="changeAllCheckResult(this.value)">
                                <option value=" ">--无--</option>
                                <option value="OK">OK</option>
                                <option value="NG">NG</option>
                            </select>
                        </td>
                        <td width="150px">&nbsp;</td>
                    </tr>
                </table>
                <table class="list" style="border-bottom-width: 0px; font-size:13px;" border="0" cellspacing="0" cellpadding="0">
                    <tr class="headerRow" height="30px">
                        <th style="width:25px" class="headerRow  booleanColumn"><input type='checkbox' onClick='checkAll(this)'/></th>
                        <th class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Name.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Asset_situation__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.SerialNumber.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Department_Name__c.label}</th>
                        <!-- <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Installation_Site__c.label}</th> -->
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Management_Code__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.CurrentContract_End_Date__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.InstallDate.label}</th>
                        <!-- <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Asset_Owner__c.label}</th> -->
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Accumulation_Repair_Amount__c.label}</th>
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Estimate_List_Price_All__c.label}</th>
                        <!--add点检改善:新增一个点检对象复选框字段,默认为true 2021.6.8 fxk Star-->
                        <th style="width:70px" class="headerRow  booleanColumn">
                        {!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Check_Object__c.label}</th>
                        <!--add点检改善:新增一个点检对象复选框字段,默认为true 2021.6.8 fxk end-->
                        <th style="width:40px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.IsNew__c.label}</th>
                        <!-- <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Last_inspection_day__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Check_Result__c.label}</th> -->
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Repair_Price__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Comment__c.label}</th>
                    </tr>
                </table>
                <apex:outputPanel layout="block" styleClass="container">
                    <apex:variable value="{!1}" var="cnt" />
                    <table class="list" style="border-top-width: 0px; font-size:12px;" border="0" cellspacing="0" cellpadding="0">
                        <apex:repeat value="{!checkedAssets}" var="ar" id="assetTable">
                            <tr class="dataRow {!IF(MOD(cnt, 2)==0, 'odd', 'even')} {!IF(cnt==1, 'first', '')}" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
                                <td class="dataCell" width="25px">
                                    <apex:inputCheckbox value="{!ar.rec_checkBox_c}" id="assetRowCheckbox" rendered="{!Not(ar.IsManual)}" disabled="{!PageDisabled}"/>
                                    <apex:outputText value="{!ar.IsManual}" id="IsManual" style="display:none;" />
                                </td>
                                <td class="dataCell">
                                    <apex:outputField value="{!ar.rec.Name}" id="assetName" rendered="{!Not(ar.IsManual)}" />
                                    <apex:inputField value="{!ar.mcae.Product_Manual__c}" id="Assert" style="width:90%;" rendered="{!ar.IsManual}" onchange="blockme();refreshProductData({!ar.lineNo});"/>
                                    <apex:inputText id="ProductId" value="{!ar.mcae.Product_Manual__c}" style="display:none;" disabled="true"/>
                                </td>
                                <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.Asset_situation__c}" rendered="{!Not(ar.IsManual)}" />
                                </td>
                                <td class="dataCell" width="70px">
                                    <apex:outputLink value="/{!ar.recId}" rendered="{!Not(ar.IsManual)}" >{!ar.rec.SerialNumber}</apex:outputLink>
                                    <apex:inputHidden id="AssetId" value="{!ar.recId}"/>
                                </td>
                                <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.Department_Name__c}" rendered="{!Not(ar.IsManual)}" />
                                </td>
                                <!-- <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.Installation_Site__c}" rendered="{!Not(ar.IsManual)}" />
                                </td> -->
                                <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.Management_Code__c}" rendered="{!Not(ar.IsManual)}" />
                                </td>
                                <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.CurrentContract_End_Date__c}" rendered="{!Not(ar.IsManual)}" />
                                </td>
                                <td class="dataCell" width="70px" style="text-align:center" >
                                    <apex:outputField value="{!ar.rec.InstallDate}" id="InstallDate" rendered="{!Not(ar.IsManual)}" />
                                </td>
                                <!-- <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.Asset_Owner__c}" rendered="{!Not(ar.IsManual)}" />
                                </td> -->
                                <td class="dataCell" width="90px" style="text-align:right" >
                                    <apex:outputField value="{!ar.rec.Accumulation_Repair_Amount__c}" rendered="{!Not(ar.IsManual)}" />
                                </td>
                                <td class="dataCell" width="90px" style="text-align:right" >
                                    <apex:outputText value="{!ar.mcae.Estimate_List_Price__c}" id="assetListPrice" style="padding-right:3px;" />
                                    <apex:outputPanel layout="none" rendered="{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.createable}" >
                                        <apex:inputHidden value="{!ar.mcae.Estimate_List_Price__c}" id="assetListPriceHidden"/>
                                        <apex:inputHidden value="{!ar.mcae.Estimate_List_Price_Page__c}" id="assetListPricePageHidden" />
                                    </apex:outputPanel>
                                    <apex:outputPanel layout="none" rendered="{!Not($ObjectType.Maintenance_Contract_Asset_Estimate__c.createable)}" >
                                        <input type="hidden" value="{!ar.mcae.Estimate_List_Price__c}" id="allPage:allForm:allBlock:assetSection:assetTable:{!Text(cnt-1)}:assetListPriceHidden"/>
                                    </apex:outputPanel>
                                </td>
                                 <!--add点检改善:新增一个点检对象复选框字段,默认为true 2021.6.8 fxk Star-->
                                <td class="dataCell" width="70px" style="text-align:center" >
                                    <apex:inputCheckbox value="{!ar.mcae.Check_Object__c}" id="assetCheck" disabled="{!ar.CheckRows}"/>
                                </td>
                                <!--add点检改善:新增一个点检对象复选框字段,默认为true 2021.6.8 fxk end-->
                                <td class="dataCell" width="40px" style="text-align:center" >
                                    <apex:inputCheckbox value="{!ar.mcae.IsNew__c}" id="assetNew" disabled="true"/>
                                    <apex:outputPanel layout="none" rendered="{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.createable}" >
                                        <apex:inputHidden value="{!ar.mcae.IsNew__c}" id="assetNewHidden" />
                                    </apex:outputPanel>
                                    <apex:outputPanel layout="none" rendered="{!Not($ObjectType.Maintenance_Contract_Asset_Estimate__c.createable)}" >
                                        <input type="hidden" value="{!ar.mcae.IsNew__c}" id="allPage:allForm:allBlock:assetSection:assetTable:{!Text(cnt-1)}:assetNewHidden" />
                                    </apex:outputPanel>
                                    <apex:outputText value="{!ar.rec.Final_Examination_Date__c}" id="finalExaminationDate" rendered="{!Not(ar.IsManual)}" style="display:none"/>
                                </td>
                                <!-- <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.Final_Examination_Date__c}" id="finalExaminationDate" rendered="{!Not(ar.IsManual)}"/>
                                </td>
                                <td class="dataCell" width="70px" style="text-align:center" >
                                    <apex:inputField value="{!ar.mcae.Check_Result__c}" id="checkResult"/>
                                </td> -->
                                <td class="dataCell" width="70px" style="text-align:right" >
                                    <apex:inputField value="{!ar.mcae.Repair_Price__c}" id="repairPrice" style="ime-mode: disabled; width:95%; text-align:right;" onchange="refreshAsset({!productCount});"/>
                                </td>
                                <td class="dataCell" width="70px" style="text-align:right" >
                                    <apex:inputField value="{!ar.mcae.Comment__c}" id="comment" style="width:95%;"/>
                                </td>
                            </tr>
                            <apex:variable value="{!cnt + 1}" var="cnt" />
                        </apex:repeat>
                    </table>
                </apex:outputPanel>
            </apex:outputPanel>
        </apex:pageblocksection>
        <!-- HWAG-B4R3SS  START 20181026-->
        <apex:outputPanel id="sumPanel"  onkeydown="if(event.keyCode==13){searchJs(); return false;}">
        <!-- HWAG-B4R3SS  END 20181026-->
            <table style="width:100%;">
                <tr>
                    <td>
                        <apex:commandButton value="行追加" action="{!addNewRows}" disabled="{!Not($ObjectType.Maintenance_Contract_Asset_Estimate__c.createable) || PageDisabled}"
                            style="margin-left:10px;float:left;" onclick="blockme();" oncomplete="unblockUI();" rerender="allForm" />
                        <apex:commandButton value="刷新选中的保有设备" disabled="{!SaveBtnDisabled || productCount2==0}" action="{!exchangeAsset}" onclick="blockme();" oncomplete="unblockUI();" rerender="allForm" />
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <!-- HWAG-B4R3SS  START 20181026-->
                        <apex:outputText value="选择条件"/>
                        &nbsp;&nbsp;
                        <apex:selectList value="{!text1}" id="text1" size="1" style="width:80px"><apex:selectOptions value="{!textOpts}"/>
                        </apex:selectList>
                        &nbsp;&nbsp;
                        <apex:selectList value="{!cond1}" id="cond1" size="1" style="width:80px">
                        <apex:selectOptions value="{!equalOpts}"/>
                        </apex:selectList>
                        &nbsp;&nbsp;
                        <!-- LJPH-BSS6E2  ---20200911 ---update by rentongxiao start -->
                        <!-- <apex:inputText value="{!val1}"
                        id="val1" style="width:100px"/> -->
                        <apex:inputText value="{!val1}"
                        id="val1" style="width:100px; background-color:{!IF(contr == '1','#e3f3ff','white')}"/>
                        <!-- LJPH-BSS6E2  ---20200911 ---update by rentongxiao end -->
                        &nbsp;
                        <apex:commandButton value="检索" onclick="searchJs();" style="width:100px" rerender="dummy"/>
                        &nbsp;
                        <apex:commandButton value="清除条件" onclick="clearAndSearch();" style="width:100px" rerender="dummy"/>
                        <!-- HWAG-B4R3SS END 20181026-->
                    </td>
                    <th width="90px" style="text-align:right">设备数量</th>
                    <td width="90px" style="text-align:right"><apex:outputtext value="{!productCount3}" id="productCount3"/></td>
                    <td width="25px">&nbsp;</td>
                    <th width="90px" style="text-align:right">报价总额</th>
                    <th width="90px" style="text-align:right"><span id="allPage:allForm:allBlock:assetListSumNum" ></span></th>
                    <td width="25px">&nbsp;</td>
                    <th width="90px" style="text-align:right">修理总额</th>
                    <th width="90px" style="text-align:right"><span id="allPage:allForm:allBlock:assetRepairSumNum" ></span></th>
                    <td width="95px">&nbsp;</td>
                </tr>
            </table>
        </apex:outputPanel>
        <apex:pageblocksection columns="1" title="未选择的保有设备" id="assetSection2" >
            <apex:outputLabel />
            <apex:outputPanel >
                <input type="hidden" id="allPage:allForm:allBlock:assetSection2:productCnt2" value="{!productCount2}" />
                <table class="list" style="border-bottom-width: 0px; font-size:13px;" border="0" cellspacing="0" cellpadding="0">
                    <tr class="headerRow" height="30px">
                        <th style="width:25px" class="headerRow  booleanColumn"><input type='checkbox' onClick='checkAll2(this)'/></th>
                        <th style="width:29%" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Name.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Asset_situation__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.SerialNumber.label}</th>
                        <th class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Department_Name__c.label}</th>
                        <!-- <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Installation_Site__c.label}</th> -->
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.IF_Warranty__c.label}</th>
                        <!-- JZHG-BSDUT4 ---20200825---update By rentongxiao---Start -->
                        <th style="width: 90px" class="headerRow booleanColumn">主机/耗材</th>
                        <!-- JZHG-BSDUT4 ---20200825---update By rentongxiao---End -->
                        <th style="width:150px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Reson_Can_not_Warranty__c.label}</th>
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.InstallDate.label}</th>
                        <!-- <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Asset_Owner__c.label}</th> -->
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Accumulation_Repair_Amount__c.label}</th>
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Estimate_List_Price__c.label}</th>
                    </tr>
                </table>
                <apex:outputPanel layout="block" styleClass="container2" style="max-height: 404px; height: auto;">
                    <apex:variable value="{!1}" var="cnt" />
                    <table class="list" style="border-top-width: 0px; font-size:12px;" border="0" cellspacing="0" cellpadding="0">
                    <apex:repeat value="{!unCheckedAssetsView}" var="assetsView" id="outassetTable2">
                        <apex:repeat value="{!assetsView}" var="ar" id="assetTable2">
                            <tr class="dataRow {!IF(MOD(cnt, 2)==0, 'odd', 'even')} {!IF(cnt==1, 'first', '')}" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
                                <td class="dataCell" width="25px">
                                    <apex:inputCheckbox value="{!ar.rec_checkBox_c}" id="assetRowCheckbox2" disabled="{!IF(ar.rec.Maintenance_Price_Month__c == 0 || ar.rec.IF_Warranty__c = '否', 'true', 'false')}"/>
                                </td>
                                <td class="dataCell" width="30%">
                                    <apex:outputField value="{!ar.rec.name}" id="assetName"/>
                                </td>
                                <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.Asset_situation__c}"/>
                                </td>
                                <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.SerialNumber}"/>
                                </td>
                                <td class="dataCell">
                                    <apex:outputField value="{!ar.rec.Department_Name__c}"/>
                                </td>
                                <!-- <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.Installation_Site__c}"/>
                                </td> -->
                                <td class="dataCell" width="90px" style="text-align:center">
                                    <apex:outputField value="{!ar.rec.IF_Warranty__c}"/>
                                </td>
                                <!-- //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start -->
                                <td class="dataCell" width="90px" style="text-align:center">
                                    <apex:outputField value="{!ar.rec.AssetMark__c}"/>
                                </td>
                                <!-- //JZHG-BSDUT4 ---20200825---update By rentongxiao---End -->
                                <td class="dataCell" width="150px" style="text-align:center">
                                    <apex:outputField value="{!ar.rec.Reson_Can_not_Warranty__c}"/>
                                </td>
                                <td class="dataCell" width="90px" style="text-align:center" >
                                    <apex:outputField value="{!ar.rec.InstallDate}"/>
                                </td>
                                <!-- <td class="dataCell" width="90px">
                                    <apex:outputField value="{!ar.rec.Asset_Owner__c}"/>
                                </td> -->
                                <td class="dataCell" width="90px" style="text-align:right" >
                                    <apex:outputField value="{!ar.rec.Accumulation_Repair_Amount__c}"/>
                                </td>
                                <td class="dataCell" width="90px" style="text-align:right" >
                                    <apex:outputField value="{!ar.rec.Maintenance_Price_Month__c}" />
                                </td>
                            </tr>
                            <apex:variable value="{!cnt + 1}" var="cnt" />
                        </apex:repeat>
                        </apex:repeat>
                    </table>
                </apex:outputPanel>
                <apex:outputPanel >
                    <dir align="right">
                        <table>
                            <tr>
                                <td>{!(currPage-1)*selctRecordNum}&nbsp;-&nbsp;{!IF(currPage*selctRecordNum > totalRecords, totalRecords, currPage*selctRecordNum)}</td>
                                <td>&nbsp;&nbsp;共{!totalRecords}个</td>
                                <td align="right" width="115px">显示
                                    <apex:selectList value="{!selRecordOption}" id="selRecordOption" size="1" onchange="blockme();recordNumChangeJs();" disabled="{!IF(totalRecords<10,true,false)}"><apex:selectOptions value="{!recordNum}"/></apex:selectList>条记录
                                </td>
                                <td align="right" width="50px">第{!currPage}页</td>
                                <td align="right" width="45px">
                                    <apex:commandLink action="{!firstPage}" value="首页" id="firstPg" onclick="blockme();" oncomplete="unblockUI();" reRender="allForm" style="{!IF(currPage==1,'display: none;','')}color: blue;"/>
                                    <apex:outputText value="首页" style="{!IF(currPage!=1,'display: none;','')}color: gray;"></apex:outputText>
                                </td>
                                <td align="right" width="40px">
                                    <apex:commandLink action="{!previousPage}" value="上一页" id="previous" onclick="blockme();" oncomplete="unblockUI();" reRender="allForm" style="{!IF(currPage==1,'display: none;','')}color: blue;"/>
                                    <apex:outputText value="上一页" style="{!IF(currPage!=1,'display: none;','')}color: gray;"></apex:outputText>
                                </td>
                                <td width="3px"></td>
                                <td align="left" width="40px">
                                    <!-- HWAG-B4R3SS  START 20181026-->
                                    <apex:commandLink action="{!nextPage}" value="下一页" id="next" onclick="blockme();" oncomplete="unblockUI();" reRender="allForm" style="{!IF(totalPage==currPage ||totalPage == 0,'display: none;','')}color: blue;"/>
                                    <apex:outputText value="下一页" style="{!IF(totalPage!=currPage && totalPage != 0,'display: none;','')}color: gray;"></apex:outputText>
                                </td>
                                <td align="left" width="45px">
                                    <apex:commandLink action="{!endPage}" value="尾页" id="endPg" onclick="blockme();" oncomplete="unblockUI();" reRender="allForm" style="{!IF(totalPage==currPage||totalPage == 0,'display: none;','')}color: blue;"/>
                                    <apex:outputText value="尾页" style="{!IF(totalPage!=currPage
                                        && totalPage != 0,'display: none;','')}color: gray;"></apex:outputText>
                                </td>
                                <!-- HWAG-B4R3SS  END 20181026-->
                                <td align="left">共{!totalPage}页</td>
                            </tr>
                        </table>
                    </dir>
                </apex:outputPanel>
            </apex:outputPanel>
        </apex:pageblocksection>
        <apex:pageblocksection columns="1" title="附加条件" id="appendCondition">
            <apex:outputLabel />
            <apex:outputPanel >
                <table style="width:100%">
                    <tr>
                        <th width="100" style="text-align:right">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.NotUse_Oxygenated_Water__c.label}</th>
                        <td width="100" style="text-align:center"><!-- <apex:inputField value="{!estimate.NotUse_Oxygenated_Water__c}" id="notUseOxygen" onclick="NotUseOxygenatedWaterAmount();"/> -->
                        <apex:inputCheckbox value="{!estimate.NotUse_Oxygenated_Water__c}" id="notUseOxygen" onclick="NotUseOxygenatedWaterAmount();" disabled="true"/>
                        </td>
                        <td width="100" style="text-align:right"><span id="allPage:allForm:allBlock:NotUseOxygenatedWaterAmount"></span></td>
                        <td width="100">&nbsp;</td>
                        <td>&nbsp;</td>
                    </tr>
                    <tr>
                        <th style="text-align:right">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Service_contract_target_number__c.label}</th>
                        <td><apex:inputField value="{!estimate.Service_contract_target_number__c}" id="Examination_Count" style="ime-mode: disabled; text-align:right; width:100px" onchange="examinationPriceCal({!productCount})"/></td>
                        <th style="text-align:right;display:none;">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Examination_Price__c.label}</th>
                        <td style="text-align:right;display:none;">
                            <apex:outputField value="{!estimate.Examination_Price__c}" id="examinationReal" />
                            <apex:inputHidden value="{!estimate.Examination_Price__c}" id="examinationRealHidden"/>
                        </td>
                        <td>&nbsp;</td>
                    </tr>
                </table>
            </apex:outputPanel>
        </apex:pageblocksection>
        <apex:pageblocksection title="合同信息" columns="1" id="contractInfo">
            <apex:outputLabel />
            <apex:outputPanel >
                <table style="width:100%">
                    <tr>
                        <td width="15%"></td>
                        <td width="14%"></td>
                        <td width="15%"></td>
                        <td width="28%"></td>
                        <td width="14%"></td>
                        <td width="14%"></td>
                    </tr>
                    <tr>
                        <th style="text-align: center">1.维修合同设备报价总额</th>
                        <th style="text-align: center">2.附加条件总额</th>
                        <th style="text-align: center">3.此次合同报价总额</th>
                        <th style="text-align: center">4.优惠率(价格)</th>
                        <th style="text-align: center">5.修理总额</th>
                        <th style="text-align: center">6.合同价格</th>
                    </tr>
                    <tr>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.Asset_Sum_Price__c}" id="assetSumPrice" />
                            <apex:inputHidden value="{!estimate.Asset_Sum_Price__c}" id="assetSumPriceHidden" />
                        </td>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.Append_Condition_Price__c}" id="appendPrice" />
                            <apex:inputHidden value="{!estimate.Append_Condition_Price__c}" id="appendPriceHidden" />
                        </td>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.Estimate_Trial_Money__c}" id="assetSum2" />
                            <apex:inputHidden value="{!estimate.Estimate_Trial_Money__c}" id="assetSum2Hidden" />
                        </td>
                        <td style="text-align: center">
                            <apex:inputField value="{!estimate.Discount_Percentage__c}" id="disPercent" style="ime-mode: disabled; text-align:right; width:100px" onchange="checkPercentage(this.value);"/><font style="font-weight: bold">&nbsp;%&nbsp;(&nbsp;</font>
                            <apex:inputField value="{!estimate.Discount_Price__c}" id="disMoney" style="ime-mode: disabled; text-align: right; width:100px" onchange="checkDiscount(this.value);"/><font style="font-weight: bold">&nbsp;)</font>
                        </td>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.Asset_Repair_Sum_Price__c}" id="assetRepairSumPrice" />
                            <apex:inputHidden value="{!estimate.Asset_Repair_Sum_Price__c}" id="assetRepairSumPriceHidden" />
                        </td>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.Maintenance_Price__c}" id="mainteReal" />
                            <apex:inputHidden value="{!estimate.Maintenance_Price__c}" id="mainteRealHidden"/>
                            <apex:inputHidden value="{!OldMaintenancePrice}" id="oldMainteReal"/>
                        </td>
                    </tr>
                    <tr>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Discount_reason__c.label}</th>
                        <td colspan="5"><apex:inputField value="{!estimate.Discount_reason__c}" id="discountReason" style="width:95%;height:50px;" /></td>
                    </tr>
                    <tr>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Improve_ConsumptionRate_Idea__c.label}</th>
                        <td colspan="5"><apex:inputField value="{!estimate.Improve_ConsumptionRate_Idea__c}" id="improveConsumptionRateIdea" style="width:95%;height:50px;" /></td>
                    </tr>
                </table>
            </apex:outputPanel>
        </apex:pageblocksection>
        <script type="text/javascript">
            refreshAsset({!productCount});
        </script>
    </apex:pageBlock>
    <table width="100%" border="0">
        <tr>
            <!-- <td width="40%" style="text-align: right;"> -->
            <td width="40%">
                <table border="0" style="background-color:#ffd6c1;">
                    <tr>
                        <th width="70px">打印报价</th>
                        <td width="80px"><apex:inputCheckbox value="{!estimate.Print_ListPrice__c}"/>报价</td>
                        <td width="80px"><apex:inputCheckbox value="{!estimate.Print_RepairPrice__c}"/>修理金额</td>
                        <td width="80px"><apex:inputCheckbox value="{!estimate.Print_SumPrice__c}"/>报价总额</td>
                        <td width="80px" style="display:none;"><apex:inputCheckbox value="{!estimate.Print_DiscountPercentage__c}"/>优惠折扣</td>
                        <td width="80px" style="display:none;"><apex:inputCheckbox value="{!estimate.Print_DiscountPrice__c}"/>优惠价格</td>
                        <td width="80px"><apex:inputCheckbox value="{!estimate.Print_MaintePrice__c}"/>合同价格</td>
                    </tr>
                    <tr>
                        <th width="70px">打印合同配置</th>
                        <td width="80px">
                        <!-- 2018/10/26HWAG-B5C88S 医院和经销商合同任何时候都不能选择 start -->
                            <apex:outputPanel rendered="false">
                                <apex:inputCheckbox value="{!estimate.Print_Contract__c}" />
                            </apex:outputPanel>
                            <apex:outputPanel rendered="{!Not(EnablePrintContract)}">
                                &nbsp;&nbsp;&nbsp;
                            </apex:outputPanel>
                            医院合同
                        </td>
                        <!-- 2018/09/26 HWAG-B4SCR3 三方和代理商合同在未decide前也不能选择 start -->
                        <td width="70px">
                            <apex:outputPanel rendered="{!EnablePrintContract}">
                                <apex:inputCheckbox id="tripartite" value="{!estimate.Print_Tripartite__c}"/>
                            </apex:outputPanel>
                            <apex:outputPanel rendered="{!Not(EnablePrintContract)}">
                                &nbsp;&nbsp;&nbsp;
                            </apex:outputPanel>
                        三方协议</td>
                        <td width="70px">
                            <apex:outputPanel rendered="false">
                                <apex:inputCheckbox id="agent" value="{!estimate.Print_Agent__c}"/>
                            </apex:outputPanel>
                            <apex:outputPanel rendered="{!Not(EnablePrintContract)}">
                                &nbsp;&nbsp;&nbsp;
                            </apex:outputPanel>
                        代理商合同</td>
                        <!-- 2018/09/26  HWAG-B4SCR3 三方和代理商合同在未decide前也不能选择 end -->
                        <!-- 2018/10/26 HWAG-B5C88S 医院和经销商合同任何时候都不能选择 end -->
                        <td colspan="3" style="text-align: right"><apex:commandButton action="{!print}" value="PDF印刷" rerender="allBlock,pdfPrint" disabled="{!PrintBtnDisabled}" onclick="if (!onclickCheckchangedAfterPrint('Pt{!SaveBtnDisabled}','false')) return false;" oncomplete="unblockUI();ComputeLTYRepair()"/></td>
                    </tr>
                </table>
            </td>
            <td>
                <table class="btntable" border="0">
                    <tr>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td width="20px">&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td width="30px">&nbsp;</td>
                        <td><apex:commandButton id="savebtn" action="{!save}" value="{!$Label.Save_Button}" disabled="{!SaveBtnDisabled}" rerender="allForm" onclick="if (!onclickCheckchangedAfterPrint('true','true')) return false;" oncomplete="unblockUI();"/></td>
                        <td width="200px"><apex:commandButton id="approvalbtn" action="{!approvalProcess}" value="提交待审批" disabled="{!ApprovalBtnDisabled}" rerender="allForm" onclick="if (!onclickCheckchangedAfterPrint('true','true')) return false;" oncomplete="unblockUI();ComputeLTYRepair();"/>
                        <!-- HWAG-B399Q8 2018/08/20 新增请提交待审批 提示字段 start-->
                        &nbsp; <apex:outputText style="color:red;font-size:20px;" value="请提交待审批" rendered="{!IS_Clone_After_Decide}"/>
                        <!-- HWAG-B399Q8 2018/08/20 新增请提交待审批 提示字段 end-->
                        </td>
                    </tr>
                    <tr>
                        <th>{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Contract_Start_Date__c.label}</th>
                        <td><apex:inputField value="{!estimate.Contract_Start_Date__c}" id="contractstartdate" onchange="changeContractStartdate(this.value);"/></td>
                        <td>&nbsp;</td>
                        <th>&nbsp;&nbsp;{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Contract_End_Date__c.label}</th>
                        <td><apex:outputField value="{!estimate.Contract_End_Date__c}" id="contractenddate"/></td>
                        <td>&nbsp;</td>
                        <td><apex:commandButton id="decidebtn" value="{!$Label.QuoteDecision_Button}" disabled="{!DecideBtnDisabled}" onclick="decideJs(); return false;"/></td>
                        <td style="text-align:right"><apex:commandButton id="undecidebtn" action="{!undecide}" value="取消{!$Label.QuoteDecision_Button}" disabled="{!UnDecideBtnDisabled}" rerender="allForm" onclick="blockme();" oncomplete="unblockUI();"/></td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</apex:form>
<apex:outputPanel id="pdfPrint">
<script type="text/javascript">
//j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
function saveBeforeCheckPriceChange() {
    sforce.connection.sessionId = Session_ID;
    var needClearId = false;
    var rowCnt = j$(escapeVfId('allPage:allForm:allBlock:assetSection:productCnt')).val();
    var assIds = "";
    var proIds = "";
    var priceMap = new Map();
    var newProductMap = new Map();
    var newProductCheck = false;
    var nowDate = new Date();
    var createdDate = null;
    var createdDateShow = j$(escapeVfId('allPage:allForm:allBlock:contract:createDateShow')).text();
    var contractDate = new Date(j$(escapeVfId('allPage:allForm:contractstartdate')).value());
    if (createdDateShow.trim() != '') {
        createdDate = new Date(createdDateShow);
        newProductCheck = true;
    } else {
        createdDate = new Date();
    }
    var threeMonthAfter = new Date(createdDate.setMonth(createdDate.getMonth() + 3));
    createdDate = new Date(createdDate.setMonth(createdDate.getMonth() - 3));
    for (var i = 0; i < rowCnt; i++) {
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        var isnew = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNewHidden')).val();
        var price = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val();
        if (isManual == 'true') {
            var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':ProductId'));
            if (a.size() > 0 && a.value() != "000000000000000000" && a.value() != "") {
                if (proIds == "") {
                    proIds = "'" + a.value() + "'";
                } else {
                    proIds = proIds + ",'" + a.value() + "'";
                }
                if (isnew == "true") {
                    priceMap.set(a.value(), price/{!isNewPriceAdj});
                } else {
                    priceMap.set(a.value(), price);
                }
                newProductMap.set(a.value(), isnew);
            } else {
                continue;
            }
        }
        else {
            var aId = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':AssetId')).value();
            if (assIds == "") {
                assIds = "'" + aId + "'";
            } else {
                assIds = assIds + ",'" + aId + "'";
            }
            if (isnew == "true") {
                priceMap.set(aId, price/{!isNewPriceAdj});
            } else {
                priceMap.set(aId, price);
            }
            newProductMap.set(aId, isnew);
        }
    }
    // 选择设备后价格变更check
    if (assIds.length > 0) {
        var sql = "SELECT Id, Maintenance_Price_Month__c, Posting_Date__c, InstallDate from Asset where Id In(" + assIds + ")";
        var rt = sforce.connection.query(sql);
        var asList = rt.getArray("records");
        if (asList != null) {
            for(var i=0;i<asList.length;i++) {
                var asvar = asList[i];
                var asId = asvar["Id"];
                var mprice = asvar["Maintenance_Price_Month__c"];
                var ptDt = asvar["Posting_Date__c"];
                var postingDate = null;
                if (ptDt != null && ptDt != '') {
                    postingDate = new Date(ptDt);
                }
                var inDt = asvar["InstallDate"];
                var installDate = null;
                if (inDt != null && inDt != '') {
                    installDate = new Date(inDt);
                }
                var priceShow = priceMap.get(asId);
                var isNew = newProductMap.get(asId);
                if ('{!DecideBtnDisabled}' == 'true') {
                    if (Number(mprice).toFixed(2) != Number(priceShow).toFixed(2)) {
                        needClearId = true;
                        // j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
                        return needClearId;
                    }
                }
                // 新品check
                var sixCreateDate = new Date(createdDate.setMonth(createdDate.getMonth() + 6));
                createdDate.setMonth(createdDate.getMonth() - 6);
                if (contractDate >= sixCreateDate && newProductCheck) {
                    if (isNew=='true') {
                        needClearId = true;
                        j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
                        return needClearId;
                    }
                } else {
                    var threeCreateDate = new Date(createdDate.setMonth(createdDate.getMonth() + 3));
                    createdDate = new Date(createdDate.setMonth(createdDate.getMonth() - 3));
                    if (newProductCheck) {
                        var isNewDate = null;
                        var isNewProduct = 'false';
                        if (contractDate >= threeMonthAfter) {
                            isNewDate = new Date(contractDate);
                        } else {
                            isNewDate = new Date(createdDate);
                        }
                        if (postingDate != null && postingDate != '' && (installDate == null || installDate == '')) {
                            if (new Date(isNewDate.setMonth(isNewDate.getMonth()-6)) < postingDate) {
                                isNewProduct = 'true';
                            }
                        } else if (postingDate != null && postingDate != '' && installDate != null && installDate != '') {
                            // alert('postingDate:'+postingDate+'/installDate:'+installDate);
                            if (new Date(postingDate.setMonth(postingDate.getMonth()+6)) >= installDate) {
                                var dt = new Date(isNewDate.setMonth(isNewDate.getMonth()-6));
                                if (dt < installDate) {
                                    isNewProduct = 'true';
                                }
                            }
                        } else if ((postingDate == null || postingDate == '') && installDate != null && installDate != '') {
                            if (new Date(isNewDate.setMonth(isNewDate.getMonth()-6)) < installDate) {
                                isNewProduct = 'true';
                            }
                            // isNewDate.setMonth(isNewDate.getMonth()+6);
                        }
                        // alert('contract:'+contractDate+'/create:'+createdDate+'/install:'+installDate+'/date:'+isNewDate);
                        // alert('oldNew:'+isNew + 'isNew:'+isNewProduct);
                        if (isNew != isNewProduct) {
                            needClearId = true;
                            j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
                            return needClearId;
                        }
                    }
                }
            }
        }
    }
    if (proIds.length > 0) {
        if ('{!DecideBtnDisabled}' == 'false') {
            var oldDateStr = j$('#oldContractDate').value();
            var oldDate = new Date();
            if (oldDateStr != null && oldDateStr != '') {
                oldDate = new Date(oldDateStr);
            }
            var crdt = new Date(j$(escapeVfId('allPage:allForm:allBlock:contract:createDateShow')).text());
            var newContractDate = new Date(j$(escapeVfId('allPage:allForm:contractstartdate')).value());
            var sixMonthAfter = new Date(crdt.setMonth(crdt.getMonth() + 6));
            if ((newContractDate > sixMonthAfter && oldDate <= sixMonthAfter) || (newContractDate <= sixMonthAfter && oldDate > sixMonthAfter)) {
                j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
                return true;
            }
        } else {
            var sql = "SELECT Id, Maintenance_Price_Month__c from Product2 where Id In(" + proIds + ")";
            var rt = sforce.connection.query(sql);
            var pdList = rt.getArray("records");
            if (pdList != null) {
                for(var i=0;i<pdList.length;i++) {
                    var pdvar = pdList[i];
                    var pdId = pdvar["Id"];
                    var mprice = pdvar["Maintenance_Price_Month__c"];
                    var priceShow = priceMap.get(pdId);
                    if (Number(mprice).toFixed(2) != Number(priceShow).toFixed(2)) {
                        needClearId = true;
                        // j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
                        return needClearId;
                    }
                }
            }
        }
    }
    // var changedPrice = j$(escapeVfId('allPage:allForm:changedSubmitPrice')).value();
    // if (changedPrice=='true') {
    //     needClearId = true;
    // }
    return needClearId;
}
// SelectAssetEstimateController#checkchangedAfterPrint と同じロジックにする必要があります。
// true 変更あり、false 変更なし
function checkchangedAfterPrint() {
    sforce.connection.sessionId = Session_ID;
    var needClearId = false;
    //j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
    var changedPrice = j$(escapeVfId('allPage:allForm:changedSubmitPrice')).value();
    // 新規の場合、targetEstimateIdがない、判断いらない
    if ('{!targetEstimateId}' == '') return needClearId;
    if ('{!estimate.Quote_Date__c}' != '' || '{!estimate.Process_Status__c}' != '草案中') {
        // xud 20140529 ここは明細変更判断
        // xudan 20150729 ソート項目にIdを追加
        var sql = "SELECT Id, Asset__c, Asset__r.SerialNumber, Check_Result__c, Product_Manual__c,"
                + " Repair_Price__c, Comment__c, Maintenance_Contract_Estimate__r.Maintenance_Price__c"
                + "  FROM Maintenance_Contract_Asset_Estimate__c"
                + " WHERE Maintenance_Contract_Estimate__c = '{!targetEstimateId}'"
                + " ORDER BY id,Asset__c,Product_Manual__c, Asset__r.SerialNumber, Asset__r.Name, Asset__r.Department_Name__c, Asset__r.InstallDate";
        var result = sforce.connection.query(sql);
        var mcaeList = result.getArray("records");
        var inputingList = [];
        var finalPrice = 0;
        // 画面入力値を整理(いらないものを対象外にする)
        var cntWithKara = {!productCount};
        for (var i = 0; i < cntWithKara; i++) {
            var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
            if (isManual == 'true') {
                var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':ProductId'));
                if (a.size() > 0 && a.value() != "000000000000000000" && a.value() != "") {
                    inputingList.push(
                        {'id' : '',
                         'Product_Manual__c' : a.value(),
                         'Check_Result__c' : j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':checkResult')).value(),
                         'Repair_Price__c' : localParseFloat(j$.trim(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).value())),
                         'Comment__c': j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':comment')).value()
                        }
                    );
                } else {
                    continue;
                }
            }
            else {
                inputingList.push(
                    {'id' : j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':AssetId')).value(),
                     'Check_Result__c' : j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':checkResult')).value(),
                     'Repair_Price__c' : localParseFloat(j$.trim(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).value())),
                     'Comment__c': j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':comment')).value()
                    }
                );
            }
        }
        //针对inputingList的重新排序
        var arrayMap = [];
        var ArrayOrderPMCnt = [];
        for(var i=0;i<mcaeList.length;i++){
            var mcaeVar = mcaeList[i];
            var AssetIDOrPMC = mcaeVar["Asset__c"]!=null?mcaeVar["Asset__c"]:mcaeVar["Product_Manual__c"];
            if(arrayMap[AssetIDOrPMC]!=null){
                arrayMap[AssetIDOrPMC] = i;
                ArrayOrderPMCnt[AssetIDOrPMC] = i;
            }else{
                // Product_Manual__c相同的话怎么办
                if(ArrayOrderPMCnt[AssetIDOrPMC]==null){
                    ArrayOrderPMCnt[AssetIDOrPMC] = i;
                }else{
                    var cacheArray = new Array();
                    cacheArray = ArrayOrderPMCnt[AssetIDOrPMC];
                    ArrayOrderPMCnt[AssetIDOrPMC] = cacheArray+','+i;
                }
            }
        }
        var inputingListCache = inputingList;
        var cntLength = mcaeList.length>inputingListCache.length?mcaeList.length:inputingListCache.length;
        if(mcaeList.length!=inputingListCache.length){
            needClearId = true;
            //j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
            return needClearId;
        }
        inputingList = new Array(cntLength);
        var inputingListOut = new Array();
        for(var i=0;i<inputingListCache.length;i++){
            var InputIdOrPMc = inputingListCache[i].id!=""?inputingListCache[i].id:inputingListCache[i].Product_Manual__c;
            var thisArray = ArrayOrderPMCnt[InputIdOrPMc];
            if(thisArray.length!=null){
                thisArray = thisArray.split(',');
                var ORDERCnt = thisArray[0];
                thisArray.shift();
                thisArray = thisArray.join(',');
                ArrayOrderPMCnt[InputIdOrPMc] = thisArray;
            }else{
                var ORDERCnt = thisArray;
            }
            if( ORDERCnt !=null){
                inputingList[ORDERCnt] = inputingListCache[i];
            }else{
                inputingList[ORDERCnt] = inputingListCache[i];
                inputingListOut.push(inputingListCache[i]);
            }
        }
        if( inputingListOut.length>0){
            for(var i = 0; i<inputingListOut.length;i++){
                inputingList.push(inputingListOut[i]);
            }
        }
        //20161122,测试发现Check_Result__c已停用,故而修改对应的Js判断部分
        /*
                            && (((mcae["Check_Result__c"] == null || mcae["Check_Result__c"] == "")
                                  && (inputing["Check_Result__c"] == null || inputing["Check_Result__c"] == "")
                                )
                                || mcae["Check_Result__c"] == inputing["Check_Result__c"]
                               )
        //==================================================================================
                            && (((mcae["Check_Result__c"] == null || mcae["Check_Result__c"] == "")
                                  && (inputing["Check_Result__c"] == null || inputing["Check_Result__c"] == "")
                                )
                                || mcae["Check_Result__c"] == inputing["Check_Result__c"]
                               )
        */
        //原是代码保留
        if (inputingList.length == mcaeList.length && needClearId == false ) {
            for (var i = 0; i < mcaeList.length; i++) {
                var mcae = mcaeList[i];
                finalPrice = mcae["Maintenance_Contract_Estimate__r"]["Maintenance_Price__c"];
                var inputing = inputingList[i];
                if (mcae["Asset__c"] != null && mcae["Asset__c"] != "") {
                    if (inputing["id"] != "" && mcae["Asset__c"] == inputing["id"]
                            && localParseFloat(mcae["Repair_Price__c"]) == inputing["Repair_Price__c"]
                            && (((mcae["Comment__c"] == null || mcae["Comment__c"] == "")
                                  && (inputing["Comment__c"] == null || inputing["Comment__c"] == "")
                                )
                                || mcae["Comment__c"] == inputing["Comment__c"]
                               )
                    ) {
                        // 同じ
                    } else {
                        needClearId = true;
                        break;
                    }
                } else {
                    if (inputing["id"] == "" && mcae["Product_Manual__c"] != null && mcae["Product_Manual__c"] != ""
                            && mcae["Product_Manual__c"] == inputing["Product_Manual__c"]
                            && localParseFloat(mcae["Repair_Price__c"]) == inputing["Repair_Price__c"]
                            && (((mcae["Comment__c"] == null || mcae["Comment__c"] == "")
                                  && (inputing["Comment__c"] == null || inputing["Comment__c"] == "")
                                )
                                || mcae["Comment__c"] == inputing["Comment__c"]
                               )
                    ) {
                        // 同じ
                    } else {
                        needClearId = true;
                        break;
                    }
                }
            }
        } else {
            needClearId = true;
        }
        // xud 20140529 ここは総金額変更判断(割引を変更したらまずい)
        var inputFinalPrice = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:mainteRealHidden')).value();
        if (toNum(inputFinalPrice) != toNum(finalPrice)) {
            needClearId = true;
        }
        if (changedPrice=='true') {
            needClearId = true;
        }
    }
    if (needClearId) {
        //j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
    }
    return needClearId;
}
if ('{!printAsset}' == 'true') {
    //打印保有設備
    window.open('/apex/MaintenanceContractEstimatePDF?id={!targetEstimateId}', 'MaintenanceContractEstimatePDF');
} else if ('{!printContract}' == 'true') {
    // 打印医院合同配置
    window.open('/apex/MceConfigPDF?id={!targetEstimateId}&flag=printContract', 'MceConfigPDF');
} else if ('{!printTripartite}' == 'true') {
    //打印三方合同
    window.open('/apex/MceConfigPDF?id={!targetEstimateId}&flag=printTripartite', 'MceConfigPDF');
} else if ('{!printAgent}' == 'true') {
    //打印经销商合同
    window.open('/apex/MceConfigPDF?id={!targetEstimateId}&flag=printAgent', 'MceConfigPDF');
}else {}
</script>
</apex:outputPanel>
</apex:page>
force-app/main/default/pages/SelectAssetEstimate.page-meta.xml
New file
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>31.0</apiVersion>
    <availableInTouch>false</availableInTouch>
    <confirmationTokenRequired>false</confirmationTokenRequired>
    <label>SelectAssetEstimate</label>
</ApexPage>
force-app/main/default/pages/SelectAssetEstimateJumpPage.page
New file
@@ -0,0 +1,22 @@
<apex:page standardcontroller="Maintenance_Contract_Estimate__c" sidebar="false">
    <!-- <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/> -->
    <script type="text/javascript">
        var rdn = '{!Maintenance_Contract_Estimate__c.RecordType_DeveloperName__c}';
        // 追加限次跳转
        var urf = '{!Maintenance_Contract_Estimate__c.URF_Contract__c}';
        if(rdn == 'NewMaintenance_Quote'){
            if (urf == 'true') {
                window.open("/apex/SelectAssetEstimateURF?id={!URLENCODE(Maintenance_Contract_Estimate__c.Id)}", "_self")
            }else{
                window.open("/apex/SelectAssetEstimateVM?id={!URLENCODE(Maintenance_Contract_Estimate__c.Id)}", "_self");
            }
        }else{
            window.open("/apex/SelectAssetEstimate?id={!URLENCODE(Maintenance_Contract_Estimate__c.Id)}", "_self");
        }
    </script>
    <body>
    </body>
</apex:page>
force-app/main/default/pages/SelectAssetEstimateJumpPage.page-meta.xml
New file
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>41.0</apiVersion>
    <availableInTouch>false</availableInTouch>
    <confirmationTokenRequired>false</confirmationTokenRequired>
    <label>SelectAssetEstimateJumpPage</label>
</ApexPage>
force-app/main/default/pages/SelectAssetEstimateURF.page
New file
@@ -0,0 +1,2613 @@
<apex:page controller="SelectAssetEstimateURFController" tabStyle="Maintenance_Contract_Estimate__c" sidebar="false" showHeader="true" id="allPage" action="{!init}" lightningStylesheets="true">
<head>
 <!-- <meta http-equiv="x-ua-compatible" content="ie=edge" /> -->
 <!-- <meta name="viewport" content="width=device-width, initial-scale=1" /> -->
 <!-- <apex:slds /> -->
</head>
    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
<style type="text/css">
    table { border-collapse: collapse; }
    .container {
        overflow:auto;
        width:100%;
        height:304px;
    }
    .container2 {
        overflow:auto;
        width:100%;
        height:404px;
    }
    .btntable.dateFormat  {
        display: none;
    }
</style>
<script type="text/javascript">
//add by rentx 2020-11-17 start 失去焦点
function setFocusOnLoad() {}
function bodyOnLoad(){setFocusOnLoad();}
//add by rentx 2020-11-17 end 失去焦点
var oxygenPriceAdj = {!oxygenPriceAdj};
var approvalDate = '';
var Session_ID = '{!$Api.Session_ID}';
var Confirm_ChangedAfterPrint = '打印后行信息有变化,是否继续操作(报价编码会变新)?';
var isNewAddMonth = {!isNewAddMonth};
var Confirm_EstimateRefresh = '已超过创建日3个月,是否更新报价?';
window.sfdcPage.appendToOnloadQueue(function() { calonLoad() });
function approvalJs() {
    approvalDate = new Date();
    var rowCnt = j$(escapeVfId('allPage:allForm:allBlock:assetSection:productCnt')).val();
    refreshAsset(rowCnt);
}
//add by gwy 2021-01-27 start 提交时的提示框
function KindsAndMonths() {
    var months      = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:contract:monthRange')).val());
    var contrNew    = document.getElementById("allPage:allForm:allBlock:contractInfo:Contract_TypeTXT").innerHTML;
    if(months>12 && months<60 && contrNew == '新品合同'){
        if(confirm("本次您提交的报价为多年期新品合同,请您在正式提交报价前先将经销商与医院签订的多年期合同邮件发送服务本部报价窗口。若已经提交请点击确定,继续保存提交。")){
            return true;
        }else{
            return false;
        }
    }
    //URF限次合同2期 LY 20220920 start
    var FirstParagraphEnd = j$(escapeVfId('allPage:allForm:allBlock:contract:FirstParagraphEnd'))[0].checked;
    if(FirstParagraphEnd){
        if (confirm('本次签约经销商是先款对象,请确认是否提交报价?')) {
            return true;
        }else{
            return false;
        }
    }
    //URF限次合同2期 LY 20220920 end
        return true;
}
//add by gwy 2021-01-27 end 提交时的提示框
function unblockUI(){
    // 2021、8、26 合同报价页面的优化,无保有设备点检对象选择框变黑 fxk star
    // disable1();
    // 2021、8、26 合同报价页面的优化,无保有设备点检对象选择框变黑 fxk end
    pageSetDisabled();
    var isChange = j$(escapeVfId('allPage:allForm:changedSubmitPrice')).value();
    if (isChange=='true') {
        j$(escapeVfId('allPage:allForm:changedSubmitPrice')).val('false');
        var rowCnt = j$(escapeVfId('allPage:allForm:allBlock:assetSection:productCnt')).val();
        refreshAsset(rowCnt);
    }
    j$("#sbArea").fadeOut(500, function(){
        j$("#sbArea").remove();
    });
}
//<!-- HWAG-B4R3SS  START 20181026-->
function clearAndSearch() {
    document.getElementById("allPage:allForm:allBlock:text1").value = "";
    document.getElementById("allPage:allForm:allBlock:cond1").value = "equals";
    document.getElementById("allPage:allForm:allBlock:val1").value = "";
    blockme();
    searchfunc();
}
function searchJs() {
    blockme();
    searchfunc();
}
//<!-- HWAG-B4R3SS  END 20181026-->
// 初始化设定画面项目不可用
function pageSetDisabled(){
    var isDisabled = {!PageDisabled};
    if (isDisabled) {
        j$(escapeVfId('allPage:allForm:allBlock:contract:depart')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contract:startdate')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contract:monthRange')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contract:estimateTarget')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contract:EndUserType')).attr("disabled", true);
        //URF限次合同2期 LY 20220811 start
        j$(escapeVfId('allPage:allForm:allBlock:contract:estimateURFVMaxRepairCount')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contract:estimateURFPMaxRepairCount')).attr("disabled", true);
        //URF限次合同2期 LY 20220811 end
        var rowCnt = {!productCount};
        for (var i = 0; i < rowCnt; i++) {
            var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
            if (isManual == 'true') {
                var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Assert'));
                a.attr("disabled", true);
            }
            j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetCheck')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':comment')).attr("disabled", true);
        }
        j$(escapeVfId('allPage:allForm:allBlock:appendCondition:Examination_Count')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disPercent')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disMoney')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:discountReason')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:improveConsumptionRateIdea')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:quotation_Amount')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Appbackground:finalPriceDecideWay')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Appbackground:Sales_incidental')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Appbackground:mainTalksTime')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Appbackground:talksStartDate')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Appbackground:AgencyHos_Price')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Appbackground:discountReason')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Appbackground:improveConsumptionRateIdea')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:contractstartdate')).attr("disabled", true);
        var target = j$(escapeVfId('allPage:allForm:allBlock:contract:estimateTarget')).val();
        if (target != '医院') {
            j$(escapeVfId('allPage:allForm:allBlock:contract:dealer')).attr("disabled", true);
            //URF限次合同2期 LY 20220920 start
            j$(escapeVfId('allPage:allForm:allBlock:contract:FirstParagraphEnd')).attr("disabled", true);
            //URF限次合同2期 LY 20220920 end
        }
    }
    if ('{!DecideBtnDisabled}' == 'false') {
        j$(escapeVfId('allPage:allForm:contractstartdate')).attr("disabled", false);
    }
}
// 2021、8、26 合同报价页面的优化,无保有设备点检对象选择框变黑 fxk star
// function disable1(){
//     var isDisabled;
//     if(isDisabled){
//         var rowCnt = {!productCount};
//         for (var i = 0; i < rowCnt; i++) {
//             // 保有设备名
//             var assN = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:'+ i +':assetName')).text();
//             var assN1 = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:'+ i +':Assert')).val();
//             // alert('1234567'+assN +'----'+assN1);
//             if(!assN1 && !assN){
//                 // alert('23456789'+assN);
//                 j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetCheck'   )).attr("disabled", true);
//             }else{
//                 j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetCheck'   )).attr("disabled", false);
//             }
//         }
//     }
// }
// 2021、8、26 合同报价页面的优化,无保有设备点检对象选择框变黑 fxk end
var winOpenObj;
function closeWin(flg) {
    winOpenObj.close();
    if (flg==2) {
        window.location.href="/{!URLENCODE(estimate.Id)}/e?completion=2";
    }
}
function controlDisabled() {
    winOpenObj = window.open("/apex/ChangeDealerApproval?eid=" + '{!URLENCODE(estimate.Id)}','ChangeDealerApproval','height=300,width=700,toolbar=no,menubar=no,left=20%,top=30%,scrollbars=yes,resizable=no,location=no,status=no');
}
// 見積もり作成後、3ヶ月以内であれば見積もりの内容を継続使用可能
function calonLoad() {
    // 2021、8、26 合同报价页面的优化,无保有设备点检对象选择框变黑 fxk star
    // disable1();
    // 2021、8、26 合同报价页面的优化,无保有设备点检对象选择框变黑 fxk end
    pageSetDisabled();
    var createdDate = new Date('{!estimate.CreatedDate}');
    // 报价中设备的机身编码为空时的新品合同有效期延长 20200710 gzw
    var aLLManual = 'true';
    var cntWithKara = {!productCount};
    for (var i = 0; i < cntWithKara; i++) {
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        if (isManual != 'true') {
            aLLManual = 'false';
            break;
        }
    }
    var nowDate = new Date();
    if (aLLManual == 'false') {
        createdDate = createdDate.setMonth(createdDate.getMonth() + 3);
        // FIX liang JSの時間って addMonthsないですか? そかも 1/1 なら、 4/1もだめですよ。
        if (createdDate < Date.parse(nowDate)) {
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:savebtntop')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:saveAndCancelBtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:approvalbtntop')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:savebtntop')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:saveAndCancelBtn')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:approvalbtntop')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:savebtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:approvalbtn')).attr("disabled", true);
            // 最初は、Decideの同時に保存もあります、それを防ぐため、保存とDecideを同時に無効にする
            // 考えてみると、クラスにDecideの判断があり、Decideの時明細変更チェックもあります、3ヶ月のチェックもあります、ここで無効にする意味がありません
            //j$(escapeVfId('allPage:allForm:decidebtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:savebtn')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:approvalbtn')).attr("class", 'btnDisabled');
            //j$(escapeVfId('allPage:allForm:decidebtn')).attr("class", 'btnDisabled');
            if (confirm(Confirm_EstimateRefresh)) {
                window.location.href="/apex/SelectAssetEstimateURF?copyid={!URLENCODE(targetEstimateId)}";
                return true;
            } else {
                if ('{!DecideBtnDisabled}' == 'false') {
                    // decide可能の場合、別途decideのチェックが必要、
                    // チェック後再度画面refreshされるため、decide可能の場合、decideボタンが使えるようになります。
                    changeContractStartdate('{!estimate.Contract_Start_Date__c}');
                }
                return false;
            }
        }
    }else{
        createdDate = createdDate.setMonth(createdDate.getMonth() + 6);
        // FIX liang JSの時間って addMonthsないですか? そかも 1/1 なら、 4/1もだめですよ。
        if (createdDate < Date.parse(nowDate)) {
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:savebtntop')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:saveAndCancelBtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:approvalbtntop')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:savebtntop')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:saveAndCancelBtn')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:approvalbtntop')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:savebtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:approvalbtn')).attr("disabled", true);
            // 最初は、Decideの同時に保存もあります、それを防ぐため、保存とDecideを同時に無効にする
            // 考えてみると、クラスにDecideの判断があり、Decideの時明細変更チェックもあります、3ヶ月のチェックもあります、ここで無効にする意味がありません
            //j$(escapeVfId('allPage:allForm:decidebtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:savebtn')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:approvalbtn')).attr("class", 'btnDisabled');
            //j$(escapeVfId('allPage:allForm:decidebtn')).attr("class", 'btnDisabled');
            if (confirm('已超过创建日6个月,是否更新报价?')) {
                window.location.href="/apex/SelectAssetEstimateURF?copyid={!URLENCODE(targetEstimateId)}";
                return true;
            } else {
                if ('{!DecideBtnDisabled}' == 'false') {
                    // decide可能の場合、別途decideのチェックが必要、
                    // チェック後再度画面refreshされるため、decide可能の場合、decideボタンが使えるようになります。
                    changeContractStartdate('{!estimate.Contract_Start_Date__c}');
                }
                return false;
            }
        }
    }
    if ('{!DecideBtnDisabled}' == 'false') {
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:oldMainteReal')).val(j$(escapeVfId('allPage:allForm:allBlock:contractInfo:mainteReal')).text());
    }
}
function checkAll(checker) {
    var cnt = j$(escapeVfId('allPage:allForm:allBlock:assetSection:productCnt')).val();
    for (var i = 0; i < cnt; i++) {
        //2021-11-30 fy add LJPH-C8W8FV 置顶 start
        if (j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetRowCheckbox')).size() == 0) {
            continue;
        }
        //2021-11-30 fy add LJPH-C8W8FV 置顶 end
        document.getElementById('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetRowCheckbox').checked = checker.checked;
    }
}
function checkAll2(checker) {
    var cnt2 = j$(escapeVfId('allPage:allForm:allBlock:assetSection2:productCnt2')).val();
    var outer = 0;
    for (var i = 0; i < cnt2; i++) {
        outer = Math.floor(i / 1000);
        if (document.getElementById('allPage:allForm:allBlock:assetSection2:outassetTable2:' + outer +':assetTable2:' + (i-(1000*outer)) + ':assetRowCheckbox2').disabled == false) {
            document.getElementById('allPage:allForm:allBlock:assetSection2:outassetTable2:' + outer +':assetTable2:' + (i-(1000*outer)) + ':assetRowCheckbox2').checked = checker.checked;
        }
    }
}
function checkDiscount(val) {
    if (val == null || val == "") {
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:quotation_Amount')).val("");
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:discount_Rate')).text("");
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:discount_RateHidden')).val(0.00);
        return;
    }
    if (isNaN(parseInt(val))) {
        alert("请输入数值");
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:quotation_Amount')).val(0.00);
        return;
    }
    val = localParseFloat(val);
    //val = Math.round(val * 100) / 100;
    val = Math.round(val);
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:quotation_Amount')).val(toNumComma(val));
   makeRealPrice(1);
}
function checkContractRange(val, cnt) {
    if (isNaN(parseInt(val))) {
        alert("必须输入合同月数!");
        j$(escapeVfId('allPage:allForm:allBlock:contract:monthRange')).val("");
        return;
    }
    if (val <= 0) {
        alert("合同月数必须大于0");
        j$(escapeVfId('allPage:allForm:allBlock:contract:monthRange')).val("");
        return;
    }
    if (val > 60) {
        alert("合同期最长只能选择60个月!");
        j$(escapeVfId('allPage:allForm:allBlock:contract:monthRange')).val("");
        return;
    }
    // HWAG-BA73ZP
    //contractStartDateChange();
    refreshAsset(cnt);
}
//URF限次合同2期 LY 20220811 start
function checkVMaxRepairCount(val, cnt) {
    var uRFSeriesMap =[];
    for (var i = 0; i < cnt; i++) {
        var uRFSeries = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':uRFSeries')).text();
        // var uRFSeries = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':uRFSeries')).value();
        uRFSeriesMap.push(uRFSeries);
    }
    if ((val == null || val == "" || val == "0") && uRFSeriesMap.includes('URF-V')){
        alert("合同对象设备中含有URF-V系列,必须选择URF-V的最大大修次数!");
        j$(escapeVfId('allPage:allForm:allBlock:contract:estimateURFVMaxRepairCount')).val("0");
        return;
    }
    if ((val == "3") && uRFSeriesMap.includes('URF-V')){
        alert("合同对象设备中URF-V系列目前不能选择3次!");
        j$(escapeVfId('allPage:allForm:allBlock:contract:estimateURFVMaxRepairCount')).val("0");
        return;
    }
    if (uRFSeriesMap.includes('URF-V')==false) {
        alert("合同对象设备中不含有URF-V系列,URF-V的最大大修次数必须选择/!");
        j$(escapeVfId('allPage:allForm:allBlock:contract:estimateURFVMaxRepairCount')).val("0");
    }
    refreshAsset(cnt);
}
function checkPMaxRepairCount(val, cnt) {
    var uRFSeriesMap =[];
    for (var i = 0; i < cnt; i++) {
        var uRFSeries = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':uRFSeries')).text();
        uRFSeriesMap.push(uRFSeries);
    }
    if ((val == null || val == "" || val == "0") && uRFSeriesMap.includes('URF-P')){
        alert("合同对象设备中含有URF-P系列,URF-P的最大大修次数必须选择!");
        //j$(escapeVfId('allPage:allForm:allBlock:contract:estimateURFPMaxRepairCount')).val("3");
    }
    if (uRFSeriesMap.includes('URF-P')==false) {
        alert("合同对象设备中不含有URF-P系列,URF-P的最大大修次数必须选择/!");
        j$(escapeVfId('allPage:allForm:allBlock:contract:estimateURFPMaxRepairCount')).val("0");
    }
    refreshAsset(cnt);
}
//URF限次合同2期 LY 20220811 end
function checkContractEstiStartDate(val, cnt) {
    if (val == null || val == "") {
        return;
    }
    for (var i = 0; i < cnt; i++) {
        var instaldate = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':InstallDate')).text();
        if (instaldate != null && instaldate != '') {
            var listprice = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val();
            var isnew = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNewHidden')).val();
            if (isnew == "true") {
                listprice = listprice / {!isNewPriceAdj};
            }
            var startdate = new Date(val);
            startdate.setMonth(startdate.getMonth() + isNewAddMonth);
            instaldate = new Date(instaldate);
            if (startdate < instaldate) {
                listprice = listprice * {!isNewPriceAdj};
                //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPrice')).text(toNumComma(listprice));
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val(listprice);
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPricePageHidden')).val(listprice);
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNew')).attr('checked',true);
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNewHidden')).val('true');
            } else {
                //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPrice')).text(toNumComma(listprice));
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val(listprice);
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPricePageHidden')).val(listprice);
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNew')).attr('checked',false);
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNewHidden')).val('false');
            }
        }
    }
    refreshAsset(cnt);
}
function refreshAsset(cnt) {
    // 提交后就页面不计算了
    var isDisabled = {!PageDisabled};
    // 合同总理
    var newCount = 0;
    var oyearCount = 0;
    var firstCCount = 0;
    var conCCount = 0;
    // row金額合計
    var repairSum = 0;
    var listSum = 0;
    // 新品合同 判断
    var newCon = true;
    var contractStartDate = new Date(j$(escapeVfId('allPage:allForm:contractstartdate')).value());
    // 预定开始日
    var startdate = new Date(j$(escapeVfId('allPage:allForm:allBlock:contract:startdate')).value());
    // 预定开始日-6个月
    startdate.setMonth(startdate.getMonth() - 6);
    // 申请日 当前日期
    if(approvalDate != ''){
        //申请日
        approvalDate = new Date(approvalDate.toLocaleDateString());
        if (Date.parse(approvalDate) < Date.parse(startdate)) {
            newCon = false;
        }
    }
    // 最高、最低价格合计
    var downPriceSum = 0;
    var upPriceSum = 0;
    // 合同月数乗算
    var month = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:contract:monthRange')).val());
    //URF限次合同2期 LY 20220811 start
    var estimateURFVMaxRepairCount=localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:contract:estimateURFVMaxRepairCount')).val())
    var estimateURFPMaxRepairCount=localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:contract:estimateURFPMaxRepairCount')).val())
    //URF限次合同2期 LY 20220811 end
    // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
    var Contract_year = 0;
    if (month == undefined || month == "" || month <= 12) {
        Contract_year = 1;
    } else{
        Contract_year = Math.ceil(month / 12);
    }
    // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
    var month2 = 0;
    if (month > 12) {
        month2 = month - 12;
        month = 12;
    }
    for (var i = 0; i < cnt; i++) {
        var strMoney = 0;
        var repairMoney = 0;
        // 行项目 最高、最低价格合计
        // 续签价格取联动价格页面计算,首签或产品取 实际价格
        // 下线价格
        var downPrice = 0;
        // 上线价格
        var upPrice = 0;
        // 12个月合同金额
        var Price_YearTXT = 0;
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        var isnew = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNewHidden')).val();
        var assetListmonth = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val();
        if (isManual == 'true') {
            var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Assert')).value();
            if (a != '') {
                // 所有设备按安装日、发货日(最早的),距离合同开始日6个月内都是新品合同
                //var isNewDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':isNewDate')).value());
                //isNewDate.setMonth(isNewDate.getMonth() + 6);
                //if (Date.parse(contractStartDate) > Date.parse(isNewDate)) {
                //    newCon = false;
                //}
                strMoney = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val();
                // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
                //URF限次合同2期 LY 20220811 start
                var uRFSeries= j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':uRFSeries')).value();
                if (uRFSeries=='URF-V' && estimateURFVMaxRepairCount==2) {
                    strMoneyMax = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':uFRMaxPrice')).val();
                    strMoneyMin = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':uFRMinPrice')).val();
                }else if (uRFSeries=='URF-V' && estimateURFVMaxRepairCount==0) {
                    strMoneyMax = 0;
                    strMoneyMin = 0;
                }else if (uRFSeries=='URF-P' && estimateURFPMaxRepairCount==0){
                    strMoneyMax = 0;
                    strMoneyMin = 0;
                }else{
                    strMoneyMax = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':uFRMaxPrice3')).val();
                    strMoneyMin = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':uFRMinPrice3')).val();
                }
                //URF限次合同2期 LY 20220811 end
                // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
                // alert(strMoney);
                Price_YearTXT = strMoney * 12;
                if (isnew == 'true') {
                    newCount ++;
                    // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
                    strMoneyMin = Contract_year * strMoneyMin;
                    strMoneyMax = Contract_year * strMoneyMax;
                    // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
                } else {
                    newCon = false;
                    // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
                    strMoneyMin = Contract_year * strMoneyMin;
                    strMoneyMax = Contract_year * strMoneyMax;
                    // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
                }
                var b = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Contract_No')).value();
                var LastMContractRecord = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':LastMContractRecord')).value();
                if(b != ''){
                    conCCount ++;
                    // 1.合同期不满一年时,合同期超过一半才可开始续签报价。(eg:11个月的合同从6个月后才可报价。)
                    // 2.一年以上的合同,在结束前6个月开始可以开放续签报价。
                    var lastendDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':End_Date')).value());
                    var lastContRange = 0;
                    if(LastMContractRecord == 'VM_Contract'){
                        newCount++;
                        lastendDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':endDateGurantee_Text')).value());
                        lastContRange = 36;
                    }else{
                        lastContRange = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':lastContRange')).value();
                    }
                    //最后结束日+1年
                    lastendDate.setMonth(lastendDate.getMonth() + 12);
                    if (Date.parse(contractStartDate) > Date.parse(lastendDate)) {
                        oyearCount ++;
                    }
                    // 取联动价格
                    // 上一期合同实际报价月额
                    //
                    var LastMContract_Price = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':LastMContract_Price')).val());
                    var Adjustment_ratio_Lower = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_ratio_Lower')).val());
                    var Adjustment_ratio_Upper = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_ratio_Upper')).val());
                    //计算惩罚率
                    var Punish = calculateNtoMRatio( lastContRange,(month + month2));
                    if(Punish == 0){
                        return;
                    }
                    // 判断有无报价:没有按照标准价格实际联动
                    var Estimate_Num = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Estimate_NumHidden')).val();
                    // if(Estimate_Num == 0){
                    //     if(LastMContractRecord == 'VM_Contract'){
                    //         //upPrice = (strMoney) * (1 + Adjustment_ratio_Upper/100);
                    //         //downPrice = (strMoney) * (1 + Adjustment_ratio_Lower/100);
                    //         upPrice = (assetListmonth * Punish) * (1 + Adjustment_ratio_Upper/100);
                    //         downPrice = (assetListmonth * Punish) * (1 + Adjustment_ratio_Lower/100);
                    //     }else{
                            // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
                            upPrice = strMoneyMax;
                            // downPrice = strMoney * 0.8;
                            downPrice = strMoneyMin;
                            // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
                    //     }
                    // }else{
                    //     upPrice = (LastMContract_Price * Punish) * (1 + Adjustment_ratio_Upper/100);
                    //     downPrice = (LastMContract_Price * Punish) * (1 + Adjustment_ratio_Lower/100);
                    // }
                }else{
                    //firstCCount ++;
                    // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
                    upPrice = strMoneyMax;
                    // downPrice = strMoney * 0.8;
                    downPrice = strMoneyMin;
                    // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
                }
                // 上下限四舍五入
                upPrice = upPrice.toFixed(2);
                downPrice = downPrice.toFixed(2);
                // 12个月合同金额
                //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceTXT')).text(toNumComma(Price_YearTXT));
                //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceTXTHidden')).val(Price_YearTXT);
                if (!isDisabled) {
                    // 实际联动价格 start
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Lower_price')).text(toNumComma(downPrice));
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Lower_priceHidden')).val(downPrice);
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Upper_price')).text(toNumComma(upPrice));
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Upper_priceHidden')).val(upPrice);
                    // 实际联动价格 end
                }
                //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPrice')).text(toNumComma(strMoney));
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPricePageHidden')).val(strMoney);
                repairMoney = j$.trim(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).value());
            } else {
                // TODO 一時的な対応、なんで別行の金額リフレッシュされた?
                //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPrice')).text("");
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPricePageHidden')).val();
                // 12个月合同金额
                //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceTXT')).text("");
                //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceTXTHidden')).val();
                if (!isDisabled) {
                    // 实际联动价格 start
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Lower_price')).text("");
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Lower_priceHidden')).val();
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Upper_price')).text("");
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Upper_priceHidden')).val();
                    // 实际联动价格 end
                 }
            }
        }
        else {
            // 所有设备按安装日、发货日(最早的),距离合同开始日6个月内都是新品合同
            var isNewDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':isNewDate')).value());
            isNewDate.setMonth(isNewDate.getMonth() + 6);
            if (Date.parse(contractStartDate) > Date.parse(isNewDate)) {
                newCon = false;
            }
            strMoney = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val();
            // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
            //URF限次合同2期 LY 20220811 start
            var uRFSeries= j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':uRFSeries')).value();
            if (uRFSeries=='URF-V' && estimateURFVMaxRepairCount==2) {
                strMoneyMax = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':uFRMaxPrice')).val();
                strMoneyMin = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':uFRMinPrice')).val();
            }else if (uRFSeries=='URF-V' && estimateURFVMaxRepairCount==0) {
                    strMoneyMax = 0;
                    strMoneyMin = 0;
            }else if (uRFSeries=='URF-P' && estimateURFPMaxRepairCount==0){
                    strMoneyMax = 0;
                    strMoneyMin = 0;
            }else{
                strMoneyMax = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':uFRMaxPrice3')).val();
                strMoneyMin = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':uFRMinPrice3')).val();
            }
            //URF限次合同2期 LY 20220811 end
            // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
            Price_YearTXT = strMoney * 12;
            if (isnew == 'true') {
                // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
                strMoneyMin = Contract_year * strMoneyMin;
                strMoneyMax = Contract_year * strMoneyMax;
                // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
            } else {
                // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
                strMoneyMin = Contract_year * strMoneyMin;
                strMoneyMax = Contract_year * strMoneyMax;
                // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
            }
            var b = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Contract_No')).value();
            var LastMContractRecord = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':LastMContractRecord')).value();
            if(b != ''){
                conCCount ++;
                // 1.合同期不满一年时,合同期超过一半才可开始续签报价。(eg:11个月的合同从6个月后才可报价。)
                // 2.一年以上的合同,在结束前6个月开始可以开放续签报价。
                var lastendDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':End_Date')).value());
                var lastContRange = 0;
                if(LastMContractRecord == 'VM_Contract'){
                    newCount++;
                    lastendDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':endDateGurantee_Text')).value());
                    lastContRange = 36;
                }else{
                    lastContRange = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':lastContRange')).value();
                }
                //最后结束日+1年
                lastendDate.setMonth(lastendDate.getMonth() + 12);
                if (Date.parse(contractStartDate) > Date.parse(lastendDate)) {
                    oyearCount ++;
                }
                // 取联动价格
                // 上一期合同实际报价月额
                //
                var LastMContract_Price = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':LastMContract_Price')).val());
                var Adjustment_ratio_Lower = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_ratio_Lower')).val());
                var Adjustment_ratio_Upper = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_ratio_Upper')).val());
                //计算惩罚率
                var Punish = calculateNtoMRatio( lastContRange,(month + month2));
                if(Punish == 0){
                    return;
                }
                // 判断有无报价:没有按照标准价格实际联动
                var Estimate_Num = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Estimate_NumHidden')).val();
                // if(Estimate_Num == 0){
                //     if(LastMContractRecord == 'VM_Contract'){
                //         //upPrice = (strMoney) * (1 + Adjustment_ratio_Upper/100);
                //         //downPrice = (strMoney) * (1 + Adjustment_ratio_Lower/100);
                //         upPrice = (assetListmonth * Punish) * (1 + Adjustment_ratio_Upper/100);
                //         downPrice = (assetListmonth * Punish) * (1 + Adjustment_ratio_Lower/100);
                //     }else{
                        // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
                        upPrice = strMoneyMax;
                        // downPrice = strMoney * 0.8;
                        downPrice = strMoneyMin;
                        // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
                //     }
                // }else{
                //     upPrice = (LastMContract_Price * Punish) * (1 + Adjustment_ratio_Upper/100);
                //     downPrice = (LastMContract_Price * Punish) * (1 + Adjustment_ratio_Lower/100);
                // }
            }else{
                if (isnew == 'true') {
                    newCount ++;
                } else {
                    newCon = false;
                    firstCCount ++;
                }
                // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
                upPrice = strMoneyMax;
                // downPrice = strMoney * 0.8;
                downPrice = strMoneyMin;
                // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
            }
            // 上下限四舍五入
            upPrice = upPrice.toFixed(2);
            downPrice = downPrice.toFixed(2);
            // 12个月合同金额
            //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceTXT')).text(toNumComma(Price_YearTXT));
            //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceTXTHidden')).val(Price_YearTXT);
            if (!isDisabled) {
                // 实际联动价格 start
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Lower_price')).text(toNumComma(downPrice));
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Lower_priceHidden')).val(downPrice);
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Upper_price')).text(toNumComma(upPrice));
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Upper_priceHidden')).val(upPrice);
                // 实际联动价格 end
            }
            //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPrice')).text(toNumComma(strMoney));
            j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPricePageHidden')).val(strMoney);
            //
            repairMoney = j$.trim(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).value());
        }
        repairSum = repairSum + localParseFloat(repairMoney);
        listSum = listSum + localParseFloat(toNum(strMoney));
        downPriceSum = downPriceSum + localParseFloat(toNum(downPrice));
        upPriceSum =  upPriceSum + localParseFloat(toNum(upPrice));
    }
    j$(escapeVfId('allPage:allForm:allBlock:assetRepairSumNum')).text(toNumComma(repairSum));
    //j$(escapeVfId('allPage:allForm:allBlock:assetListSumNum')).text(toNumComma(listSum));
    //j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetSumPrice')).text(toNumComma(listSum));
    //j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetSumPriceHidden')).val(toNum(listSum));
    if (!isDisabled) {
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:GuidePriceUp')).text(toNumComma(Math.round(upPriceSum)));
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:GuidePriceUpHidden')).val(toNum(Math.round(upPriceSum)));
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:GuidePriceDown')).text(toNumComma(Math.round(downPriceSum)));
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:GuidePriceDownHidden')).val(toNum(Math.round(downPriceSum)));
    }
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetRepairSumPrice')).text(toNumComma(repairSum));
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetRepairSumPriceHidden')).val(toNum(repairSum));
    var allcount = j$(escapeVfId('allPage:allForm:allBlock:productCount3')).value();
    var result = '';
    if (allcount == 0) {
        result = null;
    }else
    if (newCount > 0 && newCount == allcount && newCon == true) {
        result = '新品合同';
    }else if (((newCount > 0 && newCount == allcount) ||(newCount + firstCCount == allcount)) && newCon == false) {
        result = '首签合同';
    }else if(firstCCount > 0 && firstCCount == allcount){
        result = '首签合同';
    // 20220328 ljh update  LJPH-C8FB4P【委托】配合PBI设备覆盖率的数据准备 start
    // }else if(oyearCount > 0 && oyearCount == conCCount){
    }else if(oyearCount > 0 && oyearCount == conCCount && allcount == oyearCount ){
    // 20220328 ljh update  LJPH-C8FB4P【委托】配合PBI设备覆盖率的数据准备 start
        result = '非续签合同(空白期一年以上)';
    }else{
        result = '续签合同';
    }
    document.getElementById("allPage:allForm:allBlock:contractInfo:Contract_TypeTXT").innerHTML = result;
    document.getElementById("allPage:allForm:allBlock:contractInfo:Contract_TypeTXTHidden").value = result;
    // 取消酸化水
    //NotUseOxygenatedWaterAmount(1);
    examinationPriceCal(cnt);
    getLastContractRate();
}
function examinationPriceCal(cntWithKara) {
    var examinationCount = localParseInt(j$(escapeVfId('allPage:allForm:allBlock:appendCondition:Examination_Count')).val());
    var examinationCountStr = number_format_common(examinationCount, 0, ".", ",");
    j$(escapeVfId('allPage:allForm:allBlock:appendCondition:Examination_Count')).val(examinationCountStr);
    var cnt = 0;
    for (var i = 0; i < cntWithKara; i++) {
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        if (isManual == 'true') {
            var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Assert')).value();
            if (a != '') {
                cnt++;
            }
        }
        else {
            cnt++;
        }
    }
    var examinationPrice = 0;
// 今後復活かも
//    var cntLot = Math.ceil(cnt / 20);
//    if (cntLot == 0) {
//        examinationPrice = 0;
//    }
//    else if (cntLot == 1) {
//        examinationPrice = 2000;
//    }
//    else if (cntLot == 2) {
//        examinationPrice = 3800;
//    }
//    else if (cntLot == 3) {
//        examinationPrice = 5400;
//    }
//    else if (cntLot == 4) {
//        examinationPrice = 6800;
//    }
//    else if (cntLot == 5) {
//        examinationPrice = 8000;
//    }
//    else if (cntLot >= 6) {
//        examinationPrice = 1600 * cntLot;
//    }
    j$(escapeVfId('allPage:allForm:allBlock:appendCondition:examinationReal')).text(toNumComma(examinationPrice * examinationCount));
    j$(escapeVfId('allPage:allForm:allBlock:appendCondition:examinationRealHidden')).val(toNum(examinationPrice * examinationCount));
    // 付加条件総額欄
    // 20200108 去除附加条件总额
    // var oxygenPrice = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:NotUseOxygenatedWaterAmount')).text());
    // j$(escapeVfId('allPage:allForm:allBlock:contractInfo:appendPrice')).text(toNumComma(oxygenPrice + examinationPrice * examinationCount));
    // j$(escapeVfId('allPage:allForm:allBlock:contractInfo:appendPriceHidden')).val(toNum(oxygenPrice + examinationPrice * examinationCount));
    makeRealPrice(1);
}
/*
 * @param t   1: 金額により割引
 */
function makeRealPrice(t) {
    // 実際金額合計
    // 申请报价金额
    var sum1 = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:contractInfo:quotation_Amount')).val());
    // 修理总额
    var sum2 = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetRepairSumPrice')).text();
    var sum1 = localParseFloat(sum1);
    // 上限
    var upPrice = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:GuidePriceUp')).text();
    upPrice = localParseFloat(upPrice);
    // 下限
    var downPrice = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:GuidePriceDown')).text();
    downPrice = localParseFloat(downPrice);
    // 相对标准价格范围的折扣率 计算
    // 1)标准价格范围内时,结果为0;
    // 2)比标准价格低时,结果是1-希望价格/标准价的最低价格
    // 3)比标准价格高时,结果是1-希望价格/标准价的最高价格
    var disMP = 0.00;
    var disP = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:discount_RateHidden')).val();
    if(sum1 < downPrice){
        disMP = toNum((1 - sum1/downPrice) * 100);
    }else if(sum1 >= downPrice && sum1 <= upPrice){
        disMP = 0.00;
    }else if(sum1 > upPrice){
        disMP = toNum((1 - sum1/upPrice) * 100);
    }
    if (disMP != disP) {
        disMP = '' + disMP +  '%';
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:discount_Rate')).text(disMP);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:discount_RateHidden')).val(parseFloat(disMP));
    }
    // 修理総額を計上
    sum = sum1 + localParseFloat(sum2);
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:mainteReal')).text(toNumComma(sum));
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:mainteRealHidden')).val(toNum(sum));
}
function resetDealer() {
    var target = j$(escapeVfId('allPage:allForm:allBlock:contract:estimateTarget')).val();
    var obj = document.getElementById('allPage:allForm:allBlock:contract:dealer');
    //URF限次合同2期 LY 20220920 start
    var obj2 = document.getElementById('allPage:allForm:allBlock:contract:FirstParagraphEnd');
    //URF限次合同2期 LY 20220920 end
    var obj_lkwgt = document.getElementById('allPage:allForm:allBlock:contract:dealer_lkwgt');
    if (target == '医院') {
        obj.style.display = "none";
        obj_lkwgt.style.display = "none";
        //URF限次合同2期 LY 20220920 start
        obj2.style.display = "none";
        //URF限次合同2期 LY 20220920 end
    } else {
        obj.style.display = "block";
        obj_lkwgt.style.display = "block";
        //URF限次合同2期 LY 20220920 start
        obj2.style.display = "block";
        //URF限次合同2期 LY 20220920 end
    }
}
function alertMsg() {
    // body...
    if('{!isPaymentSet}' == 'false'){
        alert('请填写付款计划');
        return false;
    }else if('{!isPaymentSet}' == 'Denied'){
        alert('付款计划金额与实际不符,请重新填写');
        return false;
    }else{
        return true;
    }
}
function EGFlgconfim() {
    getEstimateCost();
    var cntWithKara = {!productCount};
    // 新合同备品确保提供 是否改变
    var alert1s = 0;
    for (var i = 0; i < cntWithKara; i++) {
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        var EGFlgtxt = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':EquipmentGuaranteeFlg')).value();
        var EGFlgnow = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':EGFlgassHidden')).value();
        if (EGFlgtxt != EGFlgnow) {
            alert1s = 1;
        }
    }
    if (alert1s == 1) {
        if (confirm("选择的保有设备[新合同备品确保提供]发生变化,是否继续?")) {
        } else {
            return false;
        }
    }
    return onclickCheckchangedAfterPrint('true','true');
}
function onclickCheckchangedAfterPrint(saveBtnDisabled, saveOrApproval) {
    //if(saveBtnDisabled == 'Pttrue'){
    //    var rs = alertMsg();
    //    if(rs){
    //    }else {
    //        return false;
    //    }
    //}
    var cntWithKara = {!productCount};
    var alerts = 0;
    // 新合同备品确保提供 是否改变
    var alert1s = 0;
    var today = new Date();
    today.setMonth(today.getMonth() - 3);
    //URF限次合同2期 LY 20220811 start
    var uRFSeriesMap =[];
    var valURFV =j$(escapeVfId('allPage:allForm:allBlock:contract:estimateURFVMaxRepairCount')).val();
    var valURFP =j$(escapeVfId('allPage:allForm:allBlock:contract:estimateURFPMaxRepairCount')).val();
    //URF限次合同2期 LY 20220811 end
    for (var i = 0; i < cntWithKara; i++) {
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        if (isManual == 'true') {
            var plkid = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Assert_lkid'));
            var pid = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':ProductId'));
            if (plkid.size() > 0 && pid.size() > 0) {
                if (pid.value() != '' && plkid.value() != pid.value().substring(0, 15)) {
                    alert('请使用产品放大镜按钮设定手动产品');
                    return false;
                }
            }
        }
        if (isManual == 'false') {
            var strDate = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':finalExaminationDate')).value();
            // var produ = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Assert')).value();
            //alert(EGFlgtxt + ':' + EGFlgnow);
            strDate = strDate.replace(/(^\s*)|(\s*$)/g, "");
            if (strDate == "" || Date.parse(strDate) < Date.parse(today)) {
                alerts = 1;
            }
        }
        //URF限次合同2期 LY 20220811 start
        var uRFSeries = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':uRFSeries')).text();
        uRFSeriesMap.push(uRFSeries);
        //URF限次合同2期 LY 20220811 end
    }
    //URF限次合同2期 LY 20220811 start
    if ((valURFV == null || valURFV == "" || valURFV == "0") && uRFSeriesMap.includes('URF-V')){
        alert("合同对象设备中含有URF-V系列,必须选择URF-V的最大大修次数!");
        j$(escapeVfId('allPage:allForm:allBlock:contract:estimateURFVMaxRepairCount')).val("");
        return;
    }
    if ((valURFP == null || valURFP == "" || valURFP == "0") && uRFSeriesMap.includes('URF-P')){
        alert("合同对象设备中含有URF-P系列,必须选择URF-P的最大大修次数!");
        j$(escapeVfId('allPage:allForm:allBlock:contract:estimateURFPMaxRepairCount')).val("0");
        return;
    }
    if (uRFSeriesMap.includes('URF-V')==false) {
        j$(escapeVfId('allPage:allForm:allBlock:contract:estimateURFVMaxRepairCount')).val("0");
    }
    // if ((valURFP == null || valURFP == "" || valURFP == "0") && uRFSeriesMap.includes('URF-P')){
    //     j$(escapeVfId('allPage:allForm:allBlock:contract:estimateURFPMaxRepairCount')).val("3");
    // }
    if (uRFSeriesMap.includes('URF-P')==false) {
        j$(escapeVfId('allPage:allForm:allBlock:contract:estimateURFPMaxRepairCount')).val("0");
    }
    //URF限次合同2期 LY 20220811 end
    if (alerts == 1) {
        if (confirm("选择的保有设备[最后点检日]为空或已经超过三个月之前,是否继续?")) {
        } else {
            return false;
        }
    }
    blockme();
    if (saveOrApproval == "true") {
        if (saveBeforeCheckPriceChange()) {
            if (confirm("行信息有变化(服务合同价格),是否更新报价?")) {
                j$(escapeVfId('allPage:allForm:changedSubmitPrice')).val('true');
            } else {
                j$(escapeVfId('allPage:allForm:changedSubmitPrice')).val('fasle');
                unblockUI();
                return false;
            }
        }
        j$(escapeVfId('allPage:allForm:isSaveOrApproval')).val('true');
    }
   return true;
    // if ((saveBtnDisabled == "true"||saveBtnDisabled == "Pttrue" )&& checkchangedAfterPrint()) {
    //     if (confirm(Confirm_ChangedAfterPrint)) {
    //         if (saveOrApproval == "true") {
    //             j$(escapeVfId('allPage:allForm:isSaveOrApproval')).val('true');
    //         }
    //         return true;
    //     } else {
    //         unblockUI();
    //         return false;
    //     }
    // } else {
    //     if (saveOrApproval == "true") {
    //         j$(escapeVfId('allPage:allForm:isSaveOrApproval')).val('true');
    //     }
    //     return true;
    // }
}
function changeEstiStartdate(val) {
    if ('{!SaveBtnDisabled}' == 'false') {
        j$(escapeVfId('allPage:allForm:contractstartdate')).val(val);
        changeContractStartdate(val);
    }
}
function changeContractStartdate(val) {
    var oldDateStr = j$('#oldContractDate').value();
    var oldDate = new Date();
    if (oldDateStr != null && oldDateStr != '') {
        oldDate = new Date(oldDateStr);
    }
    if ('{!DecideBtnDisabled}' == 'false') {
        var monthStr = '00' + (oldDate.getMonth()+1);
        monthStr = monthStr.substring(monthStr.length-2, monthStr.length);
        var dayStr = '00' + oldDate.getDate();
        dayStr = dayStr.substring(dayStr.length-2, dayStr.length);
        var oldDateVal = oldDate.getFullYear() + '/' + monthStr + '/' + dayStr;
        j$(escapeVfId('allPage:allForm:oldDecideContractDate')).val(oldDateVal);
        if (saveBeforeCheckPriceChange()) {
            //blockme();
            //contractStartDateChange();
            //refreshAsset({!productCount});
        }
        refreshAsset({!productCount});
    } else {
        var cntWithKara = {!productCount};
        var haveLine = 'false';
        for (var i = 0; i < cntWithKara; i++) {
            var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
            if (isManual == 'true') {
                var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Assert_lkid'));
                if (a.size() > 0 && a.val() != "000000000000000") {
                    haveLine = 'true';
                }
            } else {
                haveLine = 'true';
            }
        }
        if (haveLine == 'false') {
            return false;
        }
        var contractStartDate = new Date(val);
        var strCreatedDate = '{!estimate.CreatedDate}';
        var createDate = new Date();
        if (strCreatedDate != '') {
            createDate = new Date(strCreatedDate);
        }
        createDate = new Date(createDate.toDateString());
        var threeMA = new Date(createDate.setMonth(createDate.getMonth() + 3));
        var isnewMA = new Date(createDate.setMonth(createDate.getMonth() - 3 - isNewAddMonth));
        /*if (oldDate >= isnewMA && contractStartDate >= isnewMA) {
            return false;
        }
        if (oldDate < threeMA && contractStartDate < threeMA) {
            return false;
        }
        if (contractStartDate >= isnewMA) {
            alert('合同开始预定日或合同开始日发生变化并且大于创建日6个月,所有合同对象设备不适用新品价格。\n请在画面刷新后确认服务合同价格,再继续其他操作。');
        } else if (contractStartDate >= threeMA) {
            alert('合同开始预定日或合同开始日发生变化并且大于创建日3个月,所有合同对象设备使用【合同开始日】重新计算服务合同价格。\n请在画面刷新后确认服务合同价格,再继续其他操作。');
        } else {
            alert('合同开始预定日或合同开始日发生变化并且在创建日3个月以内,所有合同对象设备使用【创建日】重新计算服务合同价格。\n请在画面刷新后确认服务合同价格,再继续其他操作。');
        }*/
        j$('oldContractDate').val(val);
        //blockme();
        //contractStartDateChange();
        refreshAsset({!productCount});
    }
}
function AlertPriceBtnJs(){
    var  VarAlert  = j$(escapeVfId('allPage:allForm:alertStringValue')).val();
    var  VarAlert2 = j$(escapeVfId('allPage:allForm:alertStringValue2')).val();
    var  VarAlert3 = j$(escapeVfId('allPage:allForm:alertStringValue3')).val();
    var  PStatus   = j$(escapeVfId('allPage:allForm:PriceStatus')).val();
    blockme();
    if(PStatus!='申请中'&& PStatus!='批准'){
        ComputeLTYRepair();
        //ShowLTYRepair();
    }else if(PStatus == '申请中'||PStatus == '批准'){
        ShowLTYRepair();
    }
}
function ComputeLTY() {
    var  urlNameJs = j$(escapeVfId('allPage:allForm:urlName')).val();
    urlNameJs = '{!$Label.ID_of_SelectAssetEstimate}'+urlNameJs ;
    //URF限次合同2期 LY 20220920 start
    //var w = window.open(encodeURI(urlNameJs),'过去两年修理实绩','menubar=no,height=720,width=986');
    //w.focus();
    //URF限次合同2期 LY 20220920 end
}
function recordNumChangeJs() {
    recordNumChangeAction();
}
function checkDecideDate() {
    // 报价有效期
    var strSubmitDate = '{!estimate.Submit_quotation_day__c}';
    // 上期合同结束日 取最晚的
    var conEndDate = getLastContractendDate();
    conEndDate = new Date(conEndDate);
    // 今天
    var submitDate = new Date();
    var nowDate = new Date();
    nowDate = new Date(nowDate.toLocaleDateString());
    /// 报价中设备的机身编码为空时的新品合同有效期延长 20200710 gzw
    // 默认为3月,全是产品为6月;
    var monthGap = 6;
    var cntWithKara = {!productCount};
    for (var i = 0; i < cntWithKara; i++) {
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        if (isManual != 'true') {
            monthGap = 3;
            break;
        }
    }
    //nowDate = new Date(nowDate.getYear(),nowDate.getYear(),nowDate.getYear());
    if (strSubmitDate != '') {
        submitDate = new Date(strSubmitDate);
        submitDate = new Date(submitDate.setMonth(submitDate.getMonth() + monthGap));
        if(Date.parse(conEndDate)  > Date.parse(submitDate)){
            submitDate = new Date(conEndDate);
        }
    }
    //alert(nowDate + '=====' + submitDate);
    if (strSubmitDate != '' && nowDate > submitDate) {
        alert('已超出报价申请日'+ monthGap+'个月,不允许DECIDE。');
        return false;
    }
    return true;
}
function getLastContractendDate(){
    var rowCnt = {!productCount};
    var lastdate = null;
    for (var i = 0; i < rowCnt; i++) {
        var LastMContractID = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':LastMContractID')).value();
        if(!!LastMContractID){
            var endDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':End_Date')).value());
            if(lastdate == null){
                lastdate = new Date(endDate);
            }else if(Date.parse(endDate) > Date.parse(lastdate)){
                lastdate = new Date(endDate);
            }
        }
    }
    return lastdate;
}
function decideJs() {
    if (checkDecideDate() == true) {
        if (onclickCheckchangedAfterPrint('true','false') == true) {
            var oldDate = j$(escapeVfId('allPage:allForm:oldDecideContractDate')).value();
            var contractDate = new Date(j$(escapeVfId('allPage:allForm:contractstartdate')).value());
            //var olDt = oldDate.getFullYear() + oldDate.getMonth() + oldDate.getDate();
            var monthStr = '00' + (contractDate.getMonth()+1);
            monthStr = monthStr.substring(monthStr.length-2, monthStr.length);
            var dayStr = '00' + contractDate.getDate();
            dayStr = dayStr.substring(dayStr.length-2, dayStr.length);
            var contractDateStr = contractDate.getFullYear() + '/' + monthStr + '/' + dayStr;
            //var neDt = contractDate.getFullYear() + contractDate.getMonth() + contractDate.getDate();
            //monthStr = '00' + (oldDate.getMonth()+1);
            //monthStr = monthStr.substring(monthStr.length-2, monthStr.length);
            //dayStr = '00' + oldDate.getDate();
            //dayStr = dayStr.substring(dayStr.length-2, dayStr.length);
            //oldDateVal = oldDate.getFullYear() + '/' + monthStr + '/' + dayStr;
            if (oldDate == contractDateStr) {
                j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
                decide();
            } else {
                var oldp = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:contractInfo:oldMainteReal')).value());
                var newp = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:contractInfo:mainteReal')).text());
                if (oldp != newp) {
                    // 20201106 高章伟 提醒消息修改 start
                    j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
                    if (confirm('合同金额发生变化,请您确认。')) {
                        decide();
                    } else {
                        alert('请确认全部内容后点击Decide。');
                        j$(escapeVfId('allPage:allForm:contractstartdate')).val(oldDate);
                        j$(escapeVfId('allPage:allForm:oldDecideContractDate')).val('');
                        j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
                        decideCancle();
                    }
                } else {
                    j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
                    decide();
                    // j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
                    // if (confirm('本次合同开始日的修改不会导致合同金额发生变化,请您确认是否修改?')) {
                    //     decide();
                    // } else {
                    //     j$(escapeVfId('allPage:allForm:contractstartdate')).val(oldDate);
                    //     alert('合同开始日未进行变更,请确认全部内容后点击Decide。');
                    //     unblockUI();
                    // }
                }
                // 20201106 高章伟 提醒消息修改 end
            }
        }
    }
}
// 获取实际报价金额 按照上限比例算
function getEstimateCost() {
    // 行数
    var rowcount = {!productCount};
    // 6.合同价格
    var mainteReal = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:mainteReal')).text();
    mainteReal = localParseFloat(mainteReal);
    // 5.修理总额
    var assetRepairSumPrice = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetRepairSumPrice')).text();
    assetRepairSumPrice = localParseFloat(assetRepairSumPrice);
    // 计算实际报价总金额
    var realprice = mainteReal - assetRepairSumPrice;
    //URF限次合同2期 LY 20221009 start
    // 标准价格的最高价总额
    var GuidePriceUp = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:contractInfo:GuidePriceUpHidden')).val());
    // //标准价格的最低价总额
    var GuidePriceDown = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:contractInfo:GuidePriceDownHidden')).val());
    GuidePriceUp = localParseFloat(GuidePriceUp);
    GuidePriceDown = localParseFloat(GuidePriceDown);
    for (var i = 0; i < rowcount; i++) {
        // 去上限价格
        var assetListPrice = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Upper_priceHidden')).val();
        // //取下限价格
        var assetLowerPrice = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Lower_priceHidden')).val();
        assetListPrice = localParseFloat(assetListPrice);
        var Estimate_Cost = 0;
        if(realprice == GuidePriceUp){
            Estimate_Cost = assetListPrice;
            // j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Estimate_Cost')).val(0);
        } else if (realprice == GuidePriceDown){
            Estimate_Cost = assetLowerPrice;
        }else{
            Estimate_Cost = (realprice * (assetListPrice / GuidePriceUp)).toFixed(2);
        }
        j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Estimate_Cost')).val(Estimate_Cost);
    }
    //URF限次合同2期 LY 20221009 end
}
function getLastContractRate(){
    var rowCnt = {!productCount};
    var Contractrate = 0.00;
    var count = 0;
    for (var i = 0; i < rowCnt; i++) {
        var LastMContractID = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':LastMContractID')).value();
        if(!!LastMContractID){
            var tempContractrate = parseFloat(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Contractrate')).value().replace(/,/g,''));
            if(!!tempContractrate){
                Contractrate = Contractrate + tempContractrate;
            }
            count++;
        }
    }
    var allContractRate = '' + 0.00 + '%';
    //URF限次合同2期 LY 20220920 start
    // if( count > 0){
    //     allContractRate = '' + (Contractrate/count).toFixed(2) + '%';
    // }
    //URF限次合同2期 LY 20220920 end
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:Combinedrate')).text(allContractRate);
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:CombinedrateHidden')).val(parseFloat(allContractRate));
    return allContractRate;
}
function calculateNtoMRatio(lastContRange, month ){
    var lastContRangeYear = Math.ceil(localParseFloat(lastContRange)/12);
    var currentMonthYear = Math.ceil(localParseFloat(month)/12);
    //if(!lastendDate || currentMonthYear <= lastContRangeYear){
    if(currentMonthYear == lastContRangeYear || currentMonthYear == 1){
        return month;
    }else if(month <= 24) {
        return 12+ (month- 12) *1.1;
    }else if(month <= 36) {
        return 25.2 + (month- 24) *1.21;
    }else if(month <= 48) {
        return 39.72 + (month- 36) *1.331;
    }else if(month <= 60) {
        return 55.692 + (month- 48) *1.4641;
    }else {
        alert('合同期最长只能选择60个月!');
        return 0;
    }
}
    //URF限次合同2期 LY 20220920 start
    //获取经销商的先款标识
    function onChDealerUpdateJs(oBj){
        //获取 报价提交对象  是否为经销商
        var estimateTarget = j$(escapeVfId('allPage:allForm:allBlock:contract:estimateTarget'))[0].value;
        if(estimateTarget == '经销商'){
            //判断经销商名是否为空
            var dealerValue = j$(escapeVfId('allPage:allForm:allBlock:contract:dealer')).val();
            if(dealerValue != ''){
                //获取经销商名的id
                var dealerId = j$(escapeVfId('allPage:allForm:allBlock:contract:dealer_lkid')).val();
                //由于salesforce的查找字段是可以输入的,所以判断他如果为空或者为 000000000000000 的时候,传的参数就位经销商中文名,其他情况传id
                if(dealerId != '' && dealerId != '000000000000000'){
                    onChDealerUpdate(dealerId);
                }else{
                    onChDealerUpdate(dealerValue);
                }
            }else{
                onChDealerUpdate('');
                //j$(escapeVfId('allPage:allForm:allBlock:contract:FirstParagraphEnd'))[0].checked = false;
            }
        }
    }
    //如果选择的经销商为先款对象,那么做一下提示
    function hintAccount(){
        var xkChecked = j$(escapeVfId('allPage:allForm:allBlock:contract:FirstParagraphEnd'))[0].checked;
        if(xkChecked){
            alert('请注意,当前经销商为先款对象。');
        }
    }
    //URF限次合同2期 LY 20220920 start
</script>
<apex:form id="allForm">
    <apex:inputHidden id="alertStringValue" value="{!alertString}" />
    <apex:inputHidden id="alertStringValue2" value="{!alertString2}" />
    <apex:inputHidden id="alertStringValue3" value="{!alertString3}" />
    <apex:inputHidden id="PriceStatus" value="{!estimate.Process_Status__c}"/>
    <apex:inputHidden id="urlName" value="{!estimate.Name}"/>
    <apex:inputHidden id="changedAfterPrint" value="{!changedAfterPrint}"/>
    <apex:inputHidden id="changedSubmitPrice" value="{!changedSubmitPrice}"/>
    <apex:inputHidden id="isSaveOrApproval" value="{!isSaveOrApproval}"/>
    <!-- HWAG-B4R3SS  START 20181026-->
    <apex:actionFunction name="searchfunc" action="{!searchBtn}" rerender="Form,Block,assetSection2,pageMessages,allBlock" onComplete="unblockUI();"></apex:actionFunction>
    <!-- HWAG-B4R3SS  END 20181026-->
    <apex:actionFunction name="ComputeLTYRepair" action="{!ComputeLTYRepair}" rerender="pageMessages" oncomplete="unblockUI();ComputeLTY();"/>
    <apex:actionFunction name="ShowLTYRepair" action="{!ShowLTYRepair}"  oncomplete="unblockUI();ComputeLTY();"/>
    <apex:actionFunction name="decide" action="{!decide}" rerender="allForm" oncomplete="unblockUI();"/>
    <apex:actionFunction name="decideCancle" action="{!decideCancle}" rerender="allForm" oncomplete="unblockUI();"/>
    <apex:inputHidden id="oldDecideContractDate" value="{!OldContractStartDate}" />
    <!-- URF限次合同2期 LY 20220920 start -->
    <apex:actionFunction name="onChDealerUpdate" action="{!onChDealerUpdate}" rerender="contract" onComplete="hintAccount();">
        <apex:param name="checkDealerId" assignTo="{!checkDealerId}" value="" />
    </apex:actionFunction>
    <!-- URF限次合同2期 LY 20220920 end -->
    <input type="hidden" id="oldContractDate" value="{!estimate.Contract_Start_Date__c}" />
<script type="text/javascript">
//j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
</script>
    <apex:pageBlock title="服务合同报价" id="allBlock">
        <apex:pageBlockButtons id="blocktop" location="top">
            <apex:commandButton id="savebtntop" action="{!save}" value="{!$Label.Save_Button}" disabled="{!SaveBtnDisabled}" rerender="allForm" onclick="if (!EGFlgconfim()) return false;" oncomplete="unblockUI();"/>
           <!--  <apex:commandButton id="LastTwoYearRepairShow" value="过去两年维修实绩Repaort"  action="{!ShowLTYRepair}" rerender="alertStringValue,alertStringValue2,alertStringValue3" oncomplete="AlertPrice();"/> -->
            <apex:commandButton id="LastTwoYearRepairComp" value="过去三年维修实绩计算" rerender="PriceStatus" onclick="AlertPriceBtnJs()"/>
            <apex:commandButton id="approvalbtntop" action="{!approvalProcess}" value="提交待审批" disabled="{!ApprovalBtnDisabled}" rerender="allForm" onclick="if (!KindsAndMonths()) return false;if (!EGFlgconfim()) return false;approvalJs();" oncomplete="unblockUI();"/>
            <!-- HWAG-B399Q8 2018/08/20 新增请提交待审批 提示字段 start-->
            &nbsp; <apex:outputText style="color:red;font-size:20px" value="请提交待审批" rendered="{!IS_Clone_After_Decide}"/>
            <!-- HWAG-B399Q8 2018/08/20 新增请提交待审批 提示字段 end-->
            <apex:commandButton action="{!cancel}" value="不保存(返回)" style="float:right;" rerender="allForm" onclick="blockme();" oncomplete="unblockUI();"/>
            <apex:commandButton id="saveAndCancelBtn" action="{!saveAndCancel}" value="保存(返回)" style="float:right;" rerender="allForm" oncomplete="unblockUI();" onclick="if (!onclickCheckchangedAfterPrint('true','true')) return false;" disabled="{!SaveBtnDisabled}"/>
        </apex:pageBlockButtons>
        <apex:pageMessages id="pageMessages"></apex:pageMessages>
        <!-- update 合同报价页面的优化 添加‘assetSection’ fxk 2021/9/10 Star-->
        <apex:actionFunction name="refreshProductData" action="{!refreshProductData}" rerender="pageMessages,EquipmentGuaranteeFlg,EGFlgassHidden,EquipmentGuaranteeFlgtxt, assetListPriceHidden, productCount3, assetSection, uFRMaxPrice, uFRMinPrice, uFRMaxPrice3, uFRMinPrice3,uRFSeries" oncomplete="refreshAsset({!productCount});unblockUI();">
            <apex:param assignTo="{!productIdx}" name="productIdx" value=""/>
        </apex:actionFunction>
        <!-- update 合同报价页面的优化 添加‘assetSection’ fxk 2021/9/10 End-->
        <!--<apex:actionFunction name="contractStartDateChange" action="{!contractStartDateChange}" rerender="allForm" oncomplete="unblockUI();">
        </apex:actionFunction>-->
        <apex:actionFunction name="recordNumChangeAction" action="{!recordNumChange}" rerender="allForm" oncomplete="unblockUI();">
        </apex:actionFunction>
        <!-- update by rentx 2020-11-17  -->
            <!-- <apex:pageblocksection title="服务合同" id="contract"> -->
            <!-- <apex:outputField value="{!estimate.Name}"/> -->
            <!-- <apex:outputField value="{!contract.Management_Code__c}" /> -->
            <!-- <apex:outputField value="{!estimate.Process_Status__c}"/> -->
            <!-- <apex:outputField value="{!contract.Status__c}"/> -->
            <!-- <apex:outputField value="{!contract.Hospital__c}" /> -->
            <!-- <apex:inputField value="{!estimate.Department__c}" id="depart"/> -->
            <!-- <apex:inputField value="{!estimate.Contract_Esti_Start_Date__c}" required="true" id="startdate" onchange="changeEstiStartdate(this.value);"/>onchange="checkContractEstiStartDate(this.value, {!productCount})" -->
            <!-- <apex:inputField value="{!estimate.Contract_Range__c}" required="true" id="monthRange" onchange="checkContractRange(this.value, {!productCount})"/> -->
            <!-- <apex:inputField style="width:3px;height:15px;background-color:#cc0000; position:absolute;margin-right:5px;"> -->
            <!-- <div><div style="width:2px;height:20px;background-color:red; position:absolute;margin-right:5px;"></div></div> -->
            <!-- <apex:inputField value="{!estimate.Contract_Range__c}" required="false" id="monthRange" onchange="checkContractRange(this.value, {!productCount})"/> -->
            <!-- </apex:inputField> -->
            <!-- <apex:outputField value="{!estimate.Contract_Esti_End_Date__c}"/> -->
            <!-- <apex:outputField label="制定日" value="{!estimate.CreatedDate}" id="createDateShow"/> -->
            <!-- <apex:outputPanel > -->
                <!-- <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">报价提交对象</label> -->
                <!-- <apex:inputField value="{!estimate.Estimate_Target__c}" id="estimateTarget" onchange="resetDealer()" style="margin-left:5px"/> -->
                <!-- <apex:outputPanel rendered="{!DecideBtnDisabled==false}"> -->
                    <!-- <input type="button" class="btn" value="变更" onclick="controlDisabled()" style="margin-left:20px;width:40px;padding:0 0;"/> -->
                <!-- </apex:outputPanel> -->
                <!-- <apex:outputPanel rendered="{!DecideBtnDisabled==true}"> -->
                    <!-- <input type="button" class="btnDisabled" value="变更" disabled="true" onclick="controlDisabled()" style="margin-left:20px;width:40px;padding:0 0;"/> -->
                <!-- </apex:outputPanel> -->
            <!-- </apex:outputPanel> -->
            <!-- <apex:inputField value="{!estimate.Dealer__c}" id="dealer" /> -->
            <!-- <apex:inputField value="{!estimate.EndUserType__c}" id="EndUserType" /> -->
            <!-- <script type="text/javascript"> -->
                <!-- j$(escapeVfId('allPage:allForm:allBlock:contract:estimateTarget')).children('option[value=]').remove(); -->
                <!-- resetDealer(); -->
            <!-- </script> -->
        <!-- </apex:pageblocksection> -->
        <apex:pageBlockSection title="服务合同" id="contract">
        <!-- <apex:outputPanel/> -->
            <apex:outputPanel >
            <table align="center" width="100%"  style="border-collapse:separate; border-spacing:0px 10px" >
                <tr>
                    <td width="50%" align="right"> <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">报价编码</label> </td>
                    <td width="50%" align="left"> <apex:outputField value="{!estimate.Name}"/> </td>
                </tr>
                <tr>
                    <td width="50%" align="right"> <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">报价状态</label> </td>
                    <td width="50%" align="left"> <apex:outputField value="{!estimate.Process_Status__c}"/> </td>
                </tr>
                <tr>
                    <td width="50%" align="right"> <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">医院</label> </td>
                    <td width="50%" align="left"> <apex:outputField value="{!contract.Hospital__c}" /> </td>
                </tr>
                <tr>
                    <td width="50%" align="right"> <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">合同开始预订日</label> </td>
                    <td width="50%" align="left"> <apex:inputField value="{!estimate.Contract_Esti_Start_Date__c}" required="true" id="startdate" onchange="changeEstiStartdate(this.value);"/>
                    </td>
                </tr>
                <tr>
                    <td width="50%" align="right"><label class="labelCol vfLabelColTextWrap " style="margin-left:22%">合同结束预订日</label> </td>
                    <td width="50%" align="left"> <apex:outputField value="{!estimate.Contract_Esti_End_Date__c}"/> </td>
                </tr>
                <tr>
                    <td align="right">
                        <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">报价提交对象</label>
                    <td>
                        <apex:outputPanel >
                            <apex:inputField value="{!estimate.Estimate_Target__c}" id="estimateTarget" onchange="resetDealer()" style="margin-left:5px"/>
                            <apex:outputPanel rendered="{!DecideBtnDisabled==false}">
                                <input type="button" class="btn" value="变更" onclick="controlDisabled()" style="margin-left:20px;width:40px;padding:0 0;"/>
                            </apex:outputPanel>
                            <apex:outputPanel rendered="{!DecideBtnDisabled==true}">
                                <input type="button" class="btnDisabled" value="变更" disabled="true" onclick="controlDisabled()" style="margin-left:20px;width:40px;padding:0 0;"/>
                            </apex:outputPanel>
                        </apex:outputPanel>
                    </td>
                    </td>
                </tr>
                <tr>
                    <td align="right"> <label class="labelCol vfLabelColTextWrap " style="margin-left:22%"> 用户类型</label></td>
                    <td align="left">
                        <apex:outputField value="{!estimate.EndUserType__c}" id="EndUserType" />
                    </td>
                    <td> </td>
                </tr>
            </table>
            </apex:outputPanel>
        <apex:outputPanel >
        <table align="center" width="100%"  style="border-collapse:separate; border-spacing:0px 10px" >
            <tr>
                <td width="50%" align="right"> <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">合同询价编码</label> </td>
                <td width="50%" align="left"> <apex:outputField value="{!contract.Management_Code__c}" /> </td>
            </tr>
            <tr>
                <td width="50%" align="right"> <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">状态</label> </td>
                <td width="50%" align="left"> <apex:outputField value="{!contract.Status__c}"/> </td>
            </tr>
            <tr>
                <td width="50%" align="right"> <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">科室</label> </td>
                <td width="50%" align="left"> <apex:inputField value="{!estimate.Department__c}" id="depart"/> </td>
            </tr>
            <tr>
                <td width="50%" align="right">
                    <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">合同月数</label> </td>
                <td width="50%" align="left">
                    <div style="width:3px;height:20px;background-color:#cc0000; position:absolute;margin-right:5px" />&nbsp;
                    <apex:inputField value="{!estimate.Contract_Range__c}" required="false" id="monthRange"
                    onchange="checkContractRange(this.value, {!productCount})"
                    />
                </td>
            </tr>
            <tr>
                <td width="50%" align="right"> <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">制定日</label></td>
                <td width="50%" align="left"> <apex:outputField label="制定日" value="{!estimate.CreatedDate}" id="createDateShow"/> </td>
            </tr>
            <!-- URF限次合同2期 LY 20220811 start -->
            <tr>
                <td  width="50%" align="right">
                    <label class="labelCol vfLabelColTextWrap " style="margin-left:30%"> 经销商名</label></td>
                <td width="50%" align="left"> <apex:inputField value="{!estimate.Dealer__c}" id="dealer" onchange="onChDealerUpdateJs(this);return false;" style="float: left;"/> </td>
            </tr>
            <tr>
                <td  width="50%" align="right">
                    <label class="labelCol vfLabelColTextWrap " style="margin-left:30%"> 先款标识(经销商)</label></td>
                <td width="50%" align="left" > <apex:inputCheckbox value="{!estimate.Is_RecognitionModel__c}" id="FirstParagraphEnd" onClick="return false;" /> </td>
            </tr>
            <tr>
                <td width="50%" align="right">
                    <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">URF-V最大大修次数:</label></td>
                <td>
                    <apex:inputField value="{!estimate.URF_V_MaxRepairCount__c}" required="false" id="estimateURFVMaxRepairCount" onchange="checkVMaxRepairCount(this.value,{!productCount})" style="margin-left:5px"/>次
                </td>
            </tr>
            <tr>
                <td  width="50%" align="right">
                    <label class="labelCol vfLabelColTextWrap " style="margin-left:30%">URF-P最大大修次数:</label></td>
                <td width="50%" align="left">
                    <apex:inputField value="{!estimate.URF_P_MaxRepairCount__c}" required="false" id="estimateURFPMaxRepairCount" onchange="checkPMaxRepairCount(this.value,{!productCount})" style="margin-left:5px"/>次
                </td>
            </tr>
            <!-- URF限次合同2期 LY 20220811 end -->
        </table>
        <script type="text/javascript">
            j$(escapeVfId('allPage:allForm:allBlock:contract:estimateTarget')).children('option[value=]').remove();
            resetDealer();
            j$(escapeVfId('allPage:allForm:allBlock:contract:estimateURFVMaxRepairCount')).children('option[value=]').remove();
            j$(escapeVfId('allPage:allForm:allBlock:contract:estimateURFPMaxRepairCount')).children('option[value=]').remove();
        </script>
        </apex:outputPanel>
        </apex:pageBlockSection>
        <!-- update by rentx 2020-11-17 end -->
        <apex:pageblocksection columns="1" title="合同对象设备" id="assetSection" >
            <apex:outputLabel />
            <apex:outputPanel >
                <input type="hidden" id="allPage:allForm:allBlock:assetSection:productCnt" value="{!productCount}" />
                <!-- <table width="100%">
                    <tr>
                        <td>&nbsp;</td>
                        <td width="100px"><span>全</span>
                            <select style="vertical-align:text-bottom" id="allCheckResult" size="1" onchange="changeAllCheckResult(this.value)">
                                <option value=" ">--无--</option>
                                <option value="OK">OK</option>
                                <option value="NG">NG</option>
                            </select>
                        </td>
                        <td width="150px">&nbsp;</td>
                    </tr>
                </table> -->
                <!-- <div id = 'aaaa' class="slds-scrollable_x" style="width:450px">
                <div class="slds-table--header-fixed_container" style="height:450px;width:850px">
                    <div class="slds-scrollable_y" style="height:100%;width:850px"> -->
                <div style="width: 100%">
                <table class="list" style="border-bottom-width: 0px; font-size:13px;" border="0" cellspacing="0" cellpadding="0">
                    <tr class="headerRow" height="30px">
                        <th style="width:25px" class="headerRow  booleanColumn"><input type='checkbox' onClick='checkAll(this)'/></th>
                        <th class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Name.label}</th>
                        <!-- URF限次合同2期 LY 20220811 start -->
                        <th style="width:35px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.URF_Series__c.label}
                        </th>
                        <!-- <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.URF_Maintenance_Contract__c.label}</th> -->
                        <!-- URF限次合同2期 LY 20220811 end -->
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Asset_situation__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.SerialNumber.label}</th>
                        <th class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.EGFlg_fromContract_asset__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.InstallDate.label}</th>
                        <!--add点检改善:新增一个点检对象复选框字段,默认为true 2021.6.8 fxk Star-->
                        <!-- URF限次合同2期 LY 20220811 start -->
                        <!-- <th style="width:70px" class="headerRow  booleanColumn">
                        {!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Check_Object__c.label}</th> -->
                        <!-- URF限次合同2期 LY 20220811 end -->
                        <!--add点检改善:新增一个点检对象复选框字段,默认为true 2021.6.8 fxk end-->
                        <th style="width:40px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.IsNew__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Department_Name__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Management_Code__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Asset_Consumption_rate__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.CurrentContract_End_Date__c.label}</th>
                        <!-- 实绩联动价格计算 start -->
                        <th style="width:35px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Adjustment_Upper_price__c.label}</th>
                        <th style="width:35px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Adjustment_Lower_price__c.label}</th>
                        <!-- 实绩联动价格计算 end -->
                        <!-- 隐藏合同月数
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract__c.fields.Contract_Range__c.label}</th>-->
                        <!-- <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Asset_Owner__c.label}</th>
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Accumulation_Repair_Amount__c.label}</th>
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Estimate_List_Price_All__c.label}</th>
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Maintenance_Price_YearTXT__c.label}</th>-->
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Repair_Price__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Comment__c.label}</th>
                    </tr>
                    <apex:variable value="{!1}" var="cnt" />
                        <apex:repeat value="{!checkedAssets}" var="ar" id="assetTable">
                            <tr class="dataRow {!IF(MOD(cnt, 2)==0, 'odd', 'even')} {!IF(cnt==1, 'first', '')}" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
                                <td class="dataCell" width="25px">
                                    <apex:inputCheckbox value="{!ar.rec_checkBox_c}" id="assetRowCheckbox" rendered="{!Not(ar.IsManual)}" disabled="{!PageDisabled}"/>
                                    <apex:outputText value="{!ar.IsManual}" id="IsManual" style="display:none;" />
                                    <!-- 判断是否可报价 -->
                                    <!-- <input type="hidden" value="{!ar.estimateass}" id="allPage:allForm:allBlock:assetSection:assetTable:{!Text(cnt-1)}:estimateass"/> -->
                                    <!-- <apex:inputCheckbox value="{!ar.estimateass}" id="estimateass" style="display:none;" /> -->
                                </td>
                                <td class="dataCell">
                                    <apex:outputField value="{!ar.rec.Name}" id="assetName" rendered="{!Not(ar.IsManual)}" />
                                    <apex:inputField value="{!ar.mcae.Product_Manual__c}" id="Assert" style="width:90%;" rendered="{!ar.IsManual}" onchange="blockme();refreshProductData({!ar.lineNo});"/>
                                    <apex:inputText id="ProductId" value="{!ar.mcae.Product_Manual__c}" style="display:none;" disabled="true"/>
                                </td>
                                <!-- URF限次合同2期 LY 20220811 start -->
                                <td class="dataCell" width="70px" >
                                    <apex:outputText value="{!ar.uFRSerial}" id="uRFSeries"/>
                                </td>
                                <!-- <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.URF_Maintenance_Contract__r.Management_Code__c}" rendered="{!Not(ar.IsManual)}" id="URF_Contract_No"/>
                                </td> -->
                                    <apex:inputHidden value="{!ar.rec.URF_Maintenance_Contract__r.Management_Code__c}" rendered="{!Not(ar.IsManual)}" id="URF_Contract_No"/>
                                <!-- URF限次合同2期 LY 20220811 end -->
                                <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.Asset_situation__c}" rendered="{!Not(ar.IsManual)}" />
                                </td>
                                <td class="dataCell" width="70px">
                                    <apex:outputLink value="/{!ar.recId}" rendered="{!Not(ar.IsManual)}" >{!ar.rec.SerialNumber}</apex:outputLink>
                                    <apex:inputHidden id="AssetId" value="{!ar.recId}"/>
                                    <apex:inputField value="{!ar.rec.isNewDate_use__c}" id="isNewDate" style="display: none" showDatePicker="false"/>
                                </td>
                                <td class="dataCell" >
                                    <apex:outputField value="{!ar.mcae.EquipmentGuaranteeFlgTxt__c}" id="EquipmentGuaranteeFlgtxt"/>
                                    <apex:outputText value="{!ar.mcae.EquipmentGuaranteeFlgTxt__c}" id="EquipmentGuaranteeFlg" style="display:none;"/>
                                    <apex:inputHidden id="EGFlgassHidden" value="{!ar.etGFlg}"/>
                                </td>
                                <td class="dataCell" width="70px" style="text-align:center" >
                                    <apex:outputField value="{!ar.rec.InstallDate}" id="InstallDate" rendered="{!Not(ar.IsManual)}" />
                                </td>
                                <!--add点检改善:新增一个点检对象复选框字段,默认为true 2021.6.8 fxk Star-->
                                <!-- URF限次合同2期 LY 20220811 start -->
                                <!-- <td class="dataCell" width="70px" style="text-align:center" >
                                    <apex:inputCheckbox value="{!ar.mcae.Check_Object__c}" id="assetCheck" disabled="{!ar.CheckRows}"/>
                                </td> -->
                                <!-- URF限次合同2期 LY 20220811 end -->
                                <!--add点检改善:新增一个点检对象复选框字段,默认为true 2021.6.8 fxk end-->
                                <td class="dataCell" width="40px" style="text-align:center" >
                                    <apex:inputCheckbox value="{!ar.mcae.IsNew__c}" id="assetNew" disabled="true"/>
                                    <apex:outputPanel layout="none" rendered="{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.createable}" >
                                        <apex:inputHidden value="{!ar.mcae.IsNew__c}" id="assetNewHidden" />
                                    </apex:outputPanel>
                                    <apex:outputPanel layout="none" rendered="{!Not($ObjectType.Maintenance_Contract_Asset_Estimate__c.createable)}" >
                                        <input type="hidden" value="{!ar.mcae.IsNew__c}" id="allPage:allForm:allBlock:assetSection:assetTable:{!Text(cnt-1)}:assetNewHidden" />
                                    </apex:outputPanel>
                                    <apex:outputText value="{!ar.rec.Final_Examination_Date__c}" id="finalExaminationDate" rendered="{!Not(ar.IsManual)}" style="display:none"/>
                                </td>
                                <td class="dataCell" width="70px" >
                                    <apex:outputField value="{!ar.rec.Department_Name__c}" rendered="{!Not(ar.IsManual)}" />
                                </td>
                                <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.CurrentContract_F__r.Maintenance_Contract_No_F__c}" rendered="{!Not(ar.IsManual)}" id="Contract_No"/>
                                    <apex:inputHidden value="{!ar.rec.CurrentContract_F__r.RecordType_DeveloperName__c}" id="LastMContractRecord"/>
                                    <apex:inputField value="{!ar.rec.CurrentContract_F_asset__r.endDateGurantee_Text__c}" id="endDateGurantee_Text" style="display: none" showDatePicker="false"/>
                                    <apex:inputHidden value="{!ar.rec.CurrentContract_F__c}" id="LastMContractID"/>
                                </td>
                                <td class="dataCell" width="90px" style="text-align:right" >
                                    <apex:outputField value="{!ar.mcae.Asset_Consumption_rate__c}" rendered="{!Not(ar.IsManual)}" id="Contractrate"/>
                                    <apex:inputHidden value="{!ar.rec.CurrentContract_F__r.Contract_Range__c}" id="lastContRange"/>
                                </td>
                                <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.CurrentContract_F__r.Contract_End_Date__c}" rendered="{!(Not(ar.IsManual)&& ar.rec.CurrentContract_F__c != null)}" id="End_Date" />
                                </td>
                                 <!-- 实绩联动价格计算 start -->
                                <td class="dataCell" width="35px">
                                    <apex:outputText value="{!ar.mcae.Adjustment_Upper_price__c}" id="Adjustment_Upper_price"/>
                                    <apex:inputHidden value="{!ar.mcae.Adjustment_Upper_price__c}" id="Adjustment_Upper_priceHidden"/>
                                    <apex:inputHidden value="{!ar.mcae.Adjustment_ratio_Upper__c}" id="Adjustment_ratio_Upper"/>
                                </td>
                                <td class="dataCell" width="35px" >
                                    <apex:outputText value="{!ar.mcae.Adjustment_Lower_price__c}" id="Adjustment_Lower_price"/>
                                    <apex:inputHidden value="{!ar.mcae.LastMContract_Price__c}" id="LastMContract_Price"/>
                                    <apex:inputHidden value="{!ar.mcae.Adjustment_ratio_Lower__c}" id="Adjustment_ratio_Lower"/>
                                    <apex:inputHidden value="{!ar.mcae.Adjustment_Lower_price__c}" id="Adjustment_Lower_priceHidden"/>
                                    <apex:outputPanel layout="none" rendered="{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.createable}" >
                                        <apex:inputHidden value="{!ar.mcae.Estimate_List_Price__c}" id="assetListPriceHidden"/>
                                        <!-- XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start -->
                                        <apex:inputHidden value="{!ar.uFRMaxPrice}" id="uFRMaxPrice"/>
                                        <apex:inputHidden value="{!ar.uFRMinPrice}" id="uFRMinPrice"/>
                                        <!-- XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end -->
                                        <!-- URF限次合同2期 LY 20220811 start -->
                                        <apex:inputHidden value="{!ar.uFRMaxPrice3}" id="uFRMaxPrice3"/>
                                        <apex:inputHidden value="{!ar.uFRMinPrice3}" id="uFRMinPrice3"/>
                                        <!-- URF限次合同2期 LY 20220811 end -->
                                        <apex:inputHidden value="{!ar.mcae.Estimate_List_Price_Page__c}" id="assetListPricePageHidden" />
                                        <apex:inputHidden value="{!ar.rec.CurrentContract_F__r.Estimate_Num__c}" id="Estimate_NumHidden" />
                                    </apex:outputPanel>
                                    <apex:outputPanel layout="none" rendered="{!Not($ObjectType.Maintenance_Contract_Asset_Estimate__c.createable)}" >
                                        <input type="hidden" value="{!ar.mcae.Estimate_List_Price__c}" id="allPage:allForm:allBlock:assetSection:assetTable:{!Text(cnt-1)}:assetListPriceHidden"/>
                                        <input type="hidden" value="{!ar.rec.CurrentContract_F__r.Estimate_Num__c}" id="allPage:allForm:allBlock:assetSection:assetTable:{!Text(cnt-1)}:Estimate_NumHidden"/>
                                    </apex:outputPanel>
                                    <!-- 20200103 Gzw 计算实际报价金额 start -->
                                        <apex:inputHidden value="{!ar.mcae.Estimate_Cost__c}" id="Estimate_Cost"/>
                                    <!-- 20200103 Gzw 计算实际报价金额 end -->
                                </td>
                                <!-- 实绩联动价格计算 end -->
                                <!-- 隐藏合同月数
                                <td class="dataCell" width="90px" style="text-align:right" >
                                    <apex:outputField value="{!ar.rec.CurrentContract_F__r.Contract_Range__c}" rendered="{!Not(ar.IsManual)}" id="lastContRange" />
                                </td>-->
                                <!-- <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.Asset_Owner__c}" rendered="{!Not(ar.IsManual)}" />
                                </td>
                                <td class="dataCell" width="90px" style="text-align:right" >
                                    <apex:outputField value="{!ar.rec.Accumulation_Repair_Amount__c}" rendered="{!Not(ar.IsManual)}" />
                                </td> -->
                                <!--<td class="dataCell" width="90px" style="text-align:right" >-->
                                    <!-- 隐藏服务合同价格
                                    <apex:outputText value="{!ar.mcae.Estimate_List_Price__c}" id="assetListPrice" style="padding-right:3px;" />
                                    <apex:outputPanel layout="none" rendered="{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.createable}" >
                                        <apex:inputHidden value="{!ar.mcae.Estimate_List_Price__c}" id="assetListPriceHidden"/>
                                        <apex:inputHidden value="{!ar.mcae.Estimate_List_Price_Page__c}" id="assetListPricePageHidden" />
                                    </apex:outputPanel>
                                    <apex:outputPanel layout="none" rendered="{!Not($ObjectType.Maintenance_Contract_Asset_Estimate__c.createable)}" >
                                        <input type="hidden" value="{!ar.mcae.Estimate_List_Price__c}" id="allPage:allForm:allBlock:assetSection:assetTable:{!Text(cnt-1)}:assetListPriceHidden"/>
                                    </apex:outputPanel>-->
                                <!--</td>-->
                                <!--<td>
                                    <apex:outputText value="{!ar.mcae.Maintenance_Price_YearTXT__c}" id="assetListPriceTXT" />
                                    <apex:inputHidden value="{!ar.mcae.Maintenance_Price_YearTXT__c}" id="assetListPriceTXTHidden" />
                                </td>-->
                                <td class="dataCell" width="70px" style="text-align:right" >
                                    <apex:inputField value="{!ar.mcae.Repair_Price__c}" id="repairPrice" style="ime-mode: disabled; width:95%; text-align:right;" onchange="refreshAsset({!productCount});"/>
                                </td>
                                <td class="dataCell" width="70px" style="text-align:right" >
                                    <apex:inputField value="{!ar.mcae.Comment__c}" id="comment" style="width:95%;"/>
                                </td>
                            </tr>
                            <apex:variable value="{!cnt + 1}" var="cnt" />
                        </apex:repeat>
                </table>
                    </div>
<!-- </div>
         </div> -->
            </apex:outputPanel>
        </apex:pageblocksection>
        <!-- HWAG-B4R3SS  START 20181026-->
        <apex:outputPanel id="sumPanel"  onkeydown="if(event.keyCode==13){searchJs(); return false;}">
        <!-- HWAG-B4R3SS  END 20181026-->
            <table style="width:100%;">
                <tr>
                    <td>
                        <apex:commandButton value="行追加" action="{!addNewRows}" disabled="{!Not($ObjectType.Maintenance_Contract_Asset_Estimate__c.createable) || PageDisabled}"
                            style="margin-left:10px;float:left;" onclick="blockme();" oncomplete="unblockUI();" rerender="allForm" />
                        <apex:commandButton value="刷新选中的保有设备" disabled="{!SaveBtnDisabled || productCount2==0}" action="{!exchangeAsset}" onclick="blockme();" oncomplete="unblockUI();refreshAsset({!productCount});" rerender="allForm" />
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <!-- HWAG-B4R3SS  START 20181026-->
                        <apex:outputText value="选择条件"/>
                        &nbsp;&nbsp;
                        <apex:selectList value="{!text1}" id="text1" size="1" style="width:80px"><apex:selectOptions value="{!textOpts}"/>
                        </apex:selectList>
                        &nbsp;&nbsp;
                        <apex:selectList value="{!cond1}" id="cond1" size="1" style="width:80px">
                        <apex:selectOptions value="{!equalOpts}"/>
                        </apex:selectList>
                        &nbsp;&nbsp;
                        <!-- LJPH-BSS6E2  ---20200911 ---update by rentongxiao start -->
                        <apex:inputText value="{!val1}"
                        id="val1" style="width:100px; background-color:{!IF(contr == '1','#e3f3ff','white')}"/>
                        <!-- LJPH-BSS6E2  ---20200911 ---update by rentongxiao end -->
                        &nbsp;
                        <apex:commandButton value="检索" onclick="searchJs();" style="width:100px" rerender="dummy"/>
                        &nbsp;
                        <apex:commandButton value="清除条件" onclick="clearAndSearch();" style="width:100px" rerender="dummy"/>
                        <!-- HWAG-B4R3SS END 20181026-->
                    </td>
                    <th width="90px" style="text-align:right"></th>
                    <th width="90px" style="text-align:right"></th>
                    <th width="90px" style="text-align:right">设备数量</th>
                    <td width="90px" style="text-align:right"><apex:outputtext value="{!productCount3}" id="productCount3"/></td>
                    <td width="25px">&nbsp;</td>
                    <!--<th width="90px" style="text-align:right">报价总额</th>
                    <th width="90px" style="text-align:right"><span id="allPage:allForm:allBlock:assetListSumNum" ></span></th>-->
                    <td width="25px">&nbsp;</td>
                    <th width="90px" style="text-align:right">修理总额</th>
                    <th width="90px" style="text-align:right"><span id="allPage:allForm:allBlock:assetRepairSumNum" ></span></th>
                    <td width="95px">&nbsp;</td>
                </tr>
            </table>
        </apex:outputPanel>
        <apex:pageblocksection columns="1" title="未选择的保有设备" id="assetSection2" >
            <apex:outputLabel />
            <apex:outputPanel >
                <input type="hidden" id="allPage:allForm:allBlock:assetSection2:productCnt2" value="{!productCount2}" />
                <table class="list" style="border-bottom-width: 0px; font-size:13px;" border="0" cellspacing="0" cellpadding="0">
                    <tr class="headerRow" height="30px">
                        <th style="width:25px" class="headerRow  booleanColumn"><input type='checkbox' onClick='checkAll2(this)'/></th>
                        <th style="width:25%" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Name.label}</th>
                        <!-- URF限次合同2期 LY 20220811 start -->
                        <th style="width:90px" class="headerRow  booleanColumn">限次系列<!-- {!$ObjectType.Asset.fields.Product2.ProductURF__r.URFLimitSerial__c.label} --></th>
                        <!-- URF限次合同2期 LY 20220811 end -->
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Asset_situation__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.SerialNumber.label}</th>
                        <th class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Department_Name__c.label}</th>
                        <!-- <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Installation_Site__c.label}</th> -->
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.IF_Warranty__c.label}</th>
                         <!-- //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start -->
                        <th style="width:90px" class="headerRow  booleanColumn">主机/耗材</th>
                         <!-- //JZHG-BSDUT4 ---20200825---update By rentongxiao---End -->
                        <th class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.EGFlg_fromContract_asset__c.label}</th>
                        <th style="width:150px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Reson_Can_not_Warranty__c.label}</th>
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.InstallDate.label}</th>
                        <!-- <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Asset_Owner__c.label}</th> -->
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Accumulation_Repair_Amount__c.label}</th>
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Estimate_List_Price__c.label}</th>
                    </tr>
                    <apex:variable value="{!1}" var="cnt" />
                    <apex:repeat value="{!unCheckedAssetsView}" var="assetsView" id="outassetTable2">
                        <apex:repeat value="{!assetsView}" var="ar" id="assetTable2">
                            <tr class="dataRow {!IF(MOD(cnt, 2)==0, 'odd', 'even')} {!IF(cnt==1, 'first', '')}" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
                                <!-- <td class="dataCell" width="25px">
                                    <apex:inputCheckbox value="{!ar.rec_checkBox_c}" id="assetRowCheckbox2" disabled="{!IF(ar.uFRPrice == 0 || ar.rec.IF_Warranty__c = '否', 'true', 'false')}"/>
                                </td> -->
                                <!-- gzw update 20220823 -->
                                <td class="dataCell" width="25px">
                                    <apex:inputCheckbox value="{!ar.rec_checkBox_c}" id="assetRowCheckbox2" disabled="{!IF( ar.rec.IF_Warranty__c = '否', 'true', 'false')}"/>
                                </td>
                                <td class="dataCell" width="25%">
                                    <apex:outputField value="{!ar.rec.name}" id="assetName"/>
                                </td>
                                <!-- URF限次合同2期 LY 20220811 start -->
                                <td class="dataCell" width="90px">
                                    <!-- <apex:outputField value="{!ar.rec.Product2.ProductURF__r.URFLimitSerial__c}"/> --><apex:outputText value="{!ar.uFRSerial}"/>
                                </td>
                                <!-- URF限次合同2期 LY 20220811 end -->
                                <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.Asset_situation__c}"/>
                                </td>
                                <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.SerialNumber}"/>
                                </td>
                                <td class="dataCell">
                                    <apex:outputField value="{!ar.rec.Department_Name__c}"/>
                                </td>
                                <!-- <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.Installation_Site__c}"/>
                                </td> -->
                                <td class="dataCell" width="90px" style="text-align:center">
                                    <apex:outputField value="{!ar.rec.IF_Warranty__c}"/>
                                </td>
                                 <!-- //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start -->
                                <td class="dataCell" width="90px" style="text-align:center">
                                    <apex:outputField value="{!ar.rec.AssetMark__c}"/>
                                </td>
                                 <!-- //JZHG-BSDUT4 ---20200825---update By rentongxiao---End -->
                                <td class="dataCell" style="text-align:center" >
                                    <apex:outputField value="{!ar.rec.EquipmentGuaranteeFlg__c}"/>
                                </td>
                                <td class="dataCell" width="150px" style="text-align:center">
                                    <apex:outputField value="{!ar.rec.Reson_Can_not_Warranty__c}"/>
                                </td>
                                <td class="dataCell" width="90px" style="text-align:center" >
                                    <apex:outputField value="{!ar.rec.InstallDate}"/>
                                </td>
                                <!-- <td class="dataCell" width="90px">
                                    <apex:outputField value="{!ar.rec.Asset_Owner__c}"/>
                                </td> -->
                                <td class="dataCell" width="90px" style="text-align:right" >
                                    <apex:outputField value="{!ar.rec.Accumulation_Repair_Amount__c}"/>
                                </td>
                                <td class="dataCell" width="90px" style="text-align:right" >
                                    <!-- <apex:outputField value="{!ar.rec.Maintenance_Price_Month__c}" /> -->
                                    <apex:outputText value="{!ar.uFRPrice}" />
                                </td>
                            </tr>
                            <apex:variable value="{!cnt + 1}" var="cnt" />
                        </apex:repeat>
                    </apex:repeat>
                </table>
                <apex:outputPanel >
                    <dir align="right">
                        <table>
                            <tr>
                                <td>{!(currPage-1)*selctRecordNum}&nbsp;-&nbsp;{!IF(currPage*selctRecordNum > totalRecords, totalRecords, currPage*selctRecordNum)}</td>
                                <td>&nbsp;&nbsp;共{!totalRecords}个</td>
                                <td align="right" width="115px">显示
                                    <apex:selectList value="{!selRecordOption}" id="selRecordOption" size="1" onchange="blockme();recordNumChangeJs();" disabled="{!IF(totalRecords<10,true,false)}"><apex:selectOptions value="{!recordNum}"/></apex:selectList>条记录
                                </td>
                                <td align="right" width="50px">第{!currPage}页</td>
                                <td align="right" width="45px">
                                    <apex:commandLink action="{!firstPage}" value="首页" id="firstPg" onclick="blockme();" oncomplete="unblockUI();" reRender="allForm" style="{!IF(currPage==1,'display: none;','')}color: blue;"/>
                                    <apex:outputText value="首页" style="{!IF(currPage!=1,'display: none;','')}color: gray;"></apex:outputText>
                                </td>
                                <td align="right" width="40px">
                                    <apex:commandLink action="{!previousPage}" value="上一页" id="previous" onclick="blockme();" oncomplete="unblockUI();" reRender="allForm" style="{!IF(currPage==1,'display: none;','')}color: blue;"/>
                                    <apex:outputText value="上一页" style="{!IF(currPage!=1,'display: none;','')}color: gray;"></apex:outputText>
                                </td>
                                <td width="3px"></td>
                                <td align="left" width="40px">
                                    <!-- HWAG-B4R3SS  START 20181026-->
                                    <apex:commandLink action="{!nextPage}" value="下一页" id="next" onclick="blockme();" oncomplete="unblockUI();" reRender="allForm" style="{!IF(totalPage==currPage ||totalPage == 0,'display: none;','')}color: blue;"/>
                                    <apex:outputText value="下一页" style="{!IF(totalPage!=currPage && totalPage != 0,'display: none;','')}color: gray;"></apex:outputText>
                                </td>
                                <td align="left" width="45px">
                                    <apex:commandLink action="{!endPage}" value="尾页" id="endPg" onclick="blockme();" oncomplete="unblockUI();" reRender="allForm" style="{!IF(totalPage==currPage||totalPage == 0,'display: none;','')}color: blue;"/>
                                    <apex:outputText value="尾页" style="{!IF(totalPage!=currPage
                                        && totalPage != 0,'display: none;','')}color: gray;"></apex:outputText>
                                </td>
                                <!-- HWAG-B4R3SS  END 20181026-->
                                <td align="left">共{!totalPage}页</td>
                            </tr>
                        </table>
                    </dir>
                </apex:outputPanel>
            </apex:outputPanel>
        </apex:pageblocksection>
        <apex:pageblocksection title="合同信息" columns="1" id="contractInfo">
            <apex:outputLabel />
            <apex:outputPanel >
                <table style="width:100%">
                    <tr>
                        <td width="22%"></td>
                        <!-- <td width="14%"></td> -->
                        <td width="22%"></td>
                        <td width="28%"></td>
                        <td width="14%"></td>
                        <td width="14%"></td>
                    </tr>
                    <tr>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.GuidePrice_Down__c.label}</th>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.GuidePrice_Up__c.label}</th>
                        <th style="text-align: center">申请报价金额</th>
                        <th style="text-align: center">合同设备修理总额</th>
                        <th style="text-align: center">合同总金额</th>
                    </tr>
                    <tr>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.GuidePrice_Down__c}" id="GuidePriceDown" />
                            <apex:inputHidden value="{!estimate.GuidePrice_Down__c}" id="GuidePriceDownHidden" />
                        </td>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.GuidePrice_Up__c}" id="GuidePriceUp" />
                            <apex:inputHidden value="{!estimate.GuidePrice_Up__c}" id="GuidePriceUpHidden" />
                        </td>
                        <td style="text-align: center">
                            <!--<apex:inputField value="{!estimate.Request_quotation_Amount__c}" id="quotation_Amount" />-->
                            <apex:inputField value="{!estimate.Request_quotation_Amount__c}" style="ime-mode: disabled; text-align: right; width:100px" id="quotation_Amount" onchange="checkDiscount(this.value);"/>
                        </td>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.Asset_Repair_Sum_Price__c}" id="assetRepairSumPrice" />
                            <apex:inputHidden value="{!estimate.Asset_Repair_Sum_Price__c}" id="assetRepairSumPriceHidden" />
                        </td>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.Maintenance_Price__c}" id="mainteReal" />
                            <apex:inputHidden value="{!estimate.Maintenance_Price__c}" id="mainteRealHidden"/>
                            <apex:inputHidden value="{!OldMaintenancePrice}" id="oldMainteReal"/>
                        </td>
                    </tr>
                    <tr>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Service_discount_Rate__c.label}</th>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.New_Contract_Type_TxT__c.label}</th>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Combined_rate__c.label}</th>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Consumption_rate_Forecast__c.label}</th>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Estimate_Price_range__c.label}</th>
                    </tr>
                    <tr>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.Service_discount_Rate__c}" id="discount_Rate"/>
                            <apex:inputHidden value="{!estimate.Service_discount_Rate__c}" id="discount_RateHidden" />
                        </td>
                        <td style="text-align: center">
                            <apex:outputText value="{!estimate.New_Contract_Type_TxT__c}" id="Contract_TypeTXT" />
                            <apex:inputHidden value="{!typeresult}" id="Contract_TypeTXTHidden" />
                        </td>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.Combined_rate__c}" id="Combinedrate" />
                            <apex:inputHidden value="{!estimate.Combined_rate__c}" id="CombinedrateHidden" />
                        </td>
                        <td style="text-align: center">
                            <!-- URF限次合同2期 LY 20220920 start -->
                            <!-- <apex:outputField value="{!estimate.Consumption_rate_Forecast__c}"  /> -->
                            -
                            <!-- URF限次合同2期 LY 20220920 end -->
                        </td>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.Estimate_Price_range__c}"  />
                        </td>
                    </tr>
                    <tr>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.ContractPriceType__c.label}</th>
                        <th style="text-align: center"></th>
                        <th style="text-align: center"></th>
                        <th style="text-align: center"></th>
                        <th style="text-align: center"></th>
                    </tr>
                    <tr>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.ContractPriceType__c}"/>
                        </td>
                        <td style="text-align: center"></td>
                        <td style="text-align: center"></td>
                        <td style="text-align: center"></td>
                        <td style="text-align: center"></td>
                    </tr>
                </table>
            </apex:outputPanel>
        </apex:pageblocksection>
        <apex:pageblocksection title="申请背景" columns="1" id="Appbackground">
            <apex:outputLabel />
            <apex:outputPanel >
                <table style="width:100%">
                    <tr>
                        <td width="10%"></td>
                        <td width="30%"></td>
                        <td width="10%"></td>
                        <td width="50%"></td>
                    </tr>
                    <tr>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.finalPriceDecideWay__c.label}</th>
                        <td><apex:inputField value="{!estimate.finalPriceDecideWay__c}" id="finalPriceDecideWay" style="width:50%;" /></td>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Sales_incidental__c.label}</th>
                        <td><apex:inputField value="{!estimate.Sales_incidental__c}" id="Sales_incidental" style="width: 20px;height: 20px;" /></td>
                        <!-- lighting升级 20230210 lt 复选框大小异常问题 style="width:50%;" == style="width: 20px;height: 20px;"  -->
                    </tr>
                    <tr>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.mainTalksTime__c.label}</th>
                        <td ><apex:inputField value="{!estimate.mainTalksTime__c}"  style="width:50%;" id="mainTalksTime"/></td>
                        <th>{!$ObjectType.Maintenance_Contract_Estimate__c.fields.talksStartDate__c.label}</th>
                        <td><apex:inputField value="{!estimate.talksStartDate__c}" id="talksStartDate" style="width:50%;"  /></td>
                    </tr>
                    <tr>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.AgencyHos_Price__c.label}</th>
                        <td ><apex:inputField value="{!estimate.AgencyHos_Price__c}"  style="width:50%;" id="AgencyHos_Price"/></td>
                        <th style="text-align: center"></th>
                        <td ></td>
                    </tr>
                    <tr>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Discount_reason__c.label}</th>
                        <td colspan="3"><apex:inputField value="{!estimate.Discount_reason__c}" id="discountReason" style="width:95%;height:50px;" /></td>
                    </tr>
                    <tr>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Improve_ConsumptionRate_Idea__c.label}</th>
                        <td colspan="3"><apex:inputField value="{!estimate.Improve_ConsumptionRate_Idea__c}" id="improveConsumptionRateIdea" style="width:95%;height:50px;" /></td>
                    </tr>
                </table>
            </apex:outputPanel>
            <script type="text/javascript">
                //var applyType = j$(escapeVfId('allPage:allForm:allBlock:Appbackground:applyType')).val();
                //var obj = document.getElementById('allPage:allForm:allBlock:Appbackground:TypeOther');
                //if (applyType == '其他') {
                //    obj.style.display = "block";
                //} else {
                //    obj.style.display = "none";
                //}
                //resetapplyType();
            </script>
        </apex:pageblocksection>
        <script type="text/javascript">
            var isDisabled = {!PageDisabled};
            if(!isDisabled){
                refreshAsset({!productCount});
            }
        </script>
    </apex:pageBlock>
    <table width="100%" border="0">
        <tr>
            <!-- <td width="40%" style="text-align: right;"> -->
            <td width="50%">
                <table border="0" style="background-color:#ffd6c1;" width="100%">
                    <tr>
                        <th width="50px">打印报价</th>
                        <td width="90px"><apex:inputCheckbox id="check0" onchange="hideSimplify(0);" value="{!estimate.Print_ListPrice__c}" />完整版+折扣前</td>
                        <td width="90px"><apex:inputCheckbox id="check1" onchange="hideSimplify(1);" value="{!estimate.Print_Simplify__c}" />完整版+折扣后</td>
                        <td width="80px"><apex:inputCheckbox id="check2" onchange="hideSimplify(2);" value="{!estimate.Print_RepairPrice__c}"/>简化版+折扣前</td>
                        <td width="80px"><apex:inputCheckbox id="check3" onchange="hideSimplify(3);" value="{!estimate.Print_SumPrice__c}"/>简化版+折扣后</td>
                    </tr>
                    <tr>
                        <th width="70px">打印合同配置</th>
                        <td width="60px">
                        <!-- 2018/10/26HWAG-B5C88S 医院和经销商合同任何时候都不能选择 start -->
                            <apex:outputPanel rendered="false">
                                <apex:inputCheckbox value="{!estimate.Print_Contract__c}" />
                            </apex:outputPanel>
                            <apex:outputPanel rendered="{!Not(EnablePrintContract)}">
                                &nbsp;&nbsp;&nbsp;
                            </apex:outputPanel>
                            医院合同
                        </td>
                        <!-- 2018/09/26 HWAG-B4SCR3 三方和代理商合同在未decide前也不能选择 start -->
                        <td width="60px">
                            <apex:outputPanel rendered="{!EnablePrintContract}">
                                <apex:inputCheckbox id="tripartite" value="{!estimate.Print_Tripartite__c}"/>
                            </apex:outputPanel>
                            <apex:outputPanel rendered="{!Not(EnablePrintContract)}">
                                &nbsp;&nbsp;&nbsp;
                            </apex:outputPanel>
                        三方协议</td>
                        <td width="85px">
                            <apex:outputPanel rendered="false">
                                <apex:inputCheckbox id="agent" value="{!estimate.Print_Agent__c}"/>
                            </apex:outputPanel>
                            <apex:outputPanel rendered="{!Not(EnablePrintContract)}">
                                &nbsp;&nbsp;&nbsp;
                            </apex:outputPanel>
                        代理商合同</td>
                        <!-- 2018/09/26  HWAG-B4SCR3 三方和代理商合同在未decide前也不能选择 end -->
                        <!-- 2018/10/26 HWAG-B5C88S 医院和经销商合同任何时候都不能选择 end -->
                        <td colspan="3" style="text-align: right"><apex:commandButton action="{!print}" value="PDF印刷" rerender="allBlock,pdfPrint"  onclick="if (!onclickCheckchangedAfterPrint('Pt{!SaveBtnDisabled}','false')) return false;" oncomplete="unblockUI();ComputeLTYRepair()"/></td>
                    </tr>
                </table>
            </td>
            <td>
                <table class="btntable" border="0">
                    <tr>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td width="20px">&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td width="30px">&nbsp;</td>
                        <!-- <td><apex:commandButton id="savebtn" action="{!save}" value="{!$Label.Save_Button}" disabled="{!SaveBtnDisabled}" rerender="allForm" onclick="if (!onclickCheckchangedAfterPrint('true','true')) return false;" oncomplete="unblockUI();"/></td> -->
                        <td><apex:commandButton id="savebtn" action="{!save}" value="{!$Label.Save_Button}" disabled="{!SaveBtnDisabled}" rerender="allForm" onclick="if (!EGFlgconfim()) return false;" oncomplete="unblockUI();"/></td>
                        <td width="200px"><apex:commandButton id="approvalbtn" action="{!approvalProcess}" value="提交待审批" disabled="{!ApprovalBtnDisabled}" rerender="allForm" onclick="if (!KindsAndMonths()) return false;if (!EGFlgconfim()) return false;approvalJs();" oncomplete="unblockUI();"/>
                        <!-- HWAG-B399Q8 2018/08/20 新增请提交待审批 提示字段 start-->
                        &nbsp; <apex:outputText style="color:red;font-size:20px;" value="请提交待审批" rendered="{!IS_Clone_After_Decide}"/>
                        <!-- HWAG-B399Q8 2018/08/20 新增请提交待审批 提示字段 end-->
                        </td>
                    </tr>
                    <tr>
                        <th>{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Contract_Start_Date__c.label}</th>
                        <td><apex:inputField value="{!estimate.Contract_Start_Date__c}" id="contractstartdate" onchange="changeContractStartdate(this.value);"/></td>
                        <td>&nbsp;</td>
                        <th>&nbsp;&nbsp;{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Contract_End_Date__c.label}</th>
                        <td><apex:outputField value="{!estimate.Contract_End_Date__c}" id="contractenddate"/></td>
                        <td>&nbsp;</td>
                        <td><apex:commandButton id="decidebtn" value="{!$Label.QuoteDecision_Button}" disabled="{!DecideBtnDisabled}" onclick="decideJs(); return false;"/></td>
                        <td style="text-align:right"><apex:commandButton id="undecidebtn" action="{!undecide}" value="取消{!$Label.QuoteDecision_Button}" disabled="{!UnDecideBtnDisabled}" rerender="allForm" onclick="blockme();" oncomplete="unblockUI();"/></td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</apex:form>
<apex:outputPanel id="pdfPrint">
<script type="text/javascript">
//j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
function saveBeforeCheckPriceChange() {
    sforce.connection.sessionId = Session_ID;
    var needClearId = false;
    var rowCnt = j$(escapeVfId('allPage:allForm:allBlock:assetSection:productCnt')).val();
    var assIds = "";
    var proIds = "";
    var priceMap = new Map();
    var newProductMap = new Map();
    var newProductCheck = false;
    var nowDate = new Date();
    var createdDate = null;
    var createdDateShow = j$(escapeVfId('allPage:allForm:allBlock:contract:createDateShow')).text();
    var contractDate = new Date(j$(escapeVfId('allPage:allForm:contractstartdate')).value());
    if (createdDateShow.trim() != '') {
        createdDate = new Date(createdDateShow);
        newProductCheck = true;
    } else {
        createdDate = new Date();
    }
    var threeMonthAfter = new Date(createdDate.setMonth(createdDate.getMonth() + 3));
    createdDate = new Date(createdDate.setMonth(createdDate.getMonth() - 3));
    for (var i = 0; i < rowCnt; i++) {
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        var isnew = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNewHidden')).val();
        var price = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val();
        if (isManual == 'true') {
            var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':ProductId'));
            if (a.size() > 0 && a.value() != "000000000000000000" && a.value() != "") {
                if (proIds == "") {
                    proIds = "'" + a.value() + "'";
                } else {
                    proIds = proIds + ",'" + a.value() + "'";
                }
                if (isnew == "true") {
                    priceMap.set(a.value(), price/{!isNewPriceAdj});
                } else {
                    priceMap.set(a.value(), price);
                }
                newProductMap.set(a.value(), isnew);
            } else {
                continue;
            }
        }
        else {
            var aId = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':AssetId')).value();
            if (assIds == "") {
                assIds = "'" + aId + "'";
            } else {
                assIds = assIds + ",'" + aId + "'";
            }
            if (isnew == "true") {
                priceMap.set(aId, price/{!isNewPriceAdj});
            } else {
                priceMap.set(aId, price);
            }
            newProductMap.set(aId, isnew);
        }
    }
    // 选择设备后价格变更check
    if (assIds.length > 0) {
        // alert('222222222222' + assIds);
        var sql = "SELECT Id, Maintenance_Price_Month__c,Product2.UFR_Maintenance_Price_Month__c, Posting_Date__c, InstallDate,Product2.UFR_Maintenance_Price_Month_3__c from Asset where Id In(" + assIds + ")";
        var rt = sforce.connection.query(sql);
        var asList = rt.getArray("records");
        if (asList != null) {
            for(var i=0;i<asList.length;i++) {
                var asvar = asList[i];
                // alert('asvar' + asvar);
                var asId = asvar["Id"];
                // alert('asvar++++' + asvar["Product2"].["ProductURF__r"].["UFR_Maintenance_Price_Month__c"]);
                // var mprice = asvar["Maintenance_Price_Month__c"];
                //URF限次合同2期 LY 20220811 start
                //var mprice = asvar["Product2"].UFR_Maintenance_Price_Month__c;
                var mprice = asvar["Product2"].UFR_Maintenance_Price_Month_3__c;
                //URF限次合同2期 LY 20220811 end
                var ptDt = asvar["Posting_Date__c"];
                var postingDate = null;
                if (ptDt != null && ptDt != '') {
                    postingDate = new Date(ptDt);
                }
                var inDt = asvar["InstallDate"];
                var installDate = null;
                if (inDt != null && inDt != '') {
                    installDate = new Date(inDt);
                }
                var priceShow = priceMap.get(asId);
                var isNew = newProductMap.get(asId);
                if ('{!DecideBtnDisabled}' == 'true') {
                    if (Number(mprice).toFixed(2) != Number(priceShow).toFixed(2)) {
                        needClearId = true;
                        // j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
                        return needClearId;
                    }
                }
            }
        }
    }
    if (proIds.length > 0) {
        if ('{!DecideBtnDisabled}' == 'false') {
            var oldDateStr = j$('#oldContractDate').value();
            var oldDate = new Date();
            if (oldDateStr != null && oldDateStr != '') {
                oldDate = new Date(oldDateStr);
            }
            var crdt = new Date(j$(escapeVfId('allPage:allForm:allBlock:contract:createDateShow')).text());
            var newContractDate = new Date(j$(escapeVfId('allPage:allForm:contractstartdate')).value());
            var sixMonthAfter = new Date(crdt.setMonth(crdt.getMonth() + 6));
            if ((newContractDate > sixMonthAfter && oldDate <= sixMonthAfter) || (newContractDate <= sixMonthAfter && oldDate > sixMonthAfter)) {
                j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
                return true;
            }
        } else {
            var sql = "SELECT Id, Maintenance_Price_Month__c,UFR_Maintenance_Price_Month__c,UFR_Maintenance_Price_Month_3__c from Product2 where Id In(" + proIds + ")";
            var rt = sforce.connection.query(sql);
            var pdList = rt.getArray("records");
            if (pdList != null) {
                for(var i=0;i<pdList.length;i++) {
                    var pdvar = pdList[i];
                    var pdId = pdvar["Id"];
                    // var mprice = pdvar["Maintenance_Price_Month__c"];
                    //URF限次合同2期 LY 20220811 strat
                    //var mprice = pdvar["UFR_Maintenance_Price_Month__c"];
                    var mprice = pdvar["UFR_Maintenance_Price_Month_3__c"];
                    //URF限次合同2期 LY 20220811 end
                    var priceShow = priceMap.get(pdId);
                    if (Number(mprice).toFixed(2) != Number(priceShow).toFixed(2)) {
                        needClearId = true;
                        // j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
                        return needClearId;
                    }
                }
            }
        }
    }
    // var changedPrice = j$(escapeVfId('allPage:allForm:changedSubmitPrice')).value();
    // if (changedPrice=='true') {
    //     needClearId = true;
    // }
    return needClearId;
}
// SelectAssetEstimateController#checkchangedAfterPrint と同じロジックにする必要があります。
// true 変更あり、false 変更なし
function checkchangedAfterPrint() {
    sforce.connection.sessionId = Session_ID;
    var needClearId = false;
    //j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
    var changedPrice = j$(escapeVfId('allPage:allForm:changedSubmitPrice')).value();
    // 新規の場合、targetEstimateIdがない、判断いらない
    if ('{!targetEstimateId}' == '') return needClearId;
    if ('{!estimate.Quote_Date__c}' != '' || '{!estimate.Process_Status__c}' != '草案中') {
        // xud 20140529 ここは明細変更判断
        // xudan 20150729 ソート項目にIdを追加
        var sql = "SELECT Id, Asset__c, Asset__r.SerialNumber, Check_Result__c, Product_Manual__c,"
                + " Repair_Price__c, Comment__c, Maintenance_Contract_Estimate__r.Maintenance_Price__c"
                + "  FROM Maintenance_Contract_Asset_Estimate__c"
                + " WHERE Maintenance_Contract_Estimate__c = '{!targetEstimateId}'"
                + " ORDER BY id,Asset__c,Product_Manual__c, Asset__r.SerialNumber, Asset__r.Name, Asset__r.Department_Name__c, Asset__r.InstallDate";
        var result = sforce.connection.query(sql);
        var mcaeList = result.getArray("records");
        var inputingList = [];
        var finalPrice = 0;
        // 画面入力値を整理(いらないものを対象外にする)
        var cntWithKara = {!productCount};
        for (var i = 0; i < cntWithKara; i++) {
            var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
            if (isManual == 'true') {
                var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':ProductId'));
                if (a.size() > 0 && a.value() != "000000000000000000" && a.value() != "") {
                    inputingList.push(
                        {'id' : '',
                         'Product_Manual__c' : a.value(),
                         'Check_Result__c' : j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':checkResult')).value(),
                         'Repair_Price__c' : localParseFloat(j$.trim(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).value())),
                         'Comment__c': j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':comment')).value()
                        }
                    );
                } else {
                    continue;
                }
            }
            else {
                inputingList.push(
                    {'id' : j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':AssetId')).value(),
                     'Check_Result__c' : j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':checkResult')).value(),
                     'Repair_Price__c' : localParseFloat(j$.trim(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).value())),
                     'Comment__c': j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':comment')).value()
                    }
                );
            }
        }
        //针对inputingList的重新排序
        var arrayMap = [];
        var ArrayOrderPMCnt = [];
        for(var i=0;i<mcaeList.length;i++){
            var mcaeVar = mcaeList[i];
            var AssetIDOrPMC = mcaeVar["Asset__c"]!=null?mcaeVar["Asset__c"]:mcaeVar["Product_Manual__c"];
            if(arrayMap[AssetIDOrPMC]!=null){
                arrayMap[AssetIDOrPMC] = i;
                ArrayOrderPMCnt[AssetIDOrPMC] = i;
            }else{
                // Product_Manual__c相同的话怎么办
                if(ArrayOrderPMCnt[AssetIDOrPMC]==null){
                    ArrayOrderPMCnt[AssetIDOrPMC] = i;
                }else{
                    var cacheArray = new Array();
                    cacheArray = ArrayOrderPMCnt[AssetIDOrPMC];
                    ArrayOrderPMCnt[AssetIDOrPMC] = cacheArray+','+i;
                }
            }
        }
        var inputingListCache = inputingList;
        var cntLength = mcaeList.length>inputingListCache.length?mcaeList.length:inputingListCache.length;
        if(mcaeList.length!=inputingListCache.length){
            needClearId = true;
            //j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
            return needClearId;
        }
        inputingList = new Array(cntLength);
        var inputingListOut = new Array();
        for(var i=0;i<inputingListCache.length;i++){
            var InputIdOrPMc = inputingListCache[i].id!=""?inputingListCache[i].id:inputingListCache[i].Product_Manual__c;
            var thisArray = ArrayOrderPMCnt[InputIdOrPMc];
            if(thisArray.length!=null){
                thisArray = thisArray.split(',');
                var ORDERCnt = thisArray[0];
                thisArray.shift();
                thisArray = thisArray.join(',');
                ArrayOrderPMCnt[InputIdOrPMc] = thisArray;
            }else{
                var ORDERCnt = thisArray;
            }
            if( ORDERCnt !=null){
                inputingList[ORDERCnt] = inputingListCache[i];
            }else{
                inputingList[ORDERCnt] = inputingListCache[i];
                inputingListOut.push(inputingListCache[i]);
            }
        }
        if( inputingListOut.length>0){
            for(var i = 0; i<inputingListOut.length;i++){
                inputingList.push(inputingListOut[i]);
            }
        }
        //20161122,测试发现Check_Result__c已停用,故而修改对应的Js判断部分
        /*
                            && (((mcae["Check_Result__c"] == null || mcae["Check_Result__c"] == "")
                                  && (inputing["Check_Result__c"] == null || inputing["Check_Result__c"] == "")
                                )
                                || mcae["Check_Result__c"] == inputing["Check_Result__c"]
                               )
        //==================================================================================
                            && (((mcae["Check_Result__c"] == null || mcae["Check_Result__c"] == "")
                                  && (inputing["Check_Result__c"] == null || inputing["Check_Result__c"] == "")
                                )
                                || mcae["Check_Result__c"] == inputing["Check_Result__c"]
                               )
        */
        //原是代码保留
        if (inputingList.length == mcaeList.length && needClearId == false ) {
            for (var i = 0; i < mcaeList.length; i++) {
                var mcae = mcaeList[i];
                finalPrice = mcae["Maintenance_Contract_Estimate__r"]["Maintenance_Price__c"];
                var inputing = inputingList[i];
                if (mcae["Asset__c"] != null && mcae["Asset__c"] != "") {
                    if (inputing["id"] != "" && mcae["Asset__c"] == inputing["id"]
                            && localParseFloat(mcae["Repair_Price__c"]) == inputing["Repair_Price__c"]
                            && (((mcae["Comment__c"] == null || mcae["Comment__c"] == "")
                                  && (inputing["Comment__c"] == null || inputing["Comment__c"] == "")
                                )
                                || mcae["Comment__c"] == inputing["Comment__c"]
                               )
                    ) {
                        // 同じ
                    } else {
                        needClearId = true;
                        break;
                    }
                } else {
                    if (inputing["id"] == "" && mcae["Product_Manual__c"] != null && mcae["Product_Manual__c"] != ""
                            && mcae["Product_Manual__c"] == inputing["Product_Manual__c"]
                            && localParseFloat(mcae["Repair_Price__c"]) == inputing["Repair_Price__c"]
                            && (((mcae["Comment__c"] == null || mcae["Comment__c"] == "")
                                  && (inputing["Comment__c"] == null || inputing["Comment__c"] == "")
                                )
                                || mcae["Comment__c"] == inputing["Comment__c"]
                               )
                    ) {
                        // 同じ
                    } else {
                        needClearId = true;
                        break;
                    }
                }
            }
        } else {
            needClearId = true;
        }
        // xud 20140529 ここは総金額変更判断(割引を変更したらまずい)
        var inputFinalPrice = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:mainteRealHidden')).value();
        if (toNum(inputFinalPrice) != toNum(finalPrice)) {
            needClearId = true;
        }
        if (changedPrice=='true') {
            needClearId = true;
        }
    }
    if (needClearId) {
        //j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
    }
    return needClearId;
}
if ('{!printAsset}' == 'true') {
    //打印保有設備
    // //必须选择打印报价(详细还是简化)
    var con = 0;
    for (j = 0; j < 4; j++) {
        if (j$(escapeVfId('allPage:allForm:check' + j)).attr('checked')) {
            con ++;
        }
    }
    if(con != 1){
        alert('请您勾选打印报价版本,只能勾选一个。');
    }else{
         window.open('/apex/MaintenanceContractEstimateVMPDF?id={!targetEstimateId}', 'MaintenanceContractEstimateVMPDF');
    }
} else if ('{!printContract}' == 'true') {
    // 打印医院合同配置
    window.open('/apex/MceConfigPDF?id={!targetEstimateId}&flag=printContract', 'MceConfigPDF');
} else if ('{!printTripartite}' == 'true') {
    //打印三方合同
    window.open('/apex/MceConfigPDF?id={!targetEstimateId}&flag=printTripartite', 'MceConfigPDF');
} else if ('{!printAgent}' == 'true') {
    //打印经销商合同
    window.open('/apex/MceConfigPDF?id={!targetEstimateId}&flag=printAgent', 'MceConfigPDF');
}else {}
//当选择报价单(详细版)的时候隐藏报价单(简化版)
// 4个选项只可以选一个
function hideSimplify(cb){
    for (j = 0; j < 4; j++) {
        if (j$(escapeVfId('allPage:allForm:check' + j)).attr('checked')) {
            j$(escapeVfId('allPage:allForm:check' + j)).attr('checked',false);
            if (j == cb) {
                j$(escapeVfId('allPage:allForm:check' + j)).attr('checked',true);
            }
        }
    }
}
var isDisabled = {!PageDisabled};
if(!isDisabled){
    refreshAsset({!productCount});
}
</script>
</apex:outputPanel>
</apex:page>
force-app/main/default/pages/SelectAssetEstimateURF.page-meta.xml
New file
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>41.0</apiVersion>
    <availableInTouch>false</availableInTouch>
    <confirmationTokenRequired>false</confirmationTokenRequired>
    <label>SelectAssetEstimateURF</label>
</ApexPage>
force-app/main/default/pages/SelectAssetEstimateVM.page
New file
@@ -0,0 +1,3017 @@
<apex:page controller="SelectAssetEstimateVMController" tabStyle="Maintenance_Contract_Estimate__c" lightningStylesheets="true" sidebar="false" showHeader="true" id="allPage" action="{!init}">
<head>
 <!-- <meta http-equiv="x-ua-compatible" content="ie=edge" /> -->
 <!-- <meta name="viewport" content="width=device-width, initial-scale=1" /> -->
 <!-- <apex:slds /> -->
</head>
    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
    <apex:includeScript value="{!URLFOR($Resource.apex20)}"/>
<style type="text/css">
    table { border-collapse: collapse; }
    .container {
        overflow:auto;
        width:100%;
        height:304px;
    }
    .container2 {
        overflow:auto;
        width:100%;
        height:404px;
    }
    .btntable.dateFormat  {
        display: none;
    }
</style>
<script type="text/javascript">
//add by rentx 2020-11-17 start 失去焦点
function setFocusOnLoad() {}
function bodyOnLoad(){setFocusOnLoad();}
//add by rentx 2020-11-17 end 失去焦点
var oxygenPriceAdj = {!oxygenPriceAdj};
var approvalDate = '';
var Session_ID = '{!$Api.Session_ID}';
var Confirm_ChangedAfterPrint = '打印后行信息有变化,是否继续操作(报价编码会变新)?';
var isNewAddMonth = {!isNewAddMonth};
var Confirm_EstimateRefresh = '已超过创建日3个月,是否更新报价?';
window.sfdcPage.appendToOnloadQueue(function() { calonLoad() });
var RCbottonChanged = 0;
// 2022故障品加费 start
// var RCButtonDisable = document.getElementById("emailSend");
// RCButtonDisable.style.display = "none";
// 2022故障品加费 end
var hasSendEmail = {!hasSendEmail};
console.log('***hasSendEmail',hasSendEmail);
// if(hasSendEmail == true){
//     j$(escapeVfId('allPage:allForm:emailSend')).attr("disabled", true);
//     j$(escapeVfId('allPage:allForm:emailSend')).attr("class", 'btnDisabled');
//     console.log('已提交RC 按钮不可见');
// }
function approvalJs() {
    approvalDate = new Date();
    var rowCnt = j$(escapeVfId('allPage:allForm:allBlock:assetSection:productCnt')).val();
    refreshAsset(rowCnt);
}
//故障品加费 RC 点击后不可见
function rcJs() {
    hasSendEmail = true;
    j$(escapeVfId('allPage:allForm:emailSend')).attr("disabled", true);
    j$(escapeVfId('allPage:allForm:emailSend')).attr("class", 'btnDisabled');
    console.log('点击RC 按钮不可见hasSendEmail' +hasSendEmail);
}
//add by gwy 2021-01-27 start 提交时的提示框
function KindsAndMonths() {
   //   故障品加费 系统检查修理减价审批完成 Start
         ISReduced = j$(escapeVfId('allPage:allForm:allBlock:ISReducedpriceapproval')).val();
        console.log('点击提交待审批时 是否审批通过='+ISReduced);
        if( ISReduced == '审批中' || ISReduced == '有八折以下待审批'){
            alert('请通过修理减价审批再提交');
            // approvalbtntop1.style.display = "none";
            return false;
        }
    //   故障品加费 系统检查修理减价审批完成 end
    var months      = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:contract:monthRange')).val());
    var contrNew    = document.getElementById("allPage:allForm:allBlock:contractInfo:Contract_TypeTXT").innerHTML;
    if(months>12 && months<60 && contrNew == '新品合同'){
        if(confirm("本次您提交的报价为多年期新品合同,请您在正式提交报价前先将经销商与医院签订的多年期合同邮件发送服务本部报价窗口。若已经提交请点击确定,继续保存提交。")){
            return true;
        }else{
            return false;
        }
    }
    // 先款后修-提交报价时如果是先款对象进行提示 thh 20220408 start
    var FirstParagraphEnd = j$(escapeVfId('allPage:allForm:allBlock:contract:FirstParagraphEnd'))[0].checked;
    if(FirstParagraphEnd){
        if (confirm('本次签约经销商是先款对象,请确认是否提交报价?')) {
            return true;
        }else{
            return false;
        }
    }
    // 先款后修-提交报价时如果是先款对象进行提示 thh 20220408 end
    return true;
}
//add by gwy 2021-01-27 end 提交时的提示框
function unblockUI(){
    // 2021、8、26 合同报价页面的优化,无保有设备点检对象选择框变黑 fxk star
    // disable1();
    // 2021、8、26 合同报价页面的优化,无保有设备点检对象选择框变黑 fxk end
    pageSetDisabled();
    var isChange = j$(escapeVfId('allPage:allForm:changedSubmitPrice')).value();
    if (isChange=='true') {
        j$(escapeVfId('allPage:allForm:changedSubmitPrice')).val('false');
        var rowCnt = j$(escapeVfId('allPage:allForm:allBlock:assetSection:productCnt')).val();
        refreshAsset(rowCnt);
    }
    j$("#sbArea").fadeOut(500, function(){
        j$("#sbArea").remove();
    });
    console.log('发送邮件成功');
}
//<!-- HWAG-B4R3SS  START 20181026-->
function clearAndSearch() {
    document.getElementById("allPage:allForm:allBlock:text1").value = "";
    document.getElementById("allPage:allForm:allBlock:cond1").value = "equals";
    document.getElementById("allPage:allForm:allBlock:val1").value = "";
    blockme();
    searchfunc();
}
function searchJs() {
    blockme();
    searchfunc();
}
//<!-- HWAG-B4R3SS  END 20181026-->
// 初始化设定画面项目不可用
function pageSetDisabled(){
    // if (RCbottonChanged == 0) {
    //     console.log('test初始化');
        // 故障品加费 提交RC按钮不可见 start
        // j$(escapeVfId('allPage:allForm:emailSend')).attr("disabled", true);
        // j$(escapeVfId('allPage:allForm:emailSend')).attr("class", 'btnDisabled');
        // 故障品加费 提交RC按钮不可见 end
    // }
    // 故障品加费 start
    var hasSendEmail ={!hasSendEmail};
    console.log('page hasSendEmail',hasSendEmail);
    if(hasSendEmail == true){
        j$(escapeVfId('allPage:allForm:emailSend')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:emailSend')).attr("class", 'btnDisabled');
        console.log('已提交RC 按钮不可见 page set');
    }
    //故障品加费 end
    var isDisabled = {!PageDisabled};
    // ResonCannotWarranty = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':ResonCannotWarranty')).value();
    // if(!ResonCannotWarranty.contains("弃修")){
    //     j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Repair_Price_Auto')).attr("display", none);
    // }
    if (isDisabled) {
        j$(escapeVfId('allPage:allForm:allBlock:contract:depart')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contract:startdate')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contract:monthRange')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contract:estimateTarget')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contract:EndUserType')).attr("disabled", true);
        var rowCnt = {!productCount};
        for (var i = 0; i < rowCnt; i++) {
            // alert(11111111111111 +rowCnt);
            var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
            if (isManual == 'true') {
                var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Assert'));
                a.attr("disabled", true);
            }
            j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetCheck')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':comment')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Third_Party_Return__c')).attr("disabled", true);
        }
        j$(escapeVfId('allPage:allForm:allBlock:appendCondition:Examination_Count')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disPercent')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disMoney')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:discountReason')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:improveConsumptionRateIdea')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:quotation_Amount')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Appbackground:finalPriceDecideWay')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Appbackground:Sales_incidental')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Appbackground:mainTalksTime')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Appbackground:talksStartDate')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Appbackground:AgencyHos_Price')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Appbackground:discountReason')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:Appbackground:improveConsumptionRateIdea')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:contractstartdate')).attr("disabled", true);
        var target = j$(escapeVfId('allPage:allForm:allBlock:contract:estimateTarget')).val();
        if (target != '医院') {
            j$(escapeVfId('allPage:allForm:allBlock:contract:dealer')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:contract:FirstParagraphEnd')).attr("disabled", true);
        }
    }
    if ('{!DecideBtnDisabled}' == 'false') {
        j$(escapeVfId('allPage:allForm:contractstartdate')).attr("disabled", false);
    }
}
// 2021、8、26 合同报价页面的优化,无保有设备点检对象选择框变黑 fxk star
// function disable1(){
//     // alert(12312);
//     // addNewRows();
//     var isDisabled ;
//     var rowCnt = {!productCount}+{!productCount2};
//     if(isDisabled){
//         // alert(22222 + '444' +rowCnt);
//         for (var i = 0; i < rowCnt; i++) {
//             // 保有设备名
//             var assN = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:'+ i +':assetName')).text();
//             var assN1 = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:'+ i +':Assert')).val();
//             // alert('1234567'+assN +'----'+assN1);
//             if(!assN1 && !assN){
//                 // alert('23456789'+assN);
//                 j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetCheck'   )).attr("disabled", true);
//             }else{
//                 j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetCheck'   )).attr("disabled", false);
//             }
//         }
//     }
// }
// 2021、8、26 合同报价页面的优化,无保有设备点检对象选择框变黑 fxk end
var winOpenObj;
function closeWin(flg) {
    winOpenObj.close();
    if (flg==2) {
        window.location.href="/{!URLENCODE(estimate.Id)}/e?completion=2";
    }
}
function controlDisabled() {
    winOpenObj = window.open("/apex/ChangeDealerApproval?eid=" + '{!URLENCODE(estimate.Id)}','ChangeDealerApproval','height=300,width=700,toolbar=no,menubar=no,left=20%,top=30%,scrollbars=yes,resizable=no,location=no,status=no');
}
// 見積もり作成後、3ヶ月以内であれば見積もりの内容を継続使用可能
function calonLoad() {
    // 2021、8、26 合同报价页面的优化,无保有设备点检对象选择框变黑 fxk star
    // disable1();
    // 2021、8、26 合同报价页面的优化,无保有设备点检对象选择框变黑 fxk end
    console.log('ApprovalBtnDisabled=='+{!ApprovalBtnDisabled});
    pageSetDisabled();
    var createdDate = new Date('{!estimate.CreatedDate}');
    // 报价中设备的机身编码为空时的新品合同有效期延长 20200710 gzw
    var aLLManual = 'true';
    var cntWithKara = {!productCount};
    for (var i = 0; i < cntWithKara; i++) {
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        if (isManual != 'true') {
            aLLManual = 'false';
            break;
        }
    }
    var nowDate = new Date();
    if (aLLManual == 'false') {
        createdDate = createdDate.setMonth(createdDate.getMonth() + 3);
        // FIX liang JSの時間って addMonthsないですか? そかも 1/1 なら、 4/1もだめですよ。
        if (createdDate < Date.parse(nowDate)) {
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:savebtntop')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:saveAndCancelBtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:approvalbtntop')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:savebtntop')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:saveAndCancelBtn')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:approvalbtntop')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:savebtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:approvalbtn')).attr("disabled", true);
            // 最初は、Decideの同時に保存もあります、それを防ぐため、保存とDecideを同時に無効にする
            // 考えてみると、クラスにDecideの判断があり、Decideの時明細変更チェックもあります、3ヶ月のチェックもあります、ここで無効にする意味がありません
            //j$(escapeVfId('allPage:allForm:decidebtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:savebtn')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:approvalbtn')).attr("class", 'btnDisabled');
            //故障品加费 RC按钮
            j$(escapeVfId('allPage:allForm:emailSend')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:emailSend')).attr("class", 'btnDisabled');
            //j$(escapeVfId('allPage:allForm:decidebtn')).attr("class", 'btnDisabled');
            if (confirm(Confirm_EstimateRefresh)) {
                window.location.href="/apex/SelectAssetEstimateVM?copyid={!URLENCODE(targetEstimateId)}";
                return true;
            } else {
                if ('{!DecideBtnDisabled}' == 'false') {
                    // decide可能の場合、別途decideのチェックが必要、
                    // チェック後再度画面refreshされるため、decide可能の場合、decideボタンが使えるようになります。
                    changeContractStartdate('{!estimate.Contract_Start_Date__c}');
                }
                return false;
            }
        }
    }else{
        createdDate = createdDate.setMonth(createdDate.getMonth() + 6);
        // FIX liang JSの時間って addMonthsないですか? そかも 1/1 なら、 4/1もだめですよ。
        if (createdDate < Date.parse(nowDate)) {
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:savebtntop')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:saveAndCancelBtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:approvalbtntop')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:savebtntop')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:saveAndCancelBtn')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:approvalbtntop')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:savebtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:approvalbtn')).attr("disabled", true);
            // 最初は、Decideの同時に保存もあります、それを防ぐため、保存とDecideを同時に無効にする
            // 考えてみると、クラスにDecideの判断があり、Decideの時明細変更チェックもあります、3ヶ月のチェックもあります、ここで無効にする意味がありません
            //j$(escapeVfId('allPage:allForm:decidebtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:savebtn')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:approvalbtn')).attr("class", 'btnDisabled');
            //故障品加费RC按钮
            j$(escapeVfId('allPage:allForm:emailSend')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:emailSend')).attr("class", 'btnDisabled');
            //j$(escapeVfId('allPage:allForm:decidebtn')).attr("class", 'btnDisabled');
            if (confirm('已超过创建日6个月,是否更新报价?')) {
                window.location.href="/apex/SelectAssetEstimateVM?copyid={!URLENCODE(targetEstimateId)}";
                return true;
            } else {
                if ('{!DecideBtnDisabled}' == 'false') {
                    // decide可能の場合、別途decideのチェックが必要、
                    // チェック後再度画面refreshされるため、decide可能の場合、decideボタンが使えるようになります。
                    changeContractStartdate('{!estimate.Contract_Start_Date__c}');
                }
                return false;
            }
        }
    }
    if ('{!DecideBtnDisabled}' == 'false') {
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:oldMainteReal')).val(j$(escapeVfId('allPage:allForm:allBlock:contractInfo:mainteReal')).text());
    }
}
function checkAll(checker) {
    var cnt = j$(escapeVfId('allPage:allForm:allBlock:assetSection:productCnt')).val();
    debugger;
    for (var i = 0; i < cnt; i++) {
        //2021-11-30 fy add LJPH-C8W8FV 置顶 start
        if (j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetRowCheckbox')).size() == 0) {
            continue;
        }else{
            document.getElementById('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetRowCheckbox').checked = checker.checked;
        }
        //2021-11-30 fy add LJPH-C8W8FV 置顶 end
    }
}
function checkAll2(checker) {
    var cnt2 = j$(escapeVfId('allPage:allForm:allBlock:assetSection2:productCnt2')).val();
    var outer = 0;
    for (var i = 0; i < cnt2; i++) {
        outer = Math.floor(i / 1000);
        if (document.getElementById('allPage:allForm:allBlock:assetSection2:outassetTable2:' + outer +':assetTable2:' + (i-(1000*outer)) + ':assetRowCheckbox2').disabled == false) {
            document.getElementById('allPage:allForm:allBlock:assetSection2:outassetTable2:' + outer +':assetTable2:' + (i-(1000*outer)) + ':assetRowCheckbox2').checked = checker.checked;
        }
    }
}
function checkDiscount(val) {
    if (val == null || val == "") {
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:quotation_Amount')).val("");
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:discount_Rate')).text("");
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:discount_RateHidden')).val(0.00);
        return;
    }
    if (isNaN(parseInt(val))) {
        alert("请输入数值");
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:quotation_Amount')).val(0.00);
        return;
    }
    val = localParseFloat(val);
    //val = Math.round(val * 100) / 100;
    val = Math.round(val);
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:quotation_Amount')).val(toNumComma(val));
   makeRealPrice(1);
}
function checkContractRange(val, cnt) {
    if (isNaN(parseInt(val))) {
        alert("必须输入合同月数!");
        j$(escapeVfId('allPage:allForm:allBlock:contract:monthRange')).val("");
        return;
    }
    if (val <= 0) {
        alert("合同月数必须大于0");
        j$(escapeVfId('allPage:allForm:allBlock:contract:monthRange')).val("");
        return;
    }
    if (val > 60) {
        alert("合同期最长只能选择60个月!");
        j$(escapeVfId('allPage:allForm:allBlock:contract:monthRange')).val("");
        return;
    }
    // HWAG-BA73ZP
    //contractStartDateChange();
    refreshAsset(cnt);
}
function toChange1(){
    tochange();
    ISReducedpriceapproval = j$(escapeVfId('allPage:allForm:allBlock:ISReducedpriceapproval')).val();
    console.log('方法1是否审批通过=='+ISReducedpriceapproval+'====================');
}
function toChange2(){
    tochange2();
    ISReducedpriceapproval = j$(escapeVfId('allPage:allForm:allBlock:ISReducedpriceapproval')).val();
    console.log('方法2是否审批通过=='+ISReducedpriceapproval+'==============');
}
function refreshAsset(cnt) {
     // alert(cnt);
    // 提交后就页面不计算了
    var isDisabled = {!PageDisabled};
    // 合同总理
    var newCount = 0;
    var isresduce = 0;
    var oyearCount = 0;
    var firstCCount = 0;
    var conCCount = 0;
    // row金額合計
    var repairSum = 0;
    var listSum = 0;
    // 新品合同 判断
    var newCon = true;
    var contractStartDate = new Date(j$(escapeVfId('allPage:allForm:contractstartdate')).value());
    //上限合同 20230103 LY start
    // var mainteReal = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:mainteReal')).text();
    // Limit_Price_Amount = localParseFloat(mainteReal)*1.3;
    // console.log('Limit_Price_Amount'+Limit_Price_Amount);
    // j$(escapeVfId('allPage:allForm:allBlock:contractInfo:Limit_Price_Amount')).val(Limit_Price_Amount);
    //上限合同 20230103 LY end
    //多年保续签合同数量 thh 20220316 start
    var GuranteeCount = 0;
    //多年保续签合同数量 thh 20220316 end
    //2022故障品加费 获取userInfo简档名称 是否为FSE start
    var isFSE = {!isFSE};
    // var isFSE = true;
    console.log('***isFSE',isFSE);
    //2022故障品加费 获取userInfo简档名称 end
    // 预定开始日
    var startdate = new Date(j$(escapeVfId('allPage:allForm:allBlock:contract:startdate')).value());
    // 预定开始日-6个月
    startdate.setMonth(startdate.getMonth() - 6);
    // 申请日 当前日期
    if(approvalDate != ''){
        //申请日
        approvalDate = new Date(approvalDate.toLocaleDateString());
        if (Date.parse(approvalDate) < Date.parse(startdate)) {
            newCon = false;
        }
    }
    // 最高、最低价格合计
    var downPriceSum = 0;
    var upPriceSum = 0;
    // 合同月数乗算
    var month = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:contract:monthRange')).val());
    if (month == undefined || month == "") {
        month = 1;
    }
    var month2 = 0;
    if (month > 12) {
        month2 = month - 12;
        month = 12;
    }
    for (var i = 0; i < cnt; i++) {
        var strMoney = 0;
        var repairMoney = 0;
        // 行项目 最高、最低价格合计
        // 续签价格取联动价格页面计算,首签或产品取 实际价格
        // 下线价格
        var downPrice = 0;
        // 上线价格
        var upPrice = 0;
        // 12个月合同金额
        var Price_YearTXT = 0;
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        var isnew = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNewHidden')).val();
        var assetListmonth = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val();
        if (isManual == 'true') {
            var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Assert')).value();
            if (a != '') {
                // 所有设备按安装日、发货日(最早的),距离合同开始日6个月内都是新品合同
                //var isNewDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':isNewDate')).value());
                //isNewDate.setMonth(isNewDate.getMonth() + 6);
                //if (Date.parse(contractStartDate) > Date.parse(isNewDate)) {
                //    newCon = false;
                //}
                strMoney = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val();
                // alert(strMoney);
                Price_YearTXT = strMoney * 12;
                if (isnew == 'true') {
                    newCount ++;
                    strMoney = month * strMoney + month2 * strMoney / {!isNewPriceAdj};
                } else {
                    newCon = false;
                    strMoney = month * strMoney + month2 * strMoney;
                }
                var b = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Contract_No')).value();
                var LastMContractRecord = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':LastMContractRecord')).value();
                if(b != ''){
                    conCCount ++;
                    // 1.合同期不满一年时,合同期超过一半才可开始续签报价。(eg:11个月的合同从6个月后才可报价。)
                    // 2.一年以上的合同,在结束前6个月开始可以开放续签报价。
                    var lastendDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':End_Date')).value());
                    var lastContRange = 0;
                    if(LastMContractRecord == 'VM_Contract'){
                        newCount++;
                        //多年保续签合同数量,多年保续签到服务合同时视为首签设备 thh 20220316 start
                        GuranteeCount++;
                        newCon = false;
                        //多年保续签合同数量,多年保续签到服务合同时视为首签设备 thh 20220316 end
                        lastendDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':endDateGurantee_Text')).value());
                        lastContRange = 36;
                    }else{
                        lastContRange = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':lastContRange')).value();
                    }
                    //最后结束日+1年
                    lastendDate.setMonth(lastendDate.getMonth() + 12);
                    if (Date.parse(contractStartDate) > Date.parse(lastendDate) ) {
                        oyearCount ++;
                    }
                    // 取联动价格
                    // 上一期合同实际报价月额
                    //
                    var LastMContract_Price = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':LastMContract_Price')).val());
                    var Adjustment_ratio_Lower = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_ratio_Lower')).val());
                    var Adjustment_ratio_Upper = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_ratio_Upper')).val());
                    //计算惩罚率
                    var Punish = calculateNtoMRatio( lastContRange,(month + month2));
                    if(Punish == 0){
                        return;
                    }
                    // 判断有无报价:没有按照标准价格实际联动
                    var Estimate_Num = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Estimate_NumHidden')).val();
                    if(Estimate_Num == 0){
                        if(LastMContractRecord == 'VM_Contract'){
                            // gzw 20220630  实际联动6个月价格区分
                            var nowdate = new Date();
                            lastendDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':endDateGurantee_Text')).value());
                            nowdate = nowdate.setMonth(nowdate.getMonth() + 6);
                            if(nowdate < Date.parse(lastendDate)){
                                upPrice = strMoney;
                                downPrice = strMoney * 0.8;
                            }else{
                                upPrice = (assetListmonth * Punish) * (1 + Adjustment_ratio_Upper/100);
                                downPrice = (assetListmonth * Punish) * (1 + Adjustment_ratio_Lower/100);
                            }
                            // gzw 20220630  实际联动6个月价格区分
                        }else{
                            upPrice = strMoney;
                            downPrice = strMoney * 0.8;
                        }
                    }else{
                        upPrice = (LastMContract_Price * Punish) * (1 + Adjustment_ratio_Upper/100);
                        downPrice = (LastMContract_Price * Punish) * (1 + Adjustment_ratio_Lower/100);
                    }
                }else{
                    //firstCCount ++;
                    upPrice = strMoney;
                    downPrice = strMoney * 0.8;
                }
                // 上下限四舍五入
                upPrice = upPrice.toFixed(2);
                downPrice = downPrice.toFixed(2);
                // 12个月合同金额
                //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceTXT')).text(toNumComma(Price_YearTXT));
                //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceTXTHidden')).val(Price_YearTXT);
                if (!isDisabled) {
                    // 实际联动价格 start
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Lower_price')).text(toNumComma(downPrice));
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Lower_priceHidden')).val(downPrice);
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Upper_price')).text(toNumComma(upPrice));
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Upper_priceHidden')).val(upPrice);
                    // 实际联动价格 end
                }
                //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPrice')).text(toNumComma(strMoney));
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPricePageHidden')).val(strMoney);
                repairMoney = j$.trim(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).value());
            } else {
                // TODO 一時的な対応、なんで別行の金額リフレッシュされた?
                //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPrice')).text("");
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPricePageHidden')).val();
                // 12个月合同金额
                //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceTXT')).text("");
                //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceTXTHidden')).val();
                if (!isDisabled) {
                    // 实际联动价格 start
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Lower_price')).text("");
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Lower_priceHidden')).val();
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Upper_price')).text("");
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Upper_priceHidden')).val();
                    // 实际联动价格 end
                 }
            }
        }
        else {
            // 所有设备按安装日、发货日(最早的),距离合同开始日6个月内都是新品合同
            var isNewDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':isNewDate')).value());
            isNewDate.setMonth(isNewDate.getMonth() + 6);
            if (Date.parse(contractStartDate) > Date.parse(isNewDate)) {
                newCon = false;
            }
            strMoney = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val();
            Price_YearTXT = strMoney * 12;
            if (isnew == 'true') {
                strMoney = month * strMoney + month2 * strMoney / {!isNewPriceAdj};
            } else {
                strMoney = month * strMoney + month2 * strMoney;
            }
            var b = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Contract_No')).value();
            var LastMContractRecord = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':LastMContractRecord')).value();
            if(b != ''){
                conCCount ++;
                // 1.合同期不满一年时,合同期超过一半才可开始续签报价。(eg:11个月的合同从6个月后才可报价。)
                // 2.一年以上的合同,在结束前6个月开始可以开放续签报价。
                var lastendDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':End_Date')).value());
                var lastContRange = 0;
                if(LastMContractRecord == 'VM_Contract'){
                    newCount++;
                    //多年保续签合同数量,多年保续签到服务合同时视为首签设备 thh 20220316 start
                    GuranteeCount++;
                    newCon = false;
                    //多年保续签合同数量,多年保续签到服务合同时视为首签设备 thh 20220316 end
                    lastendDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':endDateGurantee_Text')).value());
                    lastContRange = 36;
                }else{
                    lastContRange = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':lastContRange')).value();
                }
                //最后结束日+1年
                lastendDate.setMonth(lastendDate.getMonth() + 12);
                // alert('+++++++++--------' + lastendDate);
                // alert('+++++++++--------' + Date.parse(contractStartDate) + '77777' + Date.parse(lastendDate));
                if (Date.parse(contractStartDate) > Date.parse(lastendDate)) {
                    oyearCount ++;
                }
                // 取联动价格
                // 上一期合同实际报价月额
                //
                var LastMContract_Price = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':LastMContract_Price')).val());
                var Adjustment_ratio_Lower = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_ratio_Lower')).val());
                var Adjustment_ratio_Upper = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_ratio_Upper')).val());
                //计算惩罚率
                var Punish = calculateNtoMRatio( lastContRange,(month + month2));
                if(Punish == 0){
                    return;
                }
                // 判断有无报价:没有按照标准价格实际联动
                var Estimate_Num = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Estimate_NumHidden')).val();
                if(Estimate_Num == 0){
                    if(LastMContractRecord == 'VM_Contract'){
                        // alert('11111');
                        // gzw 20220630  实际联动6个月价格区分
                        var nowdate = new Date();
                        lastendDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':endDateGurantee_Text')).value());
                        nowdate = nowdate.setMonth(nowdate.getMonth() + 6);
                        if(nowdate < Date.parse(lastendDate)){
                            upPrice = strMoney;
                            downPrice = strMoney * 0.8;
                        }else{
                            upPrice = (assetListmonth * Punish) * (1 + Adjustment_ratio_Upper/100);
                            downPrice = (assetListmonth * Punish) * (1 + Adjustment_ratio_Lower/100);
                        }
                        // gzw 20220630  实际联动6个月价格区分
                    }else{
                        upPrice = strMoney;
                        downPrice = strMoney * 0.8;
                    }
                }else{
                    upPrice = (LastMContract_Price * Punish) * (1 + Adjustment_ratio_Upper/100);
                    downPrice = (LastMContract_Price * Punish) * (1 + Adjustment_ratio_Lower/100);
                }
            }else{
                if (isnew == 'true') {
                    newCount ++;
                } else {
                    newCon = false;
                    firstCCount ++;
                }
                upPrice = strMoney;
                downPrice = strMoney * 0.8;
            }
            // 上下限四舍五入
            upPrice = upPrice.toFixed(2);
            downPrice = downPrice.toFixed(2);
            // 12个月合同金额
            //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceTXT')).text(toNumComma(Price_YearTXT));
            //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceTXTHidden')).val(Price_YearTXT);
            if (!isDisabled) {
                // 实际联动价格 start
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Lower_price')).text(toNumComma(downPrice));
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Lower_priceHidden')).val(downPrice);
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Upper_price')).text(toNumComma(upPrice));
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Upper_priceHidden')).val(upPrice);
                // 实际联动价格 end
            }
            //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPrice')).text(toNumComma(strMoney));
            j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPricePageHidden')).val(strMoney);
            //<!-- (2022年12月上线)故障品加费 start -->
            Repair_Price_AutoPrice = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Repair_Price_Auto'));
            Repair_Price_Auto = Repair_Price_AutoPrice.value();
            repairMoney = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).value();
            Repair_Price_pass = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Repair_Price_pass')).val();
            console.log((i+1)+'号repairMoney='+repairMoney);
            console.log((i+1)+'号Repair_Price_Auto='+Repair_Price_Auto);
            if ((repairMoney+1)==1) {
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).val(Repair_Price_Auto);
                console.log('repairMoney修改成功');
            }
            if ((Repair_Price_pass+1)==1) {
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Repair_Price_pass')).val(Repair_Price_Auto);
                console.log('Repair_Price_pass修改成功');
            }
            repairMoney1 = localParseFloat(repairMoney);
            ISReducedpriceapproval = j$(escapeVfId('allPage:allForm:allBlock:ISReducedpriceapproval')).val();
            console.log('ISReducedpriceapproval=='+ISReducedpriceapproval);
            if (ISReducedpriceapproval =='有八折以下待审批' || ISReducedpriceapproval =='是') {
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).attr("disabled", true);
            }else{
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).attr("disabled", false);
            }
            ISReducedpriceapproval1 = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':ISReducedpriceapproval1')).val();
            ISReduced = j$(escapeVfId('allPage:allForm:allBlock:ISReducedpriceapproval')).val();
            if (repairMoney1> 0 && (repairMoney1 <Repair_Price_Auto*0.80)) {
                isresduce = isresduce+1;
            }
            console.log('初始化isresduce='+isresduce);
            ResonCannotWarranty = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':ResonCannotWarranty')).value();
            rppa =  document.getElementById('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Repair_Price_Auto');
            situation = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Asset_situation')).value();
            // Agreed_Date =  j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Agreed_Date')).value();
            console.log('situation='+situation);
            // console.log('Agreed_Date1='+Agreed_Date);
            if(!(ResonCannotWarranty.indexOf("弃修") != -1)&&(repairMoney+1)==1){
                    rppa.style.display = "none";
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).val('');
                    console.log('###修改成功');
            }
            console.log('判断1'+(situation.indexOf("修理中")!=-1));
            // console.log('判断'+(Agreed_Date.indexOf("不为空")!=-1));
            // if ((situation.indexOf("修理中")!=-1)&& (Agreed_Date.indexOf("不为空")!=-1)) {
            //     console.log('开始操作2');
            //     j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Repair_Price_Auto')).val(0);
            //     j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).val(0);
            // }
        //<!-- (2022年12月上线)故障品加费 end -->
        }
        repairSum = repairSum + localParseFloat(repairMoney);
        listSum = listSum + localParseFloat(toNum(strMoney));
        downPriceSum = downPriceSum + localParseFloat(toNum(downPrice));
        upPriceSum =  upPriceSum + localParseFloat(toNum(upPrice));
    }
    j$(escapeVfId('allPage:allForm:allBlock:assetRepairSumNum')).text(toNumComma(repairSum));
    //j$(escapeVfId('allPage:allForm:allBlock:assetListSumNum')).text(toNumComma(listSum));
    //j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetSumPrice')).text(toNumComma(listSum));
    //j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetSumPriceHidden')).val(toNum(listSum));
    if (!isDisabled) {
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:GuidePriceUp')).text(toNumComma(Math.round(upPriceSum)));
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:GuidePriceUpHidden')).val(toNum(Math.round(upPriceSum)));
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:GuidePriceDown')).text(toNumComma(Math.round(downPriceSum)));
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:GuidePriceDownHidden')).val(toNum(Math.round(downPriceSum)));
    }
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetRepairSumPrice')).text(toNumComma(repairSum));
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetRepairSumPriceHidden')).val(toNum(repairSum));
    var allcount = j$(escapeVfId('allPage:allForm:allBlock:productCount3')).value();
    var result = '';
    if (allcount == 0) {
        result = null;
    //如果所有设备的上期合同都是多年保合同,则合同种类为市场多年保续签合同 thh 20220315 start
    }else if(GuranteeCount > 0 && GuranteeCount == allcount){
        result = '市场多年保续签合同';
    //如果所有设备的上期合同都是多年保合同,则合同种类为市场多年保续签合同 thh 20220315 end
    }else if (newCount > 0 && newCount == allcount && newCon == true) {
        result = '新品合同';
    }else if (((newCount > 0 && newCount == allcount) ||(newCount + firstCCount == allcount)) && newCon == false) {
        result = '首签合同';
    }else if(firstCCount > 0 && firstCCount == allcount){
        result = '首签合同';
    // 20220328 ljh update  LJPH-C8FB4P【委托】配合PBI设备覆盖率的数据准备 start
    // }else if(oyearCount > 0 && oyearCount == conCCount){
    }else if(oyearCount > 0 && oyearCount == conCCount && allcount == oyearCount ){
    // 20220328 ljh update  LJPH-C8FB4P【委托】配合PBI设备覆盖率的数据准备 start
        result = '非续签合同(空白期一年以上)';
    }else{
        result = '续签合同';
    }
    console.log(result);
    document.getElementById("allPage:allForm:allBlock:contractInfo:Contract_TypeTXT").innerHTML = result;
    document.getElementById("allPage:allForm:allBlock:contractInfo:Contract_TypeTXTHidden").value = result;
    // 取消酸化水
    //NotUseOxygenatedWaterAmount(1);
    examinationPriceCal(cnt);
    getLastContractRate();
}
function changeAsset(cnt) {
    // alert(cnt);
    // 提交后就页面不计算了
    var isDisabled = {!PageDisabled};
    // 合同总理
    var newCount = 0;
    var isresduce = 0;
    var oyearCount = 0;
    var firstCCount = 0;
    var conCCount = 0;
    // row金額合計
    var repairSum = 0;
    var listSum = 0;
    // 新品合同 判断
    var newCon = true;
    var contractStartDate = new Date(j$(escapeVfId('allPage:allForm:contractstartdate')).value());
    //多年保续签合同数量 thh 20220316 start
    var GuranteeCount = 0;
    //多年保续签合同数量 thh 20220316 end
    //2022故障品加费 获取userInfo简档名称 是否为FSE start
    var isFSE = {!isFSE};
    // var hasSendEmail = {!hasSendEmail};
    // var isFSE = true;
    console.log('***isFSE',isFSE);
    // console.log('***hasSendEmail',hasSendEmail);
    // if(hasSendEmail == true){
    //     j$(escapeVfId('allPage:allForm:emailSend')).attr("disabled", true);
    //     j$(escapeVfId('allPage:allForm:emailSend')).attr("class", 'btnDisabled');
    //     console.log('8折以下提交RC可见 ');
    // }
    //2022故障品加费 获取userInfo简档名称 end
    // 预定开始日
    var startdate = new Date(j$(escapeVfId('allPage:allForm:allBlock:contract:startdate')).value());
    // 预定开始日-6个月
    startdate.setMonth(startdate.getMonth() - 6);
    // 申请日 当前日期
    if(approvalDate != ''){
        //申请日
        approvalDate = new Date(approvalDate.toLocaleDateString());
        if (Date.parse(approvalDate) < Date.parse(startdate)) {
            newCon = false;
        }
    }
    // 最高、最低价格合计
    var downPriceSum = 0;
    var upPriceSum = 0;
    // 合同月数乗算
    var month = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:contract:monthRange')).val());
    if (month == undefined || month == "") {
        month = 1;
    }
    var month2 = 0;
    if (month > 12) {
        month2 = month - 12;
        month = 12;
    }
    for (var i = 0; i < cnt; i++) {
        var strMoney = 0;
        var repairMoney = 0;
        // 行项目 最高、最低价格合计
        // 续签价格取联动价格页面计算,首签或产品取 实际价格
        // 下线价格
        var downPrice = 0;
        // 上线价格
        var upPrice = 0;
        // 12个月合同金额
        var Price_YearTXT = 0;
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        var isnew = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNewHidden')).val();
        var assetListmonth = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val();
        if (isManual == 'true') {
            var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Assert')).value();
            if (a != '') {
                // 所有设备按安装日、发货日(最早的),距离合同开始日6个月内都是新品合同
                //var isNewDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':isNewDate')).value());
                //isNewDate.setMonth(isNewDate.getMonth() + 6);
                //if (Date.parse(contractStartDate) > Date.parse(isNewDate)) {
                //    newCon = false;
                //}
                strMoney = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val();
                // alert(strMoney);
                Price_YearTXT = strMoney * 12;
                if (isnew == 'true') {
                    newCount ++;
                    strMoney = month * strMoney + month2 * strMoney / {!isNewPriceAdj};
                } else {
                    newCon = false;
                    strMoney = month * strMoney + month2 * strMoney;
                }
                var b = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Contract_No')).value();
                var LastMContractRecord = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':LastMContractRecord')).value();
                if(b != ''){
                    conCCount ++;
                    // 1.合同期不满一年时,合同期超过一半才可开始续签报价。(eg:11个月的合同从6个月后才可报价。)
                    // 2.一年以上的合同,在结束前6个月开始可以开放续签报价。
                    var lastendDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':End_Date')).value());
                    var lastContRange = 0;
                    if(LastMContractRecord == 'VM_Contract'){
                        newCount++;
                        //多年保续签合同数量,多年保续签到服务合同时视为首签设备 thh 20220316 start
                        GuranteeCount++;
                        newCon = false;
                        //多年保续签合同数量,多年保续签到服务合同时视为首签设备 thh 20220316 end
                        lastendDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':endDateGurantee_Text')).value());
                        lastContRange = 36;
                    }else{
                        lastContRange = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':lastContRange')).value();
                    }
                    //最后结束日+1年
                    lastendDate.setMonth(lastendDate.getMonth() + 12);
                    if (Date.parse(contractStartDate) > Date.parse(lastendDate) ) {
                        oyearCount ++;
                    }
                    // 取联动价格
                    // 上一期合同实际报价月额
                    //
                    var LastMContract_Price = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':LastMContract_Price')).val());
                    var Adjustment_ratio_Lower = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_ratio_Lower')).val());
                    var Adjustment_ratio_Upper = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_ratio_Upper')).val());
                    //计算惩罚率
                    var Punish = calculateNtoMRatio( lastContRange,(month + month2));
                    if(Punish == 0){
                        return;
                    }
                    // 判断有无报价:没有按照标准价格实际联动
                    var Estimate_Num = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Estimate_NumHidden')).val();
                    if(Estimate_Num == 0){
                        if(LastMContractRecord == 'VM_Contract'){
                            // gzw 20220630  实际联动6个月价格区分
                            var nowdate = new Date();
                            lastendDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':endDateGurantee_Text')).value());
                            nowdate = nowdate.setMonth(nowdate.getMonth() + 6);
                            if(nowdate < Date.parse(lastendDate)){
                                upPrice = strMoney;
                                downPrice = strMoney * 0.8;
                            }else{
                                upPrice = (assetListmonth * Punish) * (1 + Adjustment_ratio_Upper/100);
                                downPrice = (assetListmonth * Punish) * (1 + Adjustment_ratio_Lower/100);
                            }
                            // gzw 20220630  实际联动6个月价格区分
                        }else{
                            upPrice = strMoney;
                            downPrice = strMoney * 0.8;
                        }
                    }else{
                        upPrice = (LastMContract_Price * Punish) * (1 + Adjustment_ratio_Upper/100);
                        downPrice = (LastMContract_Price * Punish) * (1 + Adjustment_ratio_Lower/100);
                    }
                }else{
                    //firstCCount ++;
                    upPrice = strMoney;
                    downPrice = strMoney * 0.8;
                }
                // 上下限四舍五入
                upPrice = upPrice.toFixed(2);
                downPrice = downPrice.toFixed(2);
                // 12个月合同金额
                //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceTXT')).text(toNumComma(Price_YearTXT));
                //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceTXTHidden')).val(Price_YearTXT);
                if (!isDisabled) {
                    // 实际联动价格 start
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Lower_price')).text(toNumComma(downPrice));
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Lower_priceHidden')).val(downPrice);
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Upper_price')).text(toNumComma(upPrice));
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Upper_priceHidden')).val(upPrice);
                    // 实际联动价格 end
                }
                //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPrice')).text(toNumComma(strMoney));
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPricePageHidden')).val(strMoney);
                repairMoney = j$.trim(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).value());
            } else {
                // TODO 一時的な対応、なんで別行の金額リフレッシュされた?
                //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPrice')).text("");
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPricePageHidden')).val();
                // 12个月合同金额
                //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceTXT')).text("");
                //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceTXTHidden')).val();
                if (!isDisabled) {
                    // 实际联动价格 start
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Lower_price')).text("");
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Lower_priceHidden')).val();
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Upper_price')).text("");
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Upper_priceHidden')).val();
                    // 实际联动价格 end
                 }
            }
        }
        else {
            // 所有设备按安装日、发货日(最早的),距离合同开始日6个月内都是新品合同
            var isNewDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':isNewDate')).value());
            isNewDate.setMonth(isNewDate.getMonth() + 6);
            if (Date.parse(contractStartDate) > Date.parse(isNewDate)) {
                newCon = false;
            }
            strMoney = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val();
            Price_YearTXT = strMoney * 12;
            if (isnew == 'true') {
                strMoney = month * strMoney + month2 * strMoney / {!isNewPriceAdj};
            } else {
                strMoney = month * strMoney + month2 * strMoney;
            }
            var b = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Contract_No')).value();
            var LastMContractRecord = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':LastMContractRecord')).value();
            if(b != ''){
                conCCount ++;
                // 1.合同期不满一年时,合同期超过一半才可开始续签报价。(eg:11个月的合同从6个月后才可报价。)
                // 2.一年以上的合同,在结束前6个月开始可以开放续签报价。
                var lastendDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':End_Date')).value());
                var lastContRange = 0;
                if(LastMContractRecord == 'VM_Contract'){
                    newCount++;
                    //多年保续签合同数量,多年保续签到服务合同时视为首签设备 thh 20220316 start
                    GuranteeCount++;
                    newCon = false;
                    //多年保续签合同数量,多年保续签到服务合同时视为首签设备 thh 20220316 end
                    lastendDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':endDateGurantee_Text')).value());
                    lastContRange = 36;
                }else{
                    lastContRange = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':lastContRange')).value();
                }
                //最后结束日+1年
                lastendDate.setMonth(lastendDate.getMonth() + 12);
                // alert('+++++++++--------' + lastendDate);
                // alert('+++++++++--------' + Date.parse(contractStartDate) + '77777' + Date.parse(lastendDate));
                if (Date.parse(contractStartDate) > Date.parse(lastendDate)) {
                    oyearCount ++;
                }
                // 取联动价格
                // 上一期合同实际报价月额
                //
                var LastMContract_Price = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':LastMContract_Price')).val());
                var Adjustment_ratio_Lower = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_ratio_Lower')).val());
                var Adjustment_ratio_Upper = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_ratio_Upper')).val());
                //计算惩罚率
                var Punish = calculateNtoMRatio( lastContRange,(month + month2));
                if(Punish == 0){
                    return;
                }
                // 判断有无报价:没有按照标准价格实际联动
                var Estimate_Num = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Estimate_NumHidden')).val();
                if(Estimate_Num == 0){
                    if(LastMContractRecord == 'VM_Contract'){
                        // alert('11111');
                        // gzw 20220630  实际联动6个月价格区分
                        var nowdate = new Date();
                        lastendDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':endDateGurantee_Text')).value());
                        nowdate = nowdate.setMonth(nowdate.getMonth() + 6);
                        if(nowdate < Date.parse(lastendDate)){
                            upPrice = strMoney;
                            downPrice = strMoney * 0.8;
                        }else{
                            upPrice = (assetListmonth * Punish) * (1 + Adjustment_ratio_Upper/100);
                            downPrice = (assetListmonth * Punish) * (1 + Adjustment_ratio_Lower/100);
                        }
                        // gzw 20220630  实际联动6个月价格区分
                    }else{
                        upPrice = strMoney;
                        downPrice = strMoney * 0.8;
                    }
                }else{
                    upPrice = (LastMContract_Price * Punish) * (1 + Adjustment_ratio_Upper/100);
                    downPrice = (LastMContract_Price * Punish) * (1 + Adjustment_ratio_Lower/100);
                }
            }else{
                if (isnew == 'true') {
                    newCount ++;
                } else {
                    newCon = false;
                    firstCCount ++;
                }
                upPrice = strMoney;
                downPrice = strMoney * 0.8;
            }
            // 上下限四舍五入
            upPrice = upPrice.toFixed(2);
            downPrice = downPrice.toFixed(2);
            // 12个月合同金额
            //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceTXT')).text(toNumComma(Price_YearTXT));
            //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceTXTHidden')).val(Price_YearTXT);
            if (!isDisabled) {
                // 实际联动价格 start
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Lower_price')).text(toNumComma(downPrice));
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Lower_priceHidden')).val(downPrice);
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Upper_price')).text(toNumComma(upPrice));
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Upper_priceHidden')).val(upPrice);
                // 实际联动价格 end
            }
            //j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPrice')).text(toNumComma(strMoney));
            j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPricePageHidden')).val(strMoney);
            //<!-- (2022年12月上线)故障品加费 start -->
            Repair_Price_AutoPrice = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Repair_Price_Auto'));
            Repair_Price_Auto = Repair_Price_AutoPrice.value();
            repairMoney = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).value();
            // console.log('repairMoney='+repairMoney);
            repairMoney1 = localParseFloat(repairMoney);
            ISReducedpriceapproval1 = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':ISReducedpriceapproval1')).val();
            ISReduced = j$(escapeVfId('allPage:allForm:allBlock:ISReducedpriceapproval')).val();
            console.log('ISReduced='+ISReduced);
            console.log('Repair_Price_Auto='+Repair_Price_Auto);
            console.log('第'+(i+1)+'个设备ISReducedpriceapproval1='+ISReducedpriceapproval1);
            console.log('repairMoney1='+repairMoney1);
            Repair_Price_pass1 = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Repair_Price_pass')).val();
            Repair_Price_pass2 = localParseFloat(Repair_Price_pass1);
            console.log('结果='+(repairMoney1<Repair_Price_pass2));
            console.log('Repair_Price_pass2='+Repair_Price_pass2);
            if (repairMoney1> 0 && repairMoney1<(Repair_Price_Auto*0.80) && Repair_Price_Auto != null && isFSE == true) {
                 if (Repair_Price_pass1!=null && repairMoney1<Repair_Price_pass2) {
                    alert('由于存在折扣率超过20%以上的修理加费减价申请,请先点击“提交RC评估”按钮,待RC评估后服务管理部会推进审批');
                        // j$(escapeVfId('allPage:allForm:emailSend')).attr("disabled", false);
                        // j$(escapeVfId('allPage:allForm:emailSend')).attr("class", 'btn');
                    // RCbottonChanged = 1;
                    // var change_cancel = document.getElementById("emailSend");
                    // change_cancel.style.display = "block";
                    repairMoney = Repair_Price_pass2;
                    j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).val(Repair_Price_pass2);
                 }
            }
             repairMoney2 = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).value();
            // console.log('repairMoney='+repairMoney);
            repairMoney3 = localParseFloat(repairMoney2);
             if (repairMoney3> 0 && (repairMoney3 <Repair_Price_Auto*0.80)) {
                if (Repair_Price_pass1!=null && repairMoney3<Repair_Price_pass2) {
                         isresduce = isresduce+1;
                }
            }
            ResonCannotWarranty = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':ResonCannotWarranty')).value();
            rppa =  document.getElementById('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Repair_Price_Auto');
            situation = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Asset_situation')).value();
            // Agreed_Date =  j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Agreed_Date')).value();
            console.log('situation='+situation);
            // console.log('Agreed_Date1='+Agreed_Date);
            //if(ResonCannotWarranty!=null&&!(ResonCannotWarranty.indexOf("弃修") != -1)){
           //         rppa.style.display = "none";
            //        j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).val('');
            //       console.log('###修改成功');
           // }
            // if ((situation.indexOf("修理中")!=-1)&& (Agreed_Date.indexOf("为空")!=-1)) {
            //     console.log('开始操作1');
            //     rppa.style.display = "none";
            // }
            // if ((situation.indexOf("修理中")!=-1)&& (Agreed_Date.indexOf("不为空")!=-1)) {
            //     console.log('开始操作2');
            //     j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Repair_Price_Auto')).val(0);
            //     j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).val(0);
            // }
        //<!-- (2022年12月上线)故障品加费 end -->
        }
        repairSum = repairSum + localParseFloat(repairMoney);
        listSum = listSum + localParseFloat(toNum(strMoney));
        downPriceSum = downPriceSum + localParseFloat(toNum(downPrice));
        upPriceSum =  upPriceSum + localParseFloat(toNum(upPrice));
    }
    console.log('改变金额isresduce='+isresduce);
     if (isresduce!=0) {
                toChange1();
        }else{
            if(ISReduced !='' ){
                 toChange2();
            }
        }
    j$(escapeVfId('allPage:allForm:allBlock:assetRepairSumNum')).text(toNumComma(repairSum));
    if (!isDisabled) {
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:GuidePriceUp')).text(toNumComma(Math.round(upPriceSum)));
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:GuidePriceUpHidden')).val(toNum(Math.round(upPriceSum)));
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:GuidePriceDown')).text(toNumComma(Math.round(downPriceSum)));
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:GuidePriceDownHidden')).val(toNum(Math.round(downPriceSum)));
    }
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetRepairSumPrice')).text(toNumComma(repairSum));
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetRepairSumPriceHidden')).val(toNum(repairSum));
    var allcount = j$(escapeVfId('allPage:allForm:allBlock:productCount3')).value();
    var result = '';
    if (allcount == 0) {
        result = null;
    //如果所有设备的上期合同都是多年保合同,则合同种类为市场多年保续签合同 thh 20220315 start
    }else if(GuranteeCount > 0 && GuranteeCount == allcount){
        result = '市场多年保续签合同';
    //如果所有设备的上期合同都是多年保合同,则合同种类为市场多年保续签合同 thh 20220315 end
    }else if (newCount > 0 && newCount == allcount && newCon == true) {
        result = '新品合同';
    }else if (((newCount > 0 && newCount == allcount) ||(newCount + firstCCount == allcount)) && newCon == false) {
        result = '首签合同';
    }else if(firstCCount > 0 && firstCCount == allcount){
        result = '首签合同';
    // 20220328 ljh update  LJPH-C8FB4P【委托】配合PBI设备覆盖率的数据准备 start
    // }else if(oyearCount > 0 && oyearCount == conCCount){
    }else if(oyearCount > 0 && oyearCount == conCCount && allcount == oyearCount ){
    // 20220328 ljh update  LJPH-C8FB4P【委托】配合PBI设备覆盖率的数据准备 start
        result = '非续签合同(空白期一年以上)';
    }else{
        result = '续签合同';
    }
    document.getElementById("allPage:allForm:allBlock:contractInfo:Contract_TypeTXT").innerHTML = result;
    document.getElementById("allPage:allForm:allBlock:contractInfo:Contract_TypeTXTHidden").value = result;
    examinationPriceCal(cnt);
    getLastContractRate();
}
function examinationPriceCal(cntWithKara) {
    var examinationCount = localParseInt(j$(escapeVfId('allPage:allForm:allBlock:appendCondition:Examination_Count')).val());
    var examinationCountStr = number_format_common(examinationCount, 0, ".", ",");
    j$(escapeVfId('allPage:allForm:allBlock:appendCondition:Examination_Count')).val(examinationCountStr);
    var cnt = 0;
    for (var i = 0; i < cntWithKara; i++) {
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        if (isManual == 'true') {
            var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Assert')).value();
            if (a != '') {
                cnt++;
            }
        }
        else {
            cnt++;
        }
    }
    var examinationPrice = 0;
// 今後復活かも
//    var cntLot = Math.ceil(cnt / 20);
//    if (cntLot == 0) {
//        examinationPrice = 0;
//    }
//    else if (cntLot == 1) {
//        examinationPrice = 2000;
//    }
//    else if (cntLot == 2) {
//        examinationPrice = 3800;
//    }
//    else if (cntLot == 3) {
//        examinationPrice = 5400;
//    }
//    else if (cntLot == 4) {
//        examinationPrice = 6800;
//    }
//    else if (cntLot == 5) {
//        examinationPrice = 8000;
//    }
//    else if (cntLot >= 6) {
//        examinationPrice = 1600 * cntLot;
//    }
    j$(escapeVfId('allPage:allForm:allBlock:appendCondition:examinationReal')).text(toNumComma(examinationPrice * examinationCount));
    j$(escapeVfId('allPage:allForm:allBlock:appendCondition:examinationRealHidden')).val(toNum(examinationPrice * examinationCount));
    // 付加条件総額欄
    // 20200108 去除附加条件总额
    // var oxygenPrice = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:NotUseOxygenatedWaterAmount')).text());
    // j$(escapeVfId('allPage:allForm:allBlock:contractInfo:appendPrice')).text(toNumComma(oxygenPrice + examinationPrice * examinationCount));
    // j$(escapeVfId('allPage:allForm:allBlock:contractInfo:appendPriceHidden')).val(toNum(oxygenPrice + examinationPrice * examinationCount));
    makeRealPrice(1);
}
/*
 * @param t   1: 金額により割引
 */
function makeRealPrice(t) {
    // 実際金額合計
    // 申请报价金额
    var sum1 = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:contractInfo:quotation_Amount')).val());
    // 修理总额
    var sum2 = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetRepairSumPrice')).text();
    var sum1 = localParseFloat(sum1);
    // 上限
    var upPrice = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:GuidePriceUp')).text();
    upPrice = localParseFloat(upPrice);
    // 下限
    var downPrice = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:GuidePriceDown')).text();
    downPrice = localParseFloat(downPrice);
    // 相对标准价格范围的折扣率 计算
    // 1)标准价格范围内时,结果为0;
    // 2)比标准价格低时,结果是1-希望价格/标准价的最低价格
    // 3)比标准价格高时,结果是1-希望价格/标准价的最高价格
    var disMP = 0.00;
    var disP = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:discount_RateHidden')).val();
    if(sum1 < downPrice){
        disMP = toNum((1 - sum1/downPrice) * 100);
    }else if(sum1 >= downPrice && sum1 <= upPrice){
        disMP = 0.00;
    }else if(sum1 > upPrice){
        disMP = toNum((1 - sum1/upPrice) * 100);
    }
    if (disMP != disP) {
        disMP = '' + disMP +  '%';
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:discount_Rate')).text(disMP);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:discount_RateHidden')).val(parseFloat(disMP));
    }
    // 修理総額を計上
    sum = sum1 + localParseFloat(sum2);
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:mainteReal')).text(toNumComma(sum));
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:mainteRealHidden')).val(toNum(sum));
}
function resetDealer() {
    var target = j$(escapeVfId('allPage:allForm:allBlock:contract:estimateTarget')).val();
    var obj = document.getElementById('allPage:allForm:allBlock:contract:dealer');
    var obj2 = document.getElementById('allPage:allForm:allBlock:contract:FirstParagraphEnd');
    var obj_lkwgt = document.getElementById('allPage:allForm:allBlock:contract:dealer_lkwgt');
    if (target == '医院') {
        obj.style.display = "none";
        obj2.style.display = "none";
        obj_lkwgt.style.display = "none";
    } else {
        obj.style.display = "block";
        obj_lkwgt.style.display = "block";
        obj2.style.display = "block";
    }
}
function alertMsg() {
    // body...
    if('{!isPaymentSet}' == 'false'){
        alert('请填写付款计划');
        return false;
    }else if('{!isPaymentSet}' == 'Denied'){
        alert('付款计划金额与实际不符,请重新填写');
        return false;
    }else{
        return true;
    }
}
function EGFlgconfim() {
    getEstimateCost();
    var cntWithKara = {!productCount};
    // 新合同备品确保提供 是否改变
    var alert1s = 0;
    for (var i = 0; i < cntWithKara; i++) {
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        var EGFlgtxt = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':EquipmentGuaranteeFlg')).value();
        var EGFlgnow = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':EGFlgassHidden')).value();
        if (EGFlgtxt != EGFlgnow) {
            alert1s = 1;
        }
    }
    if (alert1s == 1) {
        if (confirm("选择的保有设备[新合同备品确保提供]发生变化,是否继续?")) {
        } else {
            return false;
        }
    }
    return onclickCheckchangedAfterPrint('true','true');
}
function onclickCheckchangedAfterPrint(saveBtnDisabled, saveOrApproval) {
    //if(saveBtnDisabled == 'Pttrue'){
    //    var rs = alertMsg();
    //    if(rs){
    //    }else {
    //        return false;
    //    }
    //}
    var cntWithKara = {!productCount};
    var alerts = 0;
    // 新合同备品确保提供 是否改变
    var alert1s = 0;
    var today = new Date();
    today.setMonth(today.getMonth() - 3);
    for (var i = 0; i < cntWithKara; i++) {
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        if (isManual == 'true') {
            var plkid = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Assert_lkid'));
            var pid = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':ProductId'));
            if (plkid.size() > 0 && pid.size() > 0) {
                if (pid.value() != '' && plkid.value() != pid.value().substring(0, 15)) {
                    alert('请使用产品放大镜按钮设定手动产品');
                    return false;
                }
            }
        }
        if (isManual == 'false') {
            var strDate = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':finalExaminationDate')).value();
            // var produ = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Assert')).value();
            //alert(EGFlgtxt + ':' + EGFlgnow);
            strDate = strDate.replace(/(^\s*)|(\s*$)/g, "");
            if (strDate == "" || Date.parse(strDate) < Date.parse(today)) {
                alerts = 1;
            }
        }
    }
    if (alerts == 1) {
        if (confirm("选择的保有设备[最后点检日]为空或已经超过三个月之前,是否继续?")) {
        } else {
            return false;
        }
    }
    blockme();
    if (saveOrApproval == "true") {
        if (saveBeforeCheckPriceChange()) {
            if (confirm("行信息有变化(服务合同价格),是否更新报价?")) {
                j$(escapeVfId('allPage:allForm:changedSubmitPrice')).val('true');
            } else {
                j$(escapeVfId('allPage:allForm:changedSubmitPrice')).val('fasle');
                unblockUI();
                return false;
            }
        }
        j$(escapeVfId('allPage:allForm:isSaveOrApproval')).val('true');
    }
   return true;
    // if ((saveBtnDisabled == "true"||saveBtnDisabled == "Pttrue" )&& checkchangedAfterPrint()) {
    //     if (confirm(Confirm_ChangedAfterPrint)) {
    //         if (saveOrApproval == "true") {
    //             j$(escapeVfId('allPage:allForm:isSaveOrApproval')).val('true');
    //         }
    //         return true;
    //     } else {
    //         unblockUI();
    //         return false;
    //     }
    // } else {
    //     if (saveOrApproval == "true") {
    //         j$(escapeVfId('allPage:allForm:isSaveOrApproval')).val('true');
    //     }
    //     return true;
    // }
}
function changeEstiStartdate(val) {
    if ('{!SaveBtnDisabled}' == 'false') {
        j$(escapeVfId('allPage:allForm:contractstartdate')).val(val);
        changeContractStartdate(val);
    }
}
function changeContractStartdate(val) {
    var oldDateStr = j$('#oldContractDate').value();
    var oldDate = new Date();
    if (oldDateStr != null && oldDateStr != '') {
        oldDate = new Date(oldDateStr);
    }
    if ('{!DecideBtnDisabled}' == 'false') {
        var monthStr = '00' + (oldDate.getMonth()+1);
        monthStr = monthStr.substring(monthStr.length-2, monthStr.length);
        var dayStr = '00' + oldDate.getDate();
        dayStr = dayStr.substring(dayStr.length-2, dayStr.length);
        var oldDateVal = oldDate.getFullYear() + '/' + monthStr + '/' + dayStr;
        j$(escapeVfId('allPage:allForm:oldDecideContractDate')).val(oldDateVal);
        if (saveBeforeCheckPriceChange()) {
            //blockme();
            //contractStartDateChange();
            //refreshAsset({!productCount});
        }
        refreshAsset({!productCount});
    } else {
        var cntWithKara = {!productCount};
        var haveLine = 'false';
        for (var i = 0; i < cntWithKara; i++) {
            var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
            if (isManual == 'true') {
                var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Assert_lkid'));
                if (a.size() > 0 && a.val() != "000000000000000") {
                    haveLine = 'true';
                }
            } else {
                haveLine = 'true';
            }
        }
        if (haveLine == 'false') {
            return false;
        }
        var contractStartDate = new Date(val);
        var strCreatedDate = '{!estimate.CreatedDate}';
        var createDate = new Date();
        if (strCreatedDate != '') {
            createDate = new Date(strCreatedDate);
        }
        createDate = new Date(createDate.toDateString());
        var threeMA = new Date(createDate.setMonth(createDate.getMonth() + 3));
        var isnewMA = new Date(createDate.setMonth(createDate.getMonth() - 3 - isNewAddMonth));
        /*if (oldDate >= isnewMA && contractStartDate >= isnewMA) {
            return false;
        }
        if (oldDate < threeMA && contractStartDate < threeMA) {
            return false;
        }
        if (contractStartDate >= isnewMA) {
            alert('合同开始预定日或合同开始日发生变化并且大于创建日6个月,所有合同对象设备不适用新品价格。\n请在画面刷新后确认服务合同价格,再继续其他操作。');
        } else if (contractStartDate >= threeMA) {
            alert('合同开始预定日或合同开始日发生变化并且大于创建日3个月,所有合同对象设备使用【合同开始日】重新计算服务合同价格。\n请在画面刷新后确认服务合同价格,再继续其他操作。');
        } else {
            alert('合同开始预定日或合同开始日发生变化并且在创建日3个月以内,所有合同对象设备使用【创建日】重新计算服务合同价格。\n请在画面刷新后确认服务合同价格,再继续其他操作。');
        }*/
        j$('oldContractDate').val(val);
        //blockme();
        //contractStartDateChange();
        refreshAsset({!productCount});
    }
}
function AlertPriceBtnJs(){
    var  VarAlert  = j$(escapeVfId('allPage:allForm:alertStringValue')).val();
    var  VarAlert2 = j$(escapeVfId('allPage:allForm:alertStringValue2')).val();
    var  VarAlert3 = j$(escapeVfId('allPage:allForm:alertStringValue3')).val();
    var  PStatus   = j$(escapeVfId('allPage:allForm:PriceStatus')).val();
    blockme();
    if(PStatus!='申请中'&& PStatus!='批准'){
        ComputeLTYRepair();
        //ShowLTYRepair();
    }else if(PStatus == '申请中'||PStatus == '批准'){
        ShowLTYRepair();
    }
}
function ComputeLTY() {
    var  urlNameJs = j$(escapeVfId('allPage:allForm:urlName')).val();
    urlNameJs = '{!$Label.ID_of_SelectAssetEstimate}'+urlNameJs ;
    //URF限次合同2期 LY 20220920 start
    // var w = window.open(encodeURI(urlNameJs),'过去两年修理实绩','menubar=no,height=720,width=986');
    // w.focus();
    //URF限次合同2期 LY 20220920 end
}
function recordNumChangeJs() {
    recordNumChangeAction();
}
function checkDecideDate() {
    // 报价有效期
    var strSubmitDate = '{!estimate.Submit_quotation_day__c}';
    // 上期合同结束日 取最晚的
    var conEndDate = getLastContractendDate();
    conEndDate = new Date(conEndDate);
    // 今天
    var submitDate = new Date();
    var nowDate = new Date();
    nowDate = new Date(nowDate.toLocaleDateString());
    /// 报价中设备的机身编码为空时的新品合同有效期延长 20200710 gzw
    // 默认为3月,全是产品为6月;
    var monthGap = 6;
    var cntWithKara = {!productCount};
    for (var i = 0; i < cntWithKara; i++) {
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        if (isManual != 'true') {
            monthGap = 3;
            break;
        }
    }
    //nowDate = new Date(nowDate.getYear(),nowDate.getYear(),nowDate.getYear());
    if (strSubmitDate != '') {
        submitDate = new Date(strSubmitDate);
        submitDate = new Date(submitDate.setMonth(submitDate.getMonth() + monthGap));
        if(Date.parse(conEndDate)  > Date.parse(submitDate)){
            submitDate = new Date(conEndDate);
        }
    }
    //alert(nowDate + '=====' + submitDate);
    if (strSubmitDate != '' && nowDate > submitDate) {
        alert('已超出报价申请日'+ monthGap+'个月,不允许DECIDE。');
        return false;
    }
    return true;
}
function getLastContractendDate(){
    var rowCnt = {!productCount};
    var lastdate = null;
    for (var i = 0; i < rowCnt; i++) {
        var LastMContractID = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':LastMContractID')).value();
        if(!!LastMContractID){
            var endDate = new Date(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':End_Date')).value());
            if(lastdate == null){
                lastdate = new Date(endDate);
            }else if(Date.parse(endDate) > Date.parse(lastdate)){
                lastdate = new Date(endDate);
            }
        }
    }
    return lastdate;
}
function decideJs() {
    if (checkDecideDate() == true) {
        if (onclickCheckchangedAfterPrint('true','false') == true) {
            var oldDate = j$(escapeVfId('allPage:allForm:oldDecideContractDate')).value();
            var contractDate = new Date(j$(escapeVfId('allPage:allForm:contractstartdate')).value());
            //var olDt = oldDate.getFullYear() + oldDate.getMonth() + oldDate.getDate();
            var monthStr = '00' + (contractDate.getMonth()+1);
            monthStr = monthStr.substring(monthStr.length-2, monthStr.length);
            var dayStr = '00' + contractDate.getDate();
            dayStr = dayStr.substring(dayStr.length-2, dayStr.length);
            var contractDateStr = contractDate.getFullYear() + '/' + monthStr + '/' + dayStr;
            //var neDt = contractDate.getFullYear() + contractDate.getMonth() + contractDate.getDate();
            //monthStr = '00' + (oldDate.getMonth()+1);
            //monthStr = monthStr.substring(monthStr.length-2, monthStr.length);
            //dayStr = '00' + oldDate.getDate();
            //dayStr = dayStr.substring(dayStr.length-2, dayStr.length);
            //oldDateVal = oldDate.getFullYear() + '/' + monthStr + '/' + dayStr;
            if (oldDate == contractDateStr) {
                j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
                decide();
            } else {
                var oldp = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:contractInfo:oldMainteReal')).value());
                var newp = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:contractInfo:mainteReal')).text());
                if (oldp != newp) {
                    // 20201106 高章伟 提醒消息修改 start
                    j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
                    if (confirm('合同金额发生变化,请您确认。')) {
                        decide();
                    } else {
                        alert('请确认全部内容后点击Decide。');
                        j$(escapeVfId('allPage:allForm:contractstartdate')).val(oldDate);
                        j$(escapeVfId('allPage:allForm:oldDecideContractDate')).val('');
                        j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
                        decideCancle();
                    }
                } else {
                    j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
                    decide();
                    // j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
                    // if (confirm('本次合同开始日的修改不会导致合同金额发生变化,请您确认是否修改?')) {
                    //     decide();
                    // } else {
                    //     j$(escapeVfId('allPage:allForm:contractstartdate')).val(oldDate);
                    //     alert('合同开始日未进行变更,请确认全部内容后点击Decide。');
                    //     unblockUI();
                    // }
                }
                // 20201106 高章伟 提醒消息修改 end
            }
        }
    }
}
// 获取实际报价金额 按照上限比例算
function getEstimateCost() {
    // 行数
    var rowcount = {!productCount};
    // 6.合同价格
    var mainteReal = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:mainteReal')).text();
    mainteReal = localParseFloat(mainteReal);
    // 5.修理总额
    var assetRepairSumPrice = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetRepairSumPrice')).text();
    assetRepairSumPrice = localParseFloat(assetRepairSumPrice);
    // 计算实际报价总金额
    var realprice = mainteReal - assetRepairSumPrice;
    // 标准价格的最高价总额
    var GuidePriceUp = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:contractInfo:GuidePriceUpHidden')).val());
    GuidePriceUp = localParseFloat(GuidePriceUp);
    for (var i = 0; i < rowcount; i++) {
        // 去上限价格
        var assetListPrice = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Adjustment_Upper_priceHidden')).val();
        assetListPrice = localParseFloat(assetListPrice);
        if(GuidePriceUp == 0){
            j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Estimate_Cost')).val(0);
        }else{
            var Estimate_Cost = (realprice * (assetListPrice / GuidePriceUp)).toFixed(2);
            j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Estimate_Cost')).val(Estimate_Cost);
        }
    }
}
function getLastContractRate(){
    var rowCnt = {!productCount};
    var Contractrate = 0.00;
    var count = 0;
    for (var i = 0; i < rowCnt; i++) {
        var LastMContractID = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':LastMContractID')).value();
        if(!!LastMContractID){
            var tempContractrate = parseFloat(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Contractrate')).value().replace(/,/g,''));
            if(!!tempContractrate){
                Contractrate = Contractrate + tempContractrate;
            }
            count++;
        }
    }
    var allContractRate = '' + 0.00 + '%';
    if( count > 0){
        allContractRate = '' + (Contractrate/count).toFixed(2) + '%';
    }
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:Combinedrate')).text(allContractRate);
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:CombinedrateHidden')).val(parseFloat(allContractRate));
    return allContractRate;
}
function calculateNtoMRatio(lastContRange, month ){
    var lastContRangeYear = Math.ceil(localParseFloat(lastContRange)/12);
    var currentMonthYear = Math.ceil(localParseFloat(month)/12);
    //if(!lastendDate || currentMonthYear <= lastContRangeYear){
    if(currentMonthYear == lastContRangeYear || currentMonthYear == 1){
        return month;
    }else if(month <= 24) {
        return 12+ (month- 12) *1.1;
    }else if(month <= 36) {
        return 25.2 + (month- 24) *1.21;
    }else if(month <= 48) {
        return 39.72 + (month- 36) *1.331;
    }else if(month <= 60) {
        return 55.692 + (month- 48) *1.4641;
    }else {
        alert('合同期最长只能选择60个月!');
        return 0;
    }
}
    //获取经销商的先款标识
    function onChDealerUpdateJs(oBj){
        //获取 报价提交对象  是否为经销商
        var estimateTarget = j$(escapeVfId('allPage:allForm:allBlock:contract:estimateTarget'))[0].value;
        if(estimateTarget == '经销商'){
            //判断经销商名是否为空
            var dealerValue = j$(escapeVfId('allPage:allForm:allBlock:contract:dealer')).val();
            if(dealerValue != ''){
                //获取经销商名的id
                var dealerId = j$(escapeVfId('allPage:allForm:allBlock:contract:dealer_lkid')).val();
                //由于salesforce的查找字段是可以输入的,所以判断他如果为空或者为 000000000000000 的时候,传的参数就位经销商中文名,其他情况传id
                if(dealerId != '' && dealerId != '000000000000000'){
                    onChDealerUpdate(dealerId);
                }else{
                    onChDealerUpdate(dealerValue);
                }
            }else{
                onChDealerUpdate('');
                //j$(escapeVfId('allPage:allForm:allBlock:contract:FirstParagraphEnd'))[0].checked = false;
            }
        }
    }
    //如果选择的经销商为先款对象,那么做一下提示
    function hintAccount(){
        var xkChecked = j$(escapeVfId('allPage:allForm:allBlock:contract:FirstParagraphEnd'))[0].checked;
        if(xkChecked){
            alert('请注意,当前经销商为先款对象。');
        }
    }
//LJPH-C9SCX7 【委托】合同无空白期的提醒  lt  20211221  start
//合同开始日预定日默认为上期合同1结束日的第2天
// function DefaultStartDate(){
//     //上期合同1结束日
//     var LastContractEndDate;
//     var LastContractEndDate2;  //日期格式
//     var cnt = j$(escapeVfId('allPage:allForm:allBlock:assetSection:productCnt')).val();
//     for (var i = 0; i < cnt; i++){
//         LastContractEndDate = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':End_Date')).value();
//          //或者换隐藏标签Maintenance_Contract__r.Past_Contract_end_day__c
//         LastContractEndDate2 = LastContractEndDate;
//         if(LastContractEndDate != null && LastContractEndDate != ''){
//             break;
//         }
//     }
//     if(LastContractEndDate != null && LastContractEndDate != ''){
//         //上期合同1结束日的第2天
//         LastContractEndDate += " 00:00:00";//设置为当天凌晨12点
//         LastContractEndDate = Date.parse(new Date(LastContractEndDate))/1000;//转换为时间戳
//         LastContractEndDate += (86400) * 1;//修改后的时间戳
//         var newDate = new Date(parseInt(LastContractEndDate) * 1000);//转换为时间
//         var LastContractEndDate1 = newDate.getFullYear() + '/' + (newDate.getMonth() + 1) + '/' + newDate.getDate();;
//         //获取当前日期(currentdate)
//         var date1 = new Date();
//         var seperator = "/";
//         var year = date1.getFullYear();
//         var month = date1.getMonth() + 1;
//         var day = date1.getDate();
//         if (month >= 1 && month <= 9) {
//             month = "0" + month;
//         }
//         if (day >= 0 && day <= 9) {
//             day = "0" + day;
//         }
//         var currentdate = year + seperator + month + seperator + day;
//         //上期合同尚未结束 , 开始预定日
//         if(currentdate < LastContractEndDate2){
//             document.getElementById("allPage:allForm:allBlock:contract:startdate").value = LastContractEndDate1;
//         }
//     }
// }
//LJPH-C9SCX7 【委托】合同无空白期的提醒  lt  20211221  end
</script>
<apex:form id="allForm">
    <apex:inputHidden id="alertStringValue" value="{!alertString}" />
    <apex:inputHidden id="alertStringValue2" value="{!alertString2}" />
    <apex:inputHidden id="alertStringValue3" value="{!alertString3}" />
    <apex:inputHidden id="PriceStatus" value="{!estimate.Process_Status__c}"/>
    <apex:inputHidden id="urlName" value="{!estimate.Name}"/>
    <apex:inputHidden id="changedAfterPrint" value="{!changedAfterPrint}"/>
    <apex:inputHidden id="changedSubmitPrice" value="{!changedSubmitPrice}"/>
    <apex:inputHidden id="isSaveOrApproval" value="{!isSaveOrApproval}"/>
    <!-- HWAG-B4R3SS  START 20181026-->
    <apex:actionFunction name="searchfunc" action="{!searchBtn}" rerender="Form,Block,assetSection2,pageMessages,allBlock" onComplete="unblockUI();"></apex:actionFunction>
    <apex:actionfunction action="{!tochange}" name="tochange" rerender="ISReducedpriceapproval" oncomplete="unblockUI();">
        </apex:actionfunction>
        <apex:actionfunction action="{!tochange2}" name="tochange2" rerender="ISReducedpriceapproval" oncomplete="unblockUI();">
        </apex:actionfunction>
    <!-- HWAG-B4R3SS  END 20181026-->
    <apex:actionFunction name="ComputeLTYRepair" action="{!ComputeLTYRepair}" rerender="pageMessages" oncomplete="unblockUI();ComputeLTY();"/>
    <apex:actionFunction name="ShowLTYRepair" action="{!ShowLTYRepair}"  oncomplete="unblockUI();ComputeLTY();"/>
    <apex:actionFunction name="decide" action="{!decide}" rerender="allForm" oncomplete="unblockUI();"/>
    <apex:actionFunction name="decideCancle" action="{!decideCancle}" rerender="allForm" oncomplete="unblockUI();"/>
    <apex:inputHidden id="oldDecideContractDate" value="{!OldContractStartDate}" />
    <!-- 经销商发生变化的change时间 -->
    <apex:actionFunction name="onChDealerUpdate" action="{!onChDealerUpdate}" rerender="contract" onComplete="hintAccount();">
        <apex:param name="checkDealerId" assignTo="{!checkDealerId}" value="" />
    </apex:actionFunction>
    <input type="hidden" id="oldContractDate" value="{!estimate.Contract_Start_Date__c}" />
<script type="text/javascript">
//j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
</script>
    <apex:pageBlock title="服务合同报价" id="allBlock">
        <apex:pageBlockButtons id="blocktop" location="top">
            <apex:commandButton id="savebtntop" action="{!save}" value="{!$Label.Save_Button}" disabled="{!SaveBtnDisabled}" rerender="allForm" onclick="if (!EGFlgconfim()) return false;" oncomplete="unblockUI();"/>
           <!--  <apex:commandButton id="LastTwoYearRepairShow" value="过去两年维修实绩Repaort"  action="{!ShowLTYRepair}" rerender="alertStringValue,alertStringValue2,alertStringValue3" oncomplete="AlertPrice();"/> -->
            <apex:commandButton id="LastTwoYearRepairComp" value="过去三年维修实绩计算" rerender="PriceStatus" onclick="AlertPriceBtnJs()"/>
            <apex:commandButton id="approvalbtntop" action="{!approvalProcess}" value="提交待审批" disabled="{!ApprovalBtnDisabled}" rerender="allForm" onclick="if (!KindsAndMonths()) return false;if (!EGFlgconfim()) return false;approvalJs();" oncomplete="unblockUI();"/>
            <!-- HWAG-B399Q8 2018/08/20 新增请提交待审批 提示字段 start-->
            &nbsp; <apex:outputText style="color:red;font-size:20px" value="请提交待审批" rendered="{!IS_Clone_After_Decide}"/>
            <!-- HWAG-B399Q8 2018/08/20 新增请提交待审批 提示字段 end-->
            <apex:commandButton action="{!cancel}" value="不保存(返回)" style="float:right;" rerender="allForm" onclick="blockme();" oncomplete="unblockUI();"/>
            <apex:commandButton id="saveAndCancelBtn" action="{!saveAndCancel}" value="保存(返回)" style="float:right;" rerender="allForm" oncomplete="unblockUI();" onclick="if (!onclickCheckchangedAfterPrint('true','true')) return false;" disabled="{!SaveBtnDisabled}"/>
        </apex:pageBlockButtons>
        <apex:pageMessages id="pageMessages"></apex:pageMessages>
        <!-- update 合同报价页面的优化 添加‘assetSection’ fxk 2021/9/10 Star-->
        <apex:actionFunction name="refreshProductData" action="{!refreshProductData}" rerender="pageMessages,EquipmentGuaranteeFlg,EGFlgassHidden,EquipmentGuaranteeFlgtxt, assetListPriceHidden, productCount3,assetSection" oncomplete="refreshAsset({!productCount});unblockUI();">
            <apex:param assignTo="{!productIdx}" name="productIdx" value=""/>
        </apex:actionFunction>
        <!-- update 合同报价页面的优化 添加‘assetSection’ fxk 2021/9/10 End-->
        <!--<apex:actionFunction name="contractStartDateChange" action="{!contractStartDateChange}" rerender="allForm" oncomplete="unblockUI();">
        </apex:actionFunction>-->
        <apex:actionFunction name="recordNumChangeAction" action="{!recordNumChange}" rerender="allForm" oncomplete="unblockUI();">
        </apex:actionFunction>
        <!-- update by rentx 2020-11-17  -->
            <!-- <apex:pageblocksection title="服务合同" id="contract"> -->
            <!-- <apex:outputField value="{!estimate.Name}"/> -->
            <!-- <apex:outputField value="{!contract.Management_Code__c}" /> -->
            <!-- <apex:outputField value="{!estimate.Process_Status__c}"/> -->
            <!-- <apex:outputField value="{!contract.Status__c}"/> -->
            <!-- <apex:outputField value="{!contract.Hospital__c}" /> -->
            <!-- <apex:inputField value="{!estimate.Department__c}" id="depart"/> -->
            <!-- <apex:inputField value="{!estimate.Contract_Esti_Start_Date__c}" required="true" id="startdate" onchange="changeEstiStartdate(this.value);"/>onchange="checkContractEstiStartDate(this.value, {!productCount})" -->
            <!-- <apex:inputField value="{!estimate.Contract_Range__c}" required="true" id="monthRange" onchange="checkContractRange(this.value, {!productCount})"/> -->
            <!-- <apex:inputField style="width:3px;height:15px;background-color:#cc0000; position:absolute;margin-right:5px;"> -->
            <!-- <div><div style="width:2px;height:20px;background-color:red; position:absolute;margin-right:5px;"></div></div> -->
            <!-- <apex:inputField value="{!estimate.Contract_Range__c}" required="false" id="monthRange" onchange="checkContractRange(this.value, {!productCount})"/> -->
            <!-- </apex:inputField> -->
            <!-- <apex:outputField value="{!estimate.Contract_Esti_End_Date__c}"/> -->
            <!-- <apex:outputField label="制定日" value="{!estimate.CreatedDate}" id="createDateShow"/> -->
            <!-- <apex:outputPanel > -->
                <!-- <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">报价提交对象</label> -->
                <!-- <apex:inputField value="{!estimate.Estimate_Target__c}" id="estimateTarget" onchange="resetDealer()" style="margin-left:5px"/> -->
                <!-- <apex:outputPanel rendered="{!DecideBtnDisabled==false}"> -->
                    <!-- <input type="button" class="btn" value="变更" onclick="controlDisabled()" style="margin-left:20px;width:40px;padding:0 0;"/> -->
                <!-- </apex:outputPanel> -->
                <!-- <apex:outputPanel rendered="{!DecideBtnDisabled==true}"> -->
                    <!-- <input type="button" class="btnDisabled" value="变更" disabled="true" onclick="controlDisabled()" style="margin-left:20px;width:40px;padding:0 0;"/> -->
                <!-- </apex:outputPanel> -->
            <!-- </apex:outputPanel> -->
            <!-- <apex:inputField value="{!estimate.Dealer__c}" id="dealer" /> -->
            <!-- <apex:inputField value="{!estimate.EndUserType__c}" id="EndUserType" /> -->
            <!-- <script type="text/javascript"> -->
                <!-- j$(escapeVfId('allPage:allForm:allBlock:contract:estimateTarget')).children('option[value=]').remove(); -->
                <!-- resetDealer(); -->
            <!-- </script> -->
        <!-- </apex:pageblocksection> -->
        <apex:pageBlockSection title="服务合同" id="contract">
        <!-- <apex:outputPanel/> -->
            <apex:outputPanel >
            <table align="center" width="100%"  style="border-collapse:separate; border-spacing:0px 10px" >
                <tr>
                    <td width="50%" align="right"> <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">报价编码</label> </td>
                    <td width="50%" align="left"> <apex:outputField value="{!estimate.Name}"/> </td>
                </tr>
                <tr>
                    <td width="50%" align="right"> <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">报价状态</label> </td>
                    <td width="50%" align="left"> <apex:outputField value="{!estimate.Process_Status__c}"/> </td>
                </tr>
                <tr>
                    <td width="50%" align="right"> <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">医院</label> </td>
                    <td width="50%" align="left"> <apex:outputField value="{!contract.Hospital__c}" /> </td>
                </tr>
                <tr>
                    <td width="50%" align="right"> <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">合同开始预订日</label> </td>
                    <td width="50%" align="left"> <apex:inputField value="{!estimate.Contract_Esti_Start_Date__c}" required="true" id="startdate" onchange="changeEstiStartdate(this.value);"/>
                    </td>
                </tr>
                <tr>
                    <td width="50%" align="right"><label class="labelCol vfLabelColTextWrap " style="margin-left:22%">合同结束预订日</label> </td>
                    <td width="50%" align="left"> <apex:outputField value="{!estimate.Contract_Esti_End_Date__c}"/> </td>
                </tr>
                <tr>
                    <td align="right">
                        <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">报价提交对象</label>
                    <td>
                        <apex:outputPanel >
                            <apex:inputField value="{!estimate.Estimate_Target__c}" id="estimateTarget" onchange="resetDealer()" style="margin-left:5px"/>
                            <apex:outputPanel rendered="{!DecideBtnDisabled==false}">
                                <input type="button" class="btn" value="变更" onclick="controlDisabled()" style="margin-left:20px;width:40px;padding:0 0;"/>
                            </apex:outputPanel>
                            <apex:outputPanel rendered="{!DecideBtnDisabled==true}">
                                <input type="button" class="btnDisabled" value="变更" disabled="true" onclick="controlDisabled()" style="margin-left:20px;width:40px;padding:0 0;"/>
                            </apex:outputPanel>
                        </apex:outputPanel>
                    </td>
                    </td>
                </tr>
                <tr>
                    <td align="right"> <label class="labelCol vfLabelColTextWrap " style="margin-left:22%"> 用户类型</label></td>
                    <td align="left">
                        <apex:outputField value="{!estimate.EndUserType__c}" id="EndUserType" />
                    </td>
                    <td> </td>
                </tr>
            </table>
            </apex:outputPanel>
        <apex:outputPanel >
        <table align="center" width="100%"  style="border-collapse:separate; border-spacing:0px 10px" >
            <tr>
                <td width="50%" align="right"> <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">合同询价编码</label> </td>
                <td width="50%" align="left"> <apex:outputField value="{!contract.Management_Code__c}" /> </td>
            </tr>
            <tr>
                <td width="50%" align="right"> <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">状态</label> </td>
                <td width="50%" align="left"> <apex:outputField value="{!contract.Status__c}"/> </td>
            </tr>
            <tr>
                <td width="50%" align="right"> <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">科室</label> </td>
                <td width="50%" align="left"> <apex:inputField value="{!estimate.Department__c}" id="depart"/> </td>
            </tr>
            <tr>
                <td width="50%" align="right">
                    <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">合同月数</label> </td>
                <td width="50%" align="left">
                    <div style="width:3px;height:20px;background-color:#cc0000; position:absolute;margin-right:5px" />&nbsp;
                    <apex:inputField value="{!estimate.Contract_Range__c}" required="false" id="monthRange"
                    onchange="checkContractRange(this.value, {!productCount})"
                    />
                </td>
            </tr>
            <tr>
                <td width="50%" align="right"> <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">制定日</label></td>
                <td width="50%" align="left"> <apex:outputField label="制定日" value="{!estimate.CreatedDate}" id="createDateShow"/> </td>
            </tr>
            <tr>
                <td  width="50%" align="right">
                    <label class="labelCol vfLabelColTextWrap " style="margin-left:30%"> 经销商名</label></td>
            <!-- update     wangweipeng             2021/12/04         start -->
                <td width="50%" align="left"> <apex:inputField value="{!estimate.Dealer__c}" id="dealer" onchange="onChDealerUpdateJs(this);return false;" style="float: left;"/> </td>
            </tr>
            <tr>
                <td  width="50%" align="right">
                    <label class="labelCol vfLabelColTextWrap " style="margin-left:30%"> 先款标识(经销商)</label></td>
                <td width="50%" align="left" > <apex:inputCheckbox value="{!estimate.Is_RecognitionModel__c}" id="FirstParagraphEnd" onClick="return false;" /> </td>
            </tr>
            <!-- update     wangweipeng             2021/12/04         end -->
        </table>
        <script type="text/javascript">
            j$(escapeVfId('allPage:allForm:allBlock:contract:estimateTarget')).children('option[value=]').remove();
            resetDealer();
        </script>
        </apex:outputPanel>
        </apex:pageBlockSection>
        <!-- update by rentx 2020-11-17 end -->
        <apex:pageblocksection columns="1" title="合同对象设备" id="assetSection" >
            <apex:outputLabel />
            <apex:outputPanel >
                <input type="hidden" id="allPage:allForm:allBlock:assetSection:productCnt" value="{!productCount}" />
                <!-- <table width="100%">
                    <tr>
                        <td>&nbsp;</td>
                        <td width="100px"><span>全</span>
                            <select style="vertical-align:text-bottom" id="allCheckResult" size="1" onchange="changeAllCheckResult(this.value)">
                                <option value=" ">--无--</option>
                                <option value="OK">OK</option>
                                <option value="NG">NG</option>
                            </select>
                        </td>
                        <td width="150px">&nbsp;</td>
                    </tr>
                </table> -->
                <!-- <div id = 'aaaa' class="slds-scrollable_x" style="width:450px">
                <div class="slds-table--header-fixed_container" style="height:450px;width:850px">
                    <div class="slds-scrollable_y" style="height:100%;width:850px"> -->
                <div style="width: 100%">
                <table class="list" style="border-bottom-width: 0px; font-size:13px;" border="0" cellspacing="0" cellpadding="0">
                    <tr class="headerRow" height="30px">
                        <th style="width:25px" class="headerRow  booleanColumn"><input type='checkbox' onClick='checkAll(this)'/></th>
                        <th class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Name.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Asset_situation__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.SerialNumber.label}</th>
                        <th class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.EGFlg_fromContract_asset__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.InstallDate.label}</th>
                        <!--add点检改善:新增一个点检对象复选框字段,默认为true 2021.6.8 fxk Star-->
                        <th style="width:70px" class="headerRow  booleanColumn">
                        {!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Check_Object__c.label}</th>
                        <!--add点检改善:新增一个点检对象复选框字段,默认为true 2021.6.8 fxk end-->
                        <th style="width:40px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.IsNew__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Department_Name__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Management_Code__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Asset_Consumption_rate__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.CurrentContract_End_Date__c.label}</th>
                        <!-- 实绩联动价格计算 start -->
                        <th style="width:35px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Adjustment_Upper_price__c.label}</th>
                        <th style="width:35px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Adjustment_Lower_price__c.label}</th>
                        <!-- 实绩联动价格计算 end -->
                        <!-- 隐藏合同月数
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract__c.fields.Contract_Range__c.label}</th>-->
                        <!-- <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Asset_Owner__c.label}</th>
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Accumulation_Repair_Amount__c.label}</th>
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Estimate_List_Price_All__c.label}</th>
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Maintenance_Price_YearTXT__c.label}</th>-->
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Repair_Price__c.label}</th>
                        <!-- (2022年12月上线)故障品加费 start -->
                        <th style="width:70px" class="headerRow ">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Repair_Price_Auto__c.label}</th>
                       <!-- (2022年12月上线)故障品加费 end -->
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Comment__c.label}</th>
                        <!-- (2022年12月上线)故障品加费 第三方回归 -->
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Third_Party_Return__c.label}</th>
                    </tr>
                    <apex:variable value="{!1}" var="cnt" />
                        <apex:repeat value="{!checkedAssets}" var="ar" id="assetTable">
                            <tr class="dataRow {!IF(MOD(cnt, 2)==0, 'odd', 'even')} {!IF(cnt==1, 'first', '')}" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
                                <td class="dataCell" width="25px">
                                    <apex:inputCheckbox value="{!ar.rec_checkBox_c}" id="assetRowCheckbox" rendered="{!Not(ar.IsManual)}" disabled="{!PageDisabled}"/>
                                    <apex:outputText value="{!ar.IsManual}" id="IsManual" style="display:none;" />
                                    <!-- 判断是否可报价 -->
                                    <!-- <input type="hidden" value="{!ar.estimateass}" id="allPage:allForm:allBlock:assetSection:assetTable:{!Text(cnt-1)}:estimateass"/> -->
                                    <!-- <apex:inputCheckbox value="{!ar.estimateass}" id="estimateass" style="display:none;" /> -->
                                </td>
                                <td class="dataCell">
                                    <apex:outputField value="{!ar.rec.Name}" id="assetName" rendered="{!Not(ar.IsManual)}" />
                                    <apex:inputField value="{!ar.mcae.Product_Manual__c}" id="Assert" style="width:90%;" rendered="{!ar.IsManual}" onchange="blockme();refreshProductData({!ar.lineNo});"/>
                                    <apex:inputText id="ProductId" value="{!ar.mcae.Product_Manual__c}" style="display:none;" disabled="true"/>
                                </td>
                                <!-- URF限次合同2期 LY 20220811 start -->
                                    <apex:inputHidden value="{!ar.rec.URF_Maintenance_Contract__r.Management_Code__c}" rendered="{!Not(ar.IsManual)}" id="URF_Contract_No"/>
                                <!-- URF限次合同2期 LY 20220811 end -->
                                <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.Asset_situation__c}" rendered="{!Not(ar.IsManual)}" id="Asset_situation"/>
                                </td>
                                <td class="dataCell" width="70px">
                                    <apex:outputLink value="/{!ar.recId}" rendered="{!Not(ar.IsManual)}" >{!ar.rec.SerialNumber}</apex:outputLink>
                                    <apex:inputHidden id="AssetId" value="{!ar.recId}"/>
                                    <apex:inputField value="{!ar.rec.isNewDate_use__c}" id="isNewDate" style="display: none" showDatePicker="false"/>
                                </td>
                                <td class="dataCell" >
                                    <apex:outputField value="{!ar.mcae.EquipmentGuaranteeFlgTxt__c}" id="EquipmentGuaranteeFlgtxt"/>
                                    <apex:outputText value="{!ar.mcae.EquipmentGuaranteeFlgTxt__c}" id="EquipmentGuaranteeFlg" style="display:none;"/>
                                    <apex:inputHidden id="EGFlgassHidden" value="{!ar.etGFlg}"/>
                                </td>
                                <td class="dataCell" width="70px" style="text-align:center" >
                                    <apex:outputField value="{!ar.rec.InstallDate}" id="InstallDate" rendered="{!Not(ar.IsManual)}" />
                                </td>
                                <!--add点检改善:新增一个点检对象复选框字段,默认为true 2021.6.8 fxk Star-->
                                <td class="dataCell" width="70px" style="text-align:center" >
                                    <apex:inputCheckbox value="{!ar.mcae.Check_Object__c}" id="assetCheck" disabled="{!ar.CheckRows}"/>
                                </td>
                                <!--add点检改善:新增一个点检对象复选框字段,默认为true 2021.6.8 fxk end-->
                                <td class="dataCell" width="40px" style="text-align:center" >
                                    <apex:inputCheckbox value="{!ar.mcae.IsNew__c}" id="assetNew" disabled="true"/>
                                    <apex:outputPanel layout="none" rendered="{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.createable}" >
                                        <apex:inputHidden value="{!ar.mcae.IsNew__c}" id="assetNewHidden" />
                                    </apex:outputPanel>
                                    <apex:outputPanel layout="none" rendered="{!Not($ObjectType.Maintenance_Contract_Asset_Estimate__c.createable)}" >
                                        <input type="hidden" value="{!ar.mcae.IsNew__c}" id="allPage:allForm:allBlock:assetSection:assetTable:{!Text(cnt-1)}:assetNewHidden" />
                                    </apex:outputPanel>
                                    <apex:outputText value="{!ar.rec.Final_Examination_Date__c}" id="finalExaminationDate" rendered="{!Not(ar.IsManual)}" style="display:none"/>
                                </td>
                                <td class="dataCell" width="70px" >
                                    <apex:outputField value="{!ar.rec.Department_Name__c}" rendered="{!Not(ar.IsManual)}" />
                                </td>
                                <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.CurrentContract_F__r.Maintenance_Contract_No_F__c}" rendered="{!Not(ar.IsManual)}" id="Contract_No"/>
                                    <apex:inputHidden value="{!ar.rec.CurrentContract_F__r.RecordType_DeveloperName__c}" id="LastMContractRecord"/>
                                    <apex:inputField value="{!ar.rec.CurrentContract_F_asset__r.endDateGurantee_Text__c}" id="endDateGurantee_Text" style="display: none" showDatePicker="false"/>
                                    <apex:inputHidden value="{!ar.rec.CurrentContract_F__c}" id="LastMContractID"/>
                                </td>
                                <td class="dataCell" width="90px" style="text-align:right" >
                                    <apex:outputField value="{!ar.mcae.Asset_Consumption_rate__c}" rendered="{!Not(ar.IsManual)}" id="Contractrate"/>
                                    <apex:inputHidden value="{!ar.rec.CurrentContract_F__r.Contract_Range__c}" id="lastContRange"/>
                                </td>
                                <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.CurrentContract_F__r.Contract_End_Date__c}" rendered="{!(Not(ar.IsManual)&& ar.rec.CurrentContract_F__c != null)}" id="End_Date" />
                                </td>
                                 <!-- 实绩联动价格计算 start -->
                                <td class="dataCell" width="35px">
                                    <apex:outputText value="{!ar.mcae.Adjustment_Upper_price__c}" id="Adjustment_Upper_price"/>
                                    <apex:inputHidden value="{!ar.mcae.Adjustment_Upper_price__c}" id="Adjustment_Upper_priceHidden"/>
                                    <apex:inputHidden value="{!ar.mcae.Adjustment_ratio_Upper__c}" id="Adjustment_ratio_Upper"/>
                                </td>
                                <td class="dataCell" width="35px" >
                                    <apex:outputText value="{!ar.mcae.Adjustment_Lower_price__c}" id="Adjustment_Lower_price"/>
                                    <apex:inputHidden value="{!ar.mcae.LastMContract_Price__c}" id="LastMContract_Price"/>
                                    <apex:inputHidden value="{!ar.mcae.Adjustment_ratio_Lower__c}" id="Adjustment_ratio_Lower"/>
                                    <apex:inputHidden value="{!ar.mcae.Adjustment_Lower_price__c}" id="Adjustment_Lower_priceHidden"/>
                                    <apex:outputPanel layout="none" rendered="{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.createable}" >
                                        <apex:inputHidden value="{!ar.mcae.Estimate_List_Price__c}" id="assetListPriceHidden"/>
                                        <apex:inputHidden value="{!ar.mcae.Estimate_List_Price_Page__c}" id="assetListPricePageHidden" />
                                        <apex:inputHidden value="{!ar.rec.CurrentContract_F__r.Estimate_Num__c}" id="Estimate_NumHidden" />
                                    </apex:outputPanel>
                                    <apex:outputPanel layout="none" rendered="{!Not($ObjectType.Maintenance_Contract_Asset_Estimate__c.createable)}" >
                                        <input type="hidden" value="{!ar.mcae.Estimate_List_Price__c}" id="allPage:allForm:allBlock:assetSection:assetTable:{!Text(cnt-1)}:assetListPriceHidden"/>
                                        <input type="hidden" value="{!ar.rec.CurrentContract_F__r.Estimate_Num__c}" id="allPage:allForm:allBlock:assetSection:assetTable:{!Text(cnt-1)}:Estimate_NumHidden"/>
                                    </apex:outputPanel>
                                    <!-- 20200103 Gzw 计算实际报价金额 start -->
                                        <apex:inputHidden value="{!ar.mcae.Estimate_Cost__c}" id="Estimate_Cost"/>
                                    <!-- 20200103 Gzw 计算实际报价金额 end -->
                                </td>
                                <td class="dataCell" width="35px" style="text-align:right" >
                                    <apex:inputField value="{!ar.mcae.Repair_Price__c}" id="repairPrice" style="ime-mode: disabled; width:95%; text-align:right;" onchange="changeAsset({!productCount})"/>
                                </td>
                               <!-- (2022年12月上线)故障品加费 start -->
                                <td class="dataCell" width="35px" style="text-align:right" >
                                    <apex:outputText value="{!ar.Repair_Price_Auto}" id="Repair_Price_Auto" style="width:95%; disabled:disabled;"/>
                                    <!-- <apex:inputHiddenalue="{!ar.rec.Reson_Can_not_Warranty__c}" id="ResonCannotWarranty"/> -->
                                    <!-- <apex:outputText value="{!ar.Agreed_Date}" id="Agreed_Date" style="width:95%;display: none;"/> -->
                                    <apex:inputField value="{!ar.mcae.Repair_Price_pass__c}" id="Repair_Price_pass" style="width:95%;display: none;"/>
                                    <apex:inputHidden value="{!ar.mcae.IS_Reduced_price_approval__c}" id="ISReducedpriceapproval1"/>
                                     <apex:outputText value="{!ar.rec.Reson_Can_not_Warranty__c}" id="ResonCannotWarranty" style="display:none;" rendered="{!Not(ar.IsManual)}" />
                                </td>
                                <!-- (2022年12月上线)故障品加费 end -->
                                <td class="dataCell" width="70px" style="text-align:right" >
                                    <apex:inputField value="{!ar.mcae.Comment__c}" id="comment" style="width:95%;"/>
                                </td>
                                <!--(2022年12月上线)故障品加费 第三方回归  -->
                                <td class="dataCell" width="40px" style="text-align:center;" >
                                    <apex:inputCheckbox value="{!ar.mcae.Third_Party_Return__c}" id="Third_Party_Return__c"/>
                                </td>
                            </tr>
                            <!-- LJPH-C9SCX7 【委托】合同无空白期的提醒  lt  20211221  start  -->
                            <!-- <script>
                                DefaultStartDate();
                            </script> -->
                            <!-- LJPH-C9SCX7 【委托】合同无空白期的提醒  lt  20211221  end  -->
                            <apex:variable value="{!cnt + 1}" var="cnt" />
                        </apex:repeat>
                </table>
                    </div>
<!-- </div>
         </div> -->
            </apex:outputPanel>
        </apex:pageblocksection>
        <!-- HWAG-B4R3SS  START 20181026-->
        <apex:outputPanel id="sumPanel"  onkeydown="if(event.keyCode==13){searchJs(); return false;}">
        <!-- HWAG-B4R3SS  END 20181026-->
            <table style="width:100%;">
                <tr>
                    <td>
                        <apex:commandButton value="行追加" action="{!addNewRows}" disabled="{!Not($ObjectType.Maintenance_Contract_Asset_Estimate__c.createable) || PageDisabled}"
                            style="margin-left:10px;float:left;" onclick="blockme();" oncomplete="unblockUI();" rerender="allForm" />
                        <apex:commandButton value="刷新选中的保有设备" disabled="{!SaveBtnDisabled || productCount2==0}" action="{!exchangeAsset}" onclick="blockme();" oncomplete="unblockUI();refreshAsset({!productCount});" rerender="allForm" />
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <!-- HWAG-B4R3SS  START 20181026-->
                        <apex:outputText value="选择条件"/>
                        &nbsp;&nbsp;
                        <apex:selectList value="{!text1}" id="text1" size="1" style="width:80px"><apex:selectOptions value="{!textOpts}"/>
                        </apex:selectList>
                        &nbsp;&nbsp;
                        <apex:selectList value="{!cond1}" id="cond1" size="1" style="width:80px">
                        <apex:selectOptions value="{!equalOpts}"/>
                        </apex:selectList>
                        &nbsp;&nbsp;
                        <!-- LJPH-BSS6E2  ---20200911 ---update by rentongxiao start -->
                        <apex:inputText value="{!val1}"
                        id="val1" style="width:100px; background-color:{!IF(contr == '1','#e3f3ff','white')}"/>
                        <!-- LJPH-BSS6E2  ---20200911 ---update by rentongxiao end -->
                        &nbsp;
                        <apex:commandButton value="检索" onclick="searchJs();" style="width:100px" rerender="dummy"/>
                        &nbsp;
                        <apex:commandButton value="清除条件" onclick="clearAndSearch();" style="width:100px" rerender="dummy"/>
                        <!-- HWAG-B4R3SS END 20181026-->
                    </td>
                    <th width="90px" style="text-align:right"></th>
                    <th width="90px" style="text-align:right"></th>
                    <th width="90px" style="text-align:right">设备数量</th>
                    <td width="90px" style="text-align:right"><apex:outputtext value="{!productCount3}" id="productCount3"/></td>
                    <td width="25px">&nbsp;</td>
                    <th width="90px" style="text-align:right">
                        <apex:inputField value="{!estimate.IS_Reduced_price_approval__c}" id="ISReducedpriceapproval" style="display:none"/></th>
                         <!-- <apex:inputField value="{!estimate.IS_Reduced_price_approval__c}" id="ISReducedpriceapproval"/></th> -->
                    <td width="25px">&nbsp;</td>
                    <!--<th width="90px" style="text-align:right">报价总额</th>
                    <th width="90px" style="text-align:right"><span id="allPage:allForm:allBlock:assetListSumNum" ></span></th>-->
                    <th width="90px" style="text-align:right">修理总额</th>
                    <th width="90px" style="text-align:right"><span id="allPage:allForm:allBlock:assetRepairSumNum" ></span></th>
                    <td width="95px">&nbsp;</td>
                </tr>
            </table>
        </apex:outputPanel>
        <apex:pageblocksection columns="1" title="未选择的保有设备" id="assetSection2" >
            <apex:outputLabel />
            <apex:outputPanel >
                <input type="hidden" id="allPage:allForm:allBlock:assetSection2:productCnt2" value="{!productCount2}" />
                <table class="list" style="border-bottom-width: 0px; font-size:13px;" border="0" cellspacing="0" cellpadding="0">
                    <tr class="headerRow" height="30px">
                        <th style="width:25px" class="headerRow  booleanColumn"><input type='checkbox' onClick='checkAll2(this)'/></th>
                        <th style="width:25%" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Name.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Asset_situation__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.SerialNumber.label}</th>
                        <th class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Department_Name__c.label}</th>
                        <!-- <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Installation_Site__c.label}</th> -->
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.IF_Warranty_Service__c.label}</th>
                         <!-- //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start -->
                        <th style="width:90px" class="headerRow  booleanColumn">主机/耗材</th>
                         <!-- //JZHG-BSDUT4 ---20200825---update By rentongxiao---End -->
                        <th class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.EGFlg_fromContract_asset__c.label}</th>
                        <th style="width:150px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Reson_Can_not_Warranty__c.label}</th>
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.InstallDate.label}</th>
                        <!-- <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Asset_Owner__c.label}</th> -->
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Accumulation_Repair_Amount__c.label}</th>
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Estimate_List_Price__c.label}</th>
                    </tr>
                    <apex:variable value="{!1}" var="cnt" />
                    <apex:repeat value="{!unCheckedAssetsView}" var="assetsView" id="outassetTable2">
                        <apex:repeat value="{!assetsView}" var="ar" id="assetTable2">
                            <tr class="dataRow {!IF(MOD(cnt, 2)==0, 'odd', 'even')} {!IF(cnt==1, 'first', '')}" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
                                <td class="dataCell" width="25px">
                                    <apex:inputCheckbox value="{!ar.rec_checkBox_c}" id="assetRowCheckbox2" disabled="{!IF(ar.rec.Maintenance_Price_Month__c == 0 || ar.rec.IF_Warranty_Service__c = '否', 'true', 'false')}"/>
                                </td>
                                <td class="dataCell" width="25%">
                                    <apex:outputField value="{!ar.rec.name}" id="assetName"/>
                                </td>
                                <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.Asset_situation__c}"/>
                                </td>
                                <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.SerialNumber}"/>
                                </td>
                                <td class="dataCell">
                                    <apex:outputField value="{!ar.rec.Department_Name__c}"/>
                                </td>
                                <!-- <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.Installation_Site__c}"/>
                                </td> -->
                                <td class="dataCell" width="90px" style="text-align:center">
                                    <apex:outputField value="{!ar.rec.IF_Warranty_Service__c}"/>
                                </td>
                                 <!-- //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start -->
                                <td class="dataCell" width="90px" style="text-align:center">
                                    <apex:outputField value="{!ar.rec.AssetMark__c}"/>
                                </td>
                                 <!-- //JZHG-BSDUT4 ---20200825---update By rentongxiao---End -->
                                <td class="dataCell" style="text-align:center" >
                                    <apex:outputField value="{!ar.rec.EquipmentGuaranteeFlg__c}"/>
                                </td>
                                <td class="dataCell" width="150px" style="text-align:center">
                                    <apex:outputField value="{!ar.rec.Reson_Can_not_Warranty__c}"/>
                                </td>
                                <td class="dataCell" width="90px" style="text-align:center" >
                                    <apex:outputField value="{!ar.rec.InstallDate}"/>
                                </td>
                                <!-- <td class="dataCell" width="90px">
                                    <apex:outputField value="{!ar.rec.Asset_Owner__c}"/>
                                </td> -->
                                <td class="dataCell" width="90px" style="text-align:right" >
                                    <apex:outputField value="{!ar.rec.Accumulation_Repair_Amount__c}"/>
                                </td>
                                <td class="dataCell" width="90px" style="text-align:right" >
                                    <apex:outputField value="{!ar.rec.Maintenance_Price_Month__c}" />
                                </td>
                            </tr>
                            <apex:variable value="{!cnt + 1}" var="cnt" />
                        </apex:repeat>
                    </apex:repeat>
                </table>
                <apex:outputPanel >
                    <dir align="right">
                        <table>
                            <tr>
                                <td>{!(currPage-1)*selctRecordNum}&nbsp;-&nbsp;{!IF(currPage*selctRecordNum > totalRecords, totalRecords, currPage*selctRecordNum)}</td>
                                <td>&nbsp;&nbsp;共{!totalRecords}个</td>
                                <td align="right" width="115px">显示
                                    <apex:selectList value="{!selRecordOption}" id="selRecordOption" size="1" onchange="blockme();recordNumChangeJs();" disabled="{!IF(totalRecords<10,true,false)}"><apex:selectOptions value="{!recordNum}"/></apex:selectList>条记录
                                </td>
                                <td align="right" width="50px">第{!currPage}页</td>
                                <td align="right" width="45px">
                                    <apex:commandLink action="{!firstPage}" value="首页" id="firstPg" onclick="blockme();" oncomplete="unblockUI();" reRender="allForm" style="{!IF(currPage==1,'display: none;','')}color: blue;"/>
                                    <apex:outputText value="首页" style="{!IF(currPage!=1,'display: none;','')}color: gray;"></apex:outputText>
                                </td>
                                <td align="right" width="40px">
                                    <apex:commandLink action="{!previousPage}" value="上一页" id="previous" onclick="blockme();" oncomplete="unblockUI();" reRender="allForm" style="{!IF(currPage==1,'display: none;','')}color: blue;"/>
                                    <apex:outputText value="上一页" style="{!IF(currPage!=1,'display: none;','')}color: gray;"></apex:outputText>
                                </td>
                                <td width="3px"></td>
                                <td align="left" width="40px">
                                    <!-- HWAG-B4R3SS  START 20181026-->
                                    <apex:commandLink action="{!nextPage}" value="下一页" id="next" onclick="blockme();" oncomplete="unblockUI();" reRender="allForm" style="{!IF(totalPage==currPage ||totalPage == 0,'display: none;','')}color: blue;"/>
                                    <apex:outputText value="下一页" style="{!IF(totalPage!=currPage && totalPage != 0,'display: none;','')}color: gray;"></apex:outputText>
                                </td>
                                <td align="left" width="45px">
                                    <apex:commandLink action="{!endPage}" value="尾页" id="endPg" onclick="blockme();" oncomplete="unblockUI();" reRender="allForm" style="{!IF(totalPage==currPage||totalPage == 0,'display: none;','')}color: blue;"/>
                                    <apex:outputText value="尾页" style="{!IF(totalPage!=currPage
                                        && totalPage != 0,'display: none;','')}color: gray;"></apex:outputText>
                                </td>
                                <!-- HWAG-B4R3SS  END 20181026-->
                                <td align="left">共{!totalPage}页</td>
                            </tr>
                        </table>
                    </dir>
                </apex:outputPanel>
            </apex:outputPanel>
        </apex:pageblocksection>
        <apex:pageblocksection title="合同信息" columns="1" id="contractInfo">
            <apex:outputLabel />
            <apex:outputPanel >
                <table style="width:100%">
                    <tr>
                        <td width="22%"></td>
                        <!-- <td width="14%"></td> -->
                        <td width="22%"></td>
                        <td width="28%"></td>
                        <td width="14%"></td>
                        <td width="14%"></td>
                    </tr>
                    <tr>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.GuidePrice_Down__c.label}</th>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.GuidePrice_Up__c.label}</th>
                        <th style="text-align: center">申请报价金额</th>
                        <th style="text-align: center">合同设备修理总额</th>
                        <th style="text-align: center">合同总金额</th>
                        <!-- 上限合同 20230103 LY start -->
                        <!-- <th style="text-align: center">上限金额</th> -->
                        <!-- 上限合同 20230103 LY end -->
                    </tr>
                    <tr>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.GuidePrice_Down__c}" id="GuidePriceDown" />
                            <apex:inputHidden value="{!estimate.GuidePrice_Down__c}" id="GuidePriceDownHidden" />
                        </td>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.GuidePrice_Up__c}" id="GuidePriceUp" />
                            <apex:inputHidden value="{!estimate.GuidePrice_Up__c}" id="GuidePriceUpHidden" />
                        </td>
                        <td style="text-align: center">
                            <!--<apex:inputField value="{!estimate.Request_quotation_Amount__c}" id="quotation_Amount" />-->
                            <apex:inputField value="{!estimate.Request_quotation_Amount__c}" style="ime-mode: disabled; text-align: right; width:100px" id="quotation_Amount" onchange="checkDiscount(this.value);"/>
                        </td>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.Asset_Repair_Sum_Price__c}" id="assetRepairSumPrice" />
                            <apex:inputHidden value="{!estimate.Asset_Repair_Sum_Price__c}" id="assetRepairSumPriceHidden" />
                        </td>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.Maintenance_Price__c}" id="mainteReal" />
                            <apex:inputHidden value="{!estimate.Maintenance_Price__c}" id="mainteRealHidden"/>
                            <apex:inputHidden value="{!OldMaintenancePrice}" id="oldMainteReal"/>
                        </td>
                        <!-- 上限合同 20230103 LY start -->
                       <!--  <td style="text-align: center">
                            <apex:inputField value="{!estimate.Limit_Price_Amount__c}" style="ime-mode: disabled; text-align: right; width:100px" id="Limit_Price_Amount" />
                        </td> -->
                        <!-- 上限合同 20230103 LY end -->
                    </tr>
                    <tr>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Service_discount_Rate__c.label}</th>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.New_Contract_Type_TxT__c.label}</th>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Combined_rate__c.label}</th>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Consumption_rate_Forecast__c.label}</th>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Estimate_Price_range__c.label}</th>
                    </tr>
                    <tr>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.Service_discount_Rate__c}" id="discount_Rate"/>
                            <apex:inputHidden value="{!estimate.Service_discount_Rate__c}" id="discount_RateHidden" />
                        </td>
                        <td style="text-align: center">
                            <apex:outputText value="{!estimate.New_Contract_Type_TxT__c}" id="Contract_TypeTXT" />
                            <apex:inputHidden value="{!typeresult}" id="Contract_TypeTXTHidden" />
                        </td>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.Combined_rate__c}" id="Combinedrate" />
                            <apex:inputHidden value="{!estimate.Combined_rate__c}" id="CombinedrateHidden" />
                        </td>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.Consumption_rate_Forecast__c}"  />
                        </td>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.Estimate_Price_range__c}"  />
                        </td>
                    </tr>
                    <tr>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.ContractPriceType__c.label}</th>
                        <th style="text-align: center"></th>
                        <th style="text-align: center"></th>
                        <th style="text-align: center"></th>
                        <th style="text-align: center"></th>
                    </tr>
                    <tr>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.ContractPriceType__c}"/>
                        </td>
                        <td style="text-align: center"></td>
                        <td style="text-align: center"></td>
                        <td style="text-align: center"></td>
                        <td style="text-align: center"></td>
                    </tr>
                </table>
            </apex:outputPanel>
        </apex:pageblocksection>
        <apex:pageblocksection title="申请背景" columns="1" id="Appbackground">
            <apex:outputLabel />
            <apex:outputPanel >
                <table style="width:100%">
                    <tr>
                        <td width="10%"></td>
                        <td width="30%"></td>
                        <td width="10%"></td>
                        <td width="50%"></td>
                    </tr>
                    <tr>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.finalPriceDecideWay__c.label}</th>
                        <td><apex:inputField value="{!estimate.finalPriceDecideWay__c}" id="finalPriceDecideWay" style="width:50%;" /></td>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Sales_incidental__c.label}</th>
                        <td><apex:inputField value="{!estimate.Sales_incidental__c}" id="Sales_incidental" style="width:50%;" /></td>
                    </tr>
                    <tr>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.mainTalksTime__c.label}</th>
                        <td ><apex:inputField value="{!estimate.mainTalksTime__c}"  style="width:50%;" id="mainTalksTime"/></td>
                        <th>{!$ObjectType.Maintenance_Contract_Estimate__c.fields.talksStartDate__c.label}</th>
                        <td><apex:inputField value="{!estimate.talksStartDate__c}" id="talksStartDate" style="width:50%;"  /></td>
                    </tr>
                    <tr>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.AgencyHos_Price__c.label}</th>
                        <td ><apex:inputField value="{!estimate.AgencyHos_Price__c}"  style="width:50%;" id="AgencyHos_Price"/></td>
                        <th style="text-align: center"></th>
                        <td ></td>
                    </tr>
                    <tr>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Discount_reason__c.label}</th>
                        <td colspan="3"><apex:inputField value="{!estimate.Discount_reason__c}" id="discountReason" style="width:95%;height:50px;" /></td>
                    </tr>
                    <tr>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Improve_ConsumptionRate_Idea__c.label}</th>
                        <td colspan="3"><apex:inputField value="{!estimate.Improve_ConsumptionRate_Idea__c}" id="improveConsumptionRateIdea" style="width:95%;height:50px;" /></td>
                    </tr>
                </table>
            </apex:outputPanel>
            <script type="text/javascript">
                //var applyType = j$(escapeVfId('allPage:allForm:allBlock:Appbackground:applyType')).val();
                //var obj = document.getElementById('allPage:allForm:allBlock:Appbackground:TypeOther');
                //if (applyType == '其他') {
                //    obj.style.display = "block";
                //} else {
                //    obj.style.display = "none";
                //}
                //resetapplyType();
            </script>
        </apex:pageblocksection>
        <script type="text/javascript">
            var isDisabled = {!PageDisabled};
            if(!isDisabled){
                refreshAsset({!productCount});
            }
        </script>
    </apex:pageBlock>
    <table width="100%" border="0">
        <tr>
            <!-- <td width="40%" style="text-align: right;"> -->
            <td width="50%">
                <table border="0" style="background-color:#ffd6c1;" width="100%">
                    <tr>
                        <th width="50px">打印报价</th>
                        <td width="90px"><apex:inputCheckbox id="check0" onchange="hideSimplify(0);" value="{!estimate.Print_ListPrice__c}" />完整版+折扣前</td>
                        <td width="90px"><apex:inputCheckbox id="check1" onchange="hideSimplify(1);" value="{!estimate.Print_Simplify__c}" />完整版+折扣后</td>
                        <td width="80px"><apex:inputCheckbox id="check2" onchange="hideSimplify(2);" value="{!estimate.Print_RepairPrice__c}"/>简化版+折扣前</td>
                        <td width="80px"><apex:inputCheckbox id="check3" onchange="hideSimplify(3);" value="{!estimate.Print_SumPrice__c}"/>简化版+折扣后</td>
                    </tr>
                    <tr>
                        <th width="70px">打印合同配置</th>
                        <td width="60px">
                        <!-- 2018/10/26HWAG-B5C88S 医院和经销商合同任何时候都不能选择 start -->
                            <apex:outputPanel rendered="false">
                                <apex:inputCheckbox value="{!estimate.Print_Contract__c}" />
                            </apex:outputPanel>
                            <apex:outputPanel rendered="{!Not(EnablePrintContract)}">
                                &nbsp;&nbsp;&nbsp;
                            </apex:outputPanel>
                            医院合同
                        </td>
                        <!-- 2018/09/26 HWAG-B4SCR3 三方和代理商合同在未decide前也不能选择 start -->
                        <td width="60px">
                            <apex:outputPanel rendered="{!EnablePrintContract}">
                                <apex:inputCheckbox id="tripartite" value="{!estimate.Print_Tripartite__c}"/>
                            </apex:outputPanel>
                            <apex:outputPanel rendered="{!Not(EnablePrintContract)}">
                                &nbsp;&nbsp;&nbsp;
                            </apex:outputPanel>
                        三方协议</td>
                        <td width="85px">
                            <apex:outputPanel rendered="false">
                                <apex:inputCheckbox id="agent" value="{!estimate.Print_Agent__c}"/>
                            </apex:outputPanel>
                            <apex:outputPanel rendered="{!Not(EnablePrintContract)}">
                                &nbsp;&nbsp;&nbsp;
                            </apex:outputPanel>
                        代理商合同</td>
                        <!-- 2018/09/26  HWAG-B4SCR3 三方和代理商合同在未decide前也不能选择 end -->
                        <!-- 2018/10/26 HWAG-B5C88S 医院和经销商合同任何时候都不能选择 end -->
                        <td colspan="3" style="text-align: right"><apex:commandButton action="{!print}" value="PDF印刷" rerender="allBlock,pdfPrint"  onclick="if (!onclickCheckchangedAfterPrint('Pt{!SaveBtnDisabled}','false')) return false;" oncomplete="unblockUI();ComputeLTYRepair()"/></td>
                    </tr>
                </table>
            </td>
            <td>
                <table class="btntable" border="0">
                    <tr>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td width="20px">&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td width="30px">&nbsp;</td>
                        <!-- <td><apex:commandButton id="savebtn" action="{!save}" value="{!$Label.Save_Button}" disabled="{!SaveBtnDisabled}" rerender="allForm" onclick="if (!onclickCheckchangedAfterPrint('true','true')) return false;" oncomplete="unblockUI();"/></td> -->
                        <!-- 故障修理费  添加提交修理减价按钮  disabled="true" -->
                        <td><apex:commandButton id="emailSend" action="{!sendEmail}" value="提交RC评估" rerender="allForm" disabled="{!SendEmailBtnDisabled}" onclick="if (!EGFlgconfim()) return false;" oncomplete="unblockUI();"/></td>
                        <td>
                            <apex:commandButton id="approvalbtn1" action="{!toApprovalProcess}" value="提交修理减价审批" disabled="{!ApprovalBtnNewDisabled}" />
                        </td>
                        <td width="200px"><apex:commandButton id="approvalbtn" action="{!approvalProcess}" value="提交待审批" disabled="{!ApprovalBtnDisabled}" rerender="allForm" onclick="if (!KindsAndMonths()) return false;if (!EGFlgconfim()) return false;approvalJs();" oncomplete="unblockUI();toApprovalProcess();"/>
                        <!-- HWAG-B399Q8 2018/08/20 新增请提交待审批 提示字段 start-->
                        &nbsp; <apex:outputText style="color:red;font-size:20px;" value="请提交待审批" rendered="{!IS_Clone_After_Decide}"/>
                        <!-- HWAG-B399Q8 2018/08/20 新增请提交待审批 提示字段 end-->
                        </td>
                    </tr>
                    <tr>
                        <th>{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Contract_Start_Date__c.label}</th>
                        <td><apex:inputField value="{!estimate.Contract_Start_Date__c}" id="contractstartdate" onchange="changeContractStartdate(this.value);"/></td>
                        <td>&nbsp;</td>
                        <th>&nbsp;&nbsp;{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Contract_End_Date__c.label}</th>
                        <td><apex:outputField value="{!estimate.Contract_End_Date__c}" id="contractenddate"/></td>
                        <td>&nbsp;</td>
                        <td><apex:commandButton id="decidebtn" value="{!$Label.QuoteDecision_Button}" disabled="{!DecideBtnDisabled}" onclick="decideJs(); return false;"/></td>
                           <td>  <apex:commandButton id="savebtn" action="{!save}" value="{!$Label.Save_Button}" disabled="{!SaveBtnDisabled}" rerender="allForm" onclick="if (!EGFlgconfim()) return false;" oncomplete="unblockUI();"/>
                        </td>
                        <!-- <td><apex:commandButton id="decidebtn1" value="{!$Label.QuoteDecision_Button}" action="{!dosomething}"/></td> -->
                        <td style="text-align:right"><apex:commandButton id="undecidebtn" action="{!undecide}" value="取消{!$Label.QuoteDecision_Button}" disabled="{!UnDecideBtnDisabled}" rerender="allForm" onclick="blockme();" oncomplete="unblockUI();"/></td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</apex:form>
<apex:outputPanel id="pdfPrint">
<script type="text/javascript">
//j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
function saveBeforeCheckPriceChange() {
    sforce.connection.sessionId = Session_ID;
    var needClearId = false;
    var rowCnt = j$(escapeVfId('allPage:allForm:allBlock:assetSection:productCnt')).val();
    var assIds = "";
    var proIds = "";
    var priceMap = new Map();
    var newProductMap = new Map();
    var newProductCheck = false;
    var nowDate = new Date();
    var createdDate = null;
    var createdDateShow = j$(escapeVfId('allPage:allForm:allBlock:contract:createDateShow')).text();
    var contractDate = new Date(j$(escapeVfId('allPage:allForm:contractstartdate')).value());
    if (createdDateShow.trim() != '') {
        createdDate = new Date(createdDateShow);
        newProductCheck = true;
    } else {
        createdDate = new Date();
    }
    var threeMonthAfter = new Date(createdDate.setMonth(createdDate.getMonth() + 3));
    createdDate = new Date(createdDate.setMonth(createdDate.getMonth() - 3));
    for (var i = 0; i < rowCnt; i++) {
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        var isnew = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNewHidden')).val();
        var price = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val();
        if (isManual == 'true') {
            var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':ProductId'));
            if (a.size() > 0 && a.value() != "000000000000000000" && a.value() != "") {
                if (proIds == "") {
                    proIds = "'" + a.value() + "'";
                } else {
                    proIds = proIds + ",'" + a.value() + "'";
                }
                if (isnew == "true") {
                    priceMap.set(a.value(), price/{!isNewPriceAdj});
                } else {
                    priceMap.set(a.value(), price);
                }
                newProductMap.set(a.value(), isnew);
            } else {
                continue;
            }
        }
        else {
            var aId = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':AssetId')).value();
            if (assIds == "") {
                assIds = "'" + aId + "'";
            } else {
                assIds = assIds + ",'" + aId + "'";
            }
            if (isnew == "true") {
                priceMap.set(aId, price/{!isNewPriceAdj});
            } else {
                priceMap.set(aId, price);
            }
            newProductMap.set(aId, isnew);
        }
    }
    // 选择设备后价格变更check
    if (assIds.length > 0) {
        var sql = "SELECT Id, Maintenance_Price_Month__c, Posting_Date__c, InstallDate from Asset where Id In(" + assIds + ")";
        var rt = sforce.connection.query(sql);
        var asList = rt.getArray("records");
        if (asList != null) {
            for(var i=0;i<asList.length;i++) {
                var asvar = asList[i];
                var asId = asvar["Id"];
                var mprice = asvar["Maintenance_Price_Month__c"];
                var ptDt = asvar["Posting_Date__c"];
                var postingDate = null;
                if (ptDt != null && ptDt != '') {
                    postingDate = new Date(ptDt);
                }
                var inDt = asvar["InstallDate"];
                var installDate = null;
                if (inDt != null && inDt != '') {
                    installDate = new Date(inDt);
                }
                var priceShow = priceMap.get(asId);
                var isNew = newProductMap.get(asId);
                if ('{!DecideBtnDisabled}' == 'true') {
                    if (Number(mprice).toFixed(2) != Number(priceShow).toFixed(2)) {
                        needClearId = true;
                        // j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
                        return needClearId;
                    }
                }
            }
        }
    }
    if (proIds.length > 0) {
        if ('{!DecideBtnDisabled}' == 'false') {
            var oldDateStr = j$('#oldContractDate').value();
            var oldDate = new Date();
            if (oldDateStr != null && oldDateStr != '') {
                oldDate = new Date(oldDateStr);
            }
            var crdt = new Date(j$(escapeVfId('allPage:allForm:allBlock:contract:createDateShow')).text());
            var newContractDate = new Date(j$(escapeVfId('allPage:allForm:contractstartdate')).value());
            var sixMonthAfter = new Date(crdt.setMonth(crdt.getMonth() + 6));
            if ((newContractDate > sixMonthAfter && oldDate <= sixMonthAfter) || (newContractDate <= sixMonthAfter && oldDate > sixMonthAfter)) {
                j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
                return true;
            }
        } else {
            var sql = "SELECT Id, Maintenance_Price_Month__c from Product2 where Id In(" + proIds + ")";
            var rt = sforce.connection.query(sql);
            var pdList = rt.getArray("records");
            if (pdList != null) {
                for(var i=0;i<pdList.length;i++) {
                    var pdvar = pdList[i];
                    var pdId = pdvar["Id"];
                    var mprice = pdvar["Maintenance_Price_Month__c"];
                    var priceShow = priceMap.get(pdId);
                    if (Number(mprice).toFixed(2) != Number(priceShow).toFixed(2)) {
                        needClearId = true;
                        // j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
                        return needClearId;
                    }
                }
            }
        }
    }
    // var changedPrice = j$(escapeVfId('allPage:allForm:changedSubmitPrice')).value();
    // if (changedPrice=='true') {
    //     needClearId = true;
    // }
    return needClearId;
}
// SelectAssetEstimateController#checkchangedAfterPrint と同じロジックにする必要があります。
// true 変更あり、false 変更なし
function checkchangedAfterPrint() {
    sforce.connection.sessionId = Session_ID;
    var needClearId = false;
    //j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
    var changedPrice = j$(escapeVfId('allPage:allForm:changedSubmitPrice')).value();
    // 新規の場合、targetEstimateIdがない、判断いらない
    if ('{!targetEstimateId}' == '') return needClearId;
    if ('{!estimate.Quote_Date__c}' != '' || '{!estimate.Process_Status__c}' != '草案中') {
        // xud 20140529 ここは明細変更判断
        // xudan 20150729 ソート項目にIdを追加
        var sql = "SELECT Id, Asset__c, Asset__r.SerialNumber, Check_Result__c, Product_Manual__c,"
                + " Repair_Price__c, Comment__c, Maintenance_Contract_Estimate__r.Maintenance_Price__c,Third_Party_Return__c"
                + "  FROM Maintenance_Contract_Asset_Estimate__c"
                + " WHERE Maintenance_Contract_Estimate__c = '{!targetEstimateId}'"
                + " ORDER BY id,Asset__c,Product_Manual__c, Asset__r.SerialNumber, Asset__r.Name, Asset__r.Department_Name__c, Asset__r.InstallDate";
        var result = sforce.connection.query(sql);
        var mcaeList = result.getArray("records");
        var inputingList = [];
        var finalPrice = 0;
        // 画面入力値を整理(いらないものを対象外にする)
        var cntWithKara = {!productCount};
        for (var i = 0; i < cntWithKara; i++) {
            var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
            if (isManual == 'true') {
                var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':ProductId'));
                if (a.size() > 0 && a.value() != "000000000000000000" && a.value() != "") {
                    inputingList.push(
                        {'id' : '',
                         'Product_Manual__c' : a.value(),
                         'Check_Result__c' : j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':checkResult')).value(),
                         'Repair_Price__c' : localParseFloat(j$.trim(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).value())),
                         'Comment__c': j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':comment')).value()
                        }
                    );
                } else {
                    continue;
                }
            }
            else {
                inputingList.push(
                    {'id' : j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':AssetId')).value(),
                     'Check_Result__c' : j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':checkResult')).value(),
                     'Repair_Price__c' : localParseFloat(j$.trim(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).value())),
                     'Comment__c': j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':comment')).value()
                    }
                );
            }
        }
        //针对inputingList的重新排序
        var arrayMap = [];
        var ArrayOrderPMCnt = [];
        for(var i=0;i<mcaeList.length;i++){
            var mcaeVar = mcaeList[i];
            var AssetIDOrPMC = mcaeVar["Asset__c"]!=null?mcaeVar["Asset__c"]:mcaeVar["Product_Manual__c"];
            if(arrayMap[AssetIDOrPMC]!=null){
                arrayMap[AssetIDOrPMC] = i;
                ArrayOrderPMCnt[AssetIDOrPMC] = i;
            }else{
                // Product_Manual__c相同的话怎么办
                if(ArrayOrderPMCnt[AssetIDOrPMC]==null){
                    ArrayOrderPMCnt[AssetIDOrPMC] = i;
                }else{
                    var cacheArray = new Array();
                    cacheArray = ArrayOrderPMCnt[AssetIDOrPMC];
                    ArrayOrderPMCnt[AssetIDOrPMC] = cacheArray+','+i;
                }
            }
        }
        var inputingListCache = inputingList;
        var cntLength = mcaeList.length>inputingListCache.length?mcaeList.length:inputingListCache.length;
        if(mcaeList.length!=inputingListCache.length){
            needClearId = true;
            //j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
            return needClearId;
        }
        inputingList = new Array(cntLength);
        var inputingListOut = new Array();
        for(var i=0;i<inputingListCache.length;i++){
            var InputIdOrPMc = inputingListCache[i].id!=""?inputingListCache[i].id:inputingListCache[i].Product_Manual__c;
            var thisArray = ArrayOrderPMCnt[InputIdOrPMc];
            if(thisArray.length!=null){
                thisArray = thisArray.split(',');
                var ORDERCnt = thisArray[0];
                thisArray.shift();
                thisArray = thisArray.join(',');
                ArrayOrderPMCnt[InputIdOrPMc] = thisArray;
            }else{
                var ORDERCnt = thisArray;
            }
            if( ORDERCnt !=null){
                inputingList[ORDERCnt] = inputingListCache[i];
            }else{
                inputingList[ORDERCnt] = inputingListCache[i];
                inputingListOut.push(inputingListCache[i]);
            }
        }
        if( inputingListOut.length>0){
            for(var i = 0; i<inputingListOut.length;i++){
                inputingList.push(inputingListOut[i]);
            }
        }
        //20161122,测试发现Check_Result__c已停用,故而修改对应的Js判断部分
        /*
                            && (((mcae["Check_Result__c"] == null || mcae["Check_Result__c"] == "")
                                  && (inputing["Check_Result__c"] == null || inputing["Check_Result__c"] == "")
                                )
                                || mcae["Check_Result__c"] == inputing["Check_Result__c"]
                               )
        //==================================================================================
                            && (((mcae["Check_Result__c"] == null || mcae["Check_Result__c"] == "")
                                  && (inputing["Check_Result__c"] == null || inputing["Check_Result__c"] == "")
                                )
                                || mcae["Check_Result__c"] == inputing["Check_Result__c"]
                               )
        */
        //原是代码保留
        if (inputingList.length == mcaeList.length && needClearId == false ) {
            for (var i = 0; i < mcaeList.length; i++) {
                var mcae = mcaeList[i];
                finalPrice = mcae["Maintenance_Contract_Estimate__r"]["Maintenance_Price__c"];
                var inputing = inputingList[i];
                if (mcae["Asset__c"] != null && mcae["Asset__c"] != "") {
                    if (inputing["id"] != "" && mcae["Asset__c"] == inputing["id"]
                            && localParseFloat(mcae["Repair_Price__c"]) == inputing["Repair_Price__c"]
                            && (((mcae["Comment__c"] == null || mcae["Comment__c"] == "")
                                  && (inputing["Comment__c"] == null || inputing["Comment__c"] == "")
                                )
                                || mcae["Comment__c"] == inputing["Comment__c"]
                               )
                    ) {
                        // 同じ
                    } else {
                        needClearId = true;
                        break;
                    }
                } else {
                    if (inputing["id"] == "" && mcae["Product_Manual__c"] != null && mcae["Product_Manual__c"] != ""
                            && mcae["Product_Manual__c"] == inputing["Product_Manual__c"]
                            && localParseFloat(mcae["Repair_Price__c"]) == inputing["Repair_Price__c"]
                            && (((mcae["Comment__c"] == null || mcae["Comment__c"] == "")
                                  && (inputing["Comment__c"] == null || inputing["Comment__c"] == "")
                                )
                                || mcae["Comment__c"] == inputing["Comment__c"]
                               )
                    ) {
                        // 同じ
                    } else {
                        needClearId = true;
                        break;
                    }
                }
            }
        } else {
            needClearId = true;
        }
        // xud 20140529 ここは総金額変更判断(割引を変更したらまずい)
        var inputFinalPrice = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:mainteRealHidden')).value();
        if (toNum(inputFinalPrice) != toNum(finalPrice)) {
            needClearId = true;
        }
        if (changedPrice=='true') {
            needClearId = true;
        }
    }
    if (needClearId) {
        //j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
    }
    return needClearId;
}
if ('{!printAsset}' == 'true') {
    //打印保有設備
    // //必须选择打印报价(详细还是简化)
    var con = 0;
    for (j = 0; j < 4; j++) {
        if (j$(escapeVfId('allPage:allForm:check' + j)).attr('checked')) {
            con ++;
        }
    }
    if(con != 1){
        alert('请您勾选打印报价版本,只能勾选一个。');
    }else{
         window.open('/apex/MaintenanceContractEstimateVMPDF?id={!targetEstimateId}', 'MaintenanceContractEstimateVMPDF');
    }
} else if ('{!printContract}' == 'true') {
    // 打印医院合同配置
    window.open('/apex/MceConfigPDF?id={!targetEstimateId}&flag=printContract', 'MceConfigPDF');
} else if ('{!printTripartite}' == 'true') {
    //打印三方合同
    window.open('/apex/MceConfigPDF?id={!targetEstimateId}&flag=printTripartite', 'MceConfigPDF');
} else if ('{!printAgent}' == 'true') {
    //打印经销商合同
    window.open('/apex/MceConfigPDF?id={!targetEstimateId}&flag=printAgent', 'MceConfigPDF');
}else {}
//当选择报价单(详细版)的时候隐藏报价单(简化版)
// 4个选项只可以选一个
function hideSimplify(cb){
    for (j = 0; j < 4; j++) {
        if (j$(escapeVfId('allPage:allForm:check' + j)).attr('checked')) {
            j$(escapeVfId('allPage:allForm:check' + j)).attr('checked',false);
            if (j == cb) {
                j$(escapeVfId('allPage:allForm:check' + j)).attr('checked',true);
            }
        }
    }
}
var isDisabled = {!PageDisabled};
if(!isDisabled){
    refreshAsset({!productCount});
}
</script>
</apex:outputPanel>
</apex:page>
force-app/main/default/pages/SelectAssetEstimateVM.page-meta.xml
New file
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>41.0</apiVersion>
    <availableInTouch>false</availableInTouch>
    <confirmationTokenRequired>false</confirmationTokenRequired>
    <label>SelectAssetEstimateVM</label>
</ApexPage>