global class  SelectAssetEstimateController {
    //test
    private String targetHospitalId = null;            // 今後系列病院用
    private String targetMaintenanceContractId = null;

    public String targetEstimateId { get; private set; }
    public Boolean changedAfterPrint {get; set;}       // true の場合、画面に confirm メッセージが表示します。quoIdを新しいinsert。判定はjsにて実施
    public Decimal lastFriYearsPriceSum {get; set;}
    public Decimal lastSecYearsPriceSum {get; set;}
    Public String  alertString {get; set;}
    Public String  alertString2 {get; set;}
    Public String  alertString3 {get; set;}
    public Boolean printAsset { get; private set; }
    public Boolean printContract { get; private set; }
    public Boolean printTripartite { get; private set; }
    public Boolean printAgent { get; private set; }
    public boolean inDicideFlag {get; set;} //作为补充，对应报价决定之后，却未能讲合同起止日期传递给合同的问题
    public String isPaymentSet {get; set;}
    //public String PaymentSet {get;set;}
    // 引数のサービス契約の情報を格納する。
    public Maintenance_Contract__c contract { get; private set; }
    public Maintenance_Contract_Estimate__c estimate { get; set; }
    // 2021、8、26 合同报价页面的优化，无保有设备点检对象选择框变黑 fxk star
    public Asset ass { get; set; }
    // 2021、8、26 合同报价页面的优化，无保有设备点检对象选择框变黑 fxk end
    // 病院配下の納入機器の情報を格納する。
    private List<Asset> assetRecords;                       // TODO 系列病院の場合、この配列は固定できないです。
    public List<AssetInfo> checkedAssets { get; set; }
    private List<AssetInfo> unCheckedAssets = new List<AssetInfo>();

    //public List<List<AssetInfo>> checkedAssetsView { get; set; }
    public List<List<AssetInfo>> unCheckedAssetsView { get; set; }

    // 分页用
    public Integer currPage { get; set; } // 当前页
    public Integer totalPage { get; set; } // 总页数
    public Integer selctRecordNum { get { return Integer.valueOf(selRecordOption); } } // 选择的每页记录数
    public Integer totalRecords { get; set; }  // 总记录数
    public String selRecordOption { get; set; }
    public static List<SelectOption> recordNum { get; private set; } // 选择每页记录数List

    //HWAG-B399Q8 2018/08/20  检验是否显示'请提交待审批' start
    public Boolean IS_Clone_After_Decide { get; set; }
    //HWAG-B399Q8 2018/08/20  检验是否显示'请提交待审批' end
    static {
        recordNum = new List<SelectOption>();
        recordNum.add(new SelectOption('10', '10'));
        recordNum.add(new SelectOption('20', '20'));
        recordNum.add(new SelectOption('50', '50'));
        recordNum.add(new SelectOption('100', '100'));
        recordNum.add(new SelectOption('200', '200'));
    }
    private List<String> checkIdList = new List<String> (); // 合同对象设备的设备ID

    //-------HWAG-B4R3SS----------------update----------------------------
    public Boolean activeOn { get; set; }
    public String sortKey { get; set; }
    public Boolean sortOrderAsc { get; private set; }
    private String[] columus = new String[] {'Asset_situation__c', 'Name', 'SerialNumber', 'CurrentContract__r.Management_Code__c', 'Department_Name__c', 'Status', 'Installation_Site__c', 'Room_Number__c', 'InstallDate', 'Asset_Owner__c', 'Accumulation_Repair_Amount__c', 'AssetMark__c'};
    private Boolean isSoft;
    // 显示数据条数限制
    private static Integer SELECT_LIMIT = 200;
    public List<AssetInfo> unCheckedInfoList { get; set; }
    private String text1ForSort = null;
    private String cond1ForSort = null;
    private String val1ForSort = null;
    /*****************select option******************/
    public static List<SelectOption> textOpts { get; private set; }
    public Decimal countorder { get; set; }
    public List<String> assetSerialNumberList = new List<String>();


    static {
        textOpts = new List<SelectOption>();
        //LJPH-BSS6E2  ---20200911 ---update by rentongxiao start
        // textOpts.add(new SelectOption('','-无-'));
        //LJPH-BSS6E2  ---20200911 ---update by rentongxiao end
        //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start
        /* 在查询语句中 新增了 AssetMark__c 的字段 */
        // textOpts.add(new SelectOption('S:Asset_situation__c'  , Schema.SObjectType.Asset.fields.Asset_situation__c.label));
        // 添加新条件 -- 耗材/主机
        textOpts.add(new SelectOption('S:AssetMark__c', '主机/耗材'));
        //JZHG-BSDUT4 ---20200825---update By rentongxiao---End
        textOpts.add(new SelectOption('S:Name'                , Schema.SObjectType.Asset.fields.Name.label));
        textOpts.add(new SelectOption('S:SerialNumber'        , Schema.SObjectType.Asset.fields.SerialNumber.label));
        textOpts.add(new SelectOption('S:CurrentContract__r.Management_Code__c'  , Schema.SObjectType.Asset.fields.CurrentContract__c.label));
        //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start
        // textOpts.add(new SelectOption('S:Status'              , Schema.SObjectType.Asset.fields.Status.label));
        //JZHG-BSDUT4 ---20200825---update By rentongxiao---End
        textOpts.add(new SelectOption('S:Installation_Site__c', Schema.SObjectType.Asset.fields.Installation_Site__c.label));
        textOpts.add(new SelectOption('S:Department_Name__c'  , Schema.SObjectType.Asset.fields.Department_Name__c.label));

    }
    public static List<SelectOption> equalOpts { get; private set; }
    static {
        equalOpts = new List<SelectOption>();
        equalOpts.add(new SelectOption('equals', '等于'));
        equalOpts.add(new SelectOption('contains', '包含'));
        //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start
        //新加匹配符 不等于
        equalOpts.add(new SelectOption('notequals', '不等于'));
        //JZHG-BSDUT4 ---20200825---update By rentongxiao---End
    }
    public String text1 { get; set; } // 对象
    public String cond1 { get; set; } // 条件
    public String val1 { get; set; }  // 值

    //LJPH-BSS6E2  ---20200911 ---add by rentongxiao start
    public String contr {get; set; } //判断是否init
    //LJPH-BSS6E2  ---20200911 ---add by rentongxiao end

    // 检索按钮
    public PageReference searchBtn() {
        countorder = 1;
        //验证
        assetSerialNumberList.clear();
        getAssetSerialNumber();
        totalRecords = 0;
        List<Asset> assetconfimList = getAssetconfim(text1, cond1, val1);
        for (Asset ast : assetconfimList) {
            totalRecords ++;
        }


        // 获取assets
        List<Asset> assetList = getAsset(text1, cond1, val1);

        // 作成明细行
        getSortedUnCheckedInfoList(assetList);
        // 排序用检索条件退避
        text1ForSort = text1;
        cond1ForSort = cond1;
        val1ForSort = val1;
        currPage = 1;


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

    // 取已选择资产的机身编码
    public void getAssetSerialNumber() {

        //LJPH-BSS6E2  ---20200911 ---add by rentongxiao start
        contr = '2';
        //LJPH-BSS6E2  ---20200911 ---add by rentongxiao end
        assetSerialNumberList = new List<String>();
        assetSerialNumberList.clear();
        for (AssetInfo ai : this.checkedAssets) {
            system.debug('checkedAssets1111111' + this.checkedAssets);
            //system.debug('ai.ah.SerialNumber__c' + ai.ah.SerialNumber__c);
            if (String.isNotEmpty(ai.rec.SerialNumber)) {
                assetSerialNumberList.add(ai.rec.SerialNumber);
            }
        }
    }

    //
    private void getSortedUnCheckedInfoList(List<Asset> assetList) {
        Boolean overLimit = false;
        Map<Id, AssetInfo> markUpUnCheckMap = new Map<Id, AssetInfo>();
        for (AssetInfo unCheckinfo : unCheckedAssets) {

            // 打勾，视为优先显示明细
            if (unCheckinfo.rec_checkBox_c == true) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO , 'unCheckinfo.rec_checkBox_c' + unCheckinfo.rec_checkBox_c));
                markUpUnCheckMap.put(unCheckinfo.rec.Id, unCheckinfo);
            }
        }
        unCheckedAssets.clear();
        // 优先显示明细放在最前面
        unCheckedInfoList = new List<AssetInfo>();
        for (AssetInfo asInfo : markUpUnCheckMap.values()) {
            unCheckedAssets.add(asInfo);
        }
        SELECT_LIMIT = selctRecordNum;
        Integer selectCnt = unCheckedAssets.size();
        for (Asset asset : assetList) {
            // 201を超えた場合前200のみを出す
            if (unCheckedAssets.size() >= SELECT_LIMIT) { overLimit = true; break; }
            if (markUpUnCheckMap.containsKey(asset.Id) == false) {
                //unCheckedInfoList.add(unCheckMap.get(asset.Id));
                unCheckedAssets.add(new AssetInfo(unCheckedAssets.size(), asset));
            }
        }
    }

    //检索验证
    private List<Asset> getAssetconfim(String txt, String con, String val) {
        String soql = this.makeSoqlconfim();
        soql += makeTextSql(txt, con, val);
        system.debug('makeTextSql_soql' + soql);
        if (isSoft) {
            soql += ' order by ' + this.columus[Integer.valueOf(this.sortKey)] + ' ' + (this.sortOrderAsc == true ? 'asc nulls first' : 'desc nulls last ');
        } else {
            soql += ' order by SerialNumber, Name, Department_Name__c, InstallDate';
        }
        system.debug('====getAssetconfim:' + soql);
        return Database.query(soql);
    }

    private List<Asset> getAsset(String txt, String con, String val) {
        String soql = this.makeSoqlconfim();
        soql += makeTextSql(txt, con, val);

        if (isSoft) {
            soql += ' order by ' + this.columus[Integer.valueOf(this.sortKey)] + ' ' + (this.sortOrderAsc == true ? 'asc nulls first' : 'desc nulls last ');
        } else {
            soql += ' order by SerialNumber, Name, Department_Name__c, InstallDate';
        }
        soql += ' limit ' + System.Label.Asset_Maxcount;
        soql += ' OFFSET ' + (countorder - 1) * Integer.valueOf(System.Label.Asset_Maxcount);
        return Database.query(soql);
    }

    public Integer soqlNos() {
        List<Asset> assetconfimList = getAssetconfim(text1, cond1, val1);
        totalRecords = assetconfimList.size() ;
        //totalPage = (totalRecords/selctRecordNum) + (Math.mod(totalRecords, selctRecordNum) > 0 ? 1 : 0);
        return totalRecords;
    }

    private String makeSoqlconfim() {
        String sqlTail = '(\'';
        system.debug('assetSerialNumberList.size()' + assetSerialNumberList.size());
        for (Integer i = 0 ; i < assetSerialNumberList.size(); i++) {
            if (i < assetSerialNumberList.size() - 1) {
                sqlTail += assetSerialNumberList[i] + '\',\'';
            } else {
                sqlTail += assetSerialNumberList[i] + '\')';
            }
        }
        String soql = 'SELECT Id, Name, Asset_situation__c, SerialNumber, Department_Name__c, Installation_Site__c, '
                      + 'Posting_Date__c,Management_Code__c,IF_Warranty__c,Reson_Can_not_Warranty__c, InstallDate, '
                      + 'Asset_Owner__c, Accumulation_Repair_Amount__c, Maintenance_Price_Month__c, Final_Examination_Date__c, '
                      + 'CurrentContract_F__c,CurrentContract_F__r.Maintenance_Contract_No_F__c,CurrentContract_F__r.Contract_End_Date__c,CurrentContract_F__r.Estimate_Contract_endDate__c,'
                      + 'CurrentContract_End_Date__c, Extend_Gurantee_DateTo__c,AssetMark__c,NoPartRiskDate_F__c,NoPartRiskDate__c,SignableFlag__c FROM Asset WHERE Hospital__c = \'' + this.targetHospitalId + '\' ';
        //HWAG-BDJ43R ---XHL---20190729---
        //soql +=  ' AND AssetMark__c != \'耗材\' AND Product2.Family != \'ET\' ';
        soql +=  ' AND ( AssetMark__c != \'耗材\' OR Product2.Family != \'ET\' ) ';
        //HWAG-BDJ43R ---XHL---20190729---
        if (assetSerialNumberList.size() > 0) {
            soql += ' AND SerialNumber not in ' + sqlTail ;
        }
        return soql;
    }

    // 拼接检索条件sql文
    private String makeTextSql(String txt1, String con, String val) {
        String soql = '';
        if (String.isBlank(con)) {
            con = 'equals';
        }
        // containsの場合、日報画面の病院検索を真似し、spaceで分けて、and検索
        // equalsの場合、SF標準の検索を真似し、「,」で分けて、or検索
        if (!String.isBlank(txt1)) {
            if ((con == 'contains' || con == 'notcontains') && val.contains(' ')) {
                String[] vals = val.split(' ');

                String cSql = '';
                if (vals.size() > 0) {
                    String txt = txt1.substring(2);
                    soql += ' and ( ';
                    for (String v : vals) {
                        if (String.isNotBlank(v)) {
                            if (con == 'contains') {
                                soql += txt + ' like \'%' + v + '%\' or ';
                            } else {
                                soql += txt + ' not like \'%' + v + '%\' and ';
                            }
                        }


                    }
                    soql = soql.substring(0, soql.length() - 4);
                    soql += ')';
                }
                system.debug('containssoql:     ' + soql);
            } else if ((con == 'equals' || con == 'notequals') && val.contains(',')) {
                String[] vals = val.split(',');
                if (vals.size() > 0) {
                    String txt = txt1.substring(2);     // S:Name 、最初の２文字がタイプです
                    soql += ' and ( ';
                    for (String v : vals) {
                        if (con == 'equals') {
                            soql += txt + ' = \'' + v + '\' or ';
                        } else {
                            // notequals
                            soql += txt + ' <> \'' + v + '\' and ';
                        }
                    }
                    soql = soql.substring(0, soql.length() - 4);
                    soql += ')';
                }
            } else {
                String cSql = this.makeTextSqlStr(txt1, con, val);
                if (con != 'notcontains') {
                    soql += this.makeTextSqlStr(txt1, con, val);
                } else {
                    // notcontains
                    if (!String.isBlank(cSql)) {
                        cSql = cSql.substring(5);       // ' and ' の5文字を外す
                        soql += ' and (NOT ' + cSql + ') ';
                    }
                }
            }
        }
        // //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start
        // else {
        //     soql += 'AND AssetMark__c = \'主机\'';
        // }
        // //JZHG-BSDUT4 ---20200825---update By rentongxiao---End

        return soql;
    }

    private String makeTextSqlStr(String txt1, String con, String val) {
        String soql = '';
        if (!String.isBlank(txt1)) {
            String txt = txt1.substring(2);
            String colType = txt1.substring(0, 2);
            String tmpVal = val.trim();
            // 空白の場合''にする
            if (String.isBlank(tmpVal)) {
                if (con == 'equals') {
                    //soql += ' and ' + txt + ' = ' + tmpVal;
                    soql += ' and ' + txt + ' = null';
                } else if (con == 'notequals') {
                    soql += ' and ' + txt + ' <> null';
                } else {
                    // 空白の場合、contains, notcontains と starts withは無視
                }
            } else {
                soql += ' and ' + txt;
                if (con == 'equals') {
                    if (colType == 'S:') {
                        soql += ' = \'' + tmpVal + '\'';
                    } else {
                        soql += ' = ' + tmpVal + ' ';
                    }
                } else if (con == 'notequals') {
                    if (colType == 'S:') {
                        soql += ' <> \'' + tmpVal + '\'';
                    } else {
                        soql += ' <> ' + tmpVal + ' ';
                    }
                } else if (con == 'contains' || con == 'notcontains') {
                    soql += ' like \'%' + String.escapeSingleQuotes(tmpVal.replaceAll('%', '\\%')) + '%\'';
                } else if (con == 'starts with') {
                    soql += ' like \'' + String.escapeSingleQuotes(tmpVal.replaceAll('%', '\\%')) + '%\'';
                } else {
                    if (colType == 'S:') {
                        soql += ' ' + con + '\'' + tmpVal + '\'';
                    } else {
                        soql += ' ' + con + ' ' + tmpVal + ' ';
                    }
                }
            }
        }
        return soql;
    }

    //----------HWAG-B4R3SS------------------------------------------------------------






    public Boolean getEnablePrintContract() {
        if (String.isBlank(this.contract.Decided_Estimation__c) == false) {
            return this.estimate.Estimation_Decision__c;
        } else {
            return false;
        }
    }

    public Boolean getUnDecideBtnDisabled() {
        // 見積もりdecide取消しできない条件の判断
        if (String.isBlank(this.contract.Decided_Estimation__c) == false) {
            if (this.estimate.Estimation_Decision__c) {
                return false;
            }
        }
        // TODO 本当は特別資格があれば 決定可能にする
        return true;
    }
    public Boolean getDecideBtnDisabled() {
        // 見積もりdecideできない条件の判断
        if (String.isBlank(this.contract.Decided_Estimation__c) == false) {
            if (this.estimate.Estimation_Decision__c) {
                return true;
            }
            // TODO 特別資格があれば 決定可能にする
            return true;
        }
        if (this.estimate.Process_Status__c != '批准') {
            return true;
        } else {
            if (String.isBlank(this.estimate.Change_Dealer_Approval__c) == false
                    && this.estimate.Change_Dealer_Approval__c != '批准'
                    && this.estimate.Change_Dealer_Approval__c != '未批准') {
                return true;
            }
        }
        return false;
    }
    public Boolean getApprovalBtnDisabled() {
        // 見積もり申請できない条件の判断
        if (String.isBlank(this.contract.Decided_Estimation__c) == false) {
            // TODO 特別資格があれば 申請可能にする
            return true;
        }
        if (String.isBlank(this.estimate.Process_Status__c) == false
                && this.estimate.Process_Status__c != '草案中'
                //&& this.estimate.Process_Status__c != '不批准'
           ) {
            return true;
        }
        return false;
    }
    public Boolean getSaveBtnDisabled() {
        // 見積もりsaveできない条件の判断
        if (String.isBlank(this.contract.Decided_Estimation__c) == false) {
            return true;
        }
        if (String.isBlank(this.estimate.Process_Status__c) == false
                && this.estimate.Process_Status__c != '草案中'
                //&& this.estimate.Process_Status__c != '不批准'
           ) {
            return true;
        }
        return false;
    }
    public Boolean getPrintBtnDisabled() {
        // 印刷できない条件の判断
        if (this.estimate.Process_Status__c != '批准' || !this.contract.Status__c.equals('引合中') ) {
            return true;
        } else {
            if (String.isBlank(this.estimate.Change_Dealer_Approval__c) == false
                    && this.estimate.Change_Dealer_Approval__c != '批准'
                    && this.estimate.Change_Dealer_Approval__c != '未批准') {
                return true;
            }
        }
        return false;
    }
    // 页面项目非活性设定
    public Boolean getPageDisabled() {
        if (String.isBlank(this.contract.Decided_Estimation__c) == false) {
            return true;
        }
        if (String.isBlank(this.estimate.Process_Status__c) == false
                && this.estimate.Process_Status__c != '草案中'
           ) {
            return true;
        }
        return false;
    }
    // 2021、8、26 合同报价页面的优化，无保有设备点检对象选择框变黑 fxk star
    // public Boolean getPageDisabled1() {

    //     if (
    //         String.isBlank(this.ass.Name)
    //     ) {
    //         return true;
    //     }
    //     return false;
    // }
    // 2021、8、26 合同报价页面的优化，无保有设备点检对象选择框变黑 fxk end 
    public Integer productCount {
        get {
            return checkedAssets == null ? 0 : checkedAssets.size();
        }
    }
    public Integer productCount2 {
        get {
            return unCheckedAssets == null ? 0 : unCheckedAssets.size();
        }
    }
    public Integer productCount3 {
        get {
            Integer cnt = 0;
            for (AssetInfo input : this.checkedAssets) {
                if (!input.isManual || input.isManual && !String.isBlank(input.mcae.Product_Manual__c)) {
                    cnt += 1;
                }
            }
            return cnt;
        }
    }
    // TODO カスタムラベルから取得
    public static Decimal oxygenPriceAdj { get { return 0.1; } }          // TODO katsu 酸化水を使用しないように変更
    public Decimal isNewPriceAdj {
        // HWAG-BGT66T 2019-10-01 后不打折
        get{
            Decimal count = 0;
            if (estimate.CreatedDate == null || estimate.CreatedDate.date() >= Date.valueOf('2019-10-08')) {
                count = 1.0;
            } else{
                count = 0.7;
            }
            return count;
        }
    }

    //public String productName { get; set; }
    public Integer productIdx { get; set; }

    public Integer isNewAddMonth { get { return Integer.valueOf(System.Label.MC_New_AddMonth); } }

    public Integer keepPriceMonth { get { return Integer.valueOf(System.Label.MC_KeepPrice_Month); } }

    public Boolean isPageAction = false;

    private Integer PosttoInstall { get { return Integer.valueOf(System.Label.Post_to_Install); }}

    public Boolean changedSubmitPrice {get; set;}

    public Boolean isSaveOrApproval {get; set;}
    public String OldContractStartDate {get; set;}
    public String OldMaintenancePrice { get; set; }

    /**
     * コンストラクタ
     */
    public SelectAssetEstimateController() {
        currPage = 1;
        selRecordOption = '20';
        totalRecords = 0;
    }
    /**
     * Visaulforceから呼ばれるコンストラクタ
     */
    public SelectAssetEstimateController(ApexPages.StandardController controller) {
        //HWAG-B4R3SS  START 20181026
        currPage = 1;
        selRecordOption = '20';
        //this.targetEstimateId = (String)(ApexPages.currentPage().getParameters().get('id'));
        totalRecords = 0;
        //HWAG-B4R3SS  END 20181026
    }

    private void setThisEstimate() {
        //HWAG-B399Q8 2018/08/20  添加一额外字段 IS_Clone_After_Decide__c start
        this.estimate = [SELECT Id, Name, Maintenance_Contract__c, Estimation_Decision__c, CreatedDate, Service_Contract_Staff__c,
                         JingliApprovalManager__c, BuchangApprovalManager__c, ZongjianApprovalManager__c, Finally_Approved_Staff__c,
                         Contract_Esti_Start_Date__c, Contract_Esti_End_Date__c, Contract_Range__c, Contract_Start_Date__c, Contract_End_Date__c,
                         Maintenance_Contract_Status__c, Discount_reason__c, Improve_ConsumptionRate_Idea__c, Process_Status__c,
                         Estimate_Trial_Money__c, Maintenance_Price__c, Department__c, PrintDate__c, Quote_Date__c, Submit_quotation_day__c,
                         Examination_Price__c, Service_contract_target_number__c,
                         Maintenance_Contract__r.Payment_Plan_Sum_First__c, Maintenance_Contract__r.Payment_Plan_Date_First__c,
                         Maintenance_Contract__r.Payment_Plan_Sum_Second__c,
                         Maintenance_Contract__r.Payment_Plan_Sum_Third__c,
                         Maintenance_Contract__r.Payment_Plan_Sum_Forth__c,
                         Maintenance_Contract__r.Payment_Plan_Sum_Fifth__c,
                         Maintenance_Contract__r.Payment_Plan_Sum_Sixth__c,
                         Discount_Price__c, Discount_Percentage__c, IsSyncing__c,
                         NotUse_Oxygenated_Water__c, Estimate_Target__c, Dealer__c,
                         Append_Condition_Price__c, Asset_Sum_Price__c, Asset_Repair_Sum_Price__c,
                         Print_Contract__c, Print_RepairPrice__c, Print_DiscountPercentage__c, Print_Agent__c, Change_Dealer_Approval__c,
                         Print_DiscountPrice__c, Print_ListPrice__c, Print_MaintePrice__c, Print_SumPrice__c, Print_Tripartite__c, TKZongjianApprovalManager__c
                         , IS_Clone_After_Decide__c
                         // 上期五个合同信息 Gzw 20200810
                         , LastMContract1__c, LastMContract2__c, LastMContract3__c, LastMContract4__c, LastMContract5__c
                         , LastMContract1_ConCount__c, LastMContract2_ConCount__c, LastMContract3_ConCount__c, LastMContract4_ConCount__c, LastMContract5_ConCount__c,
                         LastMContract1_NO__c, LastMContract2_NO__c, LastMContract3_NO__c, LastMContract4_NO__c, LastMContract5_NO__c
                         FROM Maintenance_Contract_Estimate__c WHERE Id = :this.targetEstimateId];
        //HWAG-B399Q8 2018/08/20  添加一额外字段 IS_Clone_After_Decide__c end
        decimal PriceSum =  (this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_First__c == null ? 0 : this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_First__c) +
                            (this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_Second__c == null ? 0 : this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_Second__c) +
                            (this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_Third__c == null ? 0 : this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_Third__c) +
                            (this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_Forth__c == null ? 0 : this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_Forth__c) +
                            (this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_Fifth__c == null ? 0 : this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_Fifth__c) +
                            (this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_Sixth__c == null ? 0 : this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_Sixth__c);
        if ( this.estimate.Maintenance_Contract__r.Payment_Plan_Sum_First__c == null
                //102018/10/26 HWAG-B5C88S 不再根据是否填写第一次付款日期判断
           ) {
            isPaymentSet = 'false';
        } else if (this.estimate.Maintenance_Price__c != PriceSum) {
            isPaymentSet = 'Denied';
        } else {
            isPaymentSet = 'true';
        }
    }

    public void init() {
        changedAfterPrint = false;
        changedSubmitPrice = false;
        isSaveOrApproval = false;
        OldContractStartDate = null;
        OldMaintenancePrice = null;

        isSoft = false;
        activeOn = true;

        //LJPH-BSS6E2  ---20200911 ---update by rentongxiao start
        contr = '1';
        val1 = '主机';
        //LJPH-BSS6E2  ---20200911 ---update by rentongxiao end

        Date systemToday = System.today();
        if (isPageAction == false) {
            //HWAG-B399Q8 2018/08/20  添加状态5，为按save 按键后状态 start
            if (String.isBlank(ApexPages.currentPage().getParameters().get('completion')) == false) {
                if (ApexPages.currentPage().getParameters().get('completion') == '1') {
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, System.Label.Message_002));
                } else if (ApexPages.currentPage().getParameters().get('completion') == '2') {
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, '审批提交成功。'));
                } else if (ApexPages.currentPage().getParameters().get('completion') == '3') {
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, 'Decided。'));
                } else if (ApexPages.currentPage().getParameters().get('completion') == '4') {

                } else if (ApexPages.currentPage().getParameters().get('completion') == '5') {
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, System.Label.Message_002));
                }
            }
            //HWAG-B399Q8 2018/08/20  添加状态5，为按save 按键后状态 end
        }
        this.printAsset = false;
        this.printContract = false;
        this.printTripartite = false;
        this.printAgent = false;
        String copyid = '';
        Boolean ret = false;
        if (isPageAction == false) {
            this.targetEstimateId = ApexPages.currentPage().getParameters().get('copyid');
            copyid = ApexPages.currentPage().getParameters().get('copyid');
            if (this.targetEstimateId == null) {
                String paramId = ApexPages.currentPage().getParameters().get('id');
                if (String.isBlank(paramId) == false && paramId.startsWith('a0z')) {
                    Maintenance_Contract_Asset_Estimate__c mcaeParam = [Select Maintenance_Contract_Estimate__c from Maintenance_Contract_Asset_Estimate__c where Id = :paramId];
                    this.targetEstimateId = mcaeParam.Maintenance_Contract_Estimate__c;
                } else {
                    this.targetEstimateId = paramId;
                }
            }
            this.targetMaintenanceContractId = ApexPages.currentPage().getParameters().get('mcid');
        }
        // 編集から
        if (String.isBlank(this.targetEstimateId) == false) {
            setThisEstimate();
            this.targetMaintenanceContractId = this.estimate.Maintenance_Contract__c;
            this.setContractInfo(this.targetMaintenanceContractId);
        }
        // 新規から
        else if (!String.isBlank(this.targetMaintenanceContractId)) {
            this.estimate = new Maintenance_Contract_Estimate__c();
            this.estimate.Maintenance_Contract__c = this.targetMaintenanceContractId;
            this.estimate.Contract_Esti_Start_Date__c = systemToday;
            this.estimate.Contract_Start_Date__c = systemToday;
            this.setContractInfo(this.targetMaintenanceContractId);
        }
        // 何もなければ、念のため
        // update 维修合同报价，保存时，把记录类型赋值一下(由于报错) 2021.6.8 fxk start
        else {
            ret = true;
            throw new ControllerUtil.myException('无法显示维修合同报价');
        }
        if (ret) {
            return;
        }
        // update 维修合同报价，保存时，把记录类型赋值一下(由于报错) 2021.6.8 fxk end
        //HWAG-B399Q8 2018/08/20  检验是否显示'请提交待审批' start
        IS_Clone_After_Decide = false;
        if (String.isBlank(ApexPages.currentPage().getParameters().get('completion')) == false &&
                ApexPages.currentPage().getParameters().get('completion') == '5' &&
                this.estimate != null && this.estimate.IS_Clone_After_Decide__c) {
            IS_Clone_After_Decide = true;

        }
        //HWAG-B399Q8 2018/08/20  检验是否显示'请提交待审批' end
        // 納入機器の情報を取得
        if (!String.isBlank(this.targetHospitalId) && (this.targetHospitalId.length() == 15 || this.targetHospitalId.length() == 18)) {
            assetRecords = [SELECT Id, Name, Asset_situation__c, SerialNumber, Department_Name__c, Installation_Site__c, Posting_Date__c, Management_Code__c, IF_Warranty__c, Reson_Can_not_Warranty__c,
                            InstallDate, Asset_Owner__c, Accumulation_Repair_Amount__c, Maintenance_Price_Month__c, Final_Examination_Date__c, CurrentContract_End_Date__c,
                            CurrentContract_F__c, CurrentContract_F__r.Maintenance_Contract_No_F__c, CurrentContract_F__r.Contract_End_Date__c, CurrentContract_F__r.Estimate_Contract_endDate__c, AssetMark__c,
                            // 2021-01-29 LJPH-BX9CVX mzy   add  合同报价时判断零件风险
                            NoPartRiskDate_F__c, NoPartRiskDate__c, SignableFlag__c,
                            Product2.PartSupplyFinishDate__c , Product2.PartSupplyFinishDateExp__c
                            // 2021-01-29 LJPH-BX9CVX mzy   add  合同报价时判断零件风险
                            FROM Asset WHERE Hospital__c = :this.targetHospitalId AND ( AssetMark__c != '耗材' OR Product2.Family != 'ET' ) ORDER BY ID, IF_Warranty__c asc];
            // FROM Asset WHERE Hospital__c = :this.targetHospitalId AND AssetMark__c = '主机' ORDER BY ID,IF_Warranty__c asc];
        } else {
            assetRecords = new List<Asset>();
        }
        //sqlStr += ' AND AssetMark__c != \'耗材\' AND Product2.Family != \'ET\' ';
        this.checkedAssets = new List<AssetInfo>();
        this.unCheckedAssets = new List<AssetInfo>();

        // 選択済みの納入機器情報を取得
        Map<Id, Integer> selectedAssetIds = new Map<Id, Integer>();
        List<Maintenance_Contract_Asset_Estimate__c> selectedMcaes = new List<Maintenance_Contract_Asset_Estimate__c>();
        List<Maintenance_Contract_Asset_Estimate__c> newMcaes = new List<Maintenance_Contract_Asset_Estimate__c>();
        // 新規、且つ１つ目見積もりの場合、コピー元の保有設備を持つ
        if (String.isBlank(this.targetEstimateId) && this.contract.Estimate_Num__c == 0) {
            List<Maintenance_Contract_Asset__c> oldVals = [
                        select Id, Name, Asset__c, Asset__r.InstallDate, Asset__r.Posting_Date__c, Asset__r.Maintenance_Price_Month__c
                        from Maintenance_Contract_Asset__c
                        where Maintenance_Contract__c = :this.targetMaintenanceContractId];
            for (Maintenance_Contract_Asset__c mca : oldVals) {
                // oldより更新したい項目
                Boolean isNew = false;
                Decimal listPrice = mca.Asset__r.Maintenance_Price_Month__c;
                // InstallDate と 今日を比較
//                if (systemToday.addMonths(-6) < mca.Asset__r.InstallDate) {
//                if (estimate.Contract_Esti_Start_Date__c.addMonths(isNewAddMonth) < mca.Asset__r.InstallDate) {
                Date createdDate = (estimate.CreatedDate == null || !String.isBlank(copyid)) ? systemToday : estimate.CreatedDate.date();
                System.debug(createdDate + '.addMonths(' + isNewAddMonth + ')' + createdDate.addMonths(isNewAddMonth) + ' < mca.Asset__r.InstallDate:' + mca.Asset__r.InstallDate);
                if (createdDate.addMonths(isNewAddMonth) < mca.Asset__r.InstallDate) {
                    isNew = true;
                    listPrice = mca.Asset__r.Maintenance_Price_Month__c * isNewPriceAdj;
                }
                selectedAssetIds.put(mca.Asset__c, selectedMcaes.size());
                selectedMcaes.add(new Maintenance_Contract_Asset_Estimate__c(
                                      Asset__c = mca.Asset__c,
                                      isNew__c = isNew,
                                      Estimate_List_Price__c = listPrice
                                  ));
            }
        } else {
            for (Maintenance_Contract_Asset_Estimate__c mcae : [SELECT   Id,
                    Name,
                    Maintenance_Contract_Estimate__c,
                    Asset__c,
                    Asset__r.Maintenance_Price_Month__c,
                    Asset__r.InstallDate,
                    Product_Manual__c,
                    Product_Manual__r.Maintenance_Price_Month__c,
                    //add 2021-02-07 mzy  start
                    //Product_Manual__r.NoPartRiskDate_F__c,
                    //Product_Manual__r.SignableFlag__c,
                    Product_Manual__r.Name,
                    //add 2021-02-07 mzy  end
                    //add 2021.6.4 fxk  Start
                    Check_Object__c,
                    //add 2021.6.4 fxk  end
                    IsNew__c,
                    Asset__r.CurrentContract_F__c,
                    Asset__r.CurrentContract_F__r.First_Estimate_Date__c,
                    Asset__r.CurrentContract_F__r.Contract_Consumption_rate__c,
                    Asset__r.CurrentContract_F__r.First_contract_usage_Rate__c,
                    Asset__r.CurrentContract_F__r.Estimate_Contract_endDate__c,
                    Asset__r.CurrentContract_F__r.Contract_Range__c,
                    Asset__r.CurrentContract_F__r.Contract_End_Date__c,
                    Asset__r.CurrentContract_F__r.Gurantee_Estimate_startDate__c,
                    Estimate_List_Price__c,
                    Last_inspection_day__c,
                    Check_Result__c,
                    Repair_Price__c,
                    Comment__c,
                    Asset__r.Posting_Date__c,
                    Asset__r.AssetMark__c
                    FROM    Maintenance_Contract_Asset_Estimate__c
                    WHERE   Maintenance_Contract_Estimate__c = :this.targetEstimateId
                            ORDER BY
                            Id,
                    Asset__c,
                    Product_Manual__c,
                    Asset__r.SerialNumber,
                    Asset__r.Name,
                    Asset__r.Department_Name__c,
                    Asset__r.InstallDate,
                    Asset__r.AssetMark__c

                                                               ]) {
                if (String.isBlank(copyid) == false) {
                    if (mcae.Asset__c <> null) {
                        if (systemToday.addMonths(isNewAddMonth) < mcae.Asset__r.InstallDate) {
                            mcae.IsNew__c = true;
                            mcae.Estimate_List_Price__c = mcae.Asset__r.Maintenance_Price_Month__c * isNewPriceAdj;
                        } else {
                            mcae.IsNew__c = false;
                            mcae.Estimate_List_Price__c = mcae.Asset__r.Maintenance_Price_Month__c;
                        }
                    } else if (mcae.Product_Manual__c <> null) {
                        mcae.IsNew__c = true;
                        mcae.Estimate_List_Price__c = mcae.Product_Manual__r.Maintenance_Price_Month__c * isNewPriceAdj;
                    }
                }
                if (mcae.Asset__c <> null) {
                    selectedAssetIds.put(mcae.Asset__c, selectedMcaes.size());
                    selectedMcaes.add(mcae);
                } else {
                    newMcaes.add(mcae);
                }
            }
        }

        // 選択済みのものにチェックを付ける
        // TODO xudan 一覧に出る明細件数が足りないケースがある
        // ①AssetA―明細Aで明細登録
        // ②Assetの検索条件変更により、AssetAは永遠に取得できない
        // ③Assetを元にデータをマッピングする時、明細マップからAssetAを取得できない?一覧に明細Aが出ない
        // 次回、Assetの検索条件が大きく変更する時、対応必要
        for (Asset ast : this.assetRecords) {
            Boolean isNew = false;
            Decimal listPrice = ast.Maintenance_Price_Month__c;
            if (selectedAssetIds.containsKey(ast.Id)) {
                Maintenance_Contract_Asset_Estimate__c selectedLocal = selectedMcaes.get(selectedAssetIds.get(ast.Id));
                isNew = selectedLocal.isNew__c;
                listPrice = selectedLocal.Estimate_List_Price__c;
                // xudan 20160110 新品判断ここ要らない、contractStartDateChangeがやる
//                if (systemToday.addMonths(-6) < ast.InstallDate) {
//                if (estimate.Contract_Esti_Start_Date__c.addMonths(isNewAddMonth) < ast.InstallDate) {
//                Date createdDate = (estimate.CreatedDate == null || !String.isBlank(copyid)) ? systemToday : estimate.CreatedDate.date();
//System.debug(createdDate + '.addMonths(' + isNewAddMonth + ')' + createdDate.addMonths(isNewAddMonth) + ' < ast.InstallDate:' + ast.InstallDate);
//                if (createdDate.addMonths(isNewAddMonth) < ast.InstallDate) {
//                    isNew = true;
//                    listPrice = ast.Maintenance_Price_Month__c * isNewPriceAdj;
//                }
                checkedAssets.add(new AssetInfo(checkedAssets.size(), ast, isNew, listPrice, selectedLocal));
            } else {
                //update by rentongxiao 2020-09-23 start
                if (ast.AssetMark__c == '主机') {
                    totalRecords ++;
                    if (unCheckedAssets.size() < selctRecordNum) {
                        unCheckedAssets.add(new AssetInfo(unCheckedAssets.size(), ast));
                    }
                }
                //update by rentongxiao 2020-09-23 end

            }
            listCut(unCheckedAssets);
            /*
            if (ast.CheckBox__c) {
                checkedAssets.add(new AssetInfo(checkedAssets.size(), ast, isNew, listPrice));
            } else {
                unCheckedAssets.add(new AssetInfo(unCheckedAssets.size(), ast));
            }
            */
        }

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

        system.debug('顺序检测' + checkedAssets);
        for (Maintenance_Contract_Asset_Estimate__c mcae : newMcaes) {
            checkedAssets.add(new AssetInfo(checkedAssets.size(), mcae));
        }

        // 最後10行追加
        if (Schema.getGlobalDescribe().get('Maintenance_Contract_Asset_Estimate__c').getDescribe().isCreateable()) {
            this.addNewRows();
        }

        if (!String.isBlank(copyid)) {
            this.targetEstimateId = null;
            this.estimate = new Maintenance_Contract_Estimate__c();
            this.estimate.Maintenance_Contract__c = this.targetMaintenanceContractId;
        }
        assetRecords.clear();
        // 根据合同开始日重新计算维修合同价格
        contractStartDateChange();
    }

    //

    // 取得分页数据
    private void setPageRecord() {
        checkIdList = new List<String> ();
        

        if ((currPage * selctRecordNum) <= 2000) {
            String notInId = '(\'';
            if (checkIdList.size() > 0) {
                for (String str : checkIdList) {
                    notInId += str + '\', \'';
                }
            }
            notInId += '\')';

            String sqlStr = 'SELECT Id, Name, Asset_situation__c, SerialNumber, Department_Name__c, Installation_Site__c, '
                            + 'Posting_Date__c,Management_Code__c,IF_Warranty__c,Reson_Can_not_Warranty__c, InstallDate, '
                            + 'Asset_Owner__c, Accumulation_Repair_Amount__c, Maintenance_Price_Month__c, Final_Examination_Date__c, '
                            + 'CurrentContract_F__c,CurrentContract_F__r.Maintenance_Contract_No_F__c,CurrentContract_F__r.Contract_End_Date__c,'
                            + 'CurrentContract_End_Date__c, Extend_Gurantee_DateTo__c,AssetMark__c,NoPartRiskDate_F__c,NoPartRiskDate__c,SignableFlag__c,Product2.PartSupplyFinishDate__c,Product2.PartSupplyFinishDateExp__c FROM Asset WHERE Hospital__c = \'' + this.targetHospitalId + '\' '
                            + 'AND Id NOT IN ' + notInId ;
            //HWAG-B4R3SS  START 20181026
            if (String.isNotBlank(text1) && String.isNotBlank(cond1) && String.isNotBlank(val1)) {
                sqlStr += makeTextSql(text1, cond1, val1);
            }

            //JZHG-BSDUT4 ---20200904---update By rentongxiao---Start
            else {
                sqlStr += ' AND AssetMark__c = \'主机\'';
            }

            //JZHG-BSDUT4 ---20200904---update By rentongxiao---end
            //HWAG-B4R3SS  END 20181026
            //HWAG-BDJ43R---XHL---20190729---
            sqlStr += ' AND ( AssetMark__c != \'耗材\' OR Product2.Family != \'ET\' )';
            //HWAG-BDJ43R---XHL---20190729---
            sqlStr += ' ORDER BY ID,IF_Warranty__c asc ';
            if (currPage == 1) {
                sqlStr += 'limit ' + selRecordOption;
            } else {
                sqlStr += 'limit ' + selRecordOption + ' offset ' + String.valueOf((currPage - 1) * selctRecordNum);
            }
            //system.debug();
            //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,
            //               '222222222222_____'+sqlStr));
            //return;
            assetRecords = Database.query(sqlStr);
        } else {
            assetRecords.clear();
            Integer sqlLimit = currPage * selctRecordNum;
            List<Asset> temAsset = new List<Asset> ();
            //HWAG-BDJ43R ---XHL---20190729---
            String sqlStr = '';
            sqlStr  = 'SELECT Id, Name, Asset_situation__c, SerialNumber, Department_Name__c, Installation_Site__c,';
            sqlStr += 'Posting_Date__c,Management_Code__c,IF_Warranty__c,Reson_Can_not_Warranty__c,InstallDate,' ;
            sqlStr += 'Asset_Owner__c, Accumulation_Repair_Amount__c, Maintenance_Price_Month__c, Final_Examination_Date__c,';
            sqlStr += 'CurrentContract_F__c,CurrentContract_F__r.Maintenance_Contract_No_F__c,CurrentContract_F__r.Contract_End_Date__c,';
            sqlStr += 'CurrentContract_End_Date__c,Extend_Gurantee_DateTo__c,AssetMark__c,NoPartRiskDate_F__c,NoPartRiskDate__c,SignableFlag__c,Product2.PartSupplyFinishDate__c,Product2.PartSupplyFinishDateExp__c';
            sqlStr += ' FROM Asset WHERE Hospital__c = \'' + this.targetHospitalId + '\'';
            sqlStr += '  AND ( AssetMark__c != \'耗材\' OR Product2.Family != \'ET\' ) ';

            //HWAG-B4R3SS  START 20181026
            if (String.isNotBlank(text1) && String.isNotBlank(cond1) && String.isNotBlank(val1)) {
                sqlStr += makeTextSql(text1, cond1, val1);
            }
            //JZHG-BSDUT4 ---20200904---update By rentongxiao---Start
            else {
                sqlStr += 'AND AssetMark__c = \'主机\'';
            }
            //JZHG-BSDUT4 ---20200904---update By rentongxiao---end
            //HWAG-B4R3SS  END 20181026
            if (checkIdList.size() > 0) {

                sqlStr += '  AND Id NOT IN ' + checkIdList;
                //temAsset = [SELECT Id, Name, Asset_situation__c, SerialNumber, Department_Name__c, Installation_Site__c, Posting_Date__c,Management_Code__c,IF_Warranty__c,Reson_Can_not_Warranty__c,
                //            InstallDate, Asset_Owner__c, Accumulation_Repair_Amount__c, Maintenance_Price_Month__c, Final_Examination_Date__c,CurrentContract_End_Date__c,Extend_Gurantee_DateTo__c
                //            FROM Asset WHERE Hospital__c = :this.targetHospitalId AND Id NOT IN : checkIdList AND AssetMark__c != '耗材' AND Product2.Family != 'ET' ORDER BY ID,IF_Warranty__c asc limit : sqlLimit];
            } else {
                //temAsset = [SELECT Id, Name, Asset_situation__c, SerialNumber, Department_Name__c, Installation_Site__c, Posting_Date__c,Management_Code__c,IF_Warranty__c,Reson_Can_not_Warranty__c,
                //            InstallDate, Asset_Owner__c, Accumulation_Repair_Amount__c, Maintenance_Price_Month__c, Final_Examination_Date__c,CurrentContract_End_Date__c,Extend_Gurantee_DateTo__c
                //            FROM Asset WHERE Hospital__c = :this.targetHospitalId AND AssetMark__c != '耗材' AND Product2.Family != 'ET' ORDER BY ID,IF_Warranty__c asc limit : sqlLimit];
            }
            sqlStr += ' ORDER BY ID,IF_Warranty__c asc limit ' + sqlLimit;
            temAsset = Database.query(sqlStr);
            //HWAG-BDJ43R ---XHL---20190729---
            if (temAsset.size() >= (currPage * selctRecordNum)) {
                for (Integer i = ((currPage - 1) * selctRecordNum); i < (currPage * selctRecordNum); i++) {
                    assetRecords.add(temAsset.get(i));
                }
            } else {
                for (Integer i = ((currPage - 1) * selctRecordNum); i < temAsset.size(); i++) {
                    assetRecords.add(temAsset.get(i));
                }
            }
        }
        this.unCheckedAssets = new List<AssetInfo>();
        for (Asset ast : assetRecords) {
            this.unCheckedAssets.add(new AssetInfo(unCheckedAssets.size(), ast));
        }
        listCut(unCheckedAssets);
        // 根据合同开始日重新计算维修合同价格
        contractStartDateChange();
    }

    // 翻页到首页
    public void firstPage() {
        getAssetSerialNumber();
        currPage = 1;
        //HWAG-B4R3SS  END 20181026
        totalRecords = soqlNos();
        totalPage = (totalRecords / selctRecordNum) + (Math.mod(totalRecords, selctRecordNum) > 0 ? 1 : 0);
        //HWAG-B4R3SS  END 20181026
        this.setPageRecord();
    }

    // 向前翻页
    public void previousPage() {
        getAssetSerialNumber();
        currPage --;
        //HWAG-B4R3SS  START 20181026
        totalRecords = soqlNos();
        totalPage = (totalRecords / selctRecordNum) + (Math.mod(totalRecords, selctRecordNum) > 0 ? 1 : 0);
        //HWAG-B4R3SS  END 20181026
        this.setPageRecord();
    }

    // 向后翻页
    public void nextPage() {
        getAssetSerialNumber();
        //HWAG-B4R3SS  START 20181026
        totalRecords = soqlNos();
        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO , 'totalRecords——————' + totalRecords));
        totalPage = (totalRecords / selctRecordNum) + (Math.mod(totalRecords, selctRecordNum) > 0 ? 1 : 0);
        if (totalRecords == 0) {
            currPage  = 1;
            //this.unCheckedAssets.clear();
        } else {
            currPage ++;
            this.setPageRecord();
        }
        //HWAG-B4R3SS  END 20181026

    }

    // 翻页到尾页
    public void endPage() {
        getAssetSerialNumber();
        //HWAG-B4R3SS  START 20181026
        totalRecords = soqlNos();
        totalPage = (totalRecords / selctRecordNum) + (Math.mod(totalRecords, selctRecordNum) > 0 ? 1 : 0);
        if (totalRecords == 0) {
            currPage  = 1;
            this.unCheckedAssets.clear();
        } else {
            currPage = totalPage;
            this.setPageRecord();
        }
        //HWAG-B4R3SS  END 20181026
    }

    // 每页显示记录数变更
    public void recordNumChange() {
        currPage = 1;
        //totalRecords = soqlNos();
        totalPage = (totalRecords / selctRecordNum) + (Math.mod(totalRecords, selctRecordNum) > 0 ? 1 : 0);
        this.setPageRecord();
    }

    //list分割 集合大小超过1000对应
    private void listCut(List<AssetInfo> records) {
        List<AssetInfo> recordsbreak = new List<AssetInfo>();
        List<AssetInfo> recordsbreakover = new List<AssetInfo>();
        unCheckedAssetsView = new List<List<AssetInfo>>();
        AssetInfo c = null;
        recordsbreak.clear();
        recordsbreakover.clear();
        unCheckedAssetsView.clear();
        //if(records.size() > 1000){
        //    for(Integer i = 0; i < records.size(); i++){
        //        if(i < 1000){
        //            c = records.get(i);
        //            recordsbreak.add(c);
        //        }else{
        //            c = records.get(i);
        //            recordsbreakover.add(c);
        //        }
        //    }
        //    unCheckedAssetsView.add(recordsbreak);
        //    unCheckedAssetsView.add(recordsbreakover);
        //}else{
        unCheckedAssetsView.add(records);
        //}
    }
    /*
    *显示过去两年的维修实绩
    *计算该维修合同报价的所有保佑设备，过去两年的修理实绩
    */
    public static void ComputeLTYRepair(String targetHospitalId) {
        system.debug('ComputeLTYRepair=====Start');
        List<Maintenance_Contract_Asset_Estimate__c> McaeList = new List<Maintenance_Contract_Asset_Estimate__c>();
        McaeList = [select id, asset__c, Lastyear_Repair_Cost_Text__c, Last_Second_Years_Repair_Cost_Text__c, Last_Third_Years_Repair_Cost_Text__c
                    from Maintenance_Contract_Asset_Estimate__c
                    where Maintenance_Contract_Estimate__c = :targetHospitalId];
        List<id> AsList = new List<id>();
        Map<id, id> McaecToAsset = new Map<id, id>();
        for (Maintenance_Contract_Asset_Estimate__c Mcaes : McaeList) {
            AsList.add(Mcaes.asset__c);
            McaecToAsset.put(Mcaes.id, Mcaes.asset__c);
        }
        Maintenance_Contract_Estimate__c mcec = [select id, createdDate, Submit_quotation_day__c from Maintenance_Contract_Estimate__c where id = :targetHospitalId];
        //1年前维修实绩
        Date today = null;
        Date LastYearDate = null;
        Date LastSecondYearDate = null;
        Date LastThirdYearDate = null;
        Decimal LastYearPriceForMCAEC = 0;

        if (mcec.Submit_quotation_day__c != null && String.valueOf(mcec.Submit_quotation_day__c) != '') {
            today = mcec.Submit_quotation_day__c;
            LastYearDate = mcec.Submit_quotation_day__c;
            LastSecondYearDate = mcec.Submit_quotation_day__c;
            LastThirdYearDate = mcec.Submit_quotation_day__c;
        } else {
            today = mcec.Submit_quotation_day__c;
            LastYearDate = Date.valueOf(mcec.createdDate);
            LastSecondYearDate = Date.valueOf(mcec.createdDate);
            LastThirdYearDate = Date.valueOf(mcec.createdDate);
        }

        system.debug('去年' + LastYearDate + '前年' + LastSecondYearDate + '大前年' + LastThirdYearDate);

        LastYearDate = LastYearDate.addYears(-1);
        // LastYearDate = LastYearDate.addDays(1);

        //LastSecondYearDate = LastSecondYearDate.addDays(1);
        LastSecondYearDate = LastSecondYearDate.addYears(-2);

        // LastThirdYearDate = LastThirdYearDate.addDays(1);
        LastThirdYearDate = LastThirdYearDate.addYears(-3);
        system.debug('去年' + LastYearDate + '前年' + LastSecondYearDate + '大前年' + LastThirdYearDate);

        List<AggregateResult> FriRepairList = [
                select
                sum(Discount_Price_formula__c) SumPrice,
                //2019/1添加
                sum(Repair_Quotation_Id__r.sales_discount__c) sales_discount,
                sum(Repair_Quotation_Id__r.Contract_target__c) contract_target,
                sum(Repair_Quotation_Id__r.Loaner_repair__c) loaner_repair,
                sum(Repair_Quotation_Id__r.long_term_insurance__c) long_term_insurance,
                sum(Repair_Quotation_Id__r.Set_discount__c) set_discount,
                sum(Repair_Quotation_Id__r.Servince_contract_discount_amount__c) sercince,
                sum(Repair_Quotation_Id__r.Delivery_compensation__c) delivery,
                sum(Repair_Quotation_Id__r.Other_discount__c) other,
                Delivered_Product__c
                from
                Repair__c
                where
                Delivered_Product__c in:AsList
                /*and (
                            (
                                Repair_Quotation_Id__c!=null

                                    and     (Repair_Quotation_Id__r.New_QIS_free__c = 0
                                            or
                                                Repair_Quotation_Id__r.New_QIS_free__c = null)
                                    and     (Repair_Quotation_Id__r.Contract_free__c= 0
                                            or
                                                Repair_Quotation_Id__r.Contract_free__c= null)
                            )
                        or  Repair_Quotation_Id__c =null
                    )
                and Status2__c != '00.关闭'
                and Status2__c != '00.取消'
                and Status2__c != '00.删除'
                and Return_Without_Repair_IF__c = false*/
                and Agreed_Date__c != null
                and Agreed_Date__c > :LastYearDate
                and Agreed_Date__c <= :today
                group by Delivered_Product__c
                                              ];
        List<AggregateResult> SecRepairList = [
                select
                sum(Discount_Price_formula__c) SumPrice,
                //2019/1添加
                sum(Repair_Quotation_Id__r.sales_discount__c) sales_discount,
                sum(Repair_Quotation_Id__r.Contract_target__c) contract_target,
                sum(Repair_Quotation_Id__r.Loaner_repair__c) loaner_repair,
                sum(Repair_Quotation_Id__r.long_term_insurance__c) long_term_insurance,
                sum(Repair_Quotation_Id__r.Set_discount__c) set_discount,
                sum(Repair_Quotation_Id__r.Servince_contract_discount_amount__c) sercince,
                sum(Repair_Quotation_Id__r.Delivery_compensation__c) delivery,
                sum(Repair_Quotation_Id__r.Other_discount__c) other,
                Delivered_Product__c
                from
                Repair__c
                where
                Delivered_Product__c in:AsList
                /*and (
                            (
                                Repair_Quotation_Id__c!=null

                                    and     (Repair_Quotation_Id__r.New_QIS_free__c = 0
                                            or
                                                Repair_Quotation_Id__r.New_QIS_free__c = null)
                                    and     (Repair_Quotation_Id__r.Contract_free__c= 0
                                            or
                                                Repair_Quotation_Id__r.Contract_free__c= null)
                            )
                        or  Repair_Quotation_Id__c =null
                    )
                and Status2__c != '00.关闭'
                and Status2__c != '00.取消'
                and Status2__c != '00.删除'
                and Return_Without_Repair_IF__c = false*/
                and Agreed_Date__c != null
                and Agreed_Date__c <= :LastYearDate
                and Agreed_Date__c > :LastSecondYearDate
                group by Delivered_Product__c];
        List<AggregateResult> ThiRepairList = [
                select
                sum(Discount_Price_formula__c) SumPrice,
                //2019/1添加
                sum(Repair_Quotation_Id__r.sales_discount__c) sales_discount,
                sum(Repair_Quotation_Id__r.Contract_target__c) contract_target,
                sum(Repair_Quotation_Id__r.Loaner_repair__c) loaner_repair,
                sum(Repair_Quotation_Id__r.long_term_insurance__c) long_term_insurance,
                sum(Repair_Quotation_Id__r.Set_discount__c) set_discount,
                sum(Repair_Quotation_Id__r.Servince_contract_discount_amount__c) sercince,
                sum(Repair_Quotation_Id__r.Delivery_compensation__c) delivery,
                sum(Repair_Quotation_Id__r.Other_discount__c) other,
                Delivered_Product__c
                from
                Repair__c
                where
                Delivered_Product__c in:AsList
                /*and (
                            (
                                Repair_Quotation_Id__c!=null

                                    and     (Repair_Quotation_Id__r.New_QIS_free__c = 0
                                            or
                                                Repair_Quotation_Id__r.New_QIS_free__c = null)
                                    and     (Repair_Quotation_Id__r.Contract_free__c= 0
                                            or
                                                Repair_Quotation_Id__r.Contract_free__c= null)
                            )
                        or  Repair_Quotation_Id__c =null
                    )
                and Status2__c != '00.关闭'
                and Status2__c != '00.取消'
                and Status2__c != '00.删除'
                and Return_Without_Repair_IF__c = false*/
                and Agreed_Date__c != null
                and Agreed_Date__c <= :LastSecondYearDate
                and Agreed_Date__c > :LastThirdYearDate
                group by Delivered_Product__c];

        system.debug('++++++++' + FriRepairList + '++++++++' + SecRepairList + '+++++++' + ThiRepairList + '+++++');
        Map<id, Decimal> LastFriYearPriceSumMap = new Map<id, Decimal>();
        Map<id, Decimal> LastSecYearPriceSumMap = new Map<id, Decimal>();
        Map<id, Decimal> LastThiYearPriceSumMap = new Map<id, Decimal>();
        for (AggregateResult Rpc : FriRepairList) {
            id idf        = String.valueOf(Rpc.get('Delivered_Product__c'));
            //Decimal Defir = decimal.valueOf(Rpc.get('SumPrice')+'');
            Decimal Defir = sumPrice1(Rpc);
            LastFriYearPriceSumMap.put(idf, Defir);
        }
        for (AggregateResult Rpc : SecRepairList) {
            id idf        = String.valueOf(Rpc.get('Delivered_Product__c'));
            //Decimal Defir = decimal.valueOf(Rpc.get('SumPrice')+'');
            Decimal Defir = sumPrice1(Rpc);
            LastSecYearPriceSumMap.put(idf, Defir);
        }
        for (AggregateResult Rpc : ThiRepairList) {
            id idf        = String.valueOf(Rpc.get('Delivered_Product__c'));
            //Decimal Defir = decimal.valueOf(Rpc.get('SumPrice')+'');
            Decimal Defir = sumPrice1(Rpc);
            LastThiYearPriceSumMap.put(idf, Defir);
        }
        for (Maintenance_Contract_Asset_Estimate__c Mca : McaeList) {
            Mca.Lastyear_Repair_Cost_Text__c = LastFriYearPriceSumMap.get(McaecToAsset.get(Mca.id)) == null ? 0 : LastFriYearPriceSumMap.get(McaecToAsset.get(Mca.id));
            Mca.Last_Second_Years_Repair_Cost_Text__c = LastSecYearPriceSumMap.get(McaecToAsset.get(Mca.id)) == null ? 0 : LastSecYearPriceSumMap.get(McaecToAsset.get(Mca.id));
            Mca.Last_Third_Years_Repair_Cost_Text__c = LastThiYearPriceSumMap.get(McaecToAsset.get(Mca.id)) == null ? 0 : LastThiYearPriceSumMap.get(McaecToAsset.get(Mca.id));


            /* if( LastFriYearPriceSumMap.get(McaecToAsset.get(Mca.id))!=null){
                  Mca.Lastyear_Repair_Cost_Text__c = LastFriYearPriceSumMap.get(McaecToAsset.get(Mca.id));
                 system.debug(McaecToAsset.get(Mca.id)+'::::::'+Mca.Lastyear_Repair_Cost_Text__c);
             }
             if(LastSecYearPriceSumMap.get(McaecToAsset.get(Mca.id)) !=null){
                  Mca.Last_Second_Years_Repair_Cost_Text__c = LastSecYearPriceSumMap.get(McaecToAsset.get(Mca.id));
                  system.debug(McaecToAsset.get(Mca.id)+'#######'+Mca.Last_Second_Years_Repair_Cost_Text__c);
             }

             if(LastThiYearPriceSumMap.get(McaecToAsset.get(Mca.id)) !=null){
                  Mca.Last_Third_Years_Repair_Cost_Text__c = LastThiYearPriceSumMap.get(McaecToAsset.get(Mca.id));
                  system.debug(McaecToAsset.get(Mca.id)+'#######'+Mca.Last_Third_Years_Repair_Cost_Text__c);
             }*/
            Mca.The_Date_Of_Compute_The_RPCost__c = Date.today();

        }
        try {
            system.debug('McaeList:::::' + McaeList);
            update McaeList;

            //return '';
        } catch (Exception e) {
            //return 'McaeList Update Failed : '+e;
        }

    }



    public void ComputeLTYRepair() {
        system.debug('ComputeLTYRepair=====Start');
        List<Maintenance_Contract_Asset_Estimate__c> McaeList = new List<Maintenance_Contract_Asset_Estimate__c>();
        McaeList = [select id, asset__c, Lastyear_Repair_Cost_Text__c, Last_Second_Years_Repair_Cost_Text__c
                    from Maintenance_Contract_Asset_Estimate__c
                    where Maintenance_Contract_Estimate__c = :targetEstimateId];
        List<id> AsList = new List<id>();
        Map<id, id> McaecToAsset = new Map<id, id>();
        for (Maintenance_Contract_Asset_Estimate__c Mcaes : McaeList) {
            AsList.add(Mcaes.asset__c);
            McaecToAsset.put(Mcaes.id, Mcaes.asset__c);
        }

        Maintenance_Contract_Estimate__c mcec = [select id, createdDate, Submit_quotation_day__c from Maintenance_Contract_Estimate__c where id = :targetEstimateId];

        //1年前维修实绩
        Date today = null;
        Date LastYearDate = null;
        Date LastSecondYearDate = null;
        Date LastThirdYearDate = null;
        Decimal LastYearPriceForMCAEC = 0;

        if (mcec.Submit_quotation_day__c != null && String.valueOf(mcec.Submit_quotation_day__c) != '') {
            today = mcec.Submit_quotation_day__c;
            LastYearDate = mcec.Submit_quotation_day__c;
            LastSecondYearDate = mcec.Submit_quotation_day__c;
            LastThirdYearDate = mcec.Submit_quotation_day__c;
        } else {
            today = mcec.Submit_quotation_day__c;
            LastYearDate = Date.valueOf(mcec.createdDate);
            LastSecondYearDate = Date.valueOf(mcec.createdDate);
            LastThirdYearDate = Date.valueOf(mcec.createdDate);
        }

        LastYearDate = LastYearDate.addYears(-1);
        // LastYearDate = LastYearDate.addDays(1);

        // LastSecondYearDate = LastSecondYearDate.addDays(1);
        LastSecondYearDate = LastSecondYearDate.addYears(-2);

        // LastThirdYearDate = LastThirdYearDate.addDays(1);
        LastThirdYearDate = LastThirdYearDate.addYears(-3);
        system.debug('去年' + LastYearDate + '前年' + LastSecondYearDate + '大前年' + LastThirdYearDate);
        List<AggregateResult> FriRepairList = [
                select
                sum(Discount_Price_formula__c) SumPrice,
                //2019/1添加
                sum(Repair_Quotation_Id__r.sales_discount__c) sales_discount,
                sum(Repair_Quotation_Id__r.Contract_target__c) contract_target,
                sum(Repair_Quotation_Id__r.Loaner_repair__c) loaner_repair,
                sum(Repair_Quotation_Id__r.long_term_insurance__c) long_term_insurance,
                sum(Repair_Quotation_Id__r.Set_discount__c) set_discount,
                sum(Repair_Quotation_Id__r.Servince_contract_discount_amount__c) sercince,
                sum(Repair_Quotation_Id__r.Delivery_compensation__c) delivery,
                sum(Repair_Quotation_Id__r.Other_discount__c) other,
                Delivered_Product__c
                from
                Repair__c
                where
                Delivered_Product__c in:AsList
                /*and (
                            (
                                Repair_Quotation_Id__c!=null

                                    and     (Repair_Quotation_Id__r.New_QIS_free__c = 0
                                            or
                                                Repair_Quotation_Id__r.New_QIS_free__c = null)
                                    and     (Repair_Quotation_Id__r.Contract_free__c= 0
                                            or
                                                Repair_Quotation_Id__r.Contract_free__c= null)
                            )
                        or  Repair_Quotation_Id__c =null
                    )
                and Status2__c != '00.关闭'
                and Status2__c != '00.取消'
                and Status2__c != '00.删除'
                and Return_Without_Repair_IF__c = false*/
                and Agreed_Date__c != null
                and Agreed_Date__c > :LastYearDate
                and Agreed_Date__c <= :today
                group by Delivered_Product__c];
        List<AggregateResult> SecRepairList = [
                select
                sum(Discount_Price_formula__c) SumPrice,
                //2019/1添加
                sum(Repair_Quotation_Id__r.sales_discount__c) sales_discount,
                sum(Repair_Quotation_Id__r.Contract_target__c) contract_target,
                sum(Repair_Quotation_Id__r.Loaner_repair__c) loaner_repair,
                sum(Repair_Quotation_Id__r.long_term_insurance__c) long_term_insurance,
                sum(Repair_Quotation_Id__r.Set_discount__c) set_discount,
                sum(Repair_Quotation_Id__r.Servince_contract_discount_amount__c) sercince,
                sum(Repair_Quotation_Id__r.Delivery_compensation__c) delivery,
                sum(Repair_Quotation_Id__r.Other_discount__c) other,
                Delivered_Product__c
                from
                Repair__c
                where
                Delivered_Product__c in:AsList
                /* and (
                             (
                                 Repair_Quotation_Id__c!=null

                                     and     (Repair_Quotation_Id__r.New_QIS_free__c = 0
                                             or
                                                 Repair_Quotation_Id__r.New_QIS_free__c = null)
                                     and     (Repair_Quotation_Id__r.Contract_free__c= 0
                                             or
                                                 Repair_Quotation_Id__r.Contract_free__c= null)
                             )
                         or  Repair_Quotation_Id__c =null
                     )
                 and Status2__c != '00.关闭'
                 and Status2__c != '00.取消'
                 and Status2__c != '00.删除'
                 and Return_Without_Repair_IF__c = false */
                and Agreed_Date__c != null
                and Agreed_Date__c <= :LastYearDate
                and Agreed_Date__c > :LastSecondYearDate
                group by Delivered_Product__c];
        List<AggregateResult> ThiRepairList = [
                select
                sum(Discount_Price_formula__c) SumPrice,
                //2019/1添加
                sum(Repair_Quotation_Id__r.sales_discount__c) sales_discount,
                sum(Repair_Quotation_Id__r.Contract_target__c) contract_target,
                sum(Repair_Quotation_Id__r.Loaner_repair__c) loaner_repair,
                sum(Repair_Quotation_Id__r.long_term_insurance__c) long_term_insurance,
                sum(Repair_Quotation_Id__r.Set_discount__c) set_discount,
                sum(Repair_Quotation_Id__r.Servince_contract_discount_amount__c) sercince,
                sum(Repair_Quotation_Id__r.Delivery_compensation__c) delivery,
                sum(Repair_Quotation_Id__r.Other_discount__c) other,
                Delivered_Product__c
                from
                Repair__c
                where
                Delivered_Product__c in:AsList
                /* and (
                             (
                                 Repair_Quotation_Id__c!=null

                                     and     (Repair_Quotation_Id__r.New_QIS_free__c = 0
                                             or
                                                 Repair_Quotation_Id__r.New_QIS_free__c = null)
                                     and     (Repair_Quotation_Id__r.Contract_free__c= 0
                                             or
                                                 Repair_Quotation_Id__r.Contract_free__c= null)
                             )
                         or  Repair_Quotation_Id__c =null
                     )
                 and Status2__c != '00.关闭'
                 and Status2__c != '00.取消'
                 and Status2__c != '00.删除'
                 and Return_Without_Repair_IF__c = false*/
                and Agreed_Date__c != null
                and Agreed_Date__c <= :LastSecondYearDate
                and Agreed_Date__c > :LastThirdYearDate
                group by Delivered_Product__c];
        Map<id, Decimal> LastFriYearPriceSumMap = new Map<id, Decimal>();
        Map<id, Decimal> LastSecYearPriceSumMap = new Map<id, Decimal>();
        Map<id, Decimal> LastThiYearPriceSumMap = new Map<id, Decimal>();
        system.debug('1' + FriRepairList);
        system.debug('2' + SecRepairList);
        system.debug('3' + ThiRepairList);

        for (AggregateResult Rpc : FriRepairList) {
            id idf        = String.valueOf(Rpc.get('Delivered_Product__c'));
            //Decimal Defir = decimal.valueOf(Rpc.get('SumPrice')+'');
            Decimal Defir = this.sumPrice(Rpc);
            LastFriYearPriceSumMap.put(idf, Defir);
        }
        for (AggregateResult Rpc : SecRepairList) {
            id idf        = String.valueOf(Rpc.get('Delivered_Product__c'));
            //Decimal Defir = decimal.valueOf(Rpc.get('SumPrice')+'');
            Decimal Defir = this.sumPrice(Rpc);
            LastSecYearPriceSumMap.put(idf, Defir);
        }
        for (AggregateResult Rpc : ThiRepairList) {
            id idf        = String.valueOf(Rpc.get('Delivered_Product__c'));
            //Decimal Defir = decimal.valueOf(Rpc.get('SumPrice')+'');
            Decimal Defir = this.sumPrice(Rpc);
            LastThiYearPriceSumMap.put(idf, Defir);
        }
        for (Maintenance_Contract_Asset_Estimate__c Mca : McaeList) {
            Mca.Lastyear_Repair_Cost_Text__c = LastFriYearPriceSumMap.get(McaecToAsset.get(Mca.id)) == null ? 0 : LastFriYearPriceSumMap.get(McaecToAsset.get(Mca.id));
            Mca.Last_Second_Years_Repair_Cost_Text__c = LastSecYearPriceSumMap.get(McaecToAsset.get(Mca.id)) == null ? 0 : LastSecYearPriceSumMap.get(McaecToAsset.get(Mca.id));
            Mca.Last_Third_Years_Repair_Cost_Text__c = LastThiYearPriceSumMap.get(McaecToAsset.get(Mca.id)) == null ? 0 : LastThiYearPriceSumMap.get(McaecToAsset.get(Mca.id));

            /*if( LastFriYearPriceSumMap.get(McaecToAsset.get(Mca.id))!=null){
                 Mca.Lastyear_Repair_Cost_Text__c = LastFriYearPriceSumMap.get(McaecToAsset.get(Mca.id));
                system.debug(McaecToAsset.get(Mca.id)+'::::::'+Mca.Lastyear_Repair_Cost_Text__c);
            }
            if(LastSecYearPriceSumMap.get(McaecToAsset.get(Mca.id)) !=null){
                 Mca.Last_Second_Years_Repair_Cost_Text__c = LastSecYearPriceSumMap.get(McaecToAsset.get(Mca.id));
                 system.debug(McaecToAsset.get(Mca.id)+'#######'+Mca.Last_Second_Years_Repair_Cost_Text__c);
            }
            if(LastThiYearPriceSumMap.get(McaecToAsset.get(Mca.id)) !=null){
                 Mca.Last_Third_Years_Repair_Cost_Text__c = LastThiYearPriceSumMap.get(McaecToAsset.get(Mca.id));
                 system.debug(McaecToAsset.get(Mca.id)+'#######'+Mca.Last_Third_Years_Repair_Cost_Text__c);
            }*/
            Mca.The_Date_Of_Compute_The_RPCost__c = Date.today();

        }
        try {
            update McaeList;
            //return '';
        } catch (Exception e) {
            //return 'McaeList Update Failed : '+e;
        }

    }

    private Decimal sumPrice(AggregateResult rpc) {
        Decimal SumPrice = Decimal.valueOf(rpc.get('SumPrice') + '');
        system.debug(rpc.get('sales_discount') == null ? 0 : rpc.get('sales_discount'));
        Decimal sales_discount = Decimal.valueOf((rpc.get('sales_discount') == null ? 0 : rpc.get('sales_discount')) + '') * -1;
        Decimal contract_target = Decimal.valueOf((rpc.get('contract_target') == null ? 0 : rpc.get('contract_target')) + '') * -1;
        Decimal loaner_repair = Decimal.valueOf((rpc.get('loaner_repair') == null ? 0 : rpc.get('loaner_repair')) + '') * -1;
        Decimal long_term_insurance = Decimal.valueOf((rpc.get('long_term_insurance') == null ? 0 : rpc.get('long_term_insurance')) + '') * -1;
        Decimal set_discount = Decimal.valueOf((rpc.get('set_discount') == null ? 0 : rpc.get('set_discount')) + '') * -1;
        Decimal sercince = Decimal.valueOf((rpc.get('sercince') == null ? 0 : rpc.get('sercince')) + '') * -1;
        Decimal delivery = Decimal.valueOf((rpc.get('delivery') == null ? 0 : rpc.get('delivery')) + '') * -1;
        Decimal other = Decimal.valueOf((rpc.get('other') == null ? 0 : rpc.get('other')) + '') * -1;
        system.debug(rpc.get('SumPrice') + '--' + rpc.get('sales_discount') + '--' + rpc.get('contract_target') + '--' +
                     rpc.get('loaner_repair') + '--' + rpc.get('long_term_insurance') + '--' + rpc.get('set_discount') + '--' + rpc.get('sercince')
                     + '--' + rpc.get('delivery') + '--' + rpc.get('other') + '--');
        return SumPrice + sales_discount + contract_target + loaner_repair + long_term_insurance + set_discount + sercince + delivery + other;
    }

    private static Decimal sumPrice1(AggregateResult rpc) {
        Decimal SumPrice = Decimal.valueOf(rpc.get('SumPrice') + '');
        Decimal sales_discount = Decimal.valueOf((rpc.get('sales_discount') == null ? 0 : rpc.get('sales_discount')) + '') * -1;
        Decimal contract_target = Decimal.valueOf((rpc.get('contract_target') == null ? 0 : rpc.get('contract_target')) + '') * -1;
        Decimal loaner_repair = Decimal.valueOf((rpc.get('loaner_repair') == null ? 0 : rpc.get('loaner_repair')) + '') * -1;
        Decimal long_term_insurance = Decimal.valueOf((rpc.get('long_term_insurance') == null ? 0 : rpc.get('long_term_insurance')) + '') * -1;
        Decimal set_discount = Decimal.valueOf((rpc.get('set_discount') == null ? 0 : rpc.get('set_discount')) + '') * -1;
        Decimal sercince = Decimal.valueOf((rpc.get('sercince') == null ? 0 : rpc.get('sercince')) + '') * -1;
        Decimal delivery = Decimal.valueOf((rpc.get('delivery') == null ? 0 : rpc.get('delivery')) + '') * -1;
        Decimal other = Decimal.valueOf((rpc.get('other') == null ? 0 : rpc.get('other')) + '') * -1;
        system.debug(rpc.get('SumPrice') + '--' + rpc.get('sales_discount') + '--' + rpc.get('contract_target') + '--' +
                     rpc.get('loaner_repair') + '--' + rpc.get('long_term_insurance') + '--' + rpc.get('set_discount') + '--' + rpc.get('sercince')
                     + '--' + rpc.get('delivery') + '--' + rpc.get('other') + '--');
        return SumPrice + sales_discount + contract_target + loaner_repair + long_term_insurance + set_discount + sercince + delivery + other;
    }


    //废弃中=========20161024==============//
    public void ShowLTYRepair() {
        system.debug('ShowLTYRepair=====Start');
        lastFriYearsPriceSum = 0;
        lastSecYearsPriceSum = 0;
        //
        List<Maintenance_Contract_Estimate__c> McecList = new List<Maintenance_Contract_Estimate__c>();
        McecList = [select
                    Last_Year_Repair_Sum__c,
                    Year_Before_Last_Year_Re_Sum__c,
                    Last_Two_Year_Repair_sum__c,
                    Process_Status__c,//报价状态
                    Repair_Sum_Compute_Date__c
                    from
                    Maintenance_Contract_Estimate__c
                    where
                    id = :targetEstimateId
                   ];
        Maintenance_Contract_Estimate__c McecEle = new Maintenance_Contract_Estimate__c();
        if (McecList.size() > 0) {
            McecEle = McecList[0];
            Date ComputeD = McecEle.Repair_Sum_Compute_Date__c == null ? Date.today() : McecEle.Repair_Sum_Compute_Date__c;
            String DateString1 = ComputeD + '';
            String DateString2 = ComputeD.addYears(-2).addDays(1) + '';
            alertString = '集計対象期間：' + DateString1.substring(0, 10) + '~' + DateString2.substring(0, 10) + '';
            alertString2 = '去年修理実績合計：' + McecEle.Last_Year_Repair_Sum__c + ' RMB ';
            alertString3 = '前年修理実績合計：' + McecEle.Year_Before_Last_Year_Re_Sum__c + ' RMB';
        } else {
            alertString = '没有有效的维修合同报价';
        }
    }
    /**
     * 手動で商品選択後のリフレッシュ
    **/
    public void refreshProductData() {
        for (Integer i = 0; i < checkedAssets.size(); i++) {
            if (i == productIdx) {
                AssetInfo ai = checkedAssets[i];
                if (ai.mcae.Product_Manual__c == null) {
                    ai.mcae.Estimate_List_Price__c = null;
                    // add by fxk 2021/9/9 控制点检对象是否可选 Star
                    ai.CheckRows = true;
                    // add by fxk 2021/9/9 控制点检对象是否可选 End
                } else {
                    // add by mzy 2021-02-04  LJPH-BX9CVX  select 中添加 NoPartRiskDate_F__c
                    List<Product2> prd = [select Id, Maintenance_Price_Month__c, Name from Product2 where Id = :ai.mcae.Product_Manual__c];
                    ai.mcae.Estimate_List_Price__c = prd[0].Maintenance_Price_Month__c * isNewPriceAdj;
                    ai.orgPrice = prd[0].Maintenance_Price_Month__c;
                    //add by rentx 2020-11-12 LJPH-BV93RZ start
                    ai.proName = prd[0].Name;
                    //add by rentx 2020-11-12 LJPH-BV93RZ start
                    //add by mzy 2021-02-04 LJPH-BX9CVX start
                    //ai.NoPartRiskDate = prd[0].NoPartRiskDate_F__c;
                    ai.proName2 = prd[0].Name;
                    // add by fxk 2021/9/9 控制点检对象是否可选 Star
                    ai.CheckRows = false;
                    // add by fxk 2021/9/9 控制点检对象是否可选 End
                    //ai.SignableFlag = prd[0].SignableFlag__c;
                    //add by mzy 2021-02-04 LJPH-BX9CVX start

                }
            }
        }
        // HWAG-BA73ZP
        contractStartDateChange();
    }

    /**
     * 選択済み／未選択製品の置き換え
     */
    public PageReference exchangeAsset() {
        System.debug('exchangeAsset start');
        Date systemToday = System.today();
        List<AssetInfo> tmpChecked = new List<AssetInfo>();
        List<AssetInfo> tmpNewRows = new List<AssetInfo>();
        List<AssetInfo> tmpUnChecked = new List<AssetInfo>();
        for (AssetInfo ass : this.checkedAssets) {
            if (ass.isManual) {
                tmpNewRows.add(ass);
            } else if (ass.rec_checkBox_c) {
                tmpChecked.add(ass);
            } else {
                ass.mcae = null;
                tmpUnChecked.add(ass);
                totalRecords ++;
            }
        }
        for (AssetInfo ass : this.unCheckedAssets) {
            Boolean isNew = false;
            // add点检改善：新增一个点检对象复选框字段，默认为true 2021.6.8 fxk Star
            boolean isCheck = true;
            // add点检改善：新增一个点检对象复选框字段，默认为true 2021.6.8 fxk End
            Decimal listPrice = ass.rec.Maintenance_Price_Month__c;
            if (ass.rec_checkBox_c) {
                // xudan 20160110 新品判断ここ要らない、contractStartDateChangeがやる
//                if (systemToday.addMonths(-6) < ass.rec.InstallDate) {
//                if (estimate.Contract_Esti_Start_Date__c.addMonths(isNewAddMonth) < ass.rec.InstallDate) {
//                Date createdDate = estimate.CreatedDate == null ? systemToday : estimate.CreatedDate.date();
//                if (createdDate.addMonths(isNewAddMonth) < ass.rec.InstallDate) {
//                    isNew = true;
//                    listPrice = ass.rec.Maintenance_Price_Month__c * isNewPriceAdj;
//                }
                Maintenance_Contract_Asset_Estimate__c mcae = new Maintenance_Contract_Asset_Estimate__c(
                    isNew__c = isNew,
                    // add点检改善：新增一个点检对象复选框字段，默认为true 2021.6.8 fxk Star
                    Check_Object__c = isCheck,
                    // add点检改善：新增一个点检对象复选框字段，默认为true 2021.6.8 fxk end
                    Estimate_List_Price__c = listPrice
                );
                ass.mcae = mcae;
                tmpChecked.add(ass);
                totalRecords --;
            } else {
                ass.mcae = null;
                tmpUnChecked.add(ass);
            }
        }

        this.checkedAssets = new List<AssetInfo>();
        for (AssetInfo ass : tmpChecked) {
            ass.lineNo = this.checkedAssets.size();
            this.checkedAssets.add(ass);
        }
        for (AssetInfo ass : tmpNewRows) {
            ass.lineNo = this.checkedAssets.size();
            this.checkedAssets.add(ass);
        }
        this.unCheckedAssets = new List<AssetInfo>();
        this.unCheckedAssets.addAll(tmpUnChecked);

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

        //listCut(unCheckedAssets);
        // 根据合同开始日重新计算维修合同价格
        //contractStartDateChange();
        return null;
    }

    // 合同开始日变更，重新计算新品
    public PageReference contractStartDateChange() {
        Date systemToday = System.today();
        // 创建日
        Date createdDate = estimate.CreatedDate == null ? systemToday : estimate.CreatedDate.date();
        // 创建日3个月
        Date threeMonthAfter = createdDate.addMonths(keepPriceMonth);
        // 创建日6个月
        Date isNewAfter = createdDate.addMonths(-isNewAddMonth);
        // 合同开始日
        Date contractDate = estimate.Contract_Start_Date__c == null ? systemToday : estimate.Contract_Start_Date__c;

        /**********************HWAG-AYDCZX 2018/5/8 DEL START***************************/
        //// 合同开始日大于创建日6个月，都不算新品
        //if (contractDate >= isNewAfter) {
        //    system.debug('===== greater than createddate 6 months');
        //    for (AssetInfo info : checkedAssets) {
        //        if (!info.isManual) {
        //            info.mcae.isNew__c = false;
        //            info.mcae.Estimate_List_Price__c = info.orgPrice;
        //        } else if (info.isManual && !String.isBlank(info.mcae.Product_Manual__c)) {
        //            info.mcae.isNew__c = false;
        //            info.mcae.Estimate_List_Price__c = info.orgPrice;
        //        }
        //    }
        //}
        //// 合同开始日大于创建日3个月，使用合同开始日计算新品
        //else if (contractDate >= threeMonthAfter) {
        //    system.debug('===== greater than createddate 3 months');
        //    for (AssetInfo info : checkedAssets) {
        //        if (!info.isManual) {
        //            // xudan 20151224 新規、又はコピー、又は作成日から3ヶ月経過、又は3ヶ月以内且つ未提出、価格更新
        //            if (this.estimate.CreatedDate == null
        //                || String.isBlank(ApexPages.currentPage().getParameters().get('copyid')) == false
        //                || contractDate.addMonths(keepPriceMonth) < systemToday
        //                || this.estimate.Process_Status__c == '草案中') {

        //                info.mcae.isNew__c = false;
        //                info.mcae.Estimate_List_Price__c = info.orgPrice;

        //                // 110からの場合、Postあり、Installなし
        //                if (info.rec.Posting_Date__c != null && info.rec.InstallDate == null) {
        //                    if (contractDate.addMonths(isNewAddMonth) < info.rec.Posting_Date__c) {
        //                        info.mcae.isNew__c = true;
        //                        info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
        //                    }
        //                }
        //                // Installあり
        //                else if (info.rec.Posting_Date__c != null && info.rec.InstallDate != null) {
        //                    // Postから6月経ってもInstallしてない
        //                    if (info.rec.Posting_Date__c.addMonths(PosttoInstall) < info.rec.InstallDate) {
        //                        // 新品適用しない
        //                    }
        //                    else {
        //                        if (contractDate.addMonths(isNewAddMonth) < info.rec.InstallDate) {
        //                            info.mcae.isNew__c = true;
        //                            info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
        //                        }
        //                    }
        //                }
        //                // Postなし
        //                else if (info.rec.Posting_Date__c == null && info.rec.InstallDate != null) {
        //                    if (contractDate.addMonths(isNewAddMonth) < info.rec.InstallDate) {
        //                        info.mcae.isNew__c = true;
        //                        info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
        //                    }
        //                }
        //                // (info.rec.Posting_Date__c == null && info.rec.InstallDate == null)
        //                else {
        //                    // 特殊処理なし
        //                }
        //            }

        //            if (contractDate.addMonths(isNewAddMonth) < info.rec.InstallDate) {
        //                info.mcae.isNew__c = true;
        //                info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
        //            }

        //        } else if (info.isManual && !String.isBlank(info.mcae.Product_Manual__c)) {
        //            info.mcae.isNew__c = true;
        //            info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
        //        }
        //    }
        //}
        //// 使用创建日计算新品
        //else {
        //    system.debug('===== calculate by createddate');
        //    for (AssetInfo info : checkedAssets) {
        //        if (!info.isManual) {
        //            // xudan 20151224 新規、又は作成日から3ヶ月経過、又は3ヶ月以内且つ未提出、価格更新
        //            if (this.estimate.CreatedDate == null
        //                || String.isBlank(ApexPages.currentPage().getParameters().get('copyid')) == false
        //                || contractDate.addMonths(keepPriceMonth) < systemToday
        //                || this.estimate.Process_Status__c == '草案中') {

        //                info.mcae.isNew__c = false;
        //                info.mcae.Estimate_List_Price__c = info.orgPrice;

        //                // 110からの場合、Postあり、Installなし
        //                if (info.rec.Posting_Date__c != null && info.rec.InstallDate == null) {
        //                    if (createdDate.addMonths(isNewAddMonth) < info.rec.Posting_Date__c) {
        //                        info.mcae.isNew__c = true;
        //                        info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
        //                    }
        //                }
        //                // Installあり
        //                else if (info.rec.Posting_Date__c != null && info.rec.InstallDate != null) {
        //                    // Postから6月経ってもInstallしてない
        //                    if (info.rec.Posting_Date__c.addMonths(PosttoInstall) < info.rec.InstallDate) {
        //                        // 新品適用しない
        //                    }
        //                    else {
        //                        if (createdDate.addMonths(isNewAddMonth) < info.rec.InstallDate) {
        //                            info.mcae.isNew__c = true;
        //                            info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
        //                        }
        //                    }
        //                }
        //                // Postなし
        //                else if (info.rec.Posting_Date__c == null && info.rec.InstallDate != null) {
        //                    if (createdDate.addMonths(isNewAddMonth) < info.rec.InstallDate) {
        //                        info.mcae.isNew__c = true;
        //                        info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
        //                    }
        //                }
        //                // (info.rec.Posting_Date__c == null && info.rec.InstallDate == null)
        //                else {
        //                    // 特殊処理なし
        //                }
        //            }
        //            /*
        //            if (createdDate.addMonths(isNewAddMonth) < info.rec.InstallDate) {
        //                info.mcae.isNew__c = true;
        //                info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
        //            }
        //            */
        //        } else if (info.isManual && !String.isBlank(info.mcae.Product_Manual__c)) {
        //            info.mcae.isNew__c = true;
        //            info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
        //        }
        //    }
        //}
        /**********************HWAG-AYDCZX 2018/5/8 DEL END***************************/
        /**********************HWAG-AYDCZX 2018/5/8 ADD START***************************/
        // 新规、再报价、草案中 维修合同价格显示
        System.debug('********changedAfterPrint:' + (changedAfterPrint ? 'true' : 'false'));
        if (this.estimate.CreatedDate == null
                || String.isBlank(ApexPages.currentPage().getParameters().get('copyid')) == false
                || this.estimate.Process_Status__c == '草案中'
                || changedAfterPrint) {
            for (AssetInfo info : checkedAssets) {
                System.debug('********contractDate changed:' + String.valueOf(contractDate));
                // 合同开始日大于创建日6个月，都不算新品
                if (contractDate >= isNewAfter) {
                    if (!info.isManual) {
                        info.mcae.isNew__c = false;
                        info.mcae.Estimate_List_Price__c = info.orgPrice;
                    } else if (info.isManual && !String.isBlank(info.mcae.Product_Manual__c)) {
                        info.mcae.isNew__c = false;
                        info.mcae.Estimate_List_Price__c = info.orgPrice;
                    }
                }
                // 合同开始日大于创建日3个月，使用合同开始日计算新品
                // 使用创建日计算新品
                else {
                    Date isNewDate = null;
                    if (contractDate >= threeMonthAfter) {
                        isNewDate = contractDate;
                    } else {
                        isNewDate = createdDate;
                    }
                    if (!info.isManual) {
                        info.mcae.isNew__c = false;
                        info.mcae.Estimate_List_Price__c = info.orgPrice;

                        // 110からの場合、Postあり、Installなし
                        if (info.rec.Posting_Date__c != null && info.rec.InstallDate == null) {
                            if (isNewDate.addMonths(isNewAddMonth) < info.rec.Posting_Date__c) {
                                info.mcae.isNew__c = true;
                                info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
                            }
                        }
                        // Installあり
                        else if (info.rec.Posting_Date__c != null && info.rec.InstallDate != null) {
                            // Postから6月経ってもInstallしてない
                            if (info.rec.Posting_Date__c.addMonths(PosttoInstall) < info.rec.InstallDate) {
                                // 新品適用しない
                            } else {
                                if (isNewDate.addMonths(isNewAddMonth) < info.rec.InstallDate) {
                                    info.mcae.isNew__c = true;
                                    info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
                                }
                            }
                        }
                        // Postなし
                        else if (info.rec.Posting_Date__c == null && info.rec.InstallDate != null) {
                            if (isNewDate.addMonths(isNewAddMonth) < info.rec.InstallDate) {
                                info.mcae.isNew__c = true;
                                info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
                            }
                        } else {
                            // 特殊処理なし
                        }
                    } else if (info.isManual && !String.isBlank(info.mcae.Product_Manual__c)) {
                        info.mcae.isNew__c = true;
                        info.mcae.Estimate_List_Price__c = info.orgPrice * isNewPriceAdj;
                    }
                }
            }
        }
        // 新规、草案中以外
        //else {
        //    for (AssetInfo info : checkedAssets) {
        //        if ((!info.isManual) || (info.isManual && !String.isBlank(info.mcae.Product_Manual__c)) ) {
        //            boolean isNewChange =false;
        //            // 合同开始日大于创建日6个月，都不算新品
        //            if (contractDate >= isNewAfter) {
        //            }
        //            // 合同开始日大于创建日3个月，使用合同开始日计算新品
        //            // 使用创建日计算新品
        //            else {
        //                if (contractDate.addMonths(keepPriceMonth) < systemToday) {
        //                    Date isNewDate = null;
        //                    if (contractDate >= threeMonthAfter) {
        //                        isNewDate = contractDate;
        //                    } else {
        //                        isNewDate = createdDate;
        //                    }
        //                    if (!info.isManual) {
        //                        if (info.rec.Posting_Date__c != null && info.rec.InstallDate == null) {
        //                            if (isNewDate.addMonths(isNewAddMonth) < info.rec.Posting_Date__c) {
        //                                isNewChange = true;
        //                            }
        //                        }
        //                        // Installあり
        //                        else if (info.rec.Posting_Date__c != null && info.rec.InstallDate != null) {
        //                            // Postから6月経ってもInstallしてない
        //                            if (info.rec.Posting_Date__c.addMonths(PosttoInstall) < info.rec.InstallDate) {
        //                                // 新品適用しない
        //                            }
        //                            else {
        //                                if (isNewDate.addMonths(isNewAddMonth) < info.rec.InstallDate) {
        //                                    isNewChange = true;
        //                                }
        //                            }
        //                        }
        //                        // Postなし
        //                        else if (info.rec.Posting_Date__c == null && info.rec.InstallDate != null) {
        //                            if (isNewDate.addMonths(isNewAddMonth) < info.rec.InstallDate) {
        //                                isNewChange = true;
        //                            }
        //                        }
        //                        else {
        //                            // 特殊処理なし
        //                        }
        //                    } else if (info.isManual && !String.isBlank(info.mcae.Product_Manual__c)) {
        //                        isNewChange = true;
        //                    }
        //                }
        //            }
        //            if (isNewChange != info.mcae.isNew__c) {
        //                changedSubmitPrice = true;
        //            }
        //            if (info.mcae.isNew__c) {
        //                if (info.mcae.Estimate_List_Price__c.setScale(2) != (info.orgPrice * isNewPriceAdj).setScale(2)) {
        //                    changedSubmitPrice = true;
        //                }
        //            } else {
        //                if (info.mcae.Estimate_List_Price__c.setScale(2) != info.orgPrice.setScale(2)) {
        //                    changedSubmitPrice = true;
        //                }
        //            }
        //        }
        //    }
        //}

        /**********************HWAG-AYDCZX 2018/5/8 ADD END***************************/

        return null;
    }

    /**
     * 保存メソッド
     */
    public PageReference save() {
        System.debug('save start');
        //add by rentx 2020-11-13 LJPH-BV93RZ start
        if (estimate.Contract_Range__c == null) {
            this.estimate.Contract_Range__c.addError('必须输入合同月数!');
            return null;
        }
        NextMaintenanceContract();
        //add by rentx 2020-11-13 LJPH-BV93RZ end
        // add 维修合同报价，保存时，把记录类型赋值一下 2021.6.8 fxk start
        Id Maintenance_Contract = Schema.SObjectType.Maintenance_Contract_Estimate__c.getRecordTypeInfosByDeveloperName().get('Maintenance_Quote').getRecordTypeId();
        estimate.recordtypeid = Maintenance_Contract;
        // add 维修合同报价，保存时，把记录类型赋值一下 2021.6.8 fxk end
        if (changedSubmitPrice) {
            priceChangeReset();
            return null;
        }
        if (syncEstimate(false, false)) {
            ComputeLTYRepair();
            return new PageReference('/' + this.targetEstimateId + '/e?completion=5');
        }
        return null;
    }

    /**
     * 印刷メソッド、decide前は保有設備、decide後は合同配置
     */
    public void print() {
        System.debug('print start');
        this.printAsset = false;
        this.printContract = false;
        this.printTripartite = false;
        this.printAgent = false;
        this.estimate.PrintDate__c = Date.today();
        //SelectAssetEstimateController.ComputeLTYRepair(targetEstimateId);
        if (this.estimate.Quote_Date__c == null) {
            this.estimate.Quote_Date__c = Date.today();
        }



        if (this.estimate.Print_Tripartite__c && this.estimate.Print_Agent__c) {
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, '不能同时选中三方协议和代理商合同！'));
        } else


            // 保存ボタンできない場合、印刷ボタンはフラグのみ保存
            if (this.getSaveBtnDisabled()) {
                if (savePrintFlg()) {
                    // 2018/10/26 HWAG-B5C88S 原来打印逻辑 start
                    /*if (this.estimate.Print_Contract__c && !this.estimate.Print_Tripartite__c && !this.estimate.Print_Agent__c) {
                        // 打印医院合同配置
                        this.printContract = true;
                    } else if(this.estimate.Print_Tripartite__c && !this.estimate.Print_Agent__c){
                        //打印三方合同
                        this.printTripartite = true;
                    } else if(!this.estimate.Print_Tripartite__c && this.estimate.Print_Agent__c){
                        //打印经销商合同
                        this.printAgent = true;
                    }else{
                        // 打印保有設備
                        this.printAsset = true;
                    }*/
                    // 2018/10/26 HWAG-B5C88S 原来打印逻辑 end
                    // 2018/10/26 HWAG-B5C88S start 选择三方打印三方，否则decide前打印保有设备，decide后根据报价对象打印医院或经销商合同
                    if (this.estimate.Print_Tripartite__c ) {
                        //打印三方合同
                        this.printTripartite = true;
                    } else if (!this.estimate.Estimation_Decision__c) {
                        this.printAsset = true;

                    } else if (this.estimate.Estimate_Target__c != null && this.estimate.Estimate_Target__c.equals('医院')) {
                        this.printContract = true;

                    } else if (this.estimate.Estimate_Target__c != null && this.estimate.Estimate_Target__c.equals('经销商')) {
                        this.printAgent = true;
                    }
                    // 2018/10/26 HWAG-B5C88S end
                }
            }
        // 保存ボタンできる場合、印刷ボタンは全部保存
            else {
                if (syncEstimate(false, false)) {
                    // 2018/10/26 HWAG-B5C88S 原来打印逻辑 start
                    /*
                    if (this.estimate.Print_Contract__c && !this.estimate.Print_Tripartite__c && !this.estimate.Print_Agent__c) {
                        // 打印医院合同配置
                        this.printContract = true;
                    } else if(this.estimate.Print_Tripartite__c && !this.estimate.Print_Agent__c){
                        //打印三方合同
                        this.printTripartite = true;
                    } else if(!this.estimate.Print_Tripartite__c && this.estimate.Print_Agent__c){
                        //打印经销商合同
                        this.printAgent = true;
                    }else{
                        // 打印保有設備
                        this.printAsset = true;
                    }
                    */
                    // 2018/10/26 HWAG-B5C88S 原来打印逻辑 end
                    // 2018/10/26 HWAG-B5C88S start 选择三方打印三方，否则decide前打印保有设备，decide后根据报价对象打印医院或经销商合同
                    if (this.estimate.Print_Tripartite__c ) {
                        //打印三方合同
                        this.printTripartite = true;
                    } else if (!this.estimate.Estimation_Decision__c) {
                        this.printAsset = true;

                    } else if (this.estimate.Estimate_Target__c != null && this.estimate.Estimate_Target__c.equals('医院')) {
                        this.printContract = true;

                    } else if (this.estimate.Estimate_Target__c != null && this.estimate.Estimate_Target__c.equals('经销商')) {
                        this.printAgent = true;
                    }
                    // 2018/10/26 HWAG-B5C88S end
                }
            }
        //ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, '合同'+this.printContract +'三方'+this.printTripartite+'保有'+this.printAsset+'经销商合同'+this.printAgent));
    }

    /**
     * 申請メソッド、最後必ず承認プロセスに載せる
     */
    public PageReference approvalProcess() {

        //SelectAssetEstimateController Sc2 = new SelectAssetEstimateController();
        //Sc2.targetEstimateId = this.targetEstimateId;
        //Sc2.ComputeLTYRepair();

        System.debug('approvalProcess start');
        if (changedSubmitPrice) {
            priceChangeReset();
            return null;
        }
        if (syncEstimate(true, false)) {
            Savepoint sp = Database.setSavepoint();
            // 承認プロセスに載せる
            try {
                // 已填写申请状态
                this.estimate.ApprovalProcess_Status__c = '已填写完并申请';
                ControllerUtil.updateMaintenance_Contract_Estimate(new Maintenance_Contract_Estimate__c[] {this.estimate});
                // 承認プロセス
                Approval.ProcessSubmitRequest psr = new Approval.ProcessSubmitRequest();
                psr.setObjectId(this.estimate.id);
                Approval.ProcessResult submitResult = Approval.process(psr);
                if (changedAfterPrint) {
                    return new PageReference('/' + this.targetEstimateId + '/e?completion=1');
                } else {
                    return new PageReference('/' + this.targetEstimateId + '/e?completion=2');
                }
            } catch (Exception ex) {
                System.debug('=====Exception:' + ex.getMessage());
                Database.rollback(sp);
                this.estimate.ApprovalProcess_Status__c = null;
                ApexPages.addMessages(ex);
            }
        }
        return null;
    }

    /**
     * 決定取消メソッド
     */
    public PageReference undecide() {
        System.debug('undecide start');
        this.estimate.Estimation_Decision__c = false;
        this.estimate.Print_Contract__c = false;

        // 删除报价日期
        this.estimate.Quotation_Determines_Time__c = null;

        try {
            ControllerUtil.updateMaintenance_Contract_Estimate(new Maintenance_Contract_Estimate__c[] {this.estimate});
            return new PageReference('/' + this.targetEstimateId + '/e?completion=1');
        } catch (Exception ex) {
            ApexPages.addMessages(ex);
        }
        return null;
    }

    /**
     * 決定メソッド
     */
    public PageReference decide() {
        System.debug('decide start');         
        NextMaintenanceContract();
        inDicideFlag = true;
        // TODO check decide 资格
        Savepoint sp = Database.setSavepoint();
        if (syncEstimate(false, true)) {
            if (changedAfterPrint) {
                return new PageReference('/' + this.targetEstimateId + '/e?completion=1');
            } else {
                return new PageReference('/' + this.targetEstimateId + '/e?completion=3');
            }
        }

        return null;
    }
    //  public PageReference dosomething() {
    //     System.debug('dosomething start');
    //     NextMaintenanceContract();
    //     return null;
    // }
    public void NextMaintenanceContract() {
            // 20220810 询价2期开发
        List<String> asslocalList = new List<String>();
        List<String> mcalocalList = new List<String>();
        Map<Id, Maintenance_Contract__c> map3 = new Map<Id, Maintenance_Contract__c>();
        
        List<Maintenance_Contract_Asset__c> mcaupdateList = new List<Maintenance_Contract_Asset__c>();
        for (AssetInfo ass : this.checkedAssets) {
            if (!ass.isManual) {
                asslocalList.add(ass.rec.Id);
                map3.put(ass.rec.Id,this.contract);
            }
        }
        System.debug('asslocalList====%%%' +asslocalList);
         List<Maintenance_Contract_Asset__c> mcalist1 = [select id,Asset__c,Next_Maintenance_Contract__c,Maintenance_Contract__c
                                             from Maintenance_Contract_Asset__c
                                            where id in (select CurrentContract_F_asset__c
                                                                from asset
                                                                where id in :asslocalList and CurrentContract_F_asset__c!=null)];
            System.debug('mcalist1====%%%' +mcalist1);
            System.debug('map3====%%%' +map3);
        for (Maintenance_Contract_Asset__c mca : mcalist1) {
            Maintenance_Contract_Asset__c mca3 = new Maintenance_Contract_Asset__c();
            if (map3.containsKey(mca.Asset__c)) {
                mca3.id = mca.id;
                mca3.Next_Maintenance_Contract__c = map3.get(mca.Asset__c).id;
                System.debug('mca3.id====%%%' +mca3.id);
                if (mca3.id!=null&&!mcaupdateList.contains(mca3)) {
                    mcaupdateList.add(mca3);
                }
            }
        }
        System.debug('mcaupdateList====%%%' +mcaupdateList);
        if (mcaupdateList!=null&&!mcaupdateList.isEmpty()) {
            update mcaupdateList;
        }    
        System.debug('更新完成mcaupdateList');
    }

    public PageReference decideCancle() {

        return new PageReference('/' + this.targetEstimateId + '/e?completion=4');

    }

    /**
     * Process用のユーザー情報をセット、新規見積もり時用
     */

    private void setApprovalManager() {
        User loginUser = [SELECT Id, Name, JingliApprovalManager__c, BuchangApprovalManager__c, ZongjianApprovalManager__c, TongkuoZongjian__c FROM User WHERE Id = :UserInfo.getUserId()];
        // 要注意 SaveMaintenanceByCopyController と copyのurlにも、下記の項目もクリア
        this.estimate.JingliApprovalManager__c = loginUser.JingliApprovalManager__c == null ? loginUser.Id : loginUser.JingliApprovalManager__c;
        this.estimate.BuchangApprovalManager__c = loginUser.BuchangApprovalManager__c == null ? loginUser.Id : loginUser.BuchangApprovalManager__c;
        this.estimate.ZongjianApprovalManager__c = loginUser.ZongjianApprovalManager__c == null ? loginUser.Id : loginUser.ZongjianApprovalManager__c;
        this.estimate.Service_Contract_Staff__c = this.contract.Service_Contract_Staff__c;
        this.estimate.TKZongjianApprovalManager__c = loginUser.TongkuoZongjian__c == null ? loginUser.Id : loginUser.TongkuoZongjian__c;
    }

    /**
    * 印刷フラグのみを保存
    */
    @TestVisible
    private Boolean savePrintFlg() {
        try {
            Maintenance_Contract_Estimate__c mce = new Maintenance_Contract_Estimate__c();
            mce.Id = this.targetEstimateId;
            mce.Print_ListPrice__c = this.estimate.Print_ListPrice__c;
            mce.Print_RepairPrice__c = this.estimate.Print_RepairPrice__c;
            mce.Print_SumPrice__c = this.estimate.Print_SumPrice__c;
            mce.Print_DiscountPercentage__c = this.estimate.Print_DiscountPercentage__c;
            mce.Print_DiscountPrice__c = this.estimate.Print_DiscountPrice__c;
            mce.Print_MaintePrice__c = this.estimate.Print_MaintePrice__c;
            mce.Print_Contract__c = this.estimate.Print_Contract__c;

            ControllerUtil.updateMaintenance_Contract_Estimate(new Maintenance_Contract_Estimate__c[] {mce});
            return true;
        } catch (Exception ex) {
            ApexPages.addMessages(ex);
        }
        return false;
    }

    /**
     * 画面で入力データcheck, save, 親と同期 のロジック
     */
    // TODO xudan チェック追加、clsにも合計金額を計算、clsの合計金額と画面からjsの合計金額を比較
    // 異なる場合、保存完了したらwarningを出す
    private Boolean syncEstimate(boolean isApproval, boolean isDecide) {
        System.debug('syncEstimate start');
        Boolean hasDatabaseError = false;
        Savepoint sp = Database.setSavepoint();

        try {
            if (!checkValidate()) {
                return false;
            }
            if (checkChangedAfterPrint()) {
                if (isDecide) {
                    // まず Approval
                    isApproval = true;
                    isDecide = false;
                }
            }
            //>>>
            if (isApproval || isDecide) {
                Boolean hasError = false;
                if (this.estimate.Maintenance_Price__c <= 0) {
                    this.estimate.Maintenance_Price__c.addError('合同价格必需大于0');
                    hasError = true;
                }
                /*for (AssetInfo input : this.checkedAssets) {
                    if (!input.isManual || input.isManual && !String.isBlank(input.mcae.Product_Manual__c)) {
                        if (String.isBlank(input.mcae.Check_Result__c)) {
                            input.mcae.Check_Result__c.addError('点检结果必填');
                            hasError = true;
                        }
                    }
                }*/
                if (this.estimate.Discount_Price__c > 0 && String.isBlank(this.estimate.Discount_reason__c)) {
                    this.estimate.Discount_Price__c.addError('减价申请理由必填');
                    hasError = true;
                }
                if (this.estimate.Discount_Price__c > 0 && String.isBlank(this.estimate.Improve_ConsumptionRate_Idea__c)) {
                    this.estimate.Improve_ConsumptionRate_Idea__c.addError('消费率改善方案必填');
                    hasError = true;
                }
                if (hasError) {
                    return false;
                }
            }
            if (isDecide && getDecideBtnDisabled()) {
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, '已经是Decide过的合同 或 不是批准的报价，不能Decide'));
                return false;
            }
            // 追加上期合同信息 start
            List<lastMContract> lastMContractRes = getlastMContract(this.checkedAssets);
            this.estimate.LastMContract1__c = lastMContractRes[0].contractId ;
            this.estimate.LastMContract1_NO__c = lastMContractRes[0].contractNo ;
            this.estimate.LastMContract1_ConCount__c = lastMContractRes[0].count ;

            this.estimate.LastMContract2__c = lastMContractRes[1].contractId ;
            this.estimate.LastMContract2_NO__c = lastMContractRes[1].contractNo ;
            this.estimate.LastMContract2_ConCount__c = lastMContractRes[1].count ;

            this.estimate.LastMContract3__c = lastMContractRes[2].contractId ;
            this.estimate.LastMContract3_NO__c = lastMContractRes[2].contractNo ;
            this.estimate.LastMContract3_ConCount__c = lastMContractRes[2].count ;

            this.estimate.LastMContract4__c = lastMContractRes[3].contractId ;
            this.estimate.LastMContract4_NO__c = lastMContractRes[3].contractNo ;
            this.estimate.LastMContract4_ConCount__c = lastMContractRes[3].count ;

            this.estimate.LastMContract5__c = lastMContractRes[4].contractId ;
            this.estimate.LastMContract5_NO__c = lastMContractRes[4].contractNo ;
            this.estimate.LastMContract5_ConCount__c = lastMContractRes[4].count ;

            // 追加上期合同信息 end
            // 同期処理
            // ①维修合同に既存の保有设备を削除
            // ②保存した维修合同报价の保有设备を维修合同にコピー(Asset__cが設定さているデータだけ)
            // ③他の维修合同报价の同期フラグを外す
            // ④维修合同の Estimate_Trial_Money__c、Contract_Amount__c, Service_contract_target_number__c を更新
            this.estimate.IsSyncing__c = true;
            if (isDecide) {

                // 添加决定报价日期
                this.estimate.Quotation_Determines_Time__c = date.today();

                // 报价决定
                this.estimate.Estimation_Decision__c = true;
            }
            // TODO validate

            // TODO validate check新品チェック（納品日で判断）

            // save
            // ③ start
            for (List<Maintenance_Contract_Estimate__c> otherEstimates : [select Id from Maintenance_Contract_Estimate__c where Id <> :this.estimate.Id
                    and Maintenance_Contract__c = :this.contract.Id
                                                  and IsSyncing__c = true]) {
                for (Maintenance_Contract_Estimate__c other : otherEstimates) {
                    other.IsSyncing__c = false;
                    if (isDecide) {
                        other.Estimation_Decision__c = false;
                    }
                }
                ControllerUtil.updateMaintenance_Contract_Estimate(otherEstimates);
            }

            // 合同结束预定日を算出
            Date t = this.estimate.Contract_Esti_Start_Date__c.addMonths(Integer.valueOf(this.estimate.Contract_Range__c));
            // 20151217 xudan 维修合同报价SH-RS-JS0046560-01 期间显示问题
            // うるう年特殊対応
            if (this.estimate.Contract_Esti_Start_Date__c.month() == 2 && this.estimate.Contract_Esti_Start_Date__c.day() == 29
                    && t.month() == 2) {
                t = t;
            } else {
                t = t.addDays(-1);
            }

            this.estimate.Contract_Esti_End_Date__c = t;

            // 合同开始日を结束日
            if (this.estimate.Contract_Start_Date__c == null) {
                this.estimate.Contract_Start_Date__c = this.estimate.Contract_Esti_Start_Date__c;
            }
            t = this.estimate.Contract_Start_Date__c.addMonths(Integer.valueOf(this.estimate.Contract_Range__c));
            t = t.addDays(-1);
            this.estimate.Contract_End_Date__c = t;
            Date createdDate = this.estimate.CreatedDate == null ? System.today() : this.estimate.CreatedDate.date();
            // ３ヶ月超過している場合には、Decideできない
            //if (createdDate.addMonths(3) <= System.today()) {
            //    this.estimate.addError('已超过3个月，请先更新报价。');
            //    return false;
            //}

            // 维修合同报价
            if (String.isBlank(this.targetEstimateId)) {
                this.estimate.Process_Status__c = '草案中';
                // nameに番号をセット
                List<Maintenance_Contract_Estimate__c> maxNameRecords = [select Name From Maintenance_Contract_Estimate__c Where Maintenance_Contract__c = :this.contract.Id order by Name desc limit 1];
                String oppNo;
                Integer l = 1;
                if (maxNameRecords.size() > 0) {
                    try {
                        oppNo = maxNameRecords[0].Name;
                        l = Integer.valueOf(oppNo.substring(oppNo.length() - 2)) + 1;
                    } catch (System.TypeException e) {
                        System.debug('maxNameRecords Error: Maintenance_Contract__c.id=' + maxNameRecords[0].id);
                    }
                } else {
                    System.debug('first Maintenance_Contract_Estimate__c');
                }
                oppNo = '00' + String.valueof(l);
                oppNo = oppNo.substring(oppNo.length() - 2);
                this.estimate.Name = this.contract.Management_Code__c + '-' + oppNo;
                setApprovalManager();
                System.debug('Process_Status__c=' + this.estimate.Process_Status__c);
                insert this.estimate;
                this.targetEstimateId = this.estimate.Id;
                setThisEstimate();
            } else {
                if (isApproval) {
                    setApprovalManager();
                }
                ControllerUtil.updateMaintenance_Contract_Estimate(new Maintenance_Contract_Estimate__c[] {this.estimate});
            }
            // 维修合同报价/保有设备
            // delete and insertする
            List<Maintenance_Contract_Asset_Estimate__c> insertTarget = new List<Maintenance_Contract_Asset_Estimate__c>();
            for (AssetInfo input : this.checkedAssets) {
                if (!input.isManual || input.isManual && !String.isBlank(input.mcae.Product_Manual__c)) {
                    //Maintenance_Contract_Asset_Estimate__c mcae = new Maintenance_Contract_Asset_Estimate__c();
                    input.mcae.Id = null;                               // insertのため
                    // 同じの場合設定しない
                    if (input.mcae.Maintenance_Contract_Estimate__c != this.targetEstimateId) {
                        // 親変更できない可能性があるため、設定するときエラーになるが、エラーにならないように他のロジックを工夫してください。
                        input.mcae.Maintenance_Contract_Estimate__c = this.targetEstimateId;
                    }
                    input.mcae.Maintenance_Price_Month__c = input.rec.Maintenance_Price_Month__c;
                    // 病院に所属する保有設備
                    if (!input.isManual) {
                        input.mcae.Asset__c = input.rec.Id;
                        input.mcae.Product_Manual__c = null;
                    }
                    // Manual商品
                    if (input.isManual && !String.isBlank(input.mcae.Product_Manual__c)) {
                        input.mcae.Asset__c = null;
                        //mcae.Product_Manual__c = input.mcae.Product_Manual__c;
                    }
                    //mcae.Estimate_List_Price__c = input.mcae.Estimate_List_Price__c;
                    //mcae.IsNew__c = input.mcae.isNew__c;
                    //mcae.Check_Result__c = input.mcae.Check_Result__c;
                    //mcae.Repair_Price__c = input.mcae.Repair_Price__c;
                    //mcae.Comment__c = input.mcae.Comment__c;
                    insertTarget.add(input.mcae);
                }
            }
            // 本当に保存した納入機器があれば削除
            List<Maintenance_Contract_Asset_Estimate__c> selectedAsset = [SELECT Id, Name, Maintenance_Contract_Estimate__c, Asset__c, IsNew__c FROM Maintenance_Contract_Asset_Estimate__c WHERE Maintenance_Contract_Estimate__c = :this.targetEstimateId];
            if (selectedAsset.size() > 0) {
                ControllerUtil.deleteMaintenance_Contract_Asset_Estimate(selectedAsset);
            }
            if (insertTarget.size() > 0) {
                ControllerUtil.insertMaintenance_Contract_Asset_Estimate(insertTarget);
            }

            // ① start
            for (List<Maintenance_Contract_Asset__c> oldList : [select Id from Maintenance_Contract_Asset__c
                    where Maintenance_Contract__c = :this.estimate.Maintenance_Contract__c]) {
                delete oldList;
            }
            // ② start
            {
                List<Maintenance_Contract_Asset__c> newValue = new List<Maintenance_Contract_Asset__c>();
                for (Maintenance_Contract_Asset_Estimate__c target : [select Id, Asset__c, Estimate_List_Price__c,
                        //add 点检改善：合同保有设备下的点检对象与报价保有设备下的点检对象同步 2021.6.9 fxk start
                        Check_Object__c,
                        //add 点检改善：合同保有设备下的点检对象与报价保有设备下的点检对象同步 2021.6.9 fxk end
                        IsNew__c from Maintenance_Contract_Asset_Estimate__c
                        where Maintenance_Contract_Estimate__c = :this.estimate.Id and Asset__c <> null]) {
                    Maintenance_Contract_Asset__c newVal = new Maintenance_Contract_Asset__c(
                        Maintenance_Contract__c = this.estimate.Maintenance_Contract__c,
                        Asset__c = target.Asset__c,
                        Maintenance_Contract_Asset_Estimate__c = target.Id,
                        Estimate_List_Price__c = target.Estimate_List_Price__c,
                        Estimate_IsNew__c = target.IsNew__c,
                        //add 点检改善：合同保有设备下的点检对象与报价保有设备下的点检对象同步 2021.6.9 fxk start
                        Check_Object__c = target.Check_Object__c
                                          //add 点检改善：合同保有设备下的点检对象与报价保有设备下的点检对象同步 2021.6.9 fxk end
                    );
                    newValue.add(newVal);
                }
                if (newValue.size() > 0) insert newValue;
            }
            // ④ start
            this.contract.Estimation_Id__c = this.targetEstimateId;
            this.contract.Contract_Esti_Start_Date__c = this.estimate.Contract_Esti_Start_Date__c;
            this.contract.Contract_Range__c = this.estimate.Contract_Range__c;
            this.contract.Contract_Esti_End_Date__c = this.estimate.Contract_Esti_End_Date__c;
            this.contract.Estimate_Target__c = this.estimate.Estimate_Target__c;
            this.contract.Dealer__c = this.estimate.Dealer__c;
            this.contract.NotUse_Oxygenated_Water__c = this.estimate.NotUse_Oxygenated_Water__c;
            this.contract.Estimate_Trial_Money__c = this.estimate.Estimate_Trial_Money__c;
            this.contract.Contract_Amount__c = this.estimate.Maintenance_Price__c;
            this.contract.Service_contract_target_number__c = this.estimate.Service_contract_target_number__c;
            this.contract.Contract_department_manual__c = this.estimate.Department__c;


            // 追加上期合同信息 start
            this.contract.LastMContract1__c = this.estimate.LastMContract1__c ;
            this.contract.LastMContract1_NO__c = this.estimate.LastMContract1_NO__c ;
            this.contract.LastMContract1_ConCount__c =  this.estimate.LastMContract1_ConCount__c;
            //add by rentx 2021-04-22 给合同1赋值的同时，给去年合同赋值 start
            this.contract.Last_year_service_contract__c = this.estimate.LastMContract1__c;
            //add by renrx 2021-04-22 给合同1赋值的同时, 给去年合同赋值 end

            this.contract.LastMContract2__c =  this.estimate.LastMContract2__c;
            this.contract.LastMContract2_NO__c = this.estimate.LastMContract2_NO__c ;
            this.contract.LastMContract2_ConCount__c =  this.estimate.LastMContract2_ConCount__c;

            this.contract.LastMContract3__c =  this.estimate.LastMContract3__c;
            this.contract.LastMContract3_NO__c = this.estimate.LastMContract3_NO__c ;
            this.contract.LastMContract3_ConCount__c =  this.estimate.LastMContract3_ConCount__c;

            this.contract.LastMContract4__c =  this.estimate.LastMContract4__c;
            this.contract.LastMContract4_NO__c = this.estimate.LastMContract4_NO__c ;
            this.contract.LastMContract4_ConCount__c =  this.estimate.LastMContract4_ConCount__c;

            this.contract.LastMContract5__c =  this.estimate.LastMContract5__c;
            this.contract.LastMContract5_NO__c = this.estimate.LastMContract5_NO__c ;
            this.contract.LastMContract5_ConCount__c =  this.estimate.LastMContract5_ConCount__c;
            // 追加上期合同信息 end


            system.debug('测算isDecide的结果_1::::::::' + isDecide);
            if (isDecide == true) {
                system.debug('测算isDecide的结果_2::::::::' + isDecide);
//              this.contract.Contract_Start_Date__c = this.estimate.Contract_Esti_Start_Date__c;
                this.contract.Contract_Start_Date__c = this.estimate.Contract_Start_Date__c;
                this.contract.Contract_Range__c = this.estimate.Contract_Range__c;
//              this.contract.Contract_End_Date__c = this.estimate.Contract_Esti_End_Date__c;
                this.contract.Contract_End_Date__c = this.estimate.Contract_End_Date__c;
                this.contract.JingliApprovalManager__c = this.estimate.JingliApprovalManager__c;
                this.contract.BuchangApprovalManager__c = this.estimate.BuchangApprovalManager__c;
                this.contract.ZongjianApprovalManager__c = this.estimate.ZongjianApprovalManager__c;
                this.contract.Finally_Approved_Staff__c = this.estimate.Finally_Approved_Staff__c;
                this.contract.TKZongjianApprovalManager__c = this.estimate.TKZongjianApprovalManager__c;
            }
            //添加的额外对应过程
            if (inDicideFlag == true && (this.contract.Contract_Start_Date__c == null || this.contract.Contract_End_Date__c == null)) {
                system.debug('测算inDicideFlag的结果_2::::::::' + isDecide);
//              this.contract.Contract_Start_Date__c = this.estimate.Contract_Esti_Start_Date__c;
                this.contract.Contract_Start_Date__c = this.estimate.Contract_Start_Date__c;
                this.contract.Contract_Range__c = this.estimate.Contract_Range__c;
//              this.contract.Contract_End_Date__c = this.estimate.Contract_Esti_End_Date__c;
                this.contract.Contract_End_Date__c = this.estimate.Contract_End_Date__c;
                this.contract.JingliApprovalManager__c = this.estimate.JingliApprovalManager__c;
                this.contract.BuchangApprovalManager__c = this.estimate.BuchangApprovalManager__c;
                this.contract.ZongjianApprovalManager__c = this.estimate.ZongjianApprovalManager__c;
                this.contract.Finally_Approved_Staff__c = this.estimate.Finally_Approved_Staff__c;
                this.contract.TKZongjianApprovalManager__c = this.estimate.TKZongjianApprovalManager__c;
            }
            String oldProcessStatus = this.estimate.Process_Status__c;
            try {
                ControllerUtil.updateMaintenance_Contract_Estimate(new Maintenance_Contract_Estimate__c[] {this.estimate});
                update this.contract;
            } catch (Exception e) {
                // TODO 今後複数件の場合どうする？
                this.estimate.addError(e);
                // 一部の値を戻す
                this.estimate.Process_Status__c = oldProcessStatus;
                hasDatabaseError = true;
                Database.rollback(sp);
                ApexPages.addMessages(e);
            }
            if (hasDatabaseError) {
                System.debug('syncEstimate hasDatabaseError');
                return false;
            }
            if (isApproval) {
                SelectAssetEstimateController.ComputeLTYRepair(targetEstimateId);
            }
            return true;
        } catch (DMLException ex) {
            // TODO Insert失敗のIDを消す必要？
            Database.rollback(sp);
            ApexPages.addMessages(ex);
        } catch (Exception ex) {
            Database.rollback(sp);
            ApexPages.addMessages(ex);
        }

        return false;
    }

    /**
     * 印刷後変更がある場合、true
     */
    @TestVisible
    private Boolean checkChangedAfterPrint() {
        System.debug('checkChangedAfterPrint start');
        if (changedAfterPrint) {
            this.targetEstimateId = null;
            this.estimate = this.estimate.clone();
            this.estimate.IS_Clone_After_Decide__c = true;
            this.estimate.PrintDate__c = null;
            this.estimate.Quote_Date__c = null;
            this.estimate.Print_Contract__c = false;
            this.estimate.Print_RepairPrice__c = false;
            this.estimate.Print_DiscountPercentage__c = false;
            this.estimate.Print_DiscountPrice__c = false;
            this.estimate.Print_ListPrice__c = false;
            this.estimate.Print_MaintePrice__c = false;
            this.estimate.Print_SumPrice__c = false;
            this.estimate.NotUse_Oxygenated_Water__c = false;
            this.estimate.Contract_Esti_Start_Date__c = this.estimate.Contract_Start_Date__c;
            //this.estimate.Process_Status__c = '草案中';
        }
        return changedAfterPrint;
    }

    /**
     * 行追加(10行ずつ)、前提必ず最後
     */
    public PageReference addNewRows() {
        for (Integer i = 0; i < 10; i++) {
            checkedAssets.add(new AssetInfo(checkedAssets.size()));
        }
        return null;
    }

    /** 保存返回 **/
    public PageReference saveAndCancel () {
        //add by rentx 2020-11-13 LJPH-BV93RZ start
        if (estimate.Contract_Range__c == null) {
            this.estimate.Contract_Range__c.addError('必须输入合同月数!');
            return null;
        }
        NextMaintenanceContract();
        //add by rentx 2020-11-13 LJPH-BV93RZ end
        if (syncEstimate(false, false)) {
            PageReference ret = null;
            if (this.targetMaintenanceContractId != null) {
                ret = new PageReference('/' + this.targetMaintenanceContractId);
            }
            return ret;
        }
        return null;
    }

    /**
     * キャンセルメソッド
     */
    public PageReference cancel() {
        PageReference ret = null;
        if (this.targetMaintenanceContractId != null) {
            ret = new PageReference('/' + this.targetMaintenanceContractId);
        }
        return ret;
    }

    private void setContractInfo(String id) {
        this.contract = [SELECT Id, Name, Status__c, Decided_Estimation__c, Service_Contract_Staff__c,
                         Estimate_Num__c, Management_Code__c, Hospital__c
                         FROM Maintenance_Contract__c WHERE Id = :id];
        this.targetHospitalId = this.contract.Hospital__c;
    }

    private Boolean checkValidate() {
        Boolean rtn = true;
        // 2021-02-26  mzy  LJPH-BX9CVX  add 获取合同结束日和合同月数 start
        //合同月数
        Decimal ContractRange = this.estimate.Contract_Range__c;
        //合同预定结束日期
        Date t = this.estimate.Contract_Esti_Start_Date__c.addMonths(Integer.valueOf(this.estimate.Contract_Range__c));
        if (this.estimate.Contract_Esti_Start_Date__c.month() == 2 && this.estimate.Contract_Esti_Start_Date__c.day() == 29
                && t.month() == 2) {
            t = t;
        } else {
            t = t.addDays(-1);
        }
        this.estimate.Contract_Esti_End_Date__c  = t;
        // 合同开始日を结束日
        if (this.estimate.Contract_Start_Date__c == null) {
            this.estimate.Contract_Start_Date__c = this.estimate.Contract_Esti_Start_Date__c;
        }
        t = this.estimate.Contract_Start_Date__c.addMonths(Integer.valueOf(this.estimate.Contract_Range__c));
        t = t.addDays(-1);
        this.estimate.Contract_End_Date__c = t;
        Date ContractEndDate = this.estimate.Contract_End_Date__c;
        System.debug('合同结束日期 :' + ContractEndDate);
        // 2021-02-26  mzy  LJPH-BX9CVX  add 获取合同结束日和合同月数 end
        // 部品供給停止の製品はエラー
        for (AssetInfo input : this.checkedAssets) {
            if (!input.isManual || input.isManual && !String.isBlank(input.mcae.Product_Manual__c)) {
                if (input.mcae.Estimate_List_Price__c == null || input.mcae.Estimate_List_Price__c == 0) {
                    //add by rentx 2020-11-12 LJPH-BV93RZ start
                    if (String.isNotBlank(input.proName)) {
                        // input.mcae.Product_Manual__c.addError(System.Label.Error_Message47);
                        input.mcae.Product_Manual__c.addError(System.Label.Error_Message47 + '(' + input.proName + ')');
                        //add by rentx 2020-11-12 LJPH-BV93RZ start
                    }

                    rtn = false;
                }
                if (isSaveOrApproval) {
                    if (input.rec.IF_Warranty__c == '否') {
                        input.rec.Name.addError(input.rec.Name + '(' + input.rec.SerialNumber + ') -- 不能选择不可参保设备');
                        rtn = false;
                    }
                }
                // 20200805 Gzw Bug修复
                // isSaveOrApproval = false;
            }
            // 2021-03-01 LJPH-BX9CVX mzy add 合同报价时判断零件风险
            if (input != null) {
                // System.debug('无零件风险日期 校验 end ');
                if ( input.rec != null && input.rec.NoPartRiskDate_F__c != null ) {
                    // 传入参数 : 无零件风险日期 , 可签约标识 , 合同结束日期 , 合同月数
                    String msg = SelectAssetEstimateVMController.checkAssetInfo(input.rec.NoPartRiskDate_F__c, input.rec.SignableFlag__c, ContractEndDate, ContractRange);
                    // 有错误信息则显示错误信息
                    if (msg != '') {
                        input.rec.Name.addError('[' + input.rec.Name + '] (机身编码为:' + input.rec.SerialNumber + ') ' + msg);
                        rtn = false;
                    }

                }
                /*else if(input.mcae!=null&&input.mcae.Product_Manual__c !=null&&input.NoPartRiskDate!=null ){
                    // 传入参数 : 无零件风险日期 , 可签约标识 , 合同结束日期 , 合同月数
                    String msg = SelectAssetEstimateVMController.checkAssetInfo(input.NoPartRiskDate,input.SignableFlag,ContractEstiEndDate,ContractRange);
                    // 有错误信息则显示错误信息
                    if(msg != ''){
                       input.mcae.Product_Manual__c.addError('['+input.proName2+'] '+msg);
                       rtn = false;
                    }
                }*/
            }
            // 2021-03-01 LJPH-BX9CVX mzy add 合同报价时判断零件风险
        }
        return rtn;
    }

    // 价格变更后克隆报价前重新计算价格
    @TestVisible
    private void priceChangeReset() {
        // 取得master中最新价格
        List<Id> assIds = new List<Id>();
        List<Id> pdIds = new List<Id>();
        for (AssetInfo input : this.checkedAssets) {
            if (!input.isManual) {
                assIds.add(input.rec.Id);
            }
            if (input.isManual && !String.isBlank(input.mcae.Product_Manual__c)) {
                pdIds.add(input.mcae.Product_Manual__c);
            }
        }
        Map<Id, Asset> assMap = new Map<Id, Asset>();
        Map<Id, Product2> pdMap = new Map<Id, Product2>();
        if (assIds.size() > 0) {
            assMap = new Map<Id, Asset>([select id, Maintenance_Price_Month__c from Asset where Id In: assIds]);
        }
        if (pdIds.size() > 0) {
            pdMap = new Map<Id, Product2>([select id, Maintenance_Price_Month__c from Product2 where Id In: pdIds]);
        }
        if (assMap.size() > 0 || pdMap.size() > 0) {
            for (AssetInfo info : this.checkedAssets) {
                if (!info.isManual) {
                    info.orgPrice = assMap.get(info.rec.Id).Maintenance_Price_Month__c;
                }
                if (info.isManual && !String.isBlank(info.mcae.Product_Manual__c)) {
                    info.orgPrice = pdMap.get(info.mcae.Product_Manual__c).Maintenance_Price_Month__c;
                }
            }
        }
        contractStartDateChange();
    }

    public class AssetInfo {
        public Integer lineNo {get; private set;}
        public Boolean rec_checkBox_c {get; set;}
        public Asset rec { get; set; }
        public Maintenance_Contract_Asset_Estimate__c mcae { get; set; }
        public Boolean isManual { get; set; }
        public Decimal orgPrice {get; private set;}
        // add by fxk 2021/9/9 控制点检对象是否可选 Star
        public Boolean CheckRows {get; private set;}
        // add by fxk 2021/9/9 控制点检对象是否可选 End
        //add by rentx 2020-11-12 LJPH-BV93RZ start
        public String proName;
        //add by rentx 2020-11-12 LJPH-BV93RZ start
        //add by mzy 2020-11-12 LJPH-BX9CVX start
        public Date NoPartRiskDate;
        public String proName2;
        public Boolean SignableFlag;
        //add by mzy 2020-11-12 LJPH-BX9CVX start
        public Id getRecId() {
            Id rtn = null;
            if (rec != null) {
                rtn = rec.Id;
            }
            return rtn;
        }
        public void setRecId(Id value) {
            // なにもしない
        }

        // Manual専用
        public AssetInfo(Integer lineNo) {
            this.lineNo = lineNo;
            this.rec = null;
            this.mcae = new Maintenance_Contract_Asset_Estimate__c(
                isNew__c = true,
                // add点检改善：新增一个点检对象复选框字段，默认为true 2021.6.8 fxk Star
                Check_Object__c = true
                                  // add点检改善：新增一个点检对象复选框字段，默认为true 2021.6.8 fxk end
            );
            this.isManual = true;
            this.rec_checkBox_c = false;
            this.orgPrice = 0;
            // add by fxk 2021/9/9 控制点检对象是否可选 Star
            this.CheckRows = true;
            // add by fxk 2021/9/9 控制点检对象是否可选 End
        }
        // 選択された用（非Manual）
        public AssetInfo(Integer lineNo, Asset record, Boolean isNew, Decimal listPrice, Maintenance_Contract_Asset_Estimate__c mcae) {
            this.lineNo = lineNo;
            this.rec = record;
            this.mcae = new Maintenance_Contract_Asset_Estimate__c(
//                id = mcae.Id,             // 本当にいらないの？ セットしたら、新規権限がなくでも、更新できます。後藤さんに確認した、なくでもいいです。
                isNew__c = isNew,
                // add点检改善：新增一个点检对象复选框字段，默认为true 2021.6.8 fxk Star
                Check_Object__c = mcae.Check_Object__c,
                // add点检改善：新增一个点检对象复选框字段，默认为true 2021.6.8 fxk end
                Estimate_List_Price__c = listPrice,
                Check_Result__c = mcae.Check_Result__c,
                Repair_Price__c = mcae.Repair_Price__c,
                Comment__c = mcae.Comment__c
            );
            this.isManual = false;
            this.rec_checkBox_c = true;
            this.orgPrice = record.Maintenance_Price_Month__c;
            //add by rentx 2020-11-12 LJPH-BV93RZ start
            this.proName = '机身编码为:' + record.SerialNumber;
            //add by rentx 2020-11-12 LJPH-BV93RZ end
            //add by mzy 2021-02-07 start
            //this.NoPartRiskDate = mcae.Product_Manual__r.NoPartRiskDate_F__c;
            this.proName2 = mcae.Product_Manual__r.Name;
            //this.SignableFlag = mcae.Product_Manual__r.SignableFlag__c;
            //add by mzy 202-02-07  end
            // add by fxk 2021/9/9 控制点检对象是否可选 Star
            this.CheckRows = true;
            // add by fxk 2021/9/9 控制点检对象是否可选 End

        }
        // 選択された用、未納品用（Manual）
        public AssetInfo(Integer lineNo, Maintenance_Contract_Asset_Estimate__c mcae) {
            this.lineNo = lineNo;
            this.rec = null;
            this.mcae = new Maintenance_Contract_Asset_Estimate__c(
//                id = mcae.Id,             // 本当にいらないの？ セットしたら、新規権限がなくでも、更新できます。後藤さんに確認した、なくでもいいです。
                isNew__c = mcae.IsNew__c,
                // add点检改善：新增一个点检对象复选框字段，默认为true 2021.6.8 fxk Star
                Check_Object__c = mcae.Check_Object__c,
                // add点检改善：新增一个点检对象复选框字段，默认为true 2021.6.8 fxk end
                Product_Manual__c = mcae.Product_Manual__c,
                Estimate_List_Price__c = mcae.Estimate_List_Price__c,
                Check_Result__c = mcae.Check_Result__c,
                Repair_Price__c = mcae.Repair_Price__c,
                Comment__c = mcae.Comment__c
            );
            this.isManual = true;
            this.rec_checkBox_c = false;
            this.orgPrice = mcae.Product_Manual__r.Maintenance_Price_Month__c;
            //add by mzy 2021-02-07 start
            //this.NoPartRiskDate = mcae.Product_Manual__r.NoPartRiskDate_F__c;
            this.proName2 = mcae.Product_Manual__r.Name;
            //this.SignableFlag = mcae.Product_Manual__r.SignableFlag__c;
            //add by mzy 2021-02-07 end
            // add by fxk 2021/9/9 控制点检对象是否可选 Star
            this.CheckRows = true;
            // add by fxk 2021/9/9 控制点检对象是否可选 End
        }
        // 選択されなかった用
        public AssetInfo(Integer lineNo, Asset record) {
            this.lineNo = lineNo;
            this.rec = record;
            this.isManual = false;
            this.rec_checkBox_c = false;
            this.orgPrice = record.Maintenance_Price_Month__c;
            // add by fxk 2021/9/9 控制点检对象是否可选 Star
            this.CheckRows = true;
            // add by fxk 2021/9/9 控制点检对象是否可选 End
        }
    }

    WebService static String pageDecide(String strId) {
        String rs = '';
        SelectAssetEstimateController saec = new SelectAssetEstimateController();
        saec.targetEstimateId = strId;
        saec.isPageAction = true;
        saec.init();
        if (saec.getDecideBtnDisabled()) {
            rs = '已经是Decide过的合同 或 不是批准的报价，不能Decide';
            return rs;
        }
        if (saec.syncEstimate(false, true)) {
            rs = '0';
        } else {
            rs = 'Decide失败';
        }
        return rs;
    }

    WebService static String pageUndecide(String strId) {
        String rs = '';
        Integer i = 0;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        SelectAssetEstimateController saec = new SelectAssetEstimateController();
        saec.targetEstimateId = strId;
        saec.isPageAction = true;
        saec.init();
        if (saec.getUnDecideBtnDisabled()) {
            rs = '不是Decide过的报价，不能Undecide';
            return rs;
        }
        if (saec.undecide() != null) {
            rs = '0';
        } else {
            rs = 'Undecide失败';
        }
        return rs;
    }

    // 计算过去五个合同信息 Gzw 20200810
    public static List<lastMContract> getlastMContract(List<AssetInfo> checkedAssets) {
        Map<String, lastMContract> lastMContractMap = new Map<String, lastMContract>();
        for (AssetInfo ai : checkedAssets) {
            lastMContract lM = new lastMContract(ai.rec.CurrentContract_F__c, ai.rec.CurrentContract_F__r.Maintenance_Contract_No_F__c, ai.rec.CurrentContract_F__r.Contract_End_Date__c, 1);
            if (String.isNotBlank(ai.rec.CurrentContract_F__c)) {
                //20201102 songxiaoqi start
                // if(ai.rec.CurrentContract_F__r.RecordType_DeveloperName__c == 'VM_Contract'){

                // }
                // 20201102  songxiaoqi end

                if (lastMContractMap.containsKey(ai.rec.CurrentContract_F__c)) {
                    lastMContractMap.get(ai.rec.CurrentContract_F__c).count ++;
                } else {
                    lastMContractMap.put(ai.rec.CurrentContract_F__c, lM);
                }
            }
        }
        List<lastMContract> listResulttemp = new List<lastMContract>();
        List<lastMContract> listResult = new List<lastMContract>();
        for ( lastMContract ll : lastMContractMap.values()) {
            listResulttemp.add(ll);
        }
        //ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, 'listResult +++++！' + listResult));
        listResulttemp.sort();
        for (Integer i = 0; i < 5 ; i++) {
            if (listResulttemp.size() >= i + 1) {
                listResult.add(listResulttemp[i]);
            } else {
                listResult.add(new lastMContract(null, null, null, null));
            }
        }
        //List<lastMContract> listResult = new List<lastMContract>();
        return listResult;
    }


    // 续签合同信息 class
    // 计算过去五个合同信息 Gzw 20200810
    public class lastMContract implements Comparable {
        public Date endDate { get; set; }
        public Integer count { get; set; }
        public String contractId { get; set; }
        public String contractNo { get; set; }

        public lastMContract(String contractId, String contractNo, Date  endDate, Integer count) {
            this.endDate = endDate;
            this.count = count;
            this.contractId = contractId;
            this.contractNo = contractNo;
        }
        // 排序
        public Integer compareTo(Object compareTo) {
            lastMContract compareToesd = (lastMContract)compareTo;
            Integer returnValue = 0;
            if (endDate  > compareToesd.endDate ) {
                returnValue = -1;
            } else if (endDate  < compareToesd.endDate ) {
                returnValue = 1;
            } else {
                if (count  > compareToesd.count ) {
                    returnValue = -1;
                } else if (count  < compareToesd.count ) {
                    returnValue = 1;
                }
            }
            return returnValue;
        }
    }
}