/*gzw 优化Maximum view state size limit 追加 Transient */
global class lexSelectAssetEstimateURFController {

    /**
     *  lwc需要后台方法  Asset
     **/
    @AuraEnabled
    public static List<Asset> saveBeforeCheckPriceChangeAsset(String assIds){
        String sqlStr = '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+')';
        List<Asset>  assetList = Database.query(sqlStr);
        return assetList;
    }
    /**
     *  lwc需要后台方法   Product2
     **/
    @AuraEnabled
    public static List<Product2> saveBeforeCheckPriceChangeProduct2(String proIds){
        String sqlStr = 'SELECT Id, Maintenance_Price_Month__c,UFR_Maintenance_Price_Month__c,UFR_Maintenance_Price_Month_3__c FROM Product2 WHERE Id IN ('+proIds+')';
        List<Product2>  product2List = Database.query(sqlStr);
        return product2List;
    }


    
    //行追加  前端需要json化，后端转json
    @AuraEnabled
    public static String addNewRows(String checkedAssetsStr) {
        try {
            List<AssetInfo> checkedAssets = ( List<AssetInfo>)JSON.deserialize(checkedAssetsStr, List<AssetInfo>.class);

            for (Integer i = 0; i < 10; i++) {
                checkedAssets.add(new AssetInfo(checkedAssets.size()));
            }
            return JSON.serialize(checkedAssets);
        }catch (Exception ex) {
            return ex.getMessage();
        }

    }


    //传参处理
    @AuraEnabled
    public static String init(String recordId,String initFlag) {
        try {

            InitData  initData = new InitData();

            initData.currPage = 1;
            initData.selRecordOption = '20';
            initData.totalRecords = 0;
            initData.checkDealerId = '';
            //param 
            // initData.selctRecordNum = Integer.valueOf(initData.selRecordOption);

            //2021-11-30 fy add LJPH-C8W8FV 置顶 start
            initData.TopProductModel.add('CF-LV1I');
            initData.TopProductModel.add('CF-LV1L');
            initData.TopProductModel.add('CV-V1');
            initData.TopProductModel.add('GIF-LV1');
            initData.TopProductModel.add('OER-AW');
            initData.TopProductModel.add('OER-A');
            //2021-11-30 fy add LJPH-C8W8FV 置顶 end
            initData.typeresult = null;
            // AssetHandler.disabled = true;
            initData.changedAfterPrint = false;
            initData.changedSubmitPrice = false;
            initData.isSaveOrApproval = false;
            initData.OldContractStartDate = null;
            initData.OldMaintenancePrice = null;
        
            initData.inDicideFlag = false;
        
            initData.isSoft = false;
            initData.activeOn = true;
            //LJPH-BSS6E2  ---20200911 ---update by rentongxiao start
            initData.contr = '1';
            initData.val1 = '主机';
            //LJPH-BSS6E2  ---20200911 ---update by rentongxiao end

            //2022 故障品加费 获取当前user简档Name
            String uProfileId = UserInfo.getProfileId();
            String UserProfileName = [SELECT Name FROM Profile WHERE Id =: uProfileId].Name;
            if(UserProfileName == '2F3_合同组' || UserProfileName == '系统管理员'){
                initData.isFSE = false;
            }else{
                initData.isFSE = true;
            }
        
            Date systemToday = System.today();

            initData.printAsset = false;
            initData.printContract = false;
            initData.printTripartite = false;
            initData.printAgent = false;
            String copyid = '';
            if (initData.isPageAction == false) {
                if (initFlag == 'copyid') {
                    initData.targetEstimateId = recordId;
                    copyid = recordId;
                }
                if (initData.targetEstimateId == null) {
                    String paramId;
                    if ( initFlag == 'id') {
                        paramId = recordId;
                    }
                    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];
                        initData.targetEstimateId = mcaeParam.Maintenance_Contract_Estimate__c;
                    } else {
                        initData.targetEstimateId = paramId;
                    }
                } else {
                    initData.newIns = true;
                }
                if (initFlag == 'mcid') {
                    initData.targetMaintenanceContractId = recordId;
                }
            }
            // 編集から
            if (String.isBlank(initData.targetEstimateId) == false) {
                initData.estimate = setThisEstimate(initData.estimate,initData);
                initData.targetMaintenanceContractId = initData.estimate.Maintenance_Contract__c;
                initData = setContractInfo(initData.targetMaintenanceContractId,initData);
            }
            // 新規から
            else if (!String.isBlank(initData.targetMaintenanceContractId)) {
                initData.estimate = new Maintenance_Contract_Estimate__c();
                initData.estimate.Maintenance_Contract__c = initData.targetMaintenanceContractId;
                initData.estimate.Contract_Esti_Start_Date__c = systemToday;
                initData.estimate.Contract_Start_Date__c = systemToday;
                initData = setContractInfo(initData.targetMaintenanceContractId,initData);
        
                //LJPH-C9SCX7 【委托】合同无空白期的提醒  lt  20211221  start
                // Date pastDate;
                // for(Maintenance_Contract__c mc1 : [SELECT Id, Past_Contract_end_day__c //过去合同结束日
                //                                             FROM Maintenance_Contract__c 
                //                                             WHERE Id = :initData.targetMaintenanceContractId
                //                                             ]){
                //     pastDate = mc1.Past_Contract_end_day__c;                                        
                // }
                
                // System.debug('lt123pastDate上期合同结束日'+pastDate);
                // if(systemToday < pastDate){
                //     initData.estimate.Contract_Esti_Start_Date__c = pastDate.addDays(1);
                // }else{
                //     initData.estimate.Contract_Esti_Start_Date__c = systemToday;
                // }
                //LJPH-C9SCX7 【委托】合同无空白期的提醒  lt  20211221  end
        
                //this.estimate.Contract_Esti_Start_Date__c = systemToday;
                // initData.estimate.Contract_Start_Date__c = systemToday;
                // initData = setContractInfo(initData.targetMaintenanceContractId,initData);
                initData.newIns = true;
            }
            // 何もなければ、念のため
            else {
                throw new ControllerUtil.myException('无法显示维修合同报价');
                // return;
            }
            //HWAG-B399Q8 2018/08/20  检验是否显示'请提交待审批' start
            initData.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(initData.targetHospitalId) && (initData.targetHospitalId.length() == 15 || initData.targetHospitalId.length() == 18)) {
                //2021-11-30 fy add LJPH-C8W8FV 置顶 start OwnershipMachine_No__c Product2.ProductURF__c
                //tcm 添加 Management_Code__c  20211201 start
                initData.assetRecords = [SELECT Id, Name,OwnershipMachine_No__c, 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, isNewDate_use__c, Asset_Owner__c, Accumulation_Repair_Amount__c, Maintenance_Price_Month__c, Final_Examination_Date__c, CurrentContract_End_Date__c, EquipmentGuaranteeFlg__c,
                                    CurrentContract_F__c, CurrentContract_F__r.Management_Code__c,CurrentContract_F__r.Maintenance_Contract_No_F__c, CurrentContract_F__r.RecordType_DeveloperName__c, CurrentContract_F__r.Estimate_Num__c, CurrentContract_F__r.Contract_End_Date__c, CurrentContract_F__r.Estimate_Contract_endDate__c,
                                CurrentContract_F_asset__c, CurrentContract_F_asset__r.Estimate_Cost_Month_formula__c, CurrentContract_F_asset__r.endDateGurantee_Text__c, CurrentContract_F__r.Gurantee_Estimate_startDate__c,
                                CurrentContract_F__r.First_Estimate_Date__c,
                                CurrentContract_F__r.Contract_Consumption_rate__c, CurrentContract_F__r.First_contract_usage_Rate__c,
                                CurrentContract_F__r.Contract_Range__c, AssetMark__c
                                // 限次合同信息 add by gzw start
                                , Product2.ProductURF__c, Product2.ProductURF__r.URFLimitSerial__c, Product2.ProductURF__r.UFR_MaxRepairCount__c, Product2.ProductURF__r.UFR_Maintenance_Price_Month__c
                                // 限次合同信息 add by gzw end
                                //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
                                , Product2.ProductURF__r.Maintenance_Price_Year_URF_Max__c
                                , Product2.ProductURF__r.Maintenance_Price_Year_URF__c
                                //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
                                //URF限次合同2期 LY 20220811 start
                                , Product2.ProductURF__r.Maintenance_Price_Year_URF_3__c
                                , Product2.ProductURF__r.Maintenance_Price_Year_URF_Max_3__c
                                , Product2.ProductURF__r.UFR_Maintenance_Price_Month_3__c
                                , URF_Maintenance_Contract__c
                                , URF_Maintenance_Contract__r.Management_Code__c
                                , URF_Maintenance_Contract__r.Contract_End_Date__c
                                //URF限次合同2期 LY 20220811 end
                                //20231208 sx add 贸易合规二期 start
                                ,Product2.ProTradeComplianceStatus__c
                                ,Product2.Name
                                //20231208 sx add 贸易合规二期 end
                                FROM Asset WHERE Hospital__c = : initData.targetHospitalId AND ( AssetMark__c != '耗材' OR Product2.Family != 'ET' ) ORDER BY ID, IF_Warranty__c asc];
                //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start
                // assetRecords = [SELECT Id, Name, Asset_situation__c, SerialNumber, Department_Name__c, Installation_Site__c, Posting_Date__c,Management_Code__c,IF_Warranty_Service__c,Reson_Can_not_Warranty__c,
                //                      InstallDate,isNewDate_use__c, Asset_Owner__c, Accumulation_Repair_Amount__c, Maintenance_Price_Month__c, Final_Examination_Date__c,CurrentContract_End_Date__c,EquipmentGuaranteeFlg__c,
                //                      CurrentContract_F__c,CurrentContract_F__r.Maintenance_Contract_No_F__c,CurrentContract_F__r.RecordType_DeveloperName__c,CurrentContract_F__r.Estimate_Num__c,CurrentContract_F__r.Contract_End_Date__c,CurrentContract_F__r.Estimate_Contract_endDate__c,
                //                      CurrentContract_F_asset__c,CurrentContract_F_asset__r.Estimate_Cost_Month_formula__c,CurrentContract_F_asset__r.endDateGurantee_Text__c,CurrentContract_F__r.Gurantee_Estimate_startDate__c,
                //                      CurrentContract_F__r.First_Estimate_Date__c,
                //                     CurrentContract_F__r.Contract_Consumption_rate__c,CurrentContract_F__r.First_contract_usage_Rate__c,
                //                     CurrentContract_F__r.Contract_Range__c ,AssetMark__c
                //                      FROM Asset WHERE Hospital__c = :this.targetHospitalId AND AssetMark__c = '主机' ORDER BY ID,IF_Warranty_Service__c asc];
                //JZHG-BSDUT4 ---20200825---update By rentongxiao---End
            } else {
                initData.assetRecords = new List<Asset>();
            }

            //sqlStr += ' AND AssetMark__c != \'耗材\' AND Product2.Family != \'ET\' ';
            initData.checkedAssets = new List<AssetInfo>();
            initData.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>();
            // 新規、且つ１つ目見積もりの場合、コピー元の保有設備を持つ
            if (String.isBlank(initData.targetEstimateId) && initData.contract.Estimate_Num__c == 0) {
                List<Maintenance_Contract_Asset__c> oldVals = [
                    select Id, Name, Asset__c, Asset__r.InstallDate, Asset__r.isNewDate_use__c,
                    Asset__r.Posting_Date__c, Asset__r.Maintenance_Price_Month__c,
                    Asset__r.EquipmentGuaranteeFlg__c,
                    Asset__r.CurrentContract_F_asset__r.Estimate_Cost_Month_formula__c,
                    Asset__r.CurrentContract_F_asset__r.endDateGurantee_Text__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
                    // 20210315 gzw 追加限次产品信息 start
                    , Asset__r.Product2.ProductURF__c
                    , Asset__r.Product2.ProductURF__r.URFLimitSerial__c,
                    Asset__r.Product2.ProductURF__r.UFR_MaxRepairCount__c,
                    Asset__r.Product2.ProductURF__r.UFR_Maintenance_Price_Month__c
                    // 20210315 gzw 追加限次产品信息 start
                    //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
                    , Asset__r.Product2.ProductURF__r.Maintenance_Price_Year_URF_Max__c, Asset__r.Product2.ProductURF__r.Maintenance_Price_Year_URF__c
                    //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
                    //URF限次合同2期 LY 20220811 start
                    , Asset__r.Product2.ProductURF__r.Maintenance_Price_Year_URF_3__c
                    , Asset__r.Product2.ProductURF__r.Maintenance_Price_Year_URF_Max_3__c
                    , Asset__r.Product2.ProductURF__r.UFR_Maintenance_Price_Month_3__c
                    , Asset__r.URF_Maintenance_Contract__c
                    , Asset__r.URF_Maintenance_Contract__r.Management_Code__c
                    , Asset__r.URF_Maintenance_Contract__r.Contract_End_Date__c
                    //URF限次合同2期 LY 20220811 end
                    from Maintenance_Contract_Asset__c
                    where Maintenance_Contract__c = : initData.targetMaintenanceContractId AND Asset__r.Product2.ProductURF__c != null
                ];
                Date mon1stDate = Date.newInstance(Date.today().year(), Date.today().month(), 1);
                for (Maintenance_Contract_Asset__c mca : oldVals) {
                    // oldより更新したい項目
                    Boolean isNew = false;
                    // add点检改善：新增一个点检对象复选框字段，默认为true 2021.6.8 fxk Star
                    boolean isCheck = true;
                    // add点检改善：新增一个点检对象复选框字段，默认为true 2021.6.8 fxk End
                    Decimal listPrice = mca.Asset__r.Product2.ProductURF__r.UFR_Maintenance_Price_Month_3__c;
                    Decimal asset_Consumption_rate = null;
                    // 取上一期合同消费率
                    if (mca.Asset__r.CurrentContract_F__r.First_Estimate_Date__c != null && mca.Asset__r.CurrentContract_F__r.Estimate_Contract_endDate__c > mon1stDate) {
                        asset_Consumption_rate = mca.Asset__r.CurrentContract_F__r.First_contract_usage_Rate__c;
                    } else {
                        asset_Consumption_rate = mca.Asset__r.CurrentContract_F__r.Contract_Consumption_rate__c;
                    }
                    // InstallDate と 今日を比較
                    // 1.安装日或者发货日和今天比较 实时变化
                    // 2.提交后不再变化
                    //Date createdDate = (estimate.CreatedDate == null || !String.isBlank(copyid)) ? systemToday : estimate.CreatedDate.date();
                    Date createdDate = systemToday;

                    //多年保设备续签计算逻辑调整 2022/12/14 start

                    // if(createdDate.daysBetween(mca.Asset__r.CurrentContract_F_asset__r.startDateGurantee__c) > ( 365+ 365/2)){
                    //     isOrverYear = true;
                    // }else{
                    //     isOrverYear = false;
                    // }

                    // if(mca.Asset__r.Maintenance_Price_Year__c >0){
                    //     MaintenancePriceYear = mca.Asset__r.Maintenance_Price_Year__c;
                    // }
                    // if(mca.Maintenance_Contract__r.FM__c>0){
                    //     Denominator = mca.Maintenance_Contract__r.FM__c;
                    // }
                    // if (mca.Asset__r.Product2.Intra_Trade_Gurantee_RMB__c >0) {
                    //     Accrued = mca.Asset__r.Product2.Intra_Trade_Gurantee_RMB__c;
                    // }
                    // if (mca.Asset__r.Product2.Asset_Model_No__c != null ) {
                    //     ProductModel = mca.Asset__r.Product2.Asset_Model_No__c;
                    // }
                    // if (mca.Asset__r.Product2.Category4__c != null) {
                    //    Category = mca.Asset__r.Product2.Category4__c;
                    // }
                    // if (mca.Maintenance_Contract__r.Consumption_rate_Gurante__c != null) {
                    //     Consumption_rate_Gurante = mca.Maintenance_Contract__r.Consumption_rate_Gurante__c;
                    // }

                    //多年保设备续签计算逻辑调整 2022/12/14 end
                    if (createdDate.addMonths(initData.isNewAddMonth) < mca.Asset__r.isNewDate_use__c) {
                        isNew = true;
                        // add点检改善：新增一个点检对象复选框字段，默认为true 2021.6.8 fxk Star
                        isCheck = true;
                        // add点检改善：新增一个点检对象复选框字段，默认为true 2021.6.8 fxk End
                        listPrice =  mca.Asset__r.Product2.ProductURF__r.UFR_Maintenance_Price_Month_3__c  * initData.isNewPriceAdj;
                    }
                    selectedAssetIds.put(mca.Asset__c, selectedMcaes.size());
                    selectedMcaes.add(new Maintenance_Contract_Asset_Estimate__c(
                                  Asset__c = mca.Asset__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,
                                  // 取上一期合同价格
                                  LastMContract_Price__c = mca.Asset__r.CurrentContract_F_asset__r.Estimate_Cost_Month_formula__c,
        
                                  Asset_Consumption_rate__c = asset_Consumption_rate,
                                  EquipmentGuaranteeFlgTxt__c = mca.Asset__r.EquipmentGuaranteeFlg__c
                                  ));
                }
            } else {
                List<Maintenance_Contract_Asset_Estimate__c> selectlist = [SELECT Id FROM
                                                                           Maintenance_Contract_Asset_Estimate__c
                                                                           WHERE Maintenance_Contract_Estimate__c = :initData.targetEstimateId ];

                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,
                                                                    Asset__r.isNewDate_use__c,
                                                                    Asset__r.EquipmentGuaranteeFlg__c,
                                                                    //2021-11-30 fy add LJPH-C8W8FV 置顶 start
                                                                    Asset__r.OwnershipMachine_No__c,
                                                                    //2021-11-30 fy add LJPH-C8W8FV 置顶 end
                                                                    Asset_Consumption_rate__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,
                                                                    LastMContract_Price__c,
                                                                    Asset__r.CurrentContract_F_asset__r.Estimate_Cost_Month_formula__c,
                                                                    Asset__r.CurrentContract_F_asset__r.endDateGurantee_Text__c,
                                                                    Product_Manual__c,
                                                                    Product_Manual__r.EquipmentGuaranteeFlg__c,
                                                                    Product_Manual__r.Maintenance_Price_Month__c,
                                                                    Product_Manual__r.Name,
                                                                    // 20210315 gzw 追加限次产品信息 start
                                                                    Product_Manual__r.ProductURF__c,
                                                                    Product_Manual__r.ProductURF__r.URFLimitSerial__c,
                                                                    Product_Manual__r.ProductURF__r.UFR_MaxRepairCount__c,
                                                                    Product_Manual__r.ProductURF__r.UFR_Maintenance_Price_Month__c,
                                                                    //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
                                                                    Product_Manual__r.ProductURF__r.Maintenance_Price_Year_URF_Max__c,
                                                                    Product_Manual__r.ProductURF__r.Maintenance_Price_Year_URF__c,
                                                                    //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
                                                                    //URF限次合同2期 LY 20220811 start
                                                                    Product_Manual__r.ProductURF__r.Maintenance_Price_Year_URF_3__c,
                                                                    Product_Manual__r.ProductURF__r.Maintenance_Price_Year_URF_Max_3__c,
                                                                    Product_Manual__r.ProductURF__r.UFR_Maintenance_Price_Month_3__c,
                                                                    //URF限次合同2期 LY 20220811 end
                                                                    //2021-11-30 fy add LJPH-C8W8FV 置顶 start
                                                                    Product_Manual__r.Asset_Model_No__c,
                                                                    //2021-11-30 fy add LJPH-C8W8FV 置顶 end
                                                                    Asset__r.Product2.ProductURF__c,
                                                                    Asset__r.Product2.ProductURF__r.URFLimitSerial__c,
                                                                    Asset__r.Product2.ProductURF__r.UFR_MaxRepairCount__c,
                                                                    Asset__r.Product2.ProductURF__r.UFR_Maintenance_Price_Month__c,
                                                                    // WYL 贸易合规2 期 start
                                                                    Asset__r.Product2.Asset_Model_No__c,
                                                                    // WYL 贸易合规2 期 end
                                                                    //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
                                                                    Asset__r.Product2.ProductURF__r.Maintenance_Price_Year_URF_Max__c,
                                                                    Asset__r.Product2.ProductURF__r.Maintenance_Price_Year_URF__c,
                                                                    //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
                                                                    //URF限次合同2期 LY 20220811 start
                                                                    Asset__r.Product2.ProductURF__r.Maintenance_Price_Year_URF_3__c,
                                                                    Asset__r.Product2.ProductURF__r.Maintenance_Price_Year_URF_Max_3__c,
                                                                    Asset__r.Product2.ProductURF__r.UFR_Maintenance_Price_Month_3__c,
                                                                    Asset__r.URF_Maintenance_Contract__c,
                                                                    Asset__r.URF_Maintenance_Contract__r.Management_Code__c,
                                                                    Asset__r.URF_Maintenance_Contract__r.Contract_End_Date__c,
                                                                    //URF限次合同2期 LY 20220811 end
                                                                    URF_Series__c,
                                                                    Series_RepairCount__c,
                                                                    Series_MaxRepairCount__c,
                                                                    Asset_RepairCount__c,
                                                                    Asset_MaxRepairCount__c,
                                                                    // 20210315 gzw 追加限次产品信息 start
                                                                    IsNew__c,
                                                                    //add 2021.6.4 fxk  Start
                                                                    Check_Object__c,
                                                                    //add 2021.6.4 fxk  end
                                                                    Estimate_List_Price__c,
                                                                    //Maintenance_Price_YearTXT__c,
                                                                    Estimate_Cost__c,
                                                                    Adjustment_ratio_Upper__c,
                                                                    Adjustment_ratio_Lower__c,
                                                                    Adjustment_Lower_price__c,
                                                                    Adjustment_Upper_price__c,
                                                                    Last_inspection_day__c,
                                                                    Check_Result__c,
                                                                    Repair_Price__c,
                                                                    Comment__c,
                                                                    Asset__r.Posting_Date__c,
                                                                    EquipmentGuaranteeFlgTxt__c,
                                                                    EquipmentGuaranteeFlg__c,
                                                                    ifHaveleftInPrevious__c,
                                                                    // Gzw 20200807 五个去年合同相关，所以报价产品，获取上期合同 start
                                                                    Last_MContract__c
                                                                    // Gzw 20200807 五个去年合同相关，所以报价产品，获取上期合同 eng
                                                                    // LJPH-C9GD34 gzw fix start
                                                                    ,Estimate_List_Price_Page__c
                                                                    // LJPH-C9GD34 gzw fix end
                                                                    FROM Maintenance_Contract_Asset_Estimate__c
                                                                    WHERE Maintenance_Contract_Estimate__c = :initData.targetEstimateId
                                                                                                             ORDER BY
                                                                                                             Id,
                                                                    Asset__c,
                                                                    Product_Manual__c,
                                                                    Asset__r.SerialNumber,
                                                                    Asset__r.Name,
                                                                    Asset__r.Department_Name__c,
                                                                    Asset__r.InstallDate
                     ]) {


                    if (!getPageDisabled(initData.contract,initData.estimate) || getPageDisabled(initData.contract,initData.estimate)  && String.isBlank(copyid) == false){
                        //if (String.isBlank(copyid) == false) {
                        if (mcae.Asset__c <> null) {
                            mcae.EquipmentGuaranteeFlgTxt__c = mcae.Asset__r.EquipmentGuaranteeFlg__c;
                            if (systemToday.addMonths(initData.isNewAddMonth) < mcae.Asset__r.isNewDate_use__c) {
                                mcae.IsNew__c = true;
                                // mcae.Estimate_List_Price__c = mcae.Asset__r.Maintenance_Price_Month__c * initData.isNewPriceAdj;
                                if (String.isNotBlank(mcae.Asset__r.Product2.ProductURF__c)) {
                                    mcae.Estimate_List_Price__c = mcae.Asset__r.Product2.ProductURF__r.UFR_Maintenance_Price_Month_3__c * initData.isNewPriceAdj;                               
                                }
                            } else {
                                mcae.IsNew__c = false;
                                // mcae.Estimate_List_Price__c = mcae.Asset__r.Maintenance_Price_Month__c;
                                if(String.isNotBlank(mcae.Asset__r.Product2.ProductURF__c)){
                                    mcae.Estimate_List_Price__c = mcae.Asset__r.Product2.ProductURF__r.UFR_Maintenance_Price_Month_3__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 * initData.isNewPriceAdj;
                            if (String.isNotBlank(mcae.Product_Manual__r.ProductURF__c)) {
                                mcae.Estimate_List_Price__c = mcae.Product_Manual__r.ProductURF__r.UFR_Maintenance_Price_Month_3__c * initData.isNewPriceAdj;
                                
                            }
                        }
                    }
                    if (mcae.Asset__c <> null) {
                        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO , mcae.Asset__c + 'IsNew  ' + mcae.IsNew__c));
                        // selectedAssetIds.put(mcae.Asset__c, selectedMcaes.size());
                        // selectedMcaes.add(mcae);
                        if ((String.isNotBlank(mcae.Asset__r.Product2.ProductURF__c) && String.isNotBlank(copyid) ) ||
                            ((getSaveBtnDisabled(initData.contract,initData.estimate) && String.isBlank(copyid)) ||
                             (String.isBlank(copyid) && !getSaveBtnDisabled(initData.contract,initData.estimate) && String.isNotBlank(mcae.Asset__r.Product2.ProductURF__c)))) {
                            // if ((getSaveBtnDisabled() && String.isBlank(copyid) )|| (((!getSaveBtnDisabled() && String.isBlank(copyid)) && String.isNotBlank(copyid)) && String.isNotBlank(mcae.Asset__r.Product2.ProductURF__c))){
                            // ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, '1 +  ' + selectedMcaes.size()));
                            selectedAssetIds.put(mcae.Asset__c, selectedMcaes.size());
                            selectedMcaes.add(mcae);
                        }
                    } else {
                        // newMcaes.add(mcae);
                        if ((String.isNotBlank(mcae.Product_Manual__r.ProductURF__c) && String.isNotBlank(copyid) ) ||
                            ((getSaveBtnDisabled(initData.contract,initData.estimate) && String.isBlank(copyid)) ||
                             (String.isBlank(copyid) && !getSaveBtnDisabled(initData.contract,initData.estimate) && String.isNotBlank(mcae.Product_Manual__r.ProductURF__c)))) {
                            // if (getSaveBtnDisabled() || (!getSaveBtnDisabled() && String.isNotBlank(mcae.Product_Manual__r.ProductURF__c))){
                            newMcaes.add(mcae);
                        }

                    }
                }
            }
            // 選択済みのものにチェックを付ける
            // TODO xudan 一覧に出る明細件数が足りないケースがある
            // ①AssetA―明細Aで明細登録
            // ②Assetの検索条件変更により、AssetAは永遠に取得できない
            // ③Assetを元にデータをマッピングする時、明細マップからAssetAを取得できない?一覧に明細Aが出ない
            // 次回、Assetの検索条件が大きく変更する時、対応必要
            // List<Data> datatemp = new List<Data>();
            // Map<String,repair__c> assNewRepMap  = new Map<String,repair__c>();
            // assNewRepMap = getNewrep(this.assetRecords);
            // datatemp = getChartData();
            for (Asset ast : initData.assetRecords) {
                Boolean isNew = false;
                // Decimal listPrice = ast.Maintenance_Price_Month__c;
                Decimal listPrice = ast.Product2.ProductURF__r.UFR_Maintenance_Price_Month_3__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;
                    //                }
                    //              // 计算上下线调整比例
                    //              没有提交 或者在报价时从新计算
                    if (!getPageDisabled(initData.contract,initData.estimate)  || (getPageDisabled(initData.contract,initData.estimate)  && String.isBlank(copyid) == false)) {
                        Date mon1stDate = Date.newInstance(Date.today().year(), Date.today().month(), 1);
                        selectedLocal.LastMContract_Price__c = selectedLocal.Asset__r.CurrentContract_F_asset__r.Estimate_Cost_Month_formula__c == null ?   selectedLocal.LastMContract_Price__c : selectedLocal.Asset__r.CurrentContract_F_asset__r.Estimate_Cost_Month_formula__c;
                        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO , 'LastMContract_Price__c--' + selectedLocal.LastMContract_Price__c));
                        if (selectedLocal.Asset__r.CurrentContract_F__r.First_Estimate_Date__c != null && selectedLocal.Asset__r.CurrentContract_F__r.Estimate_Contract_endDate__c > mon1stDate) {
                            selectedLocal.Asset_Consumption_rate__c = selectedLocal.Asset__r.CurrentContract_F__r.First_contract_usage_Rate__c == null ? selectedLocal.Asset_Consumption_rate__c : selectedLocal.Asset__r.CurrentContract_F__r.First_contract_usage_Rate__c;
                        } else {
                            selectedLocal.Asset_Consumption_rate__c = selectedLocal.Asset__r.CurrentContract_F__r.Contract_Consumption_rate__c == null ? selectedLocal.Asset_Consumption_rate__c : selectedLocal.Asset__r.CurrentContract_F__r.Contract_Consumption_rate__c;
                        }
                        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO , selectedLocal.Asset__r.CurrentContract_F__r.First_Estimate_Date__c + 'Asset_Consumption--- ' + selectedLocal.Asset__r.CurrentContract_F__r.Estimate_Contract_endDate__c));
        
                        // if (String.isNotBlank(String.valueOf(selectedLocal.Asset_Consumption_rate__c))) {
                        //     //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO , 'Contract_Consumption_rate__c ' + selectedLocal.Asset__r.CurrentContract_F__r.Contract_Consumption_rate__c));
                        //     for (Data da : datatemp) {
                        //         if (String.isBlank(String.valueOf(da.rate_Lower)) &&  selectedLocal.Asset_Consumption_rate__c < da.rate_Upper) {
                        //             selectedLocal.Adjustment_ratio_Lower__c = da.price_Lower;
                        //             selectedLocal.Adjustment_ratio_Upper__c = da.price_Upper;
                        //             continue;
                        //         } else if (selectedLocal.Asset_Consumption_rate__c >= da.rate_Lower && String.isBlank(String.valueOf(da.rate_Upper))) {
                        //             selectedLocal.Adjustment_ratio_Lower__c = da.price_Lower;
                        //             selectedLocal.Adjustment_ratio_Upper__c = da.price_Upper;
                        //             continue;
                        //         } else if (selectedLocal.Asset_Consumption_rate__c >= da.rate_Lower
                        //                    && selectedLocal.Asset_Consumption_rate__c < da.rate_Upper) {
                        //             selectedLocal.Adjustment_ratio_Lower__c = da.price_Lower;
                        //             selectedLocal.Adjustment_ratio_Upper__c = da.price_Upper;
                        //             continue;
        
                        //         }
                        //         //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO , '下限＋上限--- ' + selectedLocal.Adjustment_ratio_Lower__c + '  ' + selectedLocal.Adjustment_ratio_Upper__c));
                        //     }
                        //     //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO , '下限＋上限+++ ' + selectedLocal.Adjustment_ratio_Lower__c + '  ' + selectedLocal.Adjustment_ratio_Upper__c));
                        // }
                    }
        
                    //
                    //
                    //
                    initData.checkedAssets.add(new AssetInfo(initData.checkedAssets.size(), ast, isNew, listPrice, selectedLocal));
                } else {
                    if (String.isBlank(ast.Product2.ProductURF__c)) continue;

                    //update by rentongxiao 2020-09-23 start
                    if (ast.AssetMark__c == '主机') {
                        initData.totalRecords++;
                        // 2023/09/01 每页显示数量 -分页  -分页改到前端处理 注释原有逻辑
                        // if (initData.unCheckedAssets.size() < initData.selctRecordNum) {
                            initData.unCheckedAssets.add(new AssetInfo(initData.unCheckedAssets.size(), ast));
                        // }
                    }
                    //update by rentongxiao 2020-09-23 end
        
                }
                // listCut(initData.unCheckedAssets);
                /*
                   if (ast.CheckBox__c) {
                        checkedAssets.add(new AssetInfo(checkedAssets.size(), ast, isNew, listPrice));
                   } else {
                        unCheckedAssets.add(new AssetInfo(unCheckedAssets.size(), ast));
                   }
                 */
            }
            initData.unCheckedAssetsView = listCut(initData.unCheckedAssets,initData.unCheckedAssetsView);

            initData.totalPage = (initData.totalRecords / initData.selctRecordNum) + (Math.mod(initData.totalRecords, initData.selctRecordNum) > 0 ? 1 : 0);


            for (Maintenance_Contract_Asset_Estimate__c mcae : newMcaes) {
                initData.checkedAssets.add(new AssetInfo(initData.checkedAssets.size(), mcae));
            }
        
            // 最後10行追加
            //2023/06/14  补充条件:checkedAssets != null
            if (Schema.getGlobalDescribe().get('Maintenance_Contract_Asset_Estimate__c').getDescribe().isCreateable()) {
                initData.checkedAssets = addNewRows(initData.checkedAssets);
            }
        
            if (!String.isBlank(copyid)) {
                initData.targetEstimateId = null;
                initData.estimate = new Maintenance_Contract_Estimate__c();
                initData.estimate.Maintenance_Contract__c = initData.targetMaintenanceContractId;
            }
            // 2021-02-07  gzw add  LJPH-BWY5QB start
            // setEndUserType(initData.targetMaintenanceContractId);
            initData = setEndUserType(initData.targetMaintenanceContractId,initData);
            // 2021-02-07  gzw add  LJPH-BWY5QB start
            initData.assetRecords.clear();
            // 根据合同开始日重新计算维修合同价格
            //contractStartDateChange();
            //2021-11-30 fy add LJPH-C8W8FV 置顶 start
            List<AssetInfo> topAsset =new List<AssetInfo>();
            List<AssetInfo> otherAsset =new List<AssetInfo>();
            
            for(AssetInfo ched : initData.checkedAssets){
                if(initData.TopProductModel.contains(ched.ProductModelNoc)||initData.TopProductModel.contains(ched.AssetModelNoc)||initData.TopProductModel.contains(ched.rec.OwnershipMachine_No__c)){
                    ched.CheckRows = true;
                    ched.mcae.Check_Object__c = false;
                    topAsset.add(ched);
                }else{
                    otherAsset.add(ched);
                }
            }
            topAsset.addAll(otherAsset);
            List<AssetInfo> NumberSort =new List<AssetInfo>();
            Integer i=0;
            for (AssetInfo ched2 : topAsset) {
                ched2.lineNo=i;
                i++;
                NumberSort.add(ched2);
            }
            initData.checkedAssets=NumberSort;
            //2021-11-30 fy add LJPH-C8W8FV 置顶 end
            //返回结果
            return JSON.serialize(initData);
        }catch(Exception ex){
            return ex.getMessage();
        }
    }

    // 2021-02-07  gzw add  LJPH-BWY5QB start
    private static InitData setEndUserType(String id,InitData  initData) {
        initData.contract = [SELECT Id, Name,AccDealerBlacklist__c,  AccDealerBlacklist2__c,//WYL 贸易合规2期 add
                             Status__c, Decided_Estimation__c, Service_Contract_Staff__c,
                         Estimate_Num__c, Management_Code__c, Hospital__c,
                         Hospital__r.MaintenanceContractUserType__c,
                         Contract_Start_Date__c, Contract_End_Date__c
                         FROM Maintenance_Contract__c WHERE Id = :id];
        if (initData.estimate.Process_Status__c == '草案中' || String.IsBlank(initData.estimate.Process_Status__c)) {
    
            initData.estimate.EndUserType__c = initData.contract.Hospital__r.MaintenanceContractUserType__c == false ? '新用户' : '既有用户';
        }
        return initData;
    }

    public static List<AssetInfo> addNewRows(List<AssetInfo> checkedAssets) {
        for (Integer i = 0; i < 10; i++) {
            checkedAssets.add(new AssetInfo(checkedAssets.size()));
        }
        return checkedAssets;
    }

    //list分割 集合大小超过1000对应
    private static List<List<AssetInfo> > listCut(List<AssetInfo> records,List<List<AssetInfo> > unCheckedAssetsView) {
        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();
        unCheckedAssetsView.add(records);
        return unCheckedAssetsView;
    }

    // 页面项目非活性设定
    public static Boolean getPageDisabled(Maintenance_Contract__c contract,Maintenance_Contract_Estimate__c estimate) {
        if (String.isBlank(contract.Decided_Estimation__c) == false) {
            return true;
        }
        if (String.isBlank(estimate.Process_Status__c) == false
            && estimate.Process_Status__c != '草案中'
            ) {
            return true;
        }
        return false;
    }
    public static Boolean getSaveBtnDisabled(Maintenance_Contract__c contract,Maintenance_Contract_Estimate__c estimate) {
        // 見積もりsaveできない条件の判断
        if (String.isBlank(contract.Decided_Estimation__c) == false) {
            return true;
        }
        if (String.isBlank(estimate.Process_Status__c) == false
            && estimate.Process_Status__c != '草案中'
            //&& this.estimate.Process_Status__c != '不批准'
            ) {
            return true;
        }
        return false;
    }

    private static InitData setContractInfo(String id,InitData  initData) {
        initData.contract = [SELECT Id, Name,AccDealerBlacklist__c, 
                            AccDealerBlacklist2__c,//WYL 贸易合规2期 add
                            Status__c, Decided_Estimation__c, Service_Contract_Staff__c,
                         Estimate_Num__c, Management_Code__c, Hospital__c,
                         //2021-01-18  mzy add  LJPH-BWY5QB   客户上的 维修合同用户类型 为true /false,报价 用户类型为 既有用户 / 新用户
                         // Hospital__r.MaintenanceContractUserType__c,
                         //2021-01-18  mzy add  LJPH-BWY5QB   客户上的 维修合同用户类型 为true /false,报价 用户类型为 既有用户 / 新用户
                         Contract_Start_Date__c, Contract_End_Date__c
                         FROM Maintenance_Contract__c WHERE Id = :id];
        initData.targetHospitalId = initData.contract.Hospital__c;
        // 2021-01-18  mzy  add LJPH-BWY5QB   客户上的 维修合同用户类型 为true /false,报价 用户类型为 既有用户 / 新用户
        // if(this.estimate.Process_Status__c == '草案中' || String.IsBlank(this.estimate.Process_Status__c)){
    
        //    this.estimate.EndUserType__c = this.contract.Hospital__r.MaintenanceContractUserType__c == false ? '新用户' : '既有用户';
        // }
        // 2021-01-18  mzy  add LJPH-BWY5QB   客户上的 维修合同用户类型 为true /false,报价 用户类型为 既有用户 / 新用户
        return initData;
    }

    private static Maintenance_Contract_Estimate__c setThisEstimate(Maintenance_Contract_Estimate__c  estimate,InitData initData) {
        //HWAG-B399Q8 2018/08/20  添加一额外字段 IS_Clone_After_Decide__c start
        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
                         //打印报价（简化版） 2019/12/18 start
                         , IS_Clone_After_Decide__c, New_contract_offer__c, NewEstimation_Amount__c, EndUserType__c, Print_Simplify__c
                         //打印报价（简化版） 2019/12/18 end
                         //最低价格 最高价格 申请背景相关字段 20200108 start
                         , GuidePrice_Up__c, GuidePrice_Down__c, finalPriceDecideWay__c, mainTalksTime__c, talksStartDate__c
                         , Combined_rate__c, New_Contract_Type_TxT__c, Estimate_Price_range__c
                         //最低价格 最高价格计算 20200108 end
                         , Sales_incidental__c, Consumption_rate_Forecast__c, AgencyHos_Price__c
                         // 申请报价金额 和 相对标准价格范围的折扣率
                         , Request_quotation_Amount__c, Service_discount_Rate__c, ContractPriceType__c
                         , 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
                        // URF限次合同2期 LY 20220811 start
                        ,Is_RecognitionModel__c
                        ,URF_P_MaxRepairCount__c,URF_V_MaxRepairCount__c
                        ,URFMContract1__c,URFMContract1_startDate__c,URFMContract1_endDate__c
                        //,URFMContract2__c,URFMContract3__c,URFMContract4__c,URFMContract5__c
                        ,URF_LastMContract1_NO__c,URF_LastMContract2_NO__c,URF_LastMContract3_NO__c,URF_LastMContract4_NO__c,URF_LastMContract5_NO__c
                        ,URF_LastMContract1_ConCount__c,URF_LastMContract2_ConCount__c,URF_LastMContract3_ConCount__c,URF_LastMContract4_ConCount__c,URF_LastMContract5_ConCount__c
                        // URF限次合同2期 LY 20220811 end
                        //贸易合规 you start
                        ,Maintenance_Contract__r.AccDealerBlacklist__c 
                        ,Maintenance_Contract__r.AccDealerBlacklist2__c//WYL 贸易合规2期 add
                        ,Maintenance_Contract__r.Hospital__r.Name
                        ,Maintenance_Contract__r.Dealer__r.Name
                        ,CreatedById
                        //贸易合规 you end

                         FROM Maintenance_Contract_Estimate__c WHERE Id = :initData.targetEstimateId];
        // //HWAG-B399Q8 2018/08/20  添加一额外字段 IS_Clone_After_Decide__c end
        // //故障品加费 2023/1/3 start
        // Boolean hasSendEmail = initData.estimate.Send_Email_To_RC__c;
        // //故障品加费 2023/1/3 end
        decimal PriceSum =  (estimate.Maintenance_Contract__r.Payment_Plan_Sum_First__c == null ? 0 : estimate.Maintenance_Contract__r.Payment_Plan_Sum_First__c) +
                           (estimate.Maintenance_Contract__r.Payment_Plan_Sum_Second__c == null ? 0 : estimate.Maintenance_Contract__r.Payment_Plan_Sum_Second__c) +
                           (estimate.Maintenance_Contract__r.Payment_Plan_Sum_Third__c == null ? 0 : estimate.Maintenance_Contract__r.Payment_Plan_Sum_Third__c) +
                           (estimate.Maintenance_Contract__r.Payment_Plan_Sum_Forth__c == null ? 0 : estimate.Maintenance_Contract__r.Payment_Plan_Sum_Forth__c) +
                           (estimate.Maintenance_Contract__r.Payment_Plan_Sum_Fifth__c == null ? 0 : estimate.Maintenance_Contract__r.Payment_Plan_Sum_Fifth__c) +
                           (estimate.Maintenance_Contract__r.Payment_Plan_Sum_Sixth__c == null ? 0 : estimate.Maintenance_Contract__r.Payment_Plan_Sum_Sixth__c);
        String isPaymentSet;
        if ( estimate.Maintenance_Contract__r.Payment_Plan_Sum_First__c == null
             //102018/10/26 HWAG-B5C88S 不再根据是否填写第一次付款日期判断
             ) {
            isPaymentSet = 'false';
        } else if (estimate.Maintenance_Price__c != PriceSum) {
            isPaymentSet = 'Denied';
        } else {
            isPaymentSet = 'true';
        }
        return estimate;
    }


    @AuraEnabled
    public static String save(String saveData) {
        try{
            InitData  initData = (InitData)JSON.deserialize(saveData, InitData.class);

            //add by rentx 2020-11-13 LJPH-BV93RZ start 
            if (initData.estimate.Contract_Range__c == null || initData.estimate.Contract_Range__c  <= 0) {
                return '必须输入合同月数!';
            }
            // NextMaintenanceContract(initData.checkedAssets,initData.contract);
            //add by rentx 2020-11-13 LJPH-BV93RZ end
        
            Id vmMaintenance_Contract = Schema.SObjectType.Maintenance_Contract_Estimate__c.getRecordTypeInfosByDeveloperName().get('NewMaintenance_Quote').getRecordTypeId();
            initData.estimate.recordtypeid = vmMaintenance_Contract;
            if (initData.changedSubmitPrice) {
                initData.checkedAssets = priceChangeReset(initData.checkedAssets);
                return null;
            }
             // AssetHandler.disabled = true;
            String syncEstimateResult = syncEstimate(false, false,initData) ;
            if (syncEstimateResult == 'true') {
                // 故障品加费2022/11/18
                // if (estimate.IS_Reduced_price_approval__c=='否' || estimate.IS_Reduced_price_approval__c=='审批中') {
                //  Approval.ProcessSubmitRequest psr = new Approval.ProcessSubmitRequest();
                // psr.setObjectId(this.estimate.id);
                // Approval.ProcessResult submitResult = Approval.process(psr);
                String computeLTYRepairResult =  ComputeLTYRepair(initData.targetEstimateId);
                if (computeLTYRepairResult != null) {
                    return computeLTYRepairResult;
                }
                return '/' + initData.targetEstimateId + '/e?completion=5';
            }
            else{
                return syncEstimateResult;
            }
        }catch(Exception ex){
            return ex.getMessage();
        }
    }
    /** 保存返回 **/
    @AuraEnabled
    public static String saveAndCancel (String saveData) {
        try {
            InitData  initData = (InitData)JSON.deserialize(saveData, InitData.class);

            // AssetHandler.disabled = true;
            // Oly_TriggerHandler.bypass('Maintenance_Contract_Asset__c');
            // Oly_TriggerHandler.bypass('AssetHandler');
            //  Oly_TriggerHandler.bypass('AssetTrigger');
            //add by rentx 2020-11-13 LJPH-BV93RZ start
            if (initData.estimate.Contract_Range__c == null) {
                
                return '必须输入合同月数!';
            }
            if (!String.isNotBlank(initData.estimate.URF_V_MaxRepairCount__c)) {

                return '请选择URF-V最大大修次数!';
            }
            if (!String.isNotBlank(initData.estimate.URF_P_MaxRepairCount__c)) {

                return '请选择URF-P最大大修次数!';
            }

            // NextMaintenanceContract(initData.checkedAssets,initData.contract);
            
            //add by rentx 2020-11-13 LJPH-BV93RZ end
            String syncEstimateResult = syncEstimate(false, false,initData) ;

            if (syncEstimateResult == 'true') {
                // PageReference ret = null;
                String ret = null;
                if (initData.targetMaintenanceContractId != null) {
                    //避免其他地方存在同样的 / ,添加标识
                    ret = '/navigateTo=' + initData.targetMaintenanceContractId;
                }
                return ret;
            }else{
                return syncEstimateResult; 
            }
        }catch(Exception ex){
            return ex.getMessage();
        }
    }
    // 前端调用方法
    @AuraEnabled
    public static String onChDealerUpdate(String estimateStr,String checkDealerId){
        try {
            Maintenance_Contract_Estimate__c estimate = (Maintenance_Contract_Estimate__c)JSON.deserialize(estimateStr, Maintenance_Contract_Estimate__c.class);
            estimate = onChDealerUpdate(estimate,checkDealerId);
            return JSON.serialize(estimate);
        }catch(Exception ex){
            return ex.getMessage();
        }
    }
    //废弃中=========20161024==============//
    @AuraEnabled
    public static String ShowLTYRepair(String targetEstimateId) {
        try {
            //组装返回json
            String returnJson = '{';
            Decimal lastFriYearsPriceSum = 0;
            returnJson += '"lastFriYearsPriceSum":"'+lastFriYearsPriceSum+'",';

            Decimal lastSecYearsPriceSum = 0;
            returnJson += '"lastSecYearsPriceSum":"'+lastFriYearsPriceSum+'",';
            //
            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) + '';
                //initData.alertString
                String alertString = '集計対象期間：' + DateString1.substring(0, 10) + '~' + DateString2.substring(0, 10) + '';
                String alertString2 = '去年修理実績合計：' + McecEle.Last_Year_Repair_Sum__c + ' RMB ';
                String alertString3 = '前年修理実績合計：' + McecEle.Year_Before_Last_Year_Re_Sum__c + ' RMB';
                returnJson += '"alertString":"'+alertString+'",';
                returnJson += '"alertString2":"'+alertString2+'",';
                returnJson += '"alertString3":"'+alertString3+'",';
            } else {
                String alertString = '没有有效的维修合同报价';
                returnJson += '"alertString":"'+alertString+'",';
            }
            return returnJson.substring(0,returnJson.length() - 1)+'}';
        }catch(Exception ex){
            return ex.getMessage();
        }
    }
     /**
     * 申請メソッド、最後必ず承認プロセスに載せる
     */
    @AuraEnabled
    public static String approvalProcess(String initDataStr) {
        try {
            InitData initData = (InitData)JSON.deserialize(initDataStr,InitData.class);

            Id vmMaintenance_Contract = Schema.SObjectType.Maintenance_Contract_Estimate__c.getRecordTypeInfosByDeveloperName().get('NewMaintenance_Quote').getRecordTypeId();
            initData.estimate.recordtypeid = vmMaintenance_Contract;
        
            // Date systemToday = System.today();
            // // 创建日/提交日
            // Date createdDate = systemToday;
            // // 创建日6个月
            // Date isNewAfter = createdDate.addMonths(-isNewAddMonth);
            // // 合同开始预定日
            // Date contractEstiDate = estimate.Contract_Esti_Start_Date__c == null ? systemToday : estimate.Contract_Esti_Start_Date__c;
            //  for (AssetInfo info : checkedAssets) {
            //       // 合同预定开始日 大于提交日6个月，都不算新品 20200218 Gzw 服务合同对应
            //       //ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, 'contractEstiDate '+ contractEstiDate +'isNewAfter '+isNewAfter));
            //       if (contractEstiDate >= 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;
            //            }
            //        }
            // }
            // NextMaintenanceContract(initData.checkedAssets,initData.contract);
            if (initData.changedSubmitPrice) {
                initData.checkedAssets = priceChangeReset(initData.checkedAssets);
                // priceChangeReset();
                return null;
            }
            
            String syncEstimateResult = syncEstimate(true, false,initData) ;

            if (syncEstimateResult == 'true') {
                Savepoint sp = Database.setSavepoint();
                // 承認プロセスに載せる
                try {
                    // 已填写申请状态
                    initData.estimate.ApprovalProcess_Status__c = '已填写完并申请';
                    ControllerUtil.updateMaintenance_Contract_Estimate(new Maintenance_Contract_Estimate__c[] {initData.estimate});
                    // 承認プロセス
                    Approval.ProcessSubmitRequest psr = new Approval.ProcessSubmitRequest();
                    psr.setObjectId(initData.estimate.id);
                    Approval.ProcessResult submitResult = Approval.process(psr);
                    String computeLTYRepairResult = ComputeLTYRepair(initData.targetEstimateId);
                    if (computeLTYRepairResult != null) {
                        return computeLTYRepairResult;
                    }
                    //最后页面跳到原报价页面 
                    //避免其他地方存在同样的 / ,添加标识
                    return '/navigateTo='+initData.targetEstimateId;
                } catch (Exception ex) {
                    Database.rollback(sp);
                    initData.estimate.ApprovalProcess_Status__c = null;
                    return ex.getMessage();
                }
            }else{
                return syncEstimateResult;
            }
        }catch(Exception ex){
            return ex.getMessage();
        }
    }

    // 2021-03-01 LJPH-BX9CVX mzy  update  如果合同结束日>无零件风险日期  end
    // 价格变更后克隆报价前重新计算价格
    @TestVisible
    private static List<AssetInfo>  priceChangeReset(List<AssetInfo> checkedAssets) {

        // 取得master中最新价格
        List<Id> assIds = new List<Id>();
        List<Id> pdIds = new List<Id>();
        for (AssetInfo input : 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, EquipmentGuaranteeFlg__c from Product2 where Id In: pdIds]);
        }
        if (assMap.size() > 0 || pdMap.size() > 0) {
            for (AssetInfo info : 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();
        return checkedAssets;
    }


    /**
     * 画面で入力データcheck, save, 親と同期 のロジック
     */
    // TODO xudan チェック追加、clsにも合計金額を計算、clsの合計金額と画面からjsの合計金額を比較
    // 異なる場合、保存完了したらwarningを出す
    public static String syncEstimate(boolean isApproval, boolean isDecide,InitData initData) {
        //2023/07/28 lwc 后台验证添加
        if (initData.estimate.Contract_Esti_Start_Date__c == null) {
            return '合同开始预定日: 必须输入一个值';
        }
        // Contract_Esti_End_Date__c 字段有计算逻辑，页面填写无意义
        // if (initData.estimate.Contract_Esti_End_Date__c == null) {
        //     return '合同结束预订日: 必须输入一个值';
        // }

        Boolean hasDatabaseError = false;
        Savepoint sp = Database.setSavepoint();

        //bug修复
        //提交 报价决定日期
        // this.estimate.Quotation_Determines_Time__c = date.today();
    
        try {
            Map<String, Integer> limitSerialMap = new Map<String, Integer>();

            String checkValidateResult = checkValidate(initData);
            if (checkValidateResult != 'true') {
                if (checkValidateResult == 'false') {
                    return '合同对象设备数据有误，请检查后再次保存！';
                }
                return checkValidateResult;
            }

            // if (!checkValidate(initData)) {
            //     // initData.syncEstimateResult = false;

            //     return 'false';
            // }
            if (checkChangedAfterPrint(initData)) {

                if (isDecide) {
                    // まず Approval
                    isApproval = true;
                    isDecide = false;
                }
            }
            // 验证 开始日期，最早允许制定日之前半年
            Date createdDate = initData.estimate.CreatedDate == null ? System.today() : initData.estimate.CreatedDate.date();
            createdDate = createdDate.addMonths(initData.isNewAddMonth);
            // if (estimate.Contract_Start_Date__c < createdDate) {
            //     this.estimate.Contract_Start_Date__c.addError('合同开始日最早允许追溯制定日之前半年');
            //     return false;
            // }
            // 验证 用户类型，必填
            if (String.isBlank(initData.estimate.EndUserType__c) ) {
                // initData.estimate.EndUserType__c.addError('请选择用户类型！');
                // return false;
                return '请选择用户类型！';
            }
            // 验证 申请报价金额，需要大于0
            if (initData.estimate.Request_quotation_Amount__c <= 0 || initData.estimate.Request_quotation_Amount__c == null) {
                // initData.estimate.Request_quotation_Amount__c.addError('申请报价金额必需大于0');
                // return false;
                return '申请报价金额必需大于0';
            }
            if (initData.estimate.Request_quotation_Amount__c < initData.estimate.GuidePrice_Down__c) {
                // this.estimate.Request_quotation_Amount__c.addError('不能申请低于标准价格最低价的金额');
                return '不能申请低于标准价格最低价的金额';
            }
            // fxk 改报错位置 2021、9、9 Star
            if (initData.estimate.Request_quotation_Amount__c > initData.estimate.GuidePrice_Up__c 
                    || initData.estimate.Request_quotation_Amount__c < initData.estimate.GuidePrice_Down__c) {
                if (!(initData.estimate.mainTalksTime__c > 0)) {
                    // initData.estimate.mainTalksTime__c.addError('主要谈判次数必填');
                    // return false;
                    return '主要谈判次数必填';
                }
                if (initData.estimate.talksStartDate__c == null) {
                    // initData.estimate.talksStartDate__c.addError('谈判的开始时间必填');
                    // return false;
                    return '谈判的开始时间必填';
                }
    
                if (String.isBlank(initData.estimate.Discount_reason__c)) {
                    // initData.estimate.Discount_reason__c.addError('价格申请理由必填');
                    // return false;
                    return '价格申请理由必填';
                }
                if (String.isBlank(initData.estimate.Improve_ConsumptionRate_Idea__c)) {
                    // initData.estimate.Improve_ConsumptionRate_Idea__c.addError('消费率改善方案必填');
                    // return false;
                    return '消费率改善方案必填';
                }
            }
            //fxk 改报错位置 2021/9/9 end
            //>>>
            if (isApproval || isDecide) {
                Boolean hasError = false;
                if (initData.estimate.Maintenance_Price__c <= 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_reason__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 '合同价格必需大于0';
                }
            }
            if (isDecide && getDecideBtnDisabled(initData.contract,initData.estimate)) {
                
                return '已经是Decide过的合同 或 不是批准的报价，不能Decide';
            }
            // 追加上期合同信息 start
            // 2021-09-10 tcm 排序逻辑调整 start
            List<lastMContract> lastMContractRes;
            if (isDecide) {
                lastMContractRes = getlastMContract(initData.checkedAssets,initData.estimate.Contract_Start_Date__c);
            } else{
                lastMContractRes = getlastMContract(initData.checkedAssets,initData.estimate.Contract_Esti_Start_Date__c);
            }
            initData.estimate.LastMContract1__c = lastMContractRes[0].contractId;
            initData.estimate.LastMContract1_NO__c = lastMContractRes[0].contractNo;
            initData.estimate.LastMContract1_ConCount__c = lastMContractRes[0].count;
    
            initData.estimate.LastMContract2__c = lastMContractRes[1].contractId;
            initData.estimate.LastMContract2_NO__c = lastMContractRes[1].contractNo;
            initData.estimate.LastMContract2_ConCount__c = lastMContractRes[1].count;
    
            initData.estimate.LastMContract3__c = lastMContractRes[2].contractId;
            initData.estimate.LastMContract3_NO__c = lastMContractRes[2].contractNo;
            initData.estimate.LastMContract3_ConCount__c = lastMContractRes[2].count;
    
            initData.estimate.LastMContract4__c = lastMContractRes[3].contractId;
            initData.estimate.LastMContract4_NO__c = lastMContractRes[3].contractNo;
            initData.estimate.LastMContract4_ConCount__c = lastMContractRes[3].count;
    
            initData.estimate.LastMContract5__c = lastMContractRes[4].contractId;
            initData.estimate.LastMContract5_NO__c = lastMContractRes[4].contractNo;
            initData.estimate.LastMContract5_ConCount__c = lastMContractRes[4].count;
            
            //URF限次合同2期 LY 20220908 start
            List<lastMContract> urfMContractRes;
            if (isDecide) {
                urfMContractRes = getURFMContract(initData.checkedAssets,initData.estimate.Contract_Start_Date__c);
            } else{
                urfMContractRes = getURFMContract(initData.checkedAssets,initData.estimate.Contract_Esti_Start_Date__c);
            }
            initData.estimate.URFMContract1__c = urfMContractRes[0].contractId;
            initData.estimate.URF_LastMContract1_NO__c = urfMContractRes[0].contractNo;
            initData.estimate.URF_LastMContract1_ConCount__c = urfMContractRes[0].count;
    
            //this.estimate.URFMContract2__c = urfMContractRes[1].contractId;
            initData.estimate.URF_LastMContract2_NO__c = urfMContractRes[1].contractNo;
            initData.estimate.URF_LastMContract2_ConCount__c = urfMContractRes[1].count;
    
            //this.estimate.URFMContract3__c = urfMContractRes[2].contractId;
            initData.estimate.URF_LastMContract3_NO__c = urfMContractRes[2].contractNo;
            initData.estimate.URF_LastMContract3_ConCount__c = urfMContractRes[2].count;
    
            //this.estimate.URFMContract4__c = urfMContractRes[3].contractId;
            initData.estimate.URF_LastMContract4_NO__c = urfMContractRes[3].contractNo;
            initData.estimate.URF_LastMContract4_ConCount__c = urfMContractRes[3].count;
    
            //this.estimate.URFMContract5__c = urfMContractRes[4].contractId;
            initData.estimate.URF_LastMContract5_NO__c = urfMContractRes[4].contractNo;
            initData.estimate.URF_LastMContract5_ConCount__c = urfMContractRes[4].count;
            //URF限次合同2期 LY 20220908 end
            Integer Contract_year = 0;
            if(initData.estimate.Contract_Range__c != null){
                if(initData.estimate.Contract_Range__c <= 12){
                    Contract_year = 1;
                } else{
                    Decimal year = initData.estimate.Contract_Range__c / 12;
                    Contract_year = (Integer)year.round(System.RoundingMode.CEILING);
                }               
            }
            // 限次汇总信息
            Map<String, Decimal> uFRSerialMap = getLimitSerialData(Contract_year,initData);
            // 原方法
            // List<lastMContract> lastMContractRes = getlastMContract(this.checkedAssets, this.estimate.Contract_Start_Date__c);
            // // ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, 'lastMContractRes +++++！' + lastMContractRes));
            // // if (true) {
            // //     return false;
            // // }
    
            // 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;
            // 2021-09-10 tcm 排序逻辑调整 start
    
            // 追加上期合同信息 end
    
    
    
            // 同期処理
            // ①维修合同に既存の保有设备を削除
            // ②保存した维修合同报价の保有设备を维修合同にコピー(Asset__cが設定さているデータだけ)
            // ③他の维修合同报价の同期フラグを外す
            // ④维修合同の Estimate_Trial_Money__c、Contract_Amount__c, Service_contract_target_number__c を更新
            initData.estimate.IsSyncing__c = true;
            if (isDecide) {
                // 20200923 Gzw bug 修改
                //清空报价批准时间
                initData.estimate.Quotation_Determines_Time__c = Date.today();
                initData.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 <> :initData.estimate.Id
                                                                          and Maintenance_Contract__c = :initData.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 = initData.estimate.Contract_Esti_Start_Date__c.addMonths(Integer.valueOf(initData.estimate.Contract_Range__c));
            // 20151217 xudan 维修合同报价SH-RS-JS0046560-01 期间显示问题
            // うるう年特殊対応
            if (initData.estimate.Contract_Esti_Start_Date__c.month() == 2 && initData.estimate.Contract_Esti_Start_Date__c.day() == 29
                && t.month() == 2) {
                t = t;
            } else {
                t = t.addDays(-1);
            }
            initData.estimate.Contract_Esti_End_Date__c = t;
            // decide 时，跳过赋值 JZHG-BRH5MU 20200715 start
            if (!isDecide) {
                initData.estimate.New_Contract_Type_TxT__c = initData.typeresult;
            }
            // decide 时，跳过赋值 JZHG-BRH5MU 20200715 end
            // 合同开始日を结束日
            if (initData.estimate.Contract_Start_Date__c == null) {
                initData.estimate.Contract_Start_Date__c = initData.estimate.Contract_Esti_Start_Date__c;
            }
            t = initData.estimate.Contract_Start_Date__c.addMonths(Integer.valueOf(initData.estimate.Contract_Range__c));
            t = t.addDays(-1);
            initData.estimate.Contract_End_Date__c = t;
            //提交之后decide之前，经销商变更的话，先款信息以变更后的经销商先款信息执行 thh 20220418 start
            //add      wangweipeng                   2021/12/26                     start
            if(String.isNotBlank(initData.estimate.Dealer__c)){
                initData.checkDealerId = initData.estimate.Dealer__c;
                initData.estimate = onChDealerUpdate(initData.estimate,initData.checkDealerId);
            }else{
                initData.estimate.Is_RecognitionModel__c = false;
            }
            //add      wangweipeng                   2021/12/26                     end
            //提交之后decide之前，经销商变更的话，先款信息以变更后的经销商先款信息执行 thh 20220418 end

            // 位置调整 在1951 line
            // Date createdDate = this.estimate.CreatedDate == null ? System.today() : this.estimate.CreatedDate.date();
            // ３ヶ月超過している場合には、Decideできない
            //if (createdDate.addMonths(3) <= System.today()) {
            //    this.estimate.addError('已超过3个月，请先更新报价。');
            //    return false;
            //}
            // 维修合同报价
            // ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error, 'this.targetEstimateId ++++++ ' + this.targetEstimateId));
            // if (true) {
            //     return false;
            // }
            if (String.isBlank(initData.targetEstimateId)) {
                initData.newIns = true;
                initData.estimate.Process_Status__c = '草案中';
                // nameに番号をセット
                List<Maintenance_Contract_Estimate__c> maxNameRecords = [select Name From Maintenance_Contract_Estimate__c Where Maintenance_Contract__c = :initData.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) {
                    }
                } else {
                }
                oppNo = '00' + String.valueof(l);
                oppNo = oppNo.substring(oppNo.length() - 2);
                initData.estimate.Name = initData.contract.Management_Code__c + '-' + oppNo;
                setApprovalManager(initData.estimate,initData.contract);
                insert initData.estimate;
                initData.targetEstimateId = initData.estimate.Id;
                initData.estimate = setThisEstimate(initData.estimate,initData);
            } else {
                if (isApproval) {
                    setApprovalManager(initData.estimate,initData.contract);
                }
                ControllerUtil.updateMaintenance_Contract_Estimate(new Maintenance_Contract_Estimate__c[] {initData.estimate});
            }
            // 维修合同报价/保有设备
            // delete and insertする
            List<Maintenance_Contract_Asset_Estimate__c> insertTarget = new List<Maintenance_Contract_Asset_Estimate__c>();
            // 是否使用首次报价日更新
            // 需要注意对报价提交日+3个月与合同结束日进行比较
            // 1）报价提交日+3个月的日期，小于合同结束日时，以合同结束日作为报价有效期的结束日
            // 2）报价提交日+3个月的日期，大于合同结束日时，报价提交日+3个月的日期作为报价有效期的结束日
            //
            //
            //  因为月初计算消费率，所以结束日在上月或以前，可以取到完整消费率，否则保存首次报价日
            Date toDate = Date.today();
            Date mon1stDate = Date.newInstance(toDate.year(), toDate.month(), 1);
            // list 修改 map
            Map<id, Maintenance_Contract__c> mcList = new Map<id, Maintenance_Contract__c>();

            //故障品加费 第三方回归 故障品标识
            Boolean hasThirdPartyReturnc = false;
            Boolean hasSurchargeDefective = false;

            for (AssetInfo input : initData.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 != initData.targetEstimateId) {
                        // 親変更できない可能性があるため、設定するときエラーになるが、エラーにならないように他のロジックを工夫してください。
                        input.mcae.Maintenance_Contract_Estimate__c = initData.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;
                        input.mcae.Estimate_Cost__c = input.mcae.Estimate_Cost__c;
                        input.mcae.LastMContract_Price__c = input.rec.CurrentContract_F_asset__r.Estimate_Cost_Month_formula__c;
                        //input.mcae.Asset_Consumption_rate__c = input.mcae.Asset_Consumption_rate__c;
                    }
                    // 提交时，更新 是否使用上一期维修合同首次报价日
                    if (isApproval) {
                        Maintenance_Contract__c mctemp = new Maintenance_Contract__c();
                        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO , '+++++ ' + ass.rec.CurrentContract_F__r.Contract_End_Date__c + '   ' + mon1stDate));
                        // 因为月初计算消费率，所以结束日在上月或以前，可以取到完整消费率，否则保存首次报价日
                        if (input.rec.CurrentContract_F__r.Contract_End_Date__c >= mon1stDate) {
                            if (input.rec.CurrentContract_F__r.First_Estimate_Date__c == null) {
                                mctemp.Id = input.rec.CurrentContract_F__c;
                                mctemp.First_contract_usage_Rate__c = input.rec.CurrentContract_F__r.Contract_Consumption_rate__c;
                                mctemp.First_Estimate_Date__c = Date.today();
                                mcList.put(mctemp.Id, mctemp);
                                input.mcae.ifHaveleftInPrevious__c = true;
                            }
                        }
                    }
                    // 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;
                    }
                    if (!isDecide) {
                        // input.mcae.EquipmentGuaranteeFlgTxt__c = input.etGFlg;
                        if (input.uFRSerial=='URF-V') {
                            input.uFRRepairCount = Integer.valueOf(initData.estimate.URF_V_MaxRepairCount__c);
                        }
                        if (input.uFRSerial=='URF-P') {
                            input.uFRRepairCount = Integer.valueOf(initData.estimate.URF_P_MaxRepairCount__c);
                        }
                        //URF限次合同2期 LY 20220811 end
                        // 限次信息保存
                        input.mcae.URF_Series__c = input.uFRSerial;
                        input.mcae.Series_RepairCount__c = 0;
                        input.mcae.Series_MaxRepairCount__c = uFRSerialMap.get(input.uFRSerial);
                        input.mcae.Asset_RepairCount__c = 0;
                        //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
                        input.mcae.Asset_MaxRepairCount__c = input.uFRRepairCount * Contract_year;
                        //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
    
                    }
                    // Gzw 20200807 五个去年合同相关，所以报价产品，获取上期合同 start
                    //新规时，保存新合同备品保证提供 Decide 后
                    if (!isDecide) {
                        input.mcae.EquipmentGuaranteeFlgTxt__c = input.etGFlg;
                    }
    
                    // 2020/10/30 songxiaoqi start
                    if (input.rec.CurrentContract_F__r.RecordType_DeveloperName__c != 'VM_Contract') {
                        input.mcae.Last_MContract__c = input.rec.CurrentContract_F__c;
    
                    }
                    //songxiaoqi end
                    
                    // Gzw 20200807 五个去年合同相关，所以报价产品，获取上期合同 end
                    //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);

                    //故障品加费 第三方回归 、故障品标识 start 2022/12/30    
                    // if(input.mcae.Third_Party_Return__c == true){
                    //     hasThirdPartyReturnc = true;
                    // }

                    // if(input.mcae.Repair_Price__c>0 && input.mcae.Third_Party_Return__c == false){
                    //     hasSurchargeDefective = true;
                    // }
                    //故障品加费 第三方回归 、故障品标识 end 2022/12/30

                }
            }

            //故障品加费 维修合同、报价  第三方回归 、故障品标识 start 2022/12/30  
            // System.debug(LoggingLevel.INFO, '*** hasThirdPartyReturnc: ' + hasThirdPartyReturnc);
            // System.debug(LoggingLevel.INFO, '*** hasThirdPartyReturnc: ' + hasSurchargeDefective);
            // if(hasThirdPartyReturnc == true){
            //     //报价
            //     initData.estimate.Third_Party_Return__c = true;
            //     initData.estimate.Surcharge_Defective_Contract__c = false;
            //     //维修合同
            //     initData.contract.Third_Party_Return_Contract__c = initData.estimate.Third_Party_Return__c;
            //     initData.contract.Surcharge_Defective_Contract__c = initData.estimate.Surcharge_Defective_Contract__c;
            // }else if(hasThirdPartyReturnc == false && hasSurchargeDefective == true){
            //     //报价
            //     initData.estimate.Surcharge_Defective_Contract__c = true;
            //     initData.estimate.Third_Party_Return__c = false;
            //     //维修合同
            //     initData.contract.Third_Party_Return_Contract__c = initData.estimate.Third_Party_Return__c;
            //     initData.contract.Surcharge_Defective_Contract__c = initData.estimate.Surcharge_Defective_Contract__c;
            // }else if(hasThirdPartyReturnc == false && hasSurchargeDefective == false){
            //     //报价
            //     initData.estimate.Surcharge_Defective_Contract__c = false;
            //     initData.estimate.Third_Party_Return__c = false;
            //     //维修合同
            //     initData.contract.Third_Party_Return_Contract__c = initData.estimate.Third_Party_Return__c;
            //     initData.contract.Surcharge_Defective_Contract__c = initData.estimate.Surcharge_Defective_Contract__c;
            // }  
            //故障品加费 维修合同、报价  第三方回归 、故障品标识 end 2022/12/30    

            // 本当に保存した納入機器があれば削除
            // AssetHandler.disabled = true;
            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 = :initData.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 = :initData.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, Estimate_Cost__c,  IsNew__c, EquipmentGuaranteeFlgTxt__c,
                                                                      //add 点检改善：合同保有设备下的点检对象与报价保有设备下的点检对象同步 2021.6.9 fxk start
                                                                      Check_Object__c,
                                                                      //add 点检改善：合同保有设备下的点检对象与报价保有设备下的点检对象同步 2021.6.9 fxk end
                                                                      // Gzw 20200807 五个去年合同相关，所以报价产品，获取上期合同 start
                                                                      Last_MContract__c
                                                                      // Gzw 20200807 五个去年合同相关，所以报价产品，获取上期合同 eng
                                                                      , Last_MContract__r.RecordType_DeveloperName__c
                                                                      // LJPH-C9GD34 gzw fix start
                                                                      ,Estimate_List_Price_Page__c
                                                                      // LJPH-C9GD34 gzw fix end
                                                                      from Maintenance_Contract_Asset_Estimate__c
                                                                      where Maintenance_Contract_Estimate__c = :initData.estimate.Id and Asset__c <> null]) {
    
                    Maintenance_Contract_Asset__c newVal = new Maintenance_Contract_Asset__c(
                        Maintenance_Contract__c = initData.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,
                        //Maintenance_Price_YearTXT__c = target.Maintenance_Price_YearTXT__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
                        //EquipmentGuaranteeFlgTxt__c = target.EquipmentGuaranteeFlgTxt__c,
                        // Gzw 20200807 五个去年合同相关，所以报价产品，获取上期合同 start
                        // LastMContract__c = target.Last_MContract__c
                        // Gzw 20200807 五个去年合同相关，所以报价产品，获取上期合同 end
                        //如果是多年保修合同,不更新上期维修合同信息 LJPH-BUU3E3 update by rentx  2020-11-03

                        //故障品加费  第三方回归、故障品加费 标识start
                        // Third_Party_Return__c = target.Third_Party_Return__c,
                        // Surcharge_Defective_Contract__c = target.Surcharge_Defective_Contract__c,
                        //故障品加费  第三方回归、故障品加费 标识end

                        LastMContract__c = target.Last_MContract__r.RecordType_DeveloperName__c == 'VM_Contract' ? null : target.Last_MContract__c
                        );
                    newValue.add(newVal);
                }
                if (newValue.size() > 0) insert newValue;
            }
            // ④ start
            initData.contract.Estimation_Id__c = initData.targetEstimateId;     
            initData.contract.Contract_Esti_Start_Date__c = initData.estimate.Contract_Esti_Start_Date__c;
            initData.contract.Contract_Range__c = initData.estimate.Contract_Range__c;
            initData.contract.Contract_Esti_End_Date__c = initData.estimate.Contract_Esti_End_Date__c;
            initData.contract.Estimate_Target__c = initData.estimate.Estimate_Target__c;
            initData.contract.Dealer__c = initData.estimate.Dealer__c;
            initData.contract.old_Is_RecognitionModel__c = initData.estimate.Is_RecognitionModel__c;
            initData.contract.NotUse_Oxygenated_Water__c = initData.estimate.NotUse_Oxygenated_Water__c;
            initData.contract.Estimate_Trial_Money__c = initData.estimate.Estimate_Trial_Money__c;
            initData.contract.Contract_Amount__c = initData.estimate.Maintenance_Price__c;
            // 点检总次数自动赋值 gzw fix 20211122 start
            initData.contract.Service_contract_target_number__c = initData.estimate.Service_contract_target_number__c;
            // 点检总次数自动赋值 gzw fix 20211122 end
            initData.contract.Contract_department_manual__c = initData.estimate.Department__c;
    
            // 追加上期合同信息 start
            initData.contract.LastMContract1__c = initData.estimate.LastMContract1__c;
            initData.contract.LastMContract1_NO__c = initData.estimate.LastMContract1_NO__c;
            initData.contract.LastMContract1_ConCount__c =  initData.estimate.LastMContract1_ConCount__c;
    
            //add by rentx 2021-04-22 给合同1赋值的同时，给去年合同赋值 start
            initData.contract.Last_year_service_contract__c = initData.estimate.LastMContract1__c;
            //add by renrx 2021-04-22 给合同1赋值的同时, 给去年合同赋值 end
    
            initData.contract.LastMContract2__c =  initData.estimate.LastMContract2__c;
            initData.contract.LastMContract2_NO__c = initData.estimate.LastMContract2_NO__c;
            initData.contract.LastMContract2_ConCount__c =  initData.estimate.LastMContract2_ConCount__c;
    
            initData.contract.LastMContract3__c =  initData.estimate.LastMContract3__c;
            initData.contract.LastMContract3_NO__c = initData.estimate.LastMContract3_NO__c;
            initData.contract.LastMContract3_ConCount__c =  initData.estimate.LastMContract3_ConCount__c;
    
            initData.contract.LastMContract4__c =  initData.estimate.LastMContract4__c;
            initData.contract.LastMContract4_NO__c = initData.estimate.LastMContract4_NO__c;
            initData.contract.LastMContract4_ConCount__c =  initData.estimate.LastMContract4_ConCount__c;
    
            initData.contract.LastMContract5__c =  initData.estimate.LastMContract5__c;
            initData.contract.LastMContract5_NO__c = initData.estimate.LastMContract5_NO__c;
            initData.contract.LastMContract5_ConCount__c =  initData.estimate.LastMContract5_ConCount__c;
            // 追加上期合同信息 end

            //URF限次合同2期 LY 20220908 start
            //追加上期限次合同信息 start
            initData.contract.URF_LastMContract1__c = initData.estimate.URFMContract1__c;
            initData.contract.URF_LastMContract1_startDate__c = initData.estimate.URFMContract1_startDate__c;
            initData.contract.URF_LastMContract1_endDate__c = initData.estimate.URFMContract1_endDate__c;
            initData.contract.URF_LastMContract1_NO__c = initData.estimate.URF_LastMContract1_NO__c;
            initData.contract.URF_LastMContract1_ConCount__c =  initData.estimate.URF_LastMContract1_ConCount__c;
    
            //this.contract.URF_LastMContract2__c =  this.estimate.URFMContract2__c;
            initData.contract.URF_LastMContract2_NO__c = initData.estimate.URF_LastMContract2_NO__c;
            initData.contract.URF_LastMContract2_ConCount__c =  initData.estimate.URF_LastMContract2_ConCount__c;
    
            //this.contract.URF_LastMContract3__c =  this.estimate.URFMContract3__c;
            initData.contract.URF_LastMContract3_NO__c = initData.estimate.URF_LastMContract3_NO__c;
            initData.contract.URF_LastMContract3_ConCount__c =  initData.estimate.URF_LastMContract3_ConCount__c;
    
            //this.contract.URF_LastMContract4__c =  this.estimate.URFMContract4__c;
            initData.contract.URF_LastMContract4_NO__c = initData.estimate.URF_LastMContract4_NO__c;
            initData.contract.URF_LastMContract4_ConCount__c =  initData.estimate.URF_LastMContract4_ConCount__c;
    
            //this.contract.URF_LastMContract5__c =  this.estimate.URFMContract5__c;
            initData.contract.URF_LastMContract5_NO__c = initData.estimate.URF_LastMContract5_NO__c;
            initData.contract.URF_LastMContract5_ConCount__c =  initData.estimate.URF_LastMContract5_ConCount__c;
            // 追加上期限次合同信息 end
            //URF限次合同2期 LY 20220908 end
    
            if (isDecide == true) {
                //              this.contract.Contract_Start_Date__c = this.estimate.Contract_Esti_Start_Date__c;
                initData.contract.Contract_Start_Date__c = initData.estimate.Contract_Start_Date__c;
                initData.contract.Contract_Range__c = initData.estimate.Contract_Range__c;
                //              this.contract.Contract_End_Date__c = this.estimate.Contract_Esti_End_Date__c;
                initData.contract.Contract_End_Date__c = initData.estimate.Contract_End_Date__c;
                initData.contract.JingliApprovalManager__c = initData.estimate.JingliApprovalManager__c;
                initData.contract.BuchangApprovalManager__c = initData.estimate.BuchangApprovalManager__c;
                initData.contract.ZongjianApprovalManager__c = initData.estimate.ZongjianApprovalManager__c;
                initData.contract.Finally_Approved_Staff__c = initData.estimate.Finally_Approved_Staff__c;
                initData.contract.TKZongjianApprovalManager__c = initData.estimate.TKZongjianApprovalManager__c;
                // JZHG-BQV3P4 20200624 Gzw add
                initData.contract.HospitalAmountText__c = initData.estimate.AgencyHos_Price__c;
                // JZHG-BQV3P4 20200624 Gzw add
            }
            //添加的额外对应过程
            if (initData.inDicideFlag == true && (initData.contract.Contract_Start_Date__c == null || initData.contract.Contract_End_Date__c == null)) {
                //              this.contract.Contract_Start_Date__c = this.estimate.Contract_Esti_Start_Date__c;
                initData.contract.Contract_Start_Date__c = initData.estimate.Contract_Start_Date__c;
                initData.contract.Contract_Range__c = initData.estimate.Contract_Range__c;
                //              this.contract.Contract_End_Date__c = this.estimate.Contract_Esti_End_Date__c;
                initData.contract.Contract_End_Date__c = initData.estimate.Contract_End_Date__c;
                initData.contract.JingliApprovalManager__c = initData.estimate.JingliApprovalManager__c;
                initData.contract.BuchangApprovalManager__c = initData.estimate.BuchangApprovalManager__c;
                initData.contract.ZongjianApprovalManager__c = initData.estimate.ZongjianApprovalManager__c;
                initData.contract.Finally_Approved_Staff__c = initData.estimate.Finally_Approved_Staff__c;
                initData.contract.TKZongjianApprovalManager__c = initData.estimate.TKZongjianApprovalManager__c;
                // JZHG-BQV3P4 20200624 Gzw add
                initData.contract.HospitalAmountText__c = initData.estimate.AgencyHos_Price__c;
                // JZHG-BQV3P4 20200624 Gzw add
            }
            String oldProcessStatus = initData.estimate.Process_Status__c;
            try {
                if (mcList.size() > 0) {
                    ControllerUtil.updMcList(mcList.values());
                }
                ControllerUtil.updateMaintenance_Contract_Estimate(new Maintenance_Contract_Estimate__c[] {initData.estimate});
                update initData.contract;
            } catch (Exception e) {
                // TODO 今後複数件の場合どうする？
                // initData.estimate.addError(e);
                // 一部の値を戻す
                initData.estimate.Process_Status__c = oldProcessStatus;
                hasDatabaseError = true;
                Database.rollback(sp);
                // ApexPages.addMessages(e);
                return e.getMessage();
            }
            // if (hasDatabaseError) {
            //     System.debug('syncEstimate hasDatabaseError');

            //     //initData 赋值返回
            //     // initData.estimate = estimate ;
            //     // initData.isNewAddMonth = isNewAddMonth;
            //     // initData.checkedAssets = checkedAssets;
            //     // initData.contract = contract;
            //     // initData.checkDealerId = checkDealerId;
            //     // initData.targetEstimateId = targetEstimateId;
            //     // initData.newIns = newIns;
            //     // initData.inDicideFlag = inDicideFlag;

            //     // return false;
            // }
            if (isApproval) {
                SelectAssetEstimateURFController.ComputeLTYRepair(initData.targetEstimateId);
            }

            return 'true';
        } catch (DMLException ex) {
            // TODO Insert失敗のIDを消す必要？
            Database.rollback(sp);
            return ex.getMessage();
        } catch (Exception ex) {
            Database.rollback(sp);
            return ex.getMessage();
        }
    }



     public static Map<String, Decimal> getLimitSerialData(Integer Contract_year,InitData initData) {
        Map<String, Decimal> limitSerial = new Map<String, Decimal>();
        for (AssetInfo input : initData.checkedAssets) {
            //URF限次合同2期 LY 20220811 start

            if (String.isNotBlank(input.uFRSerial) && input.uFRSerial=='URF-V'){
                input.uFRRepairCount = Integer.valueOf(initData.estimate.URF_V_MaxRepairCount__c);
            }else if (String.isNotBlank(input.uFRSerial) && input.uFRSerial=='URF-P'){
                input.uFRRepairCount = Integer.valueOf(initData.estimate.URF_P_MaxRepairCount__c);
            }else{
                input.uFRRepairCount = 0;
            }

            //URF限次合同2期 LY 20220811 end

            //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start

            if (String.isNotBlank(input.uFRSerial) && limitSerial.containsKey(input.uFRSerial)) {
                limitSerial.put(input.uFRSerial, limitSerial.get(input.uFRSerial) + input.uFRRepairCount * Contract_year);
            } else {
                limitSerial.put(input.uFRSerial, input.uFRRepairCount * Contract_year);
            }
            //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
            // 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('点检结果必填');
            //     }
            // }
        }
        return limitSerial;
    }




    private static String checkValidate(InitData initData) {
        //定义变量用于 逻辑中使用的数据 在返回前赋值回initData
        // Maintenance_Contract_Estimate__c estimate = initData.estimate;
        // Maintenance_Contract__c contract = initData.contract;
        // List<AssetInfo> checkedAssets = initData.checkedAssets;
        
        Boolean rtn = true;
        Date today = Date.today();
        if (getPageDisabled(initData.contract,initData.estimate)) {
            today = initData.estimate.Submit_quotation_day__c;
        }
        // 2021-02-26  mzy  LJPH-BX9CVX  add 获取合同结束日和合同月数 start
        //合同月数
        Decimal ContractRange = initData.estimate.Contract_Range__c;
        //合同预定结束日期
        Date t = initData.estimate.Contract_Esti_Start_Date__c.addMonths(Integer.valueOf(initData.estimate.Contract_Range__c));
        if (initData.estimate.Contract_Esti_Start_Date__c.month() == 2 && initData.estimate.Contract_Esti_Start_Date__c.day() == 29
            && t.month() == 2) {
            t = t;
        } else {
            t = t.addDays(-1);
        }
        initData.estimate.Contract_Esti_End_Date__c  = t;
        // 合同开始日を结束日
        if (initData.estimate.Contract_Start_Date__c == null) {
            initData.estimate.Contract_Start_Date__c = initData.estimate.Contract_Esti_Start_Date__c;
        }
        t = initData.estimate.Contract_Start_Date__c.addMonths(Integer.valueOf(initData.estimate.Contract_Range__c));
        t = t.addDays(-1);
        initData.estimate.Contract_End_Date__c = t;
        Date ContractEndDate = initData.estimate.Contract_End_Date__c;
        // 2021-02-26  mzy  LJPH-BX9CVX  add 获取合同结束日和合同月数 end
        // 部品供給停止の製品はエラー
        for (AssetInfo input : initData.checkedAssets) {
            //如果是手动产品
            // 20210121 gzw 服务合同也验证设备价格是否为空 start
            if (!input.isManual || input.isManual && !String.isBlank(input.mcae.Product_Manual__c)) {
                // if (input.isManual && !String.isBlank(input.mcae.Product_Manual__c)) {
                // 20210121 gzw 服务合同也验证设备价格是否为空 end
                if (input.mcae.Estimate_List_Price__c == null || input.mcae.Estimate_List_Price__c == 0) {
                    //update by rentx 2020-11-12 LJPH-BV93RZ start
                    // input.mcae.Product_Manual__c.addError(System.Label.Error_Message47);
                    //add by rentx 2021-01-25 start
                    //如果保有设备不为空的话在保有设备上报错
                    if (input.rec != null) {
                        
                        return input.rec.Name + ' (机身编码为:' + input.rec.SerialNumber + ') 无合同金额,不建议参保';
    
                    } else
                    //add by rentx 2021-01-25 end
                    if (String.isNotBlank(input.proName)) {
                        
                        return System.Label.Error_Message47 + '(' + input.proName + ')';
                    }
                    //update by rentx 2020-11-12 LJPH-BV93RZ end
                    rtn = false;
                }
            }
            if (!input.isManual) {
                //update by rentx 2020-11-13 start
                if (!Test.isRunningTest() && (input.mcae.Adjustment_Upper_price__c == null || input.mcae.Adjustment_Upper_price__c == 0) ) {
                    
                    rtn = false;
                    return input.proSerialName + '(' + input.proSerialNumber + ') 签约价格为0，-- 建议先与服务商品部咨询后再提交报价。';

                }
                if (!Test.isRunningTest() && (input.mcae.Adjustment_Lower_price__c == null || input.mcae.Adjustment_Lower_price__c == 0) ) {
                    
                    rtn = false;
                    return input.proSerialName + '(' + input.proSerialNumber + ') 签约价格为0，-- 建议先与服务商品部咨询后再提交报价。';

                }
                //update by rentx 2020-11-13 end
    
                //1.合同期不满一年时，合同期超过一半才可开始续签报价。(eg:11个月的合同从6个月后才可报价。)
                //2.一年以上的合同，在结束前6个月开始可以开放续签报价。
                //3.管理员跳过，
                //WLIG-CDFBV3 开通续签报价为true的可以开放续签报价 thh 20220413
                if (input.rec.CurrentContract_F__r.Open_RenewalQuotation__c == false && UserInfo.getProfileId() != System.Label.ProfileId_SystemAdmin && 
                        String.isNotBlank(input.rec.CurrentContract_F__c) && input.rec.CurrentContract_F__r.RecordType_DeveloperName__c != 'VM_Contract') {

                    Integer noOfDays = today.daysBetween(input.rec.CurrentContract_F__r.Contract_End_Date__c);
                    Decimal monthCon = (Decimal)noOfDays / 365 * 12;
                    // 可开始报价的月数限制
                    if (input.rec.CurrentContract_F__r.Contract_Range__c >= 12 && monthCon > 6) {
                        
                        rtn = false;
                        return input.rec.Name + '(' + input.rec.SerialNumber + ') -- 合同结束前6个月开始可以制作报价。';

                    }
                    //ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, '---' + monthCon  + ' +++ ' + Math.floor(input.rec.CurrentContract_F__r.Contract_Range__c/2)));
                    //rtn = false;
                    if (input.rec.CurrentContract_F__r.Contract_Range__c < 12 && monthCon > Math.floor(input.rec.CurrentContract_F__r.Contract_Range__c / 2)) {
                        
                        rtn = false;
                        return input.rec.Name + '(' + input.rec.SerialNumber + ') -- 经历月数过半方可制作报价';

                    }
                }
        // 多年保判断
        if ( String.isNotBlank(input.rec.CurrentContract_F__c) && input.rec.CurrentContract_F__r.RecordType_DeveloperName__c == 'VM_Contract') {
            //if (UserInfo.getProfileId() != System.Label.ProfileId_SystemAdmin && String.isNotBlank(input.rec.CurrentContract_F__c) && input.rec.CurrentContract_F__r.RecordType_DeveloperName__c == 'VM_Contract') {
    
            // modify by lc 20220607 多年保续签和实绩连动状态对应 start
            Integer noOfDays = today.daysBetween(input.rec.CurrentContract_F_asset__r.endDateGurantee_Text__c);
            Decimal monthCon = (Decimal)noOfDays/365*12;
            // 可开始报价的月数限制
            //变更多年保续签开始日 thh 20220315 start
            //if (input.rec.CurrentContract_F__r.Gurantee_Estimate_startDate__c > Date.today()) {
            // gzw 20220630 开通续签报价权限后，超过6个月也可以续签
            // 续签情况 ① 上期合同 Open_RenewalQuotation__c & 6个月以内  ② VM_Contract_Check__c Open_RenewalQuotation__c 2个都打钩
            // ① 2个开关都打开 ②VM_Contract_Check__c打开 小于6个月
            if (!((initData.contract.Open_RenewalQuotation__c && input.rec.CurrentContract_F__r.VM_Contract_Check__c) || (input.rec.CurrentContract_F__r.VM_Contract_Check__c && monthCon < 6))) {
                if(monthCon < 6){
                    // input.rec.Name.addError(input.rec.Name + '(' + input.rec.SerialNumber + ') -- 可以加入服务合同，加入价格请联系服务管理部。');
                     rtn = false;
                    return input.rec.Name + '(' + input.rec.SerialNumber + ') -- 可以加入服务合同，加入价格请联系服务管理部。';

                }else{
                    // input.rec.Name.addError(input.rec.Name + '(' + input.rec.SerialNumber + ') -- 没有续签报价权限，或者还没到续签时间。');
                     rtn = false;
                    return input.rec.Name + '(' + input.rec.SerialNumber + ') -- 没有续签报价权限，或者还没到续签时间。';

                }
                //input.rec.Name.addError(input.rec.Name + '(' + input.rec.SerialNumber + ') -- 没有续签报价权限，或者还没到续签时间。');
               
            }
            /*if (input.rec.CurrentContract_F__r.Gurantee_Renew_startDate__c > Date.today()) {
                input.rec.Name.addError(input.rec.Name + '(' + input.rec.SerialNumber + ') -- 第一个设备结束后可以制作报价。');
                rtn = false;
            }*/
            //变更多年保续签开始日 thh 20220315 end
            // modify by lc 20220607 多年保续签和实绩连动状态对应 end

        }
                //ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, '---' + input.rec.CurrentContract_F__r.Contract_End_Date__c));
                if (initData.inDicideFlag && String.isNotBlank(input.rec.CurrentContract_F__c) && initData.estimate.Skip_DJ__c == false ) {
                    //ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, '+++' + input.rec.CurrentContract_F__r.Contract_End_Date__c));
                    //多年保结束日到续签开始日之间的空白期大于30日,且在合同开始日前三个月内没有点检记录,报错 20220429 thh start
                    if(input.rec.CurrentContract_F__r.RecordType_DeveloperName__c == 'VM_Contract' &&
                        input.rec.CurrentContract_F__r.Contract_End_Date__c > input.rec.CurrentContract_F__r.Gurantee_Renew_startDate__c.addDays(30) 
                        && (input.rec.Final_Examination_Date__c == null
                            || input.rec.Final_Examination_Date__c < initData.estimate.Contract_Start_Date__c.addMonths(-3))){

                        rtn = false;
                        return input.rec.Name + '(' + input.rec.SerialNumber + ') -- 没有最新的点检记录';

                    }
                    //多年保结束日到续签开始日之间的空白期大于30日,且在合同开始日前三个月内没有点检记录,报错 20220429 thh end

                    // 合同开始日大于上期合同结束日加一个月，且没有点检日期或者最近一次点检日期是3个月前  报错
                    if (initData.estimate.Contract_Start_Date__c > input.rec.CurrentContract_F__r.Contract_End_Date__c.addMonths(1)
                        && (input.rec.Final_Examination_Date__c == null
                            || input.rec.Final_Examination_Date__c < initData.estimate.Contract_Start_Date__c.addMonths(-3))) {
                        
                        rtn = false;
                        return input.rec.Name + '(' + input.rec.SerialNumber + ') -- 没有最新的点检记录';

                    }
                }
    
                if (initData.isSaveOrApproval) {
                    if (input.rec.IF_Warranty_Service__c == '否') {
                        
                        rtn = false;
                        return input.rec.Name + '(' + input.rec.SerialNumber + ') -- 不能选择不可参保设备';

                    }
                }
                // 20200805 Gzw Bug修复
                // isSaveOrApproval = false;
            }
    
            // 2021-03-01 LJPH-BX9CVX mzy  update  如果合同结束日>无零件风险日期  start
            if (input != null) {
    
                //校验无零件风险
                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 != '') {
                        
                        rtn = false;
                        return '[' + input.rec.Name + '] (机身编码为:' + input.rec.SerialNumber + ') ' + msg;

                    }
    
                }
                /*else if(input.mcae!=null&&input.mcae.Product_Manual__c !=null&&input.NoPartRiskDate!=null ){
                        // 传入参数 : 无零件风险日期 , 可签约标识 , 合同结束日期 , 合同月数
                        String msg = 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  update  如果合同结束日>无零件风险日期  end
    
        }
        return rtn + '';
    }

    /**
     * 印刷後変更がある場合、true
     */
    @TestVisible
    private static Boolean checkChangedAfterPrint(InitData initData) {

        if (initData.changedAfterPrint) {
            initData.targetEstimateId = null;
            initData.estimate = initData.estimate.clone();
            initData.estimate.IS_Clone_After_Decide__c = true;
            initData.estimate.PrintDate__c = null;
            initData.estimate.Quote_Date__c = null;
            initData.estimate.Print_Contract__c = false;
            initData.estimate.Print_RepairPrice__c = false;
            initData.estimate.Print_DiscountPercentage__c = false;
            initData.estimate.Print_DiscountPrice__c = false;
            initData.estimate.Print_ListPrice__c = false;
            //打印报价（简化版） 2019/12/18 start
            initData.estimate.Print_Simplify__c = false;
            //打印报价（简化版） 2019/12/18 end
            initData.estimate.Print_MaintePrice__c = false;
            initData.estimate.Print_SumPrice__c = false;
            initData.estimate.NotUse_Oxygenated_Water__c = false;
            initData.estimate.Contract_Esti_Start_Date__c = initData.estimate.Contract_Start_Date__c;
            //this.estimate.Process_Status__c = '草案中';
        }
        return initData.changedAfterPrint;
    }

    public static Boolean getDecideBtnDisabled(Maintenance_Contract__c contract,Maintenance_Contract_Estimate__c estimate) {

        // 見積もりdecideできない条件の判断
        if (String.isBlank(contract.Decided_Estimation__c) == false) {
            if (estimate.Estimation_Decision__c) {
                return true;
            }
            // TODO 特別資格があれば 決定可能にする
            return true;
        }
        if (estimate.Process_Status__c != '批准') {
            return true;
        } else {
            if (String.isBlank(estimate.Change_Dealer_Approval__c) == false
                && estimate.Change_Dealer_Approval__c != '批准'
                && estimate.Change_Dealer_Approval__c != '未批准') {
                return true;
            }
        }
        return false;
    }

    public static List<lastMContract> getlastMContract(List<AssetInfo> checkedAssets, Date startDate) {

        Map<String, lastMContract> lastMContractMap = new Map<String, lastMContract>();
        Map<String, lastMContract> lastMContractMap1 = new Map<String, lastMContract>();
        for (AssetInfo ai : checkedAssets) {
            lastMContract lM = new lastMContract(ai.rec.CurrentContract_F__c, ai.rec.CurrentContract_F__r.Management_Code__c, ai.rec.CurrentContract_F__r.Contract_End_Date__c, 1);
    
            // 2021-09-10 tcm 排序逻辑调整 start
            // 计算空白期
            if (startDate != null && lM.endDate != null) {
                if (startDate.daysbetween(lM.endDate) > -366 && startDate.daysbetween(lM.endDate) < 366) {
                    lm.ayearcontract = true;
                } else {
                    lm.ayearcontract = false;
                }
            } else {
                lm.ayearcontract = false;
            }
            // 2021-09-10 tcm 排序逻辑调整 end
    
            // if (String.isNotBlank(ai.rec.CurrentContract_F__c) ) {
            //判断 如果上一期维修合同为 多年保修合同 的话 则不放入map进行更新 LJPH-BUU3E3 update by rentx 2020-11-03 start
            if (String.isNotBlank(ai.rec.CurrentContract_F__c) && ai.rec.CurrentContract_F__r.RecordType_DeveloperName__c != 'VM_Contract') {
    
                // 2021-09-10 tcm 排序逻辑调整 start
                if (lm.ayearcontract) {
                    // 2021-09-10 tcm 排序逻辑调整 end
    
                    //判断 如果上一期维修合同为 多年保修合同 的话 则不放入map进行更新 LJPH-BUU3E3 update by rentx 2020-11-03 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);
                    }
                    // 非空白期
                } else {
                    if (lastMContractMap1.containsKey(ai.rec.CurrentContract_F__c)) {
                        lastMContractMap1.get(ai.rec.CurrentContract_F__c).count++;
                    } else {
                        lastMContractMap1.put(ai.rec.CurrentContract_F__c, lM);
                    }
                }
            }
        }
    
        List<lastMContract> listResulttemp = new List<lastMContract>();
        List<lastMContract> listResult = new List<lastMContract>();
        // 2021-09-10 tcm 排序逻辑调整 start
        List<lastMContract> listResulttemp1 = new List<lastMContract>();
        List<lastMContract> listResult1 = new List<lastMContract>();
        // 2021-09-10 tcm 排序逻辑调整 end
        // 空白期
        for ( lastMContract ll : lastMContractMap.values()) {
            listResulttemp.add(ll);
        }
        // 2021-09-10 tcm 排序逻辑调整 start
        // 非空白期
        for ( lastMContract ll : lastMContractMap1.values()) {
            listResulttemp1.add(ll);
        }
        // 2021-09-10 tcm 排序逻辑调整 end
        //ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, 'listResult +++++！' + listResult));
    
        // 空白期
        listResulttemp.sort();
        // 2021-09-10 tcm 排序逻辑调整 start  （修改了循环次数 原5）
        for (Integer i = 0; i < listResulttemp.size(); i++) {
            // 2021-09-10 tcm 排序逻辑调整 end
            if (listResulttemp.size() >= i + 1) {
                listResult.add(listResulttemp[i]);
            }
        }
    
        // 2021-09-10 tcm 排序逻辑调整 start
        // 非空白期
        listResulttemp1.sort();
        for (Integer i = 0; i < 5 - listResulttemp.size(); i++) {
            if (listResulttemp1.size() >= i + 1) {
                listResult1.add(listResulttemp1[i]);
            } else {
                listResult1.add(new lastMContract(null, null, null, null));
            }
        }
        // 合并
        listResult.addAll(listResult1);
        // 2021-09-10 tcm 排序逻辑调整 end
        //List<lastMContract> listResult = new List<lastMContract>();
        return listResult;
    }

    /**
     * Process用のユーザー情報をセット、新規見積もり時用
     */
    
    private static void setApprovalManager(Maintenance_Contract_Estimate__c estimate,Maintenance_Contract__c contract) {
        
        User loginUser = [SELECT Id, Name, JingliApprovalManager__c, BuchangApprovalManager__c, ZongjianApprovalManager__c, TongkuoZongjian__c FROM User WHERE Id = :UserInfo.getUserId()];
        
        // 要注意 SaveMaintenanceByCopyController と copyのurlにも、下記の項目もクリア
        estimate.JingliApprovalManager__c = loginUser.JingliApprovalManager__c == null ? loginUser.Id : loginUser.JingliApprovalManager__c;
        estimate.BuchangApprovalManager__c = loginUser.BuchangApprovalManager__c == null ? loginUser.Id : loginUser.BuchangApprovalManager__c;
        estimate.ZongjianApprovalManager__c = loginUser.ZongjianApprovalManager__c == null ? loginUser.Id : loginUser.ZongjianApprovalManager__c;
        estimate.Service_Contract_Staff__c = contract.Service_Contract_Staff__c;
        estimate.TKZongjianApprovalManager__c = loginUser.TongkuoZongjian__c == null ? loginUser.Id : loginUser.TongkuoZongjian__c;
    }

    //URF限次合同2期 LY 20220908 start
    //对限次合同进行排序
    public static List<lastMContract> getURFMContract(List<AssetInfo> checkedAssets, Date startDate) {

        Map<String, lastMContract> urfMContractMap = new Map<String, lastMContract>();
        Map<String, lastMContract> lastMContractMap1 = new Map<String, lastMContract>();
        for (AssetInfo ai : checkedAssets) {
            lastMContract urfMC = new lastMContract(ai.rec.URF_Maintenance_Contract__c, ai.rec.URF_Maintenance_Contract__r.Management_Code__c, ai.rec.URF_Maintenance_Contract__r.Contract_End_Date__c, 1);
            if (String.isNotBlank(ai.rec.URF_Maintenance_Contract__c)) {
                if (urfMContractMap.containsKey(ai.rec.URF_Maintenance_Contract__c)) {
                    urfMContractMap.get(ai.rec.URF_Maintenance_Contract__c).count++;
                } else {
                    urfMContractMap.put(ai.rec.URF_Maintenance_Contract__c, urfMC);
                }
            }
        }
        List<lastMContract> listResulttemp = new List<lastMContract>();
        List<lastMContract> listResult = new List<lastMContract>();
        
        for ( lastMContract ll : urfMContractMap.values()) {
            listResulttemp.add(ll);
        }
        listResulttemp.sort();
        if (listResulttemp.size() >= 5){
            for (Integer i = 0; i < listResulttemp.size(); i++) {
            
                if (listResulttemp.size() >= i + 1) {
                    listResult.add(listResulttemp[i]);
                }
            }
        }else {
            for (Integer i = 0; i < listResulttemp.size(); i++) {
                if (listResulttemp.size() >= i + 1) {
                    listResult.add(listResulttemp[i]);
                }
            }
            for (Integer i = listResulttemp.size(); i < 5; i++) {
                listResult.add(new lastMContract(null, null, null, null));
            }
        }
        
        return listResult;
    }

    //add     wangweipeng                     2021/12/26                 start
    //获取当前选中的经销商是否为先款标识
    public static Maintenance_Contract_Estimate__c onChDealerUpdate(Maintenance_Contract_Estimate__c estimate,String checkDealerId){

        //checkDealerId  此变量可能会存 经销商id或经销商中文名
        if(String.isNotBlank(checkDealerId)){
            try {
                List<Account> accListC = [select id,name,FirstParagraphEnd__c from Account where id = :checkDealerId OR name = :checkDealerId];
                if(accListC != null && accListC.size() == 1){
                    if(accListC[0].FirstParagraphEnd__c){
                        estimate.Is_RecognitionModel__c = true;
                    }else{
                        estimate.Is_RecognitionModel__c = false;
                    }
                }else{
                    estimate.Is_RecognitionModel__c = false;
                }
            } catch (Exception e) {
                //return 'McaeList Update Failed : '+e;
            }
        }else{
            estimate.Is_RecognitionModel__c = false;
        }
        return estimate;
    }
    //end
    @AuraEnabled
    public static String ComputeLTYRepair(String targetEstimateId) {
        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, Three_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 = new Maintenance_Contract_Estimate__c();
        List<Maintenance_Contract_Estimate__c>  mcecList = new List<Maintenance_Contract_Estimate__c>();
        mcecList = [select id, createdDate, Submit_quotation_day__c from Maintenance_Contract_Estimate__c where id = :targetEstimateId];
        if (mcecList.size() == 0) {
            // ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error, '请先保存报价！'));
            return '请先保存报价！';
        } else {
            mcec = mcecList[0];
        }
        //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 = Date.valueOf(mcec.createdDate);
            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);
        // 20191210 Gzw 服务合同过去3年修理实绩合并
        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.long_term_insurance_MD__c) long_term_insuranceMD,
            sum(Repair_Quotation_Id__r.Delivery_compensation__c) delivery,
            sum(Repair_Quotation_Id__r.Other_discount__c) other,
            AVG(Delivered_Product__r.Last_Years_Repair_Month__c) threeYearM,
            Delivered_Product__c
            from
            Repair__c
            where
            Delivered_Product__c in:AsList
            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.long_term_insurance_MD__c) long_term_insuranceMD,
            sum(Repair_Quotation_Id__r.Delivery_compensation__c) delivery,
            sum(Repair_Quotation_Id__r.Other_discount__c) other,
            AVG(Delivered_Product__r.Last_Years_Repair_Month__c) threeYearM,
            Delivered_Product__c
            from
            Repair__c
            where
            Delivered_Product__c in:AsList
            and Agreed_Date__c != null
            and Agreed_Date__c <= :LastYearDate
            and Agreed_Date__c > :LastSecondYearDate
            group by Delivered_Product__c
        ];
        // 过去3年间修理实绩
        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.long_term_insurance_MD__c) long_term_insuranceMD,
            sum(Repair_Quotation_Id__r.Delivery_compensation__c) delivery,
            sum(Repair_Quotation_Id__r.Other_discount__c) other,
            AVG(Delivered_Product__r.Last_Years_Repair_Month__c) threeYearM,
            Delivered_Product__c
            from
            Repair__c
            where
            Delivered_Product__c in:AsList
            and Agreed_Date__c != null
            and Agreed_Date__c <= :LastSecondYearDate
            and Agreed_Date__c > :LastThirdYearDate
            group by Delivered_Product__c
        ];
        // 过去3年修理实绩
        List<AggregateResult> ThreeyearList = [
            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.long_term_insurance_MD__c) long_term_insuranceMD,
            sum(Repair_Quotation_Id__r.Delivery_compensation__c) delivery,
            sum(Repair_Quotation_Id__r.Other_discount__c) other,
            AVG(Delivered_Product__r.Last_Years_Repair_Month__c) threeYearM,
            Delivered_Product__c
            from
            Repair__c
            where
            Delivered_Product__c in:AsList
            and Agreed_Date__c != null
            and Agreed_Date__c <= :today
            and Agreed_Date__c > :LastThirdYearDate
            group by Delivered_Product__c
        ];
        // 过去1年间
        Map<id, Decimal> LastFriYearPriceSumMap = new Map<id, Decimal>();
        // 过去2年间
        Map<id, Decimal> LastSecYearPriceSumMap = new Map<id, Decimal>();
        // 过去3年间
        Map<id, Decimal> LastThiYearPriceSumMap = new Map<id, Decimal>();
        // 过去3年
        Map<id, Decimal> ThreeYearPriceSumMap = new Map<id, Decimal>();
        Map<id, Decimal> ThiYearMonthMap = 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 = 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 = 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 = sumPrice1(Rpc);
            LastThiYearPriceSumMap.put(idf, Defir);
        }
        for (AggregateResult Rpc : ThreeyearList) {
            id idf        = String.valueOf(Rpc.get('Delivered_Product__c'));
            //Decimal Defir = decimal.valueOf(Rpc.get('SumPrice')+'');
            Decimal threeYearM = decimal.valueOf(Rpc.get('threeYearM') + '');
            Decimal Defir = sumPrice1(Rpc);
            ThreeYearPriceSumMap.put(idf, Defir);
            ThiYearMonthMap.put(idf, threeYearM);
        }
        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));
            Mca.Three_Years_Repair_Cost_Text__c = ThreeYearPriceSumMap.get(McaecToAsset.get(Mca.id)) == null ? 0 : ThreeYearPriceSumMap.get(McaecToAsset.get(Mca.id));
            Mca.The_Date_Of_Compute_The_RPCost__c = Date.today();
            Mca.Last_Third_Years_Repair_Month__c = ThiYearMonthMap.get(McaecToAsset.get(Mca.id)) == null ? 0 : ThiYearMonthMap.get(McaecToAsset.get(Mca.id));
        }
        try {
            update McaeList;
        } catch (Exception e) {
        }
        return null;
    
    }
    //end
    private static Decimal sumPrice(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 long_term_insuranceMD = Decimal.valueOf((rpc.get('long_term_insuranceMD') == null ? 0 : rpc.get('long_term_insuranceMD')) + '') * -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;
        
        return SumPrice + sales_discount + contract_target + loaner_repair + long_term_insurance + sercince + set_discount + long_term_insuranceMD + delivery + other;
    }
    //end
    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 long_term_insuranceMD = Decimal.valueOf((rpc.get('long_term_insuranceMD') == null ? 0 : rpc.get('long_term_insuranceMD')) + '') * -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;
        
        return SumPrice + sales_discount + contract_target + loaner_repair + long_term_insurance + sercince + set_discount + long_term_insuranceMD + delivery + other;
    }

    /**
     * 手動で商品選択後のリフレッシュ
     **/
    @AuraEnabled
    public static String refreshProductData(String checkedAssetsStr,String topProductModelStr,Integer productIdx,Decimal isNewPriceAdj) {
        try {
            List<AssetInfo> checkedAssets = ( List<AssetInfo>)JSON.deserialize(checkedAssetsStr, List<AssetInfo>.class);
            List<String> TopProductModel = ( List<String>)JSON.deserialize(topProductModelStr, List<String>.class);

            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;
                        //2021-11-30 fy add LJPH-C8W8FV 置顶 start
                        // ai.ProductModelNoc=null;
                        // ai.AssetModelNoc=null;
                        // ai.MDMModelNoc=null;
                        ai.mcae.Check_Object__c = true;
                        //2021-11-30 fy add LJPH-C8W8FV 置顶 end
                        // add by fxk 2021/9/9 控制点检对象是否可选 End
                    } else {
                        //2021-02-04 mzy select语句查询结果中加了 NoPartRiskDate_F__c
                        //2021-11-30 fy add LJPH-C8W8FV 置顶 start Asset_Model_No__c ProductURF__c
                        List<Product2> prd =[select Id,Asset_Model_No__c, Maintenance_Price_Month__c, EquipmentGuaranteeFlg__c, Name,
                                              ProductURF__c, ProductURF__r.URFLimitSerial__c, ProductURF__r.UFR_MaxRepairCount__c, ProductURF__r.UFR_Maintenance_Price_Month__c
                                              //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
                                              , ProductURF__r.Maintenance_Price_Year_URF__c, ProductURF__r.Maintenance_Price_Year_URF_Max__c
                                              //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
                                              //URF限次合同2期 LY 20220811 start
                                              , ProductURF__r.Maintenance_Price_Year_URF_3__c
                                              , ProductURF__r.Maintenance_Price_Year_URF_Max_3__c
                                              , ProductURF__r.UFR_Maintenance_Price_Month_3__c
                                              //URF限次合同2期 LY 20220811 end
                                              from Product2 where Id = :ai.mcae.Product_Manual__c];
                        // ai.mcae.Estimate_List_Price__c = prd[0].Maintenance_Price_Month__c * isNewPriceAdj;
                        //ai.mcae.Maintenance_Price_YearTXT__c = ai.mcae.Estimate_List_Price__c * 12;
                        // ai.orgPrice = prd[0].Maintenance_Price_Month__c;
                        ai.mcae.EquipmentGuaranteeFlgTxt__c = prd[0].EquipmentGuaranteeFlg__c;
                        ai.etGFlg = prd[0].EquipmentGuaranteeFlg__c;
                        //add by rentx 2020-11-12 LJPH-BV93RZ start
                        ai.proName = prd[0].Name;
                        //add by rentx 2020-11-12 LJPH-BV93RZ end
                        // add by fxk 2021/9/9 控制点检对象是否可选 Star
                        ai.CheckRows = false;
        
                        //2021-11-30 fy add LJPH-C8W8FV 置顶 start
                        if (String.isBlank(prd[0].ProductURF__c)) {
                            // ai.mcae.Product_Manual__c.addError(prd[0].Name + ' 不是限次产品，请重新选择!');
                            return prd[0].Name + ' 不是限次产品，请重新选择!';
                        }
                        ai.mcae.Estimate_List_Price__c = prd[0].ProductURF__r.UFR_Maintenance_Price_Month_3__c * isNewPriceAdj;
                        ai.orgPrice = prd[0].ProductURF__r.UFR_Maintenance_Price_Month__c;
                        ai.uFRPrice = prd[0].ProductURF__r.UFR_Maintenance_Price_Month__c;
                        ai.uFRSerial = prd[0].ProductURF__r.URFLimitSerial__c;
                        ai.uFRRepairCount = 0;
                        ai.MDMModelNoc = prd[0].Asset_Model_No__c;

                        if(TopProductModel.contains(ai.MDMModelNoc)){
                            ai.CheckRows = true;
                            ai.mcae.Check_Object__c = false;
                        }else {
                            if(String.isNotBlank(prd[0].ProductURF__c)){
                                ai.mcae.Check_Object__c = false;
                            }else{
                                ai.mcae.Check_Object__c = true;
                            }
                            ai.CheckRows = false;
                        }
                        //2021-11-30 fy add LJPH-C8W8FV 置顶 end

                         //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
                        ai.uFRMaxPrice = prd[0].ProductURF__r.Maintenance_Price_Year_URF_Max__c;
                        ai.uFRMinPrice = prd[0].ProductURF__r.Maintenance_Price_Year_URF__c;
                        //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
                        //URF限次合同2期 LY 20220811 start
                        ai.uFRMaxPrice3 = prd[0].ProductURF__r.Maintenance_Price_Year_URF_Max_3__c;
                        ai.uFRMinPrice3 = prd[0].ProductURF__r.Maintenance_Price_Year_URF_3__c;
                        //URF限次合同2期 LY 20220811 end
        
                        
                    }
                    // checkedAssets[i]=ai;
                }
            }
            // HWAG-BA73ZP
            //contractStartDateChange();
            return JSON.serialize(checkedAssets);
        }catch(Exception ex){
            return ex.getMessage();
        }
    }

    // 检索按钮 end
    @AuraEnabled
    public static String searchBtn(String initDataStr) {
        try {
            InitData  initData = (InitData)JSON.deserialize(initDataStr, InitData.class);
            initData.countorder = 1;
            //验证
            initData.assetSerialNumberList.clear();
            getAssetSerialNumber(initData);
            initData.totalRecords = 0;
            List<Asset> assetconfimList = getAssetconfim(initData.text1, initData.cond1, initData.val1,initData);
            for (Asset ast : assetconfimList) {
                initData.totalRecords++;
            }
        
        
            // 获取assets
            List<Asset> assetList = getAsset(initData.text1, initData.cond1, initData.val1,initData);
        
            // 作成明细行
            getSortedUnCheckedInfoList(assetList,initData);
            // 排序用检索条件退避
            initData.text1ForSort = initData.text1;
            initData.cond1ForSort = initData.cond1;
            initData.val1ForSort = initData.val1;
            initData.currPage = 1;
        
        
            initData.totalPage = (initData.totalRecords / initData.selctRecordNum) + (Math.mod(initData.totalRecords, initData.selctRecordNum) > 0 ? 1 : 0);
            return JSON.serialize(initData);
        }catch(Exception ex){
            return ex.getMessage();
        }
    }

    // 取已选择资产的机身编码
    public static void getAssetSerialNumber(InitData initData) {
        //LJPH-BSS6E2  ---20200911 ---add by rentongxiao start
        initData.contr = '2';
        //LJPH-BSS6E2  ---20200911 ---add by rentongxiao end
        initData.assetSerialNumberList = new List<String>();
        initData.assetSerialNumberList.clear();
        for (AssetInfo ai : initData.checkedAssets) {
            if (String.isNotEmpty(ai.rec.SerialNumber)) {
                initData.assetSerialNumberList.add(ai.rec.SerialNumber);
            }
        }
    }
    //检索验证
    private static List<Asset> getAssetconfim(String txt, String con, String val,InitData initData) {
        String soql = makeSoqlconfim(initData.assetSerialNumberList,initData.targetHospitalId);
        soql += makeTextSql(txt, con, val);
        if (initData.isSoft) {
            soql += ' order by ' + initData.columus[Integer.valueOf(initData.sortKey)] + ' ' + (initData.sortOrderAsc == true ? 'asc nulls first' : 'desc nulls last ');
        } else {
            soql += ' order by SerialNumber, Name, Department_Name__c, InstallDate';
        }
        return Database.query(soql);
    }
    private static String makeSoqlconfim(List<String> assetSerialNumberList,String targetHospitalId) {
        String sqlTail = '(\'';
        for (Integer i = 0; i < assetSerialNumberList.size(); i++) {
            if (i < assetSerialNumberList.size() - 1) {
                sqlTail += assetSerialNumberList[i] + '\',\'';
            } else {
                sqlTail += assetSerialNumberList[i] + '\')';
            }
        }
        //2021-11-30 fy add LJPH-C8W8FV 置顶 start OwnershipMachine_No__c
                //tcm 删除第4行 Maintenance_Contract_No_F__c 替换 Management_Code__c  20211201
        String soql = 'SELECT Id, Name,OwnershipMachine_No__c, 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,isNewDate_use__c, '
                      + 'Asset_Owner__c, Accumulation_Repair_Amount__c, Maintenance_Price_Month__c, Final_Examination_Date__c, '
                          + 'CurrentContract_F__c,CurrentContract_F__r.Management_Code__c,CurrentContract_F__r.Maintenance_Contract_No_F__c,CurrentContract_F__r.RecordType_DeveloperName__c,CurrentContract_F__r.Estimate_Num__c,CurrentContract_F__r.Contract_End_Date__c,'
                      + 'CurrentContract_F_asset__c,CurrentContract_F_asset__r.Estimate_Cost_Month_formula__c,CurrentContract_F_asset__r.endDateGurantee_Text__c,CurrentContract_F__r.Gurantee_Estimate_startDate__c, '
                      + 'CurrentContract_F__r.First_Estimate_Date__c,CurrentContract_F__r.Estimate_Contract_endDate__c,'
                      + 'CurrentContract_F__r.Contract_Consumption_rate__c,CurrentContract_F__r.First_contract_usage_Rate__c,CurrentContract_F__r.Contract_Range__c,'
                      + 'Product2.ProductURF__c,Product2.ProductURF__r.URFLimitSerial__c,Product2.ProductURF__r.UFR_MaxRepairCount__c,Product2.ProductURF__r.UFR_Maintenance_Price_Month__c,'
                      //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
                      + 'Product2.ProductURF__r.Maintenance_Price_Year_URF_Max__c, Product2.ProductURF__r.Maintenance_Price_Year_URF__c,'  
                      //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
                      //URF限次合同2期 LY 20220811 start
                      + 'Product2.ProductURF__r.Maintenance_Price_Year_URF_3__c, Product2.ProductURF__r.Maintenance_Price_Year_URF_Max_3__c, Product2.ProductURF__r.UFR_Maintenance_Price_Month_3__c,'
                      + 'URF_Maintenance_Contract__c,URF_Maintenance_Contract__r.Management_Code__c,URF_Maintenance_Contract__r.Contract_End_Date__c,'
                      //URF限次合同2期 LY 20220811 end
                      + 'CurrentContract_End_Date__c, Extend_Gurantee_DateTo__c,EquipmentGuaranteeFlg__c,AssetMark__c FROM Asset WHERE Product2.ProductURF__c != null AND Hospital__c = \'' + targetHospitalId + '\' ';
        //HWAG-BDJ43R ---XHL---20190729---
        //soql +=  ' AND AssetMark__c != \'耗材\' AND Product2.Family != \'ET\' ';
        //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start
        // soql +=  ' AND ( AssetMark__c != \'耗材\' OR Product2.Family != \'ET\' ) ';
        //JZHG-BSDUT4 ---20200825---update By rentongxiao---End
        //HWAG-BDJ43R ---XHL---20190729---
        if (assetSerialNumberList.size() > 0) {
            soql += ' AND SerialNumber not in ' + sqlTail;
        }
        return soql;
    }
    // 拼接检索条件sql文
    private static 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 += ')';
                }
            } else if ((con == 'equals' || con == 'notequals') && val.contains(',')) {
                String[] vals = val.split(',');
                if (vals.size() > 0) {
                    String txt = txt1.substring(2);                 // S:Name 、最初の２文字がタイプです
                    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 = makeTextSqlStr(txt1, con, val);
                if (con != 'notcontains') {
                    soql += 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 static List<Asset> getAsset(String txt, String con, String val,InitData initData) {
        String soql = makeSoqlconfim(initData.assetSerialNumberList,initData.targetHospitalId);
        soql += makeTextSql(txt, con, val);
    
        if (initData.isSoft) {
            soql += ' order by ' + initData.columus[Integer.valueOf(initData.sortKey)] + ' ' + (initData.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 ' + (initData.countorder - 1) * Integer.valueOf(System.Label.Asset_Maxcount);
        return Database.query(soql);
    }
    private static void getSortedUnCheckedInfoList(List<Asset> assetList,InitData initData) {
        Boolean overLimit = false;
        Map<Id, AssetInfo> markUpUnCheckMap = new Map<Id, AssetInfo>();
        for (AssetInfo unCheckinfo : initData.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);
            }
        }
        initData.unCheckedAssets.clear();
        // 优先显示明细放在最前面
        initData.unCheckedInfoList = new List<AssetInfo>();
        for (AssetInfo asInfo : markUpUnCheckMap.values()) {
            initData.unCheckedAssets.add(asInfo);
        }
        initData.SELECT_LIMIT = initData.selctRecordNum;
        Integer selectCnt = initData.unCheckedAssets.size();
        for (Asset asset : assetList) {
            // 201を超えた場合前200のみを出す
            // 2023/09/01 改为前端分页，注释原有逻辑
            // if (initData.unCheckedAssets.size() >= initData.SELECT_LIMIT) { overLimit = true; break; }
            if (markUpUnCheckMap.containsKey(asset.Id) == false) {
                //unCheckedInfoList.add(unCheckMap.get(asset.Id));
                initData.unCheckedAssets.add(new AssetInfo(initData.unCheckedAssets.size(), asset));
            }
        }
    }
    private static 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;
    }
    /**
     * 選択済み／未選択製品の置き換え
     */
    @AuraEnabled
    public static String exchangeAsset(String initDataStr) {
        try {
            InitData initData = (InitData)JSON.deserialize(initDataStr,InitData.class);
            System.debug(LoggingLevel.INFO, '*** initData: ' + initData);
            Date systemToday = System.today();
            List<AssetInfo> tmpChecked = new List<AssetInfo>();
            List<AssetInfo> tmpNewRows = new List<AssetInfo>();
            List<AssetInfo> tmpUnChecked = new List<AssetInfo>();
            //2021-11-30 fy add LJPH-C8W8FV 置顶 start
            List<AssetInfo> tmpnewChecked = new List<AssetInfo>();
            //2021-11-30 fy add LJPH-C8W8FV 置顶 end
            // 限次合同不需要上下限 20210315 gzw start
            // List<Data> datatemp = new List<Data>();
            // datatemp = getChartData();
            // 限次合同不需要上下限 20210315 gzw end
            for (AssetInfo ass : initData.checkedAssets) {
                if (ass.isManual) {
                    tmpNewRows.add(ass);
                } else if (ass.rec_checkBox_c) {
                    tmpChecked.add(ass);
                } else {
                    ass.mcae = null;
                    tmpUnChecked.add(ass);
                    initData.totalRecords++;
                }
            }
            for (AssetInfo ass : initData.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;
                //URF限次合同2期 LY 20220811 start
                //Decimal listPrice = ass.rec.Product2.ProductURF__r.UFR_Maintenance_Price_Month__c;
                // Decimal listPrice =0;
                // if (Integer.valueOf(this.estimate.URF_V_MaxRepairCount__c)==2){
                //  listPrice = ass.rec.Product2.ProductURF__r.UFR_Maintenance_Price_Month__c;
                // }else{
                    Decimal listPrice = ass.rec.Product2.ProductURF__r.UFR_Maintenance_Price_Month_3__c;
                // }
                
                //URF限次合同2期 LY 20220811 end
                //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220510 start
                // Decimal MaxPrice = ass.rec.Product2.ProductURF__r.Maintenance_Price_Year_URF_Max__c;
                // Decimal MinPrice = ass.rec.Product2.ProductURF__r.Maintenance_Price_Year_URF__c;
                Decimal MaxPrice = ass.rec.Product2.ProductURF__r.Maintenance_Price_Year_URF_Max_3__c;
                Decimal MinPrice = ass.rec.Product2.ProductURF__r.Maintenance_Price_Year_URF_3__c;
                //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220510 end
                if (ass.rec_checkBox_c) {
                    //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO , 'unCheckedAssets ' ));
                    // 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,
                        //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
                        Adjustment_Upper_price__c = MaxPrice,
                        Adjustment_Lower_price__c = MinPrice,
                        //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
                        EquipmentGuaranteeFlgTxt__c = ass.rec.EquipmentGuaranteeFlg__c
                        );
                    ass.mcae = mcae;
                    // 计算上下线调整比例
                    // 限次合同不需要上下限 20210315 gzw start
                    if (!getPageDisabled(initData.contract,initData.estimate)) {
                        // 取当前月第一天
                        Date mon1stDate = Date.newInstance(Date.today().year(), Date.today().month(), 1);
                        mcae.LastMContract_Price__c = ass.rec.CurrentContract_F_asset__r.Estimate_Cost_Month_formula__c == null ? mcae.LastMContract_Price__c : ass.rec.CurrentContract_F_asset__r.Estimate_Cost_Month_formula__c;
                        if (ass.rec.CurrentContract_F__r.First_Estimate_Date__c != null && ass.rec.CurrentContract_F__r.Estimate_Contract_endDate__c > mon1stDate) {
                            mcae.Asset_Consumption_rate__c = ass.rec.CurrentContract_F__r.First_contract_usage_Rate__c == null ? mcae.Asset_Consumption_rate__c : ass.rec.CurrentContract_F__r.First_contract_usage_Rate__c;
                        } else {
                            mcae.Asset_Consumption_rate__c = ass.rec.CurrentContract_F__r.Contract_Consumption_rate__c == null ? mcae.Asset_Consumption_rate__c : ass.rec.CurrentContract_F__r.Contract_Consumption_rate__c;
                        }
                        // if(String.isNotBlank(String.valueOf(mcae.Asset_Consumption_rate__c))){
                        //     for (Data da : datatemp) {
                        //         if (String.isBlank(String.valueOf(da.rate_Lower)) &&  mcae.Asset_Consumption_rate__c < da.rate_Upper) {
                        //             mcae.Adjustment_ratio_Lower__c = da.price_Lower;
                        //             mcae.Adjustment_ratio_Upper__c = da.price_Upper;
                        //             continue;
                        //         }else if (mcae.Asset_Consumption_rate__c >= da.rate_Lower && String.isBlank(String.valueOf(da.rate_Upper))) {
                        //             mcae.Adjustment_ratio_Lower__c = da.price_Lower;
                        //             mcae.Adjustment_ratio_Upper__c = da.price_Upper;
                        //             continue;
                        //         }else if (mcae.Asset_Consumption_rate__c >= da.rate_Lower
                        //                 && mcae.Asset_Consumption_rate__c < da.rate_Upper) {
                        //             mcae.Adjustment_ratio_Lower__c = da.price_Lower;
                        //             mcae.Adjustment_ratio_Upper__c = da.price_Upper;
                        //             continue;
                        //         }
                        //     }
                        // }
                    }
                    // 限次合同不需要上下限 20210315 gzw end
        
        
        
                    // tmpChecked.add(ass);
                    //2021-11-30 fy add LJPH-C8W8FV 置顶 start
                    tmpnewChecked.add(ass);
                    //2021-11-30 fy add LJPH-C8W8FV 置顶 end
                    initData.totalRecords--;
                } else {
                    ass.mcae = null;
                    tmpUnChecked.add(ass);
                }
            }
        
            initData.checkedAssets = new List<AssetInfo>();
            //2021-11-30 fy add LJPH-C8W8FV 置顶 start
            for (AssetInfo ass : tmpnewChecked) {
                if(String.isNotBlank(ass.rec.Product2.ProductURF__c)){
                    ass.mcae.Check_Object__c = false;
                }
                tmpChecked.add(ass);
            }
            //2021-11-30 fy add LJPH-C8W8FV 置顶 end
            for (AssetInfo ass : tmpChecked) {
                ass.lineNo = initData.checkedAssets.size();
                initData.checkedAssets.add(ass);
            }
            for (AssetInfo ass : tmpNewRows) {
                ass.lineNo = initData.checkedAssets.size();
                initData.checkedAssets.add(ass);
            }
            initData.unCheckedAssets = new List<AssetInfo>();
            initData.unCheckedAssets.addAll(tmpUnChecked);
        
            initData.totalPage = (initData.totalRecords / initData.selctRecordNum) + (Math.mod(initData.totalRecords, initData.selctRecordNum) > 0 ? 1 : 0);
            setPageRecord(initData);
        
            //listCut(unCheckedAssets);
            // 根据合同开始日重新计算维修合同价格
            //contractStartDateChange();
            //2021-11-30 fy add LJPH-C8W8FV 置顶 start
            List<AssetInfo> topAsset =new List<AssetInfo>();
            List<AssetInfo> otherAsset =new List<AssetInfo>();
            for(AssetInfo ched : initData.checkedAssets){
                if(initData.TopProductModel.contains(ched.ProductModelNoc)||initData.TopProductModel.contains(ched.AssetModelNoc)||initData.TopProductModel.contains(ched.rec.OwnershipMachine_No__c)){
                    ched.CheckRows = true;
                    ched.mcae.Check_Object__c = false;
                    topAsset.add(ched);
                }else{
                    otherAsset.add(ched);
                }
            }
            topAsset.addAll(otherAsset);
            List<AssetInfo> NumberSort =new List<AssetInfo>();
            Integer i=0;
            for (AssetInfo ched2 : topAsset) {
                ched2.lineNo=i;
                i++;
                NumberSort.add(ched2);
            }
            System.debug(LoggingLevel.INFO, '*** NumberSort: ' + NumberSort);
            initData.checkedAssets=NumberSort;
            //2021-11-30 fy add LJPH-C8W8FV 置顶 end
            return JSON.serialize(initData);
        }catch(Exception ex){
            return ex.getMessage();
        }
    }
    // 取得分页数据
    private static void setPageRecord(InitData initData) {
        initData.checkIdList = new List<String> ();
        for (AssetInfo ass : initData.checkedAssets) {
            if (!ass.isManual) {
                initData.checkIdList.add(ass.rec.Id);
            }
        }
        
        if ((initData.currPage * initData.selctRecordNum) <= 2000) {
            String notInId = '(\'';
            if (initData.checkIdList.size() > 0) {
                for (String str : initData.checkIdList) {
                    notInId += str + '\', \'';
                }
            }
            notInId += '\')';
            //2021-11-30 fy add LJPH-C8W8FV 置顶 start OwnershipMachine_No__c
            //tcm 删除第4行 Maintenance_Contract_No_F__c 替换 Management_Code__c  20211201 start
            String sqlStr = 'SELECT Id, Name,OwnershipMachine_No__c, 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,isNewDate_use__c, '
                            + 'Asset_Owner__c, Accumulation_Repair_Amount__c, Maintenance_Price_Month__c, Final_Examination_Date__c, '
                            + 'CurrentContract_End_Date__c, Extend_Gurantee_DateTo__c,EquipmentGuaranteeFlg__c, '
                                + 'CurrentContract_F__c,CurrentContract_F__r.Management_Code__c,CurrentContract_F__r.Maintenance_Contract_No_F__c,CurrentContract_F__r.RecordType_DeveloperName__c,CurrentContract_F__r.Estimate_Num__c,CurrentContract_F__r.Contract_End_Date__c,'
                            + 'CurrentContract_F_asset__c,CurrentContract_F_asset__r.Estimate_Cost_Month_formula__c,CurrentContract_F_asset__r.endDateGurantee_Text__c,CurrentContract_F__r.Gurantee_Estimate_startDate__c, '
                            + 'CurrentContract_F__r.First_Estimate_Date__c,CurrentContract_F__r.Estimate_Contract_endDate__c,'
                            + 'CurrentContract_F__r.Contract_Consumption_rate__c,CurrentContract_F__r.First_contract_usage_Rate__c,'
                            + 'Product2.ProductURF__c,Product2.ProductURF__r.URFLimitSerial__c,Product2.ProductURF__r.UFR_MaxRepairCount__c,Product2.ProductURF__r.UFR_Maintenance_Price_Month__c,'
                            //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
                            + 'Product2.ProductURF__r.Maintenance_Price_Year_URF__c, Product2.ProductURF__r.Maintenance_Price_Year_URF_Max__c,' 
                            //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
                            //URF限次合同2期 LY 20220811 start
                            + 'Product2.ProductURF__r.Maintenance_Price_Year_URF_3__c, Product2.ProductURF__r.Maintenance_Price_Year_URF_Max_3__c, Product2.ProductURF__r.UFR_Maintenance_Price_Month_3__c,'
                            + 'URF_Maintenance_Contract__c,URF_Maintenance_Contract__r.Management_Code__c,URF_Maintenance_Contract__r.Contract_End_Date__c,'
                            //URF限次合同2期 LY 20220811 end
                            + 'CurrentContract_F__r.Contract_Range__c,AssetMark__c FROM Asset WHERE Product2.ProductURF__c != null AND Hospital__c = \'' + initData.targetHospitalId + '\' '
                            + 'AND Id NOT IN ' + notInId;
            //HWAG-B4R3SS  START 20181026
            if (String.isNotBlank(initData.text1) && String.isNotBlank(initData.cond1) && String.isNotBlank(initData.val1)) {
                sqlStr += makeTextSql(initData.text1,initData.cond1,initData.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 ';
            //2023/09/01 改为前端分页，注释原有逻辑
            // if (initData.currPage == 1) {
            //     sqlStr += 'limit ' + initData.selRecordOption;
            // } else {
            //     sqlStr += 'limit ' + initData.selRecordOption + ' offset ' + String.valueOf((initData.currPage - 1) * initData.selctRecordNum);
            // }
            initData.assetRecords = Database.query(sqlStr);
        } else {
            initData.assetRecords.clear();
            Integer sqlLimit = initData.currPage * initData.selctRecordNum;
            List<Asset> temAsset = new List<Asset> ();
            //HWAG-BDJ43R ---XHL---20190729---
            String sqlStr = '';
            //2021-11-30 fy add LJPH-C8W8FV 置顶 start OwnershipMachine_No__c
            //tcm 删除第4行 Maintenance_Contract_No_F__c 替换 Management_Code__c  20211201 start 
            sqlStr  = 'SELECT Id, Name,OwnershipMachine_No__c, 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,isNewDate_use__c,';
            sqlStr += 'Asset_Owner__c, Accumulation_Repair_Amount__c, Maintenance_Price_Month__c, Final_Examination_Date__c,';
            sqlStr += 'CurrentContract_End_Date__c,Extend_Gurantee_DateTo__c,EquipmentGuaranteeFlg__c,';
                sqlStr += 'CurrentContract_F__c,CurrentContract_F__r.Management_Code__c,CurrentContract_F__r.Maintenance_Contract_No_F__c,CurrentContract_F__r.RecordType_DeveloperName__c,CurrentContract_F__r.Estimate_Num__c,CurrentContract_F__r.Contract_End_Date__c,';
            sqlStr += 'CurrentContract_F_asset__c,CurrentContract_F_asset__r.Estimate_Cost_Month_formula__c,CurrentContract_F_asset__r.endDateGurantee_Text__c,CurrentContract_F__r.Gurantee_Estimate_startDate__c,';
            sqlStr += 'CurrentContract_F__r.First_Estimate_Date__c,CurrentContract_F__r.Estimate_Contract_endDate__c,';
            sqlStr += 'CurrentContract_F__r.Contract_Consumption_rate__c,CurrentContract_F__r.First_contract_usage_Rate__c,';
            sqlStr += 'Product2.ProductURF__c,Product2.ProductURF__r.URFLimitSerial__c,Product2.ProductURF__r.UFR_MaxRepairCount__c,Product2.ProductURF__r.UFR_Maintenance_Price_Month__c,';
            //URF限次合同2期 LY 20220811 start
            sqlStr += 'Product2.ProductURF__r.UFR_Maintenance_Price_Month_3__c,';
            sqlStr += 'URF_Maintenance_Contract__c,URF_Maintenance_Contract__r.Management_Code__c,URF_Maintenance_Contract__r.Contract_End_Date__c,';
            //URF限次合同2期 LY 20220811 end
            sqlStr += ' CurrentContract_F__r.Contract_Range__c,AssetMark__c FROM Asset WHERE Product2.ProductURF__c != null AND Hospital__c = \'' + initData.targetHospitalId + '\'';
            //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start
            // sqlStr += '  AND ( AssetMark__c != \'耗材\' OR Product2.Family != \'ET\' ) ';
            //JZHG-BSDUT4 ---20200825---update By rentongxiao---End
            //HWAG-B4R3SS  START 20181026
            if (String.isNotBlank(initData.text1) && String.isNotBlank(initData.cond1) && String.isNotBlank(initData.val1)) {
                sqlStr += makeTextSql(initData.text1, initData.cond1, initData.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 (initData.checkIdList.size() > 0) {
    
                sqlStr += '  AND Id NOT IN ' + initData.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() >= (initData.currPage * initData.selctRecordNum)) {
                for (Integer i = ((initData.currPage - 1) * initData.selctRecordNum); i < (initData.currPage * initData.selctRecordNum); i++) {
                    initData.assetRecords.add(temAsset.get(i));
                }
            } else {
                for (Integer i = ((initData.currPage - 1) * initData.selctRecordNum); i < temAsset.size(); i++) {
                    initData.assetRecords.add(temAsset.get(i));
                }
            }
        }
        initData.unCheckedAssets = new List<AssetInfo>();
        for (Asset ast : initData.assetRecords) {
            initData.unCheckedAssets.add(new AssetInfo(initData.unCheckedAssets.size(), ast));
        }
        initData.unCheckedAssetsView = listCut(initData.unCheckedAssets,initData.unCheckedAssetsView);
        // 根据合同开始日重新计算维修合同价格
        //contractStartDateChange();
    }
    /**
     * 印刷メソッド、decide前は保有設備、decide後は合同配置
     */
    @AuraEnabled
    public static String print(String initDataStr) {
        try {
            InitData initData = (InitData)JSON.deserialize(initDataStr,InitData.class);
            initData.printAsset = false;
            initData.printContract = false;
            initData.printTripartite = false;
            initData.printAgent = false;
            initData.estimate.PrintDate__c = Date.today();
            //SelectAssetEstimateURFController.ComputeLTYRepair(targetEstimateId);
            if (initData.estimate.Quote_Date__c == null) {
                initData.estimate.Quote_Date__c = Date.today();
            }
        
            if (initData.estimate.Print_Tripartite__c && initData.estimate.Print_Agent__c) {

                return '不能同时选中三方协议和代理商合同！';
            }
        
        
            // 保存ボタンできない場合、印刷ボタンはフラグのみ保存
            if (getSaveBtnDisabled(initData.contract,initData.estimate)) {
                String savePrintFlgResult = savePrintFlg(initData);
                if (savePrintFlgResult == 'true') {
                // 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 (initData.estimate.Print_Tripartite__c ) {
                        //打印三方合同
                        initData.printTripartite = true;
                    } else if (!initData.estimate.Estimation_Decision__c) {
                        initData.printAsset = true;
        
                    } else if (initData.estimate.Estimate_Target__c != null && initData.estimate.Estimate_Target__c.equals('医院')) {
                        initData.printContract = true;
        
                    } else if (initData.estimate.Estimate_Target__c != null && initData.estimate.Estimate_Target__c.equals('经销商')) {
                        initData.printAgent = true;
                    }
                    // 2018/10/26 HWAG-B5C88S end
                }else{
                    return savePrintFlgResult;
                }
            }
            // 保存ボタンできる場合、印刷ボタンは全部保存
            else {
                String syncEstimateResult = syncEstimate(false, false,initData) ;

                if (syncEstimateResult == 'true') {
                // 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 (initData.estimate.Print_Tripartite__c ) {
                        //打印三方合同
                        initData.printTripartite = true;
                    } else if (!initData.estimate.Estimation_Decision__c) {
                        initData.printAsset = true;
        
                    } else if (initData.estimate.Estimate_Target__c != null && initData.estimate.Estimate_Target__c.equals('医院')) {
                        initData.printContract = true;
        
                    } else if (initData.estimate.Estimate_Target__c != null && initData.estimate.Estimate_Target__c.equals('经销商')) {
                        initData.printAgent = true;
                    }
                    // 2018/10/26 HWAG-B5C88S end
                }else{
                    return syncEstimateResult;
                }
            }
            //ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, '合同'+this.printContract +'三方'+this.printTripartite+'保有'+this.printAsset+'经销商合同'+this.printAgent));
            return JSON.serialize(initData);
        }catch(Exception ex){
            return ex.getMessage();
        }
    }
    /**
     * 印刷フラグのみを保存
     */
    @TestVisible
    private static String savePrintFlg(InitData initData) {
        try {
            Maintenance_Contract_Estimate__c mce = new Maintenance_Contract_Estimate__c();
            mce.Id = initData.targetEstimateId;
            //打印报价（简化版） 2019/12/18 start
            mce.Print_Simplify__c = initData.estimate.Print_Simplify__c;
            //打印报价（简化版） 2019/12/18 end
            mce.Print_ListPrice__c = initData.estimate.Print_ListPrice__c;
            mce.Print_RepairPrice__c = initData.estimate.Print_RepairPrice__c;
            mce.Print_SumPrice__c = initData.estimate.Print_SumPrice__c;
            mce.Print_DiscountPercentage__c = initData.estimate.Print_DiscountPercentage__c;
            mce.Print_DiscountPrice__c = initData.estimate.Print_DiscountPrice__c;
            mce.Print_MaintePrice__c = initData.estimate.Print_MaintePrice__c;
            mce.Print_Contract__c = initData.estimate.Print_Contract__c;
    
            ControllerUtil.updateMaintenance_Contract_Estimate(new Maintenance_Contract_Estimate__c[] {mce});
            // return true;
            return 'true';
        } catch (Exception ex) {
            // ApexPages.addMessages(ex);
            return ex.getMessage();
        }
        // return false;
    }
    // 每页显示记录数变更 - del
    // @AuraEnabled
    // public static String recordNumChange(String initDataStr) {
    //     try {
    //         InitData initData = (InitData)JSON.deserialize(initDataStr,InitData.class);
    //         initData.currPage = 1;
    //         //totalRecords = soqlNos();
    //         initData.totalPage = (initData.totalRecords / initData.selctRecordNum) + (Math.mod(initData.totalRecords, initData.selctRecordNum) > 0 ? 1 : 0);
    //         setPageRecord(initData);
    //         return JSON.serialize(initData);
    //     }catch(Exception ex){
    //         return ex.getMessage();
    //     }
    // }
    // 翻页到首页
    // @AuraEnabled
    // public static String firstPage(String initDataStr) {
    //     try {
    //         InitData initData = (InitData)JSON.deserialize(initDataStr,InitData.class);
    //         getAssetSerialNumber(initData);
    //         initData.currPage = 1;
    //         //HWAG-B4R3SS  END 20181026
    //         initData.totalRecords = soqlNos(initData);
    //         initData.totalPage = (initData.totalRecords / initData.selctRecordNum) + (Math.mod(initData.totalRecords, initData.selctRecordNum) > 0 ? 1 : 0);
    //         //HWAG-B4R3SS  END 20181026
    //         setPageRecord(initData);
    //         return JSON.serialize(initData);
    //     }catch(Exception ex){
    //         return ex.getMessage();
    //     }
    // }
    // public static Integer soqlNos(InitData initData) {
    //     List<Asset> assetconfimList = getAssetconfim(initData.text1, initData.cond1, initData.val1,initData);
    //     Integer totalRecords = assetconfimList.size();
    //     //totalPage = (totalRecords/selctRecordNum) + (Math.mod(totalRecords, selctRecordNum) > 0 ? 1 : 0);
    //     return totalRecords;
    // }
     // 向前翻页
    // @AuraEnabled
    // public static String previousPage(String initDataStr) {
    //     try {
    //         InitData initData = (InitData)JSON.deserialize(initDataStr,InitData.class);
    //         getAssetSerialNumber(initData);
    //         initData.currPage--;
    //         //HWAG-B4R3SS  START 20181026
    //         initData.totalRecords = soqlNos(initData);
    //         initData.totalPage = (initData.totalRecords / initData.selctRecordNum) + (Math.mod(initData.totalRecords, initData.selctRecordNum) > 0 ? 1 : 0);
    //         //HWAG-B4R3SS  END 20181026
    //         setPageRecord(initData);
    //         return JSON.serialize(initData);
    //     }catch(Exception ex){
    //         return ex.getMessage();
    //     }
    // }
    
    // // 向后翻页
    // @AuraEnabled
    // public static String nextPage(String initDataStr) {
    //     try {
    //         InitData initData = (InitData)JSON.deserialize(initDataStr,InitData.class);
    //         getAssetSerialNumber(initData);
    //         //HWAG-B4R3SS  START 20181026
    //         initData.totalRecords = soqlNos(initData);
    //         //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO , 'totalRecords——————' + totalRecords));
    //         initData.totalPage = (initData.totalRecords / initData.selctRecordNum) + (Math.mod(initData.totalRecords, initData.selctRecordNum) > 0 ? 1 : 0);
    //         if (initData.totalRecords == 0) {
    //             initData.currPage  = 1;
    //             //this.unCheckedAssets.clear();
    //         } else {
    //             initData.currPage++;
    //             setPageRecord(initData);
    //         }
    //         //HWAG-B4R3SS  END 20181026
    //         return JSON.serialize(initData);
    //     }catch(Exception ex){
    //         return ex.getMessage();
    //     }
    // }
    
    // // 翻页到尾页
    // @AuraEnabled
    // public static String endPage(String initDataStr) {
    //     try {
    //         InitData initData = (InitData)JSON.deserialize(initDataStr,InitData.class);
    //         getAssetSerialNumber(initData);
    //         //HWAG-B4R3SS  START 20181026
    //         initData.totalRecords = soqlNos(initData);
    //         initData.totalPage = (initData.totalRecords / initData.selctRecordNum) + (Math.mod(initData.totalRecords, initData.selctRecordNum) > 0 ? 1 : 0);
    //         if (initData.totalRecords == 0) {
    //             initData.currPage  = 1;
    //             initData.unCheckedAssets.clear();
    //         } else {
    //             initData.currPage = initData.totalPage;
    //             setPageRecord(initData);
    //         }
    //         //HWAG-B4R3SS  END 20181026
    //         return JSON.serialize(initData);
    //     }catch(Exception ex){
    //         return ex.getMessage();
    //     }
    // }

    //贸易合规 you start
    @AuraEnabled
    public static String interceptsend(String estimateStr,String targetEstimateId){
        try{
            //String BuchangApprovalManager = this.estimate.BuchangApprovalManager__c;
            //String JingliApprovalManager = this.estimate.JingliApprovalManager__c;
            Maintenance_Contract_Estimate__c estimate = (Maintenance_Contract_Estimate__c)JSON.deserialize(estimateStr, Maintenance_Contract_Estimate__c.class);
            String fseid = estimate.CreatedById;
            String AccDealerBlacklist = estimate.Maintenance_Contract__r.AccDealerBlacklist__c;
            String accname = estimate.Maintenance_Contract__r.Hospital__r.Name;
            String deaname = estimate.Maintenance_Contract__r.Dealer__r.Name;
            //FSE领导
            String[] FSEStr = new String[] {};
            //if(String.isNotBlank(BuchangApprovalManager)){
            //    FSEStr.add(BuchangApprovalManager);
            //}
            //if(String.isNotBlank(JingliApprovalManager)){
            //    FSEStr.add(JingliApprovalManager);
            //}
            FSEStr.add(fseid);

            Boolean reflag = OpportunityWebService.accSendEmailFW(AccDealerBlacklist,accname,deaname,targetEstimateId,'decide_con',FSEStr);
            return 'success';
        }catch(Exception ex){
            return ex.getMessage();
        }
    }
    //贸易合规 you end

   /**
     * 決定メソッド
     */
    @AuraEnabled
    public static String decide(String initDataStr) {
        try {
            InitData initData = (InitData)JSON.deserialize(initDataStr,InitData.class);
            initData.inDicideFlag = true;

            // TODO check decide 资格
            Savepoint sp = Database.setSavepoint();

            String syncEstimateResult = syncEstimate(false, true,initData) ;

            if (syncEstimateResult == 'true') {
                //提交 报价决定日期
                initData.estimate.Quotation_Determines_Time__c = date.today();
        
                if (initData.changedAfterPrint) {
                    return '/' + initData.targetEstimateId + '/e?completion=1';

                } else {
                    return '/' + initData.targetEstimateId + '/e?completion=3';

                }
            }else{
                return syncEstimateResult;
            }
        }catch(Exception ex){
            return ex.getMessage();
        }
    }

    /**
     * 決定取消メソッド
     */
    @AuraEnabled
    public static String undecide(String targetEstimateId,String estimateStr) {
        Maintenance_Contract_Estimate__c estimate = (Maintenance_Contract_Estimate__c) JSON.deserialize(estimateStr,Maintenance_Contract_Estimate__c.class);
    
        estimate.Estimation_Decision__c = false;
        estimate.Print_Contract__c = false;
    
        //清空报价批准时间
        estimate.Quotation_Determines_Time__c = null;
    
        try {
            ControllerUtil.updateMaintenance_Contract_Estimate(new Maintenance_Contract_Estimate__c[] {estimate});
            return '/' + targetEstimateId + '/e?completion=1';
        } catch (Exception ex) {
            return ex.getMessage();
        }
    }
    /**
     *  lwc需要后台方法 行追加按钮 禁用 后端返回判断条件
     **/
    @AuraEnabled
    public static Boolean getMCAEIsCreateable(){
        return Schema.getGlobalDescribe().get('Maintenance_Contract_Asset_Estimate__c').getDescribe().isCreateable();
    }

    //定义内部类

    public class AssetInfo {
        // 新合同备品确保提供 当前标记
        public Boolean etGFlg {get; set;}
        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 Decimal orgPrice12 {get; private set;}
        
        //2021-11-30 fy add LJPH-C8W8FV 置顶 start
        public String ProductModelNoc;
        public String AssetModelNoc;
        public String MDMModelNoc;
        //2021-11-30 fy add LJPH-C8W8FV 置顶 end
        
        //add by rentx 2020-11-12 LJPH-BV93RZ start
        public String proName;
        public String proSerialNumber;
        public String proSerialName;
        //add by rentx 2020-11-12 LJPH-BV93RZ end
        // add by fxk 2021/9/9 控制点检对象是否可选 Star
        public Boolean CheckRows {get; private set;}
        // add by fxk 2021/9/9 控制点检对象是否可选 End
        // 限次价格 add by gzw start
        public Decimal uFRPrice {get; private set;}
        // 限次系列
        public String uFRSerial {get; private set;}
        // 最大大修次数
        public Decimal uFRRepairCount {get; private set;}
        
        // 限次价格 add by gzw end

        // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
        public Decimal uFRMaxPrice {get; set;}
        public Decimal uFRMinPrice {get; set;}
        // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
        //URF限次合同2期 LY 20220811 start
        public Decimal uFRMaxPrice3 {get; set;}
        public Decimal uFRMinPrice3 {get; set;}
        //URF限次合同2期 LY 20220811 end
        
        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;
            this.orgPrice12 = 0;
            this.etGFlg = false;
            this.uFRPrice = 0;
            this.uFRRepairCount = 0;
            // add by fxk 2021/9/9 控制点检对象是否可选 Star
            this.CheckRows = true;
            // add by fxk 2021/9/9 控制点检对象是否可选 End
            // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
            this.uFRMaxPrice = mcae.Product_Manual__r.ProductURF__r.Maintenance_Price_Year_URF_Max__c;
            this.uFRMinPrice = mcae.Product_Manual__r.ProductURF__r.Maintenance_Price_Year_URF__c;
            //URF限次合同2期 LY 20220811 start
            this.uFRMaxPrice3 = mcae.Product_Manual__r.ProductURF__r.Maintenance_Price_Year_URF_Max_3__c;
            this.uFRMinPrice3 = mcae.Product_Manual__r.ProductURF__r.Maintenance_Price_Year_URF_3__c;
            //URF限次合同2期 LY 20220811 end
            // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 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,
                //Maintenance_Price_YearTXT__c = mcae.Maintenance_Price_YearTXT__c,
                Check_Result__c = mcae.Check_Result__c,
                Repair_Price__c = mcae.Repair_Price__c,
                Comment__c = mcae.Comment__c,
                EquipmentGuaranteeFlgTxt__c = mcae.EquipmentGuaranteeFlgTxt__c,
                Estimate_Cost__c = mcae.Estimate_Cost__c,
                Adjustment_ratio_Upper__c = mcae.Adjustment_ratio_Upper__c,
                Adjustment_ratio_Lower__c = mcae.Adjustment_ratio_Lower__c,
                Adjustment_Upper_price__c = mcae.Adjustment_Upper_price__c,
                LastMContract_Price__c = mcae.LastMContract_Price__c,
                Adjustment_Lower_price__c = mcae.Adjustment_Lower_price__c,
                Asset_Consumption_rate__c = mcae.Asset_Consumption_rate__c
                                            // 追加限次信息
                , URF_Series__c = mcae.URF_Series__c,
                Series_RepairCount__c = mcae.Series_RepairCount__c,
                Series_MaxRepairCount__c = mcae.Series_MaxRepairCount__c,
                Asset_RepairCount__c = mcae.Asset_RepairCount__c,
                Asset_MaxRepairCount__c = mcae.Asset_MaxRepairCount__c
                // LJPH-C9GD34 gzw fix start
                ,Estimate_List_Price_Page__c = mcae.Estimate_List_Price_Page__c
                // LJPH-C9GD34 gzw fix end
        
                );
            this.isManual = false;
            this.rec_checkBox_c = true;
            this.orgPrice = record.Maintenance_Price_Month__c;
            this.orgPrice12 = this.orgPrice * 12;
            this.etGFlg = record.EquipmentGuaranteeFlg__c;
            //add by rentx 2020-11-12 LJPH-BV93RZ start
            this.proName = '机身编码为:' + record.SerialNumber;
            this.proSerialNumber = record.SerialNumber;
            this.proSerialName = record.Name;
        
            //2021-11-30 fy add LJPH-C8W8FV 置顶 start
            this.ProductModelNoc = mcae.Product_Manual__r.Asset_Model_No__c;
            this.AssetModelNoc = mcae.Asset__r.OwnershipMachine_No__c;
            //2021-11-30 fy add LJPH-C8W8FV 置顶 end
        
            //add by rentx 2020-11-12 LJPH-BV93RZ end
            //URF限次合同2期 LY 20220811 start
            //this.uFRPrice = record.Product2.ProductURF__r.UFR_Maintenance_Price_Month__c;
            this.uFRPrice = record.Product2.ProductURF__r.UFR_Maintenance_Price_Month_3__c;
            //URF限次合同2期 LY 20220811 end
            this.uFRSerial = record.Product2.ProductURF__r.URFLimitSerial__c;
            //this.uFRRepairCount = record.Product2.ProductURF__r.UFR_MaxRepairCount__c;
            //URF限次合同2期 LY 20220811 start
            this.uFRRepairCount = 0;
            // if (this.uFRSerial=='URF-V'){
            //  this.uFRRepairCount=2;
            // }else{
            //  this.uFRRepairCount=3;
            // }
            //URF限次合同2期 LY 20220811 start
            //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
            this.uFRMaxPrice = record.Product2.ProductURF__r.Maintenance_Price_Year_URF_Max__c;
            this.uFRMinPrice = record.Product2.ProductURF__r.Maintenance_Price_Year_URF__c;
            //URF限次合同2期 LY 20220811 start
            this.uFRMaxPrice3 = record.Product2.ProductURF__r.Maintenance_Price_Year_URF_Max_3__c;
            this.uFRMinPrice3 = record.Product2.ProductURF__r.Maintenance_Price_Year_URF_3__c;
            //URF限次合同2期 LY 20220811 end
            // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 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,
                //Maintenance_Price_YearTXT__c = mcae.Maintenance_Price_YearTXT__c,
                Check_Result__c = mcae.Check_Result__c,
                Repair_Price__c = mcae.Repair_Price__c,
                Comment__c = mcae.Comment__c,
                EquipmentGuaranteeFlgTxt__c = mcae.EquipmentGuaranteeFlgTxt__c,
                Estimate_Cost__c = mcae.Estimate_Cost__c,
                Adjustment_ratio_Upper__c = mcae.Adjustment_ratio_Upper__c,
                Adjustment_ratio_Lower__c = mcae.Adjustment_ratio_Lower__c,
                Adjustment_Upper_price__c = mcae.Adjustment_Upper_price__c,
                LastMContract_Price__c = mcae.LastMContract_Price__c,
                Adjustment_Lower_price__c = mcae.Adjustment_Lower_price__c,
                Asset_Consumption_rate__c = mcae.Asset_Consumption_rate__c
                                            // 追加限次信息
                , URF_Series__c = mcae.URF_Series__c,
                Series_RepairCount__c = mcae.Series_RepairCount__c,
                Series_MaxRepairCount__c = mcae.Series_MaxRepairCount__c,
                Asset_RepairCount__c = mcae.Asset_RepairCount__c,
                Asset_MaxRepairCount__c = mcae.Asset_MaxRepairCount__c
                // LJPH-C9GD34 gzw fix start
                ,Estimate_List_Price_Page__c = mcae.Estimate_List_Price_Page__c
                // LJPH-C9GD34 gzw fix end
                );
            this.isManual = true;
            this.rec_checkBox_c = false;
            this.orgPrice = mcae.Product_Manual__r.Maintenance_Price_Month__c;
            this.orgPrice12 = this.orgPrice * 12;
            this.proName = mcae.Product_Manual__r.Name;
            this.etGFlg = mcae.Product_Manual__r.EquipmentGuaranteeFlg__c;
            //this.uFRPrice = mcae.Product_Manual__r.ProductURF__r.UFR_Maintenance_Price_Month__c;
            this.uFRSerial = mcae.Product_Manual__r.ProductURF__r.URFLimitSerial__c;
            //this.uFRRepairCount = mcae.Product_Manual__r.ProductURF__r.UFR_MaxRepairCount__c;
            //URF限次合同2期 LY 20220811 start
            this.uFRRepairCount =0;
            this.uFRPrice = mcae.Product_Manual__r.ProductURF__r.UFR_Maintenance_Price_Month_3__c;
            //URF限次合同2期 LY 20220811 end
            //2021-11-30 fy add LJPH-C8W8FV 置顶 start
            this.ProductModelNoc = mcae.Product_Manual__r.Asset_Model_No__c;
            this.AssetModelNoc = mcae.Asset__r.OwnershipMachine_No__c;
            //2021-11-30 fy add LJPH-C8W8FV 置顶 end
            // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
            this.uFRMaxPrice = mcae.Product_Manual__r.ProductURF__r.Maintenance_Price_Year_URF_Max__c;
            this.uFRMinPrice = mcae.Product_Manual__r.ProductURF__r.Maintenance_Price_Year_URF__c;
            // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
            //URF限次合同2期 LY 20220811 start
            this.uFRMaxPrice3 = mcae.Product_Manual__r.ProductURF__r.Maintenance_Price_Year_URF_Max_3__c;
            this.uFRMinPrice3 = mcae.Product_Manual__r.ProductURF__r.Maintenance_Price_Year_URF_3__c;
            //URF限次合同2期 LY 20220811 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;
            this.orgPrice12 = this.orgPrice * 12;
            this.etGFlg = record.EquipmentGuaranteeFlg__c;
            this.proSerialName = record.Name;
            this.proSerialNumber = record.SerialNumber;
            //this.uFRPrice = record.Product2.ProductURF__r.UFR_Maintenance_Price_Month__c;
            this.uFRSerial = record.Product2.ProductURF__r.URFLimitSerial__c;
            //this.uFRRepairCount = record.Product2.ProductURF__r.UFR_MaxRepairCount__c;
            //URF限次合同2期 LY 20220811 start
            this.uFRRepairCount =0;
            this.uFRPrice = record.Product2.ProductURF__r.UFR_Maintenance_Price_Month_3__c;
            //URF限次合同2期 LY 20220811 start
            //XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 start
            this.uFRMaxPrice = record.Product2.ProductURF__r.Maintenance_Price_Year_URF_Max__c;
            this.uFRMinPrice = record.Product2.ProductURF__r.Maintenance_Price_Year_URF__c;
            // XLIU-CE7AVC【委托】URF限次修理合同的最高价格修改 thh 20220509 end
            //URF限次合同2期 LY 20220811 start
            this.uFRMaxPrice3 = record.Product2.ProductURF__r.Maintenance_Price_Year_URF_Max_3__c;
            this.uFRMinPrice3 = record.Product2.ProductURF__r.Maintenance_Price_Year_URF_3__c;
            //URF限次合同2期 LY 20220811 end
        }
    }
   
    // 续签合同信息 class
    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; }
        // 2021-09-10 tcm 排序逻辑调整 start
        public Boolean ayearcontract { get; set; }
        // 2021-09-10 tcm 排序逻辑调整 end
        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;
        
            // 2021-09-10 tcm 排序逻辑调整 start
            // 判断在数量
            if (count  > compareToesd.count) {
                returnValue = -1;
            } else if (count  < compareToesd.count) {
                returnValue = 1;
            } else {
                if (endDate  > compareToesd.endDate ) {
                    returnValue = 1;
                } else {
                    returnValue = -1;
                }
            }
            return returnValue;
            // 2021-09-10 tcm 排序逻辑调整 end
        }
    }
    // 初始化返回数据
    public class InitData {
        //init 数据处理
        @AuraEnabled
        public String targetHospitalId = null;                                    // 今後系列病院用
        @AuraEnabled
        public String targetMaintenanceContractId = null;
        @AuraEnabled
        public String typeresult {get; set;}
        @AuraEnabled
        public String targetEstimateId { get; private set; }
        @AuraEnabled
        public Boolean changedAfterPrint {get; set;}                               // true の場合、画面に confirm メッセージが表示します。quoIdを新しいinsert。判定はjsにて実施

        @AuraEnabled
        public String alertString {get; set;}
        @AuraEnabled
        public String alertString2 {get; set;}
        @AuraEnabled
        public String alertString3 {get; set;}
        @AuraEnabled
        public Boolean printAsset { get; private set; }
        @AuraEnabled
        public Boolean printContract { get; private set; }
        @AuraEnabled
        public Boolean printTripartite { get; private set; }
        @AuraEnabled
        public Boolean printAgent { get; private set; }
        @AuraEnabled
        public boolean inDicideFlag {get; set;}                         //作为补充，对应报价决定之后，却未能讲合同起止日期传递给合同的问题
        @AuraEnabled
        public String isPaymentSet {get; set;}
//     // 引数のサービス契約の情報を格納する。
        @AuraEnabled 
        public Maintenance_Contract__c contract { get; private set; }
        @AuraEnabled 
        public Maintenance_Contract_Estimate__c estimate { get; set; }
    //     // 2021、8、26 合同报价页面的优化，无保有设备点检对象选择框变黑 fxk star
    //     public static Asset ass { get; set; }
    //     // 2021、8、26 合同报价页面的优化，无保有设备点检对象选择框变黑 fxk end
    //     // 病院配下の納入機器の情報を格納する。
        @AuraEnabled 
        public Transient List<Asset> assetRecords;
        @AuraEnabled // TODO 系列病院の場合、この配列は固定できないです。
        public List<AssetInfo> checkedAssets { get; set; }
        @AuraEnabled
        public List<AssetInfo> unCheckedAssets = new List<AssetInfo>();
    
        @AuraEnabled 
        public List<List<AssetInfo> > unCheckedAssetsView { get; set; }
        
        // 分页用
        @AuraEnabled 
        public Integer currPage { get; set; }                         // 当前页
        @AuraEnabled 
        public Integer ProductCountAll { get; set; }  
        @AuraEnabled 
        public Integer VMProductCountAll { get; set; } 
        @AuraEnabled 
        public Integer totalPage { get; set; }                         // 总页数
        @AuraEnabled 
        public Integer selctRecordNum { get { return Integer.valueOf(selRecordOption); } }                       // 选择的每页记录数
        
        @AuraEnabled 
        public Integer totalRecords { get; set; }                          // 总记录数
        @AuraEnabled 
        public String selRecordOption { get; set; }
    
//     //HWAG-B399Q8 2018/08/20  检验是否显示'请提交待审批' start
        @AuraEnabled 
        public Boolean IS_Clone_After_Decide { get; set; }
//     //HWAG-B399Q8 2018/08/20  检验是否显示'请提交待审批' end
//     //2021-11-30 fy add LJPH-C8W8FV 置顶 start
        @AuraEnabled 
        public List<String> TopProductModel = new List<String>();
       
//     //2021-11-30 fy add LJPH-C8W8FV 置顶 end

       @AuraEnabled 
       public List<String> checkIdList = new List<String> ();                         // 合同对象设备的设备ID
    
//     //-------HWAG-B4R3SS----------------update----------------------------
       @AuraEnabled 
       public Boolean activeOn { get; set; }
       @AuraEnabled 
       public String sortKey { get; set; }
       @AuraEnabled 
        public Boolean sortOrderAsc { get; private set; }
       @AuraEnabled 
        public 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'};
       @AuraEnabled 
       public Boolean isSoft;
//     // 显示数据条数限制
       @AuraEnabled 
        public Integer SELECT_LIMIT = 200;
       @AuraEnabled 
        public List<AssetInfo> unCheckedInfoList { get; set; }
       @AuraEnabled 
        public String text1ForSort = null;
       @AuraEnabled 
        public String cond1ForSort = null;
       @AuraEnabled 
        public String val1ForSort = null;
//     /*****************select option******************/
       @AuraEnabled 
        public Decimal countorder { get; set; }
       @AuraEnabled 
        public List<String> assetSerialNumberList = new List<String>();
//     // 新规 或者 copy
       @AuraEnabled 
       public Boolean newIns = false;
    //     //add   wangweipeng     2021/12/06     start
        @AuraEnabled 
        public String checkDealerId{get;set;}
        @AuraEnabled
        public String text1 { get; set; }                         // 对象
        @AuraEnabled
        public String cond1 { get; set; }                         // 条件
        @AuraEnabled 
        public String val1 { get; set; }                    // 值
    //     //LJPH-BSS6E2  ---20200911 ---add by rentongxiao start
        @AuraEnabled 
        public  String contr {get; set; }                         //判断是否init
    //     //LJPH-BSS6E2  ---20200911 ---add by rentongxiao end
        
        //2022 故障品加费 是否是FSE操作 提价减价申请按钮是否可见
        @AuraEnabled 
        public  Boolean isFSE { get; set; }
        @AuraEnabled 
        public Boolean sendEmailSuccess { get; set; }
        @AuraEnabled 
        public Boolean hasSendEmail { get; set; }

       // 2021、8、26 合同报价页面的优化，无保有设备点检对象选择框变黑 fxk end
        @AuraEnabled 
        public Integer productCount {
            get {
                return checkedAssets == null ? 0 : checkedAssets.size();
            }
        }
        @AuraEnabled 
        public Integer productCount2 {
            get {
                return unCheckedAssets == null ? 0 : unCheckedAssets.size();
            }
        }
        @AuraEnabled 
        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;
            }
        }

        @AuraEnabled 
        public Decimal isNewPriceAdj { get { return 1; } }

        
        
        @AuraEnabled 
        public Integer isNewAddMonth { get { return Integer.valueOf(System.Label.MC_New_AddMonth); }         
    //     public static Integer keepPriceMonth { get { return Integer.valueOf(System.Label.MC_KeepPrice_Month); } }
        }
        
        @AuraEnabled 
        public Boolean isPageAction = false;
        
        @AuraEnabled 
        public Boolean changedSubmitPrice {get; set;}
        
        
        @AuraEnabled 
        public Boolean isSaveOrApproval {get; set;}
        
        @AuraEnabled 
        public String OldContractStartDate {get; set;}
        
        @AuraEnabled 
        public String OldMaintenancePrice { get; set; }
        @AuraEnabled 
        public Boolean isAgreeRenewTen { get; set; }
        // 上限合同 hql 20230216 start
        @AuraEnabled 
        public Boolean isLimitPrice { get; set; }
        // 上限合同 hql 20230216 end
        // 报价规则改善 20230309 start 
        @AuraEnabled 
        public Boolean refreshDisabled {get; set;}
        @AuraEnabled 
        public Boolean Is_Blank_period {get; set;}
        @AuraEnabled 
        public String Cost_rate_ForecastF{get;set;}
        @AuraEnabled 
        public String Past_Contract_end_day{get;set;}
        @AuraEnabled 
        public String PastContractendday{get;set;}
        @AuraEnabled 
        public Decimal OldLimitPrice { get; set; }
        // 报价合并 20230602 start
        @AuraEnabled 
        public String MaintanceContractPackId { get; set; }
        // 报价合并 20230602 end
        // 报价规则改善 20230309 end 
        // 报价规则改善 20230331 start
        //后台未使用，将该变量直接设在前端
        @AuraEnabled 
        public String startdateaddsix4 { get; set; }
        @AuraEnabled  
        public String startdateaddsix1 { get; set; }
        @AuraEnabled  
        public String startdateaddsix2 { get; set; }
        @AuraEnabled  
        public String startdateaddsix3 { get; set; }
        @AuraEnabled  
        public String GuidePriceUp2 { get; set; }
        @AuraEnabled  
        public String GuidePriceDown2 { get; set; } 
        @AuraEnabled 
        public String GuidePriceUp3 { get; set; }
        @AuraEnabled  
        public String GuidePriceDown3 { get; set; }
        @AuraEnabled  
        public String GuidePriceUp4 { get; set; } 
        @AuraEnabled 
        public String GuidePriceDown4 { get; set; } 
        @AuraEnabled 
        public String GuidePriceUp5 { get; set; } 
        @AuraEnabled 
        public String GuidePriceDown5 { get; set; } 
       // 报价规则改善 20230331 start
        //lwc js label 引用
        @AuraEnabled 
        public String TradeComplianceStatusFlagFW { get{ return Label.TradeComplianceStatusFlagFW; } } 
        @AuraEnabled 
        public String IFTradeComplianceAlert { get{ return Label.IFTradeComplianceAlert; } } 
        public InitData() {
        }
    }

}