<?xml version="1.0" encoding="UTF-8"?>
<!--
    $Author: ouyangzhaochang2663 $
    $Date: 2012/05/11 09:58:18 $
    $Revision: 1.62 $
    $Purpose: 租金试算的新建和维护页面
    
    updated by ouyangzhaochang 2012/02/27
     contents: 机号校验添加一个参数 'budgetno',相关修改有 js函数verify_serialno及其调用
-->
<a:screen xmlns:a="http://www.leaf-framework.org/application" trace="true">
    <a:init-procedure>
        <!--<model-query fetchAll="true" model="agent.bgt.bgt_downpayrate" rootPath="downpayrate_model"/>-->
        <!--<model-query fetchAll="true" model="agent.bgt.bgt_init_budget_head_info" rootPath="head_model"/>-->
        <!--<model-query fetchAll="true" model="agent.bgt.bgt_init_floating_para" rootPath="floating_interest_para_model"/>-->
    </a:init-procedure>
    <a:view>
        <style><![CDATA[
        html,body{overflow-x: hidden}
        .lov-field{background-color:#b5b8c8;}
        ]]></style>
        <!--<script src="${/request/@context_path}/javascripts/finereport.js"><![CDATA[ ]]></script>-->
        <script><![CDATA[
            // 新增标记,1新增,0修改
            var isAdd = Ext.isEmpty('${/parameter/@isAdd}') ? 1 : 0;
            
            var isRecalculatFlg = '0';
            
            // 保存标记。当有数据修改时,修改为false,保存后修改为true;
            var isSaved = true;
            // 读取明细数据的次数,判断当前加载数据次数,如果是第一次打开页面,在读取数据后将isSaved还原为true;
            var loadDetailCount = 0;
            
            // 备份数组,当用户选择了“不均等付款”,
            // 改变了某一行数值的时候,取消当前行勾选,将数据还原
            var back_data_array = null;
            
            var budgetno = null; // 保存时传递budgetno到页面
            
            var mdf_array_size = 16;
            var mdf_array = new Array(mdf_array_size); // “重要数据是否修改的标记”的数组,用于存放所有“改变即需要重算”的变量
            var mdf_message_array = new Array(mdf_array_size);
            
            /*
             * WARNING ! DON'T change the variable's value below,they were designed to be
             * CONSTANTS in this program. But the JavaScript itself doesn't support
             * CONSTANTS.
             */
            var BUDGET_TYPE_INDEX = 0; // 合同类型标志
            var BUDGET_CATEGORY_INDEX = 1;
            var CUSTOMER_NAME_INDEX = 2; // 客户名称标志
            var MACHAMT_INDEX = 3; // 主机金额
            var OPTIONSAMT_INDEX = 4; // 附件金额
            var DOWNPAYMENT_INDEX = 5; // 首付款
            var MODELCD_INDEX = 6; // 机型
            var LEASEBGNDT_INDEX = 7; // 租赁开始日
            var PAYBGNDT_INDEX = 8; // 支付开始日
            var LEASEPRD_INDEX = 9; // 租赁期间
            var INTEREST_INDEX = 10; // 利率
            var RTNWAY_INDEX = 11; // 均等付款
            var ROUNDCALCFLAG_INDEX = 12; // 百元取整
            var RESULT_PAYAMT_INDEX = 13; //
            var OVHDEXPENSES_INDEX = 14; // 管理费
            var MARGIN_INDEX = 15; // 保证金
            
            /*
             * the end;
             */
            
            function initValidArray() {
                for (var i = 0;i < mdf_array.length;i++) {
                    mdf_array[i] = 0;
                }
            
                mdf_message_array[BUDGET_TYPE_INDEX] = "概算书类型";
                mdf_message_array[BUDGET_CATEGORY_INDEX] = "概算书类别";
                mdf_message_array[CUSTOMER_NAME_INDEX] = "客户名称";
                mdf_message_array[MACHAMT_INDEX] = "主机金额";
                mdf_message_array[OPTIONSAMT_INDEX] = "附件金额";
                mdf_message_array[DOWNPAYMENT_INDEX] = "首付款";
                mdf_message_array[MODELCD_INDEX] = "机型";
                mdf_message_array[LEASEBGNDT_INDEX] = "租赁开始日";
                mdf_message_array[PAYBGNDT_INDEX] = "支付开始日";
                mdf_message_array[LEASEPRD_INDEX] = "租赁期间";
                mdf_message_array[INTEREST_INDEX] = "利率";
                mdf_message_array[RTNWAY_INDEX] = "不均等付款";
                mdf_message_array[ROUNDCALCFLAG_INDEX] = "百元取整";
                mdf_message_array[RESULT_PAYAMT_INDEX] = "支付金额";
                mdf_message_array[OVHDEXPENSES_INDEX] = "管理费";
                mdf_message_array[MARGIN_INDEX] = "保证金";
            }
            
            function reset_form() {
                var ds = $("ord_contract_ds");
                ds.reset();
                record = ds.getCurrentRecord();
                record.set("budget_category", '${/parameter/@budget_category}');
                if ('${/parameter/@budget_category}' == 'FIXED') {
                    record.set('hclc_budget_category_dis', '${l:EOSBizdict.businID.BUDGET_CATEGORY.FIXED}');
                } else {
                    record.set('hclc_budget_category_dis', '${l:EOSBizdict.businID.BUDGET_CATEGORY.FLOATING}');
                }
            }
            
            /**
             * 页面初始化用,主要用于初始化UI
             */
            
            function initPageView() {
            
                //alert("${/model/floating_interest_para_model/record/@lowest_unequal_payment}");
            
                var budget_category = '${/parameter/@budget_category}';
                if (budget_category) {
                    if (budget_category == 'FIXED') {
                        $('ord_contract_ds').getCurrentRecord().set('hclc_budget_category', 'FIXED');
                        $('ord_contract_ds').getCurrentRecord().set('budget_category', 'FIXED');
                        $('ord_contract_ds').getCurrentRecord().set('hclc_budget_category_dis', '${l:EOSBizdict.businID.BUDGET_CATEGORY.FIXED}');
                    } else {
                        $('ord_contract_ds').getCurrentRecord().set('hclc_budget_category', 'FLOATING');
                        $('ord_contract_ds').getCurrentRecord().set('budget_category', 'FLOATING');
                        $('ord_contract_ds').getCurrentRecord().set('hclc_budget_category_dis', '${l:EOSBizdict.businID.BUDGET_CATEGORY.FLOATING}');
                    }
                }
            
                if (isAdd == 0) {
                    // 试算结果框
                    var result_div = document.getElementById('calculate_result_div');
                    result_div.style.display = "block";
            
                    var record = $("ord_contract_ds").getCurrentRecord();
                    var pattern_field = record.getMeta().getField('pattern');
                    pattern_field.setLovPara('modelcd', record.get('modelcd'));
            
                    var old_box = document.getElementById("old_box");
                    var release_box = document.getElementById("release_box");
                    var budget_type = record.get("hclc_budget_type");
                    // 显示以旧换新内容
                    if (budget_type == "OLD") {
                        if (record.get("dp_cash_amt") > record.get("downpayment")) {
                            Aurora.showMessage('提示信息', '现金支付金额大于首付款');
                            return false;
                        }
                        old_box.style.display = "block";
                        var amt = ((record.get("downpayment") || 0) - (record.get("dp_cash_amt") || 0)).toFixed(2);
                        record.set("dp_interfree_amt", amt);
                        var dp_interfree_paydt_field = record.getMeta().getField('dp_interfree_paydt');
                        dp_interfree_paydt_field.setRequired(true);
                    }
                    // 显示二次租赁内容
                    if (budget_type == "RELEASE") {
                        release_box.style.display = "block";
                        var hclc_repur_number_field = record.getMeta().getField('hclc_repur_number');
                        var serialno_field = record.getMeta().getField('serialno');
                        var modelcd_field = record.getMeta().getField('modelcd');
                        var pattern_field = record.getMeta().getField('pattern');
            
                        hclc_repur_number_field.setRequired(true);
                        modelcd_field.setRequired(false);
                        pattern_field.setRequired(false);
            
                        serialno_field.setReadOnly(true);
                        modelcd_field.setReadOnly(true);
                        pattern_field.setReadOnly(true);
                    }
            
                    // 针对利率类型进行页面UI调整
                    // 百元取整和不均等付款复选组
                    var calculateOptionsBox = document.getElementById('try_calculat_box');
                    // 试算结果中的浮动利率框
                    var resultRatebox = document.getElementById('result_fRate_box');
            
                    if (record.get("budget_category") == "FIXED") {
                        calculateOptionsBox.style.display = "block";
                        resultRatebox.style.display = "none";
                    } else if (record.get("budget_category") == "FLOATING") {
                        // calculateOptionsBox.style.display = "block";
                        calculateOptionsBox.style.display = "none";
                        if (record.get("rtnway") == '1') {
                            resultRatebox.style.display = "block";
                        } else if (record.get("rtnway") == '2') {
                            resultRatebox.style.display = "none";
                        }
                    }
            
                    document.getElementById('reset_btn').style.display = 'none';
            
                    record.set("budgetno_temp", "${/parameter/@budgetno}");
            
                    $("detail_ds").setQueryUrl("${/request/@context_path}/autocrud/agent.bgt.ld005/query?budgetno=${/parameter/@budgetno}"); //
                    $("detail_ds").query();
                }
            }
            
            initValidArray();
            
            function query() {
                $('ord_contract_ds').query();
            }
            
            /**
             * 获得基准利率
             */
            
            function getBaseIntr() {
                var info_ds = $("ord_contract_ds");
                var record = info_ds.getCurrentRecord();
            
                // 获取销售金额
                var saleamt = parseFloat(record.get("saleamt")) || 0;
            
                // 获取主机金额
                var machamt = record.get("machamt");
            
                // 获取首付款
                var downpayment = record.get("downpayment");
            
                // 获取租赁开始日
                var leasebgndt = record.get("leasebgndt");
            
                // 支付开始日
                var paybgndt = record.get("paybgndt");
            
                // 获取租赁期间
                var leaseprd = record.get("leaseprd");
                // 获取机型
                var modelcd = record.get("modelcd");
            
                // 获取首付款比率
                var init_downpayrate = parseFloat("${/model/downpayrate_model/record/@businname}") || 0;
            
                if ((!Ext.isEmpty(machamt)) && (!Ext.isEmpty(downpayment)) && (!Ext.isEmpty(leasebgndt)) && (!Ext.isEmpty(leaseprd)) && !Ext.isEmpty(modelcd)) {
                    optionsamt = parseFloat(machamt) || 0;
            
                    // 校验首付款比率
                    var temp_pay_rate = parseFloat((downpayment / saleamt) * 100).toFixed(2);
                    var is_payRate = verify_payRate(temp_pay_rate, init_downpayrate);
            
                    // 校验期数范围
                    var is_times = verify_times(record.get("hclc_budget_type"), leaseprd);
            
                    // 校验支付日
                    var is_paybgdt = verify_paydate(paybgndt, leasebgndt);
            
                    if (is_payRate && is_times && is_paybgdt) {
                        // 请求得到基准利率
                        Leaf.request({
                            url: '${/request/@context_path}/autocrud/agent.bgt.bgt_calculate_rent_get_stdintrrate/execute',
                            para: {
                                budget_category: record.get("budget_category"),
                                leasebgndt: leasebgndt,
                                leaseprd: leaseprd,
                                pay_rate: temp_pay_rate,
                                dealercd: "${/session/@dealer_cd}",
                                modelcd: modelcd
                            },
                            success: function(result) {
            
                                record.set("_stdinterest_errorcode", result.result.errcode);
                                if (result.result.errcode == 0) {
                                    record.set("stdintrrate", result.result.stdintrrate);
                                    record.set("pbc_bcmk_interest_rate", result.result.pbc_bcmk_interest_rate);
                                    record.set("pbc_bcmk_interest_effdate", Aurora.dateFormat.parseDate(result.result.pbc_bcmk_interest_effdate, 'yyyy-mm-dd'));
                                    record.set("hclc_interest_effdate", Aurora.dateFormat.parseDate(result.result.hclc_interest_effdate, 'yyyy-mm-dd'));
                                    record.set("fnd_interest_head_id", result.result.fnd_interest_head_id);
                                } else {
                                    if (result.result.errcode == '-1') {
                                        Aurora.showMessage('提示信息', '未取到合适的利率表');
                                    } else if (result.result.errcode == '-2') {
                                        Aurora.showMessage('提示信息', '未取到合适的利率');
                                    } else if (result.result.errcode == '-9') {
                                        Aurora.showMessage('提示信息', '取利率错误');
                                    }
                                    record.set("_stdinterest_errorcode", -9);
                                    record.set("stdintrrate", null);
                                    record.set("pbc_bcmk_interest_rate", null);
                                    record.set("pbc_bcmk_interest_effdate", null);
                                    record.set("hclc_interest_effdate", null);
                                    record.set("fnd_interest_head_id", null);
                                }
                            },
                            scope: this,
                            sync: true
                        });
                    } else {
                        record.set("stdintrrate", null);
                        record.set("_stdinterest_errorcode", -9);
                    }
                } else {
                    record.set("stdintrrate", null);
                }
            }
            
            /**
             * 校验机号
             *
             * @param serialno
             * @param modelcd
             * @returns {Boolean}
             */
            
            function verify_serialno(serialno, modelcd, budgetno) {
            
                var result_boolean = true;
                var strlength = 0;
            
                if (Ext.isEmpty(serialno)) {
                    result_boolean = true;
                    return result_boolean;
                }
            
                if ((serialno != "") && (serialno != null)) {
                    strlength = serialno.length;
            
                    if ((strlength != 10 && strlength != 12) && (strlength != 0)) {
                        Aurora.showMessage('提示信息', '机号长度应为10位或12位');
                        result_boolean = false;
                        return result_boolean;
                    }
                    var str1 = serialno.substring(0, 4);
                    // 判断是否为全英文大写
                    var reg = /^[A-Z]+$$/;
                    if (!reg.test(str1)) {
                        Aurora.showMessage('提示信息', '机号前4位应为英文字母');
                        result_boolean = false;
                        return result_boolean;
                    }
                    var str2;
                    if (strlength == 10) {
                        str2 = serialno.substring(4, 10);
                        reg = /^[0-9]+$$/;
                        if (!reg.test(str2)) {
                            Aurora.showMessage('提示信息', '机号后6位应为数字');
                            result_boolean = false;
                            return result_boolean;
                        }
                    } else if (strlength == 12) {
                        str2 = serialno.substring(6, 12);
                        reg = /^[0-9]+$$/;
                        if (!reg.test(str2)) {
                            Aurora.showMessage('提示信息', '机号后6位应为数字');
                            result_boolean = false;
                            return result_boolean;
                        }
                    }
                }
            
                var para;
                if ( !! budgetno) {
                    para = {
                        modelcd: modelcd,
                        serialno: serialno,
                        budgetno: budgetno
                    };
                } else {
                    para = {
                        modelcd: modelcd,
                        serialno: serialno
                    };
                }

                Leaf.request({
                    url: '${/request/@context_path}/autocrud/agent.bgt.bgt_calculate_rent_validate_serialno/execute',
                    para: para,
                    success: function(result) {
                        var verify_serialno_code = result.result.error_code;
                        if (verify_serialno_code != 0) {
                            Aurora.showMessage('提示信息', result.result.error_message);
                            result_boolean = false;
                        } else {
                            result_boolean = true;
                        }
                    },
                    scope: this,
                    sync: true
                });
            
                return result_boolean;
            }
            
            
            /**
             * 校验支付开始日
             *
             * @param paybgndt
             *            支付开始日
             * @param leasebgndt
             *            租赁起始日
             * @returns {Boolean} 通过true,非法false
             */
            
            function verify_paydate(paybgndt, leasebgndt) {
                var result = false;
            
                var year1 = leasebgndt.getYear();
                var year2 = paybgndt.getYear();
            
                var month1 = leasebgndt.getMonth();
                var month2 = paybgndt.getMonth();
            
            
                if ((year1 + 1) == year2) {
            
                    if ((month1 == 11) && (month2 == 0)) {
                        result = true;
                    } else {
                        result = false;
                    }
                } else if (year1 == year2) {
                    if ((month1 + 1) == month2) {
                        result = true;
                    } else {
                        result = false;
                    }
                } else {
                    result = false;
                }
            
                if (!result) {
                    Aurora.showMessage('提示信息', "支付开始日必须在租赁开始日所在月的次月范围内");
                }
            
                return result;
            
            }
            
            /**
             * 校验期数范围
             *
             * @param hclc_budget_type
             *            概算类型
             * @param leaseprd
             *            期数
             * @returns {Boolean} 通过true,非法false
             */
            
            function verify_times(hclc_budget_type, leaseprd) {
                // 如果是二次租赁
                if (hclc_budget_type == 'RELEASE') {
                    var info_ds = $("ord_contract_ds");
                    var record = info_ds.getCurrentRecord();
            
                    var repurno = record.get("hclc_repur_number");
                    if (Ext.isEmpty(repurno)) {
                        Leaf.showMessage('提示信息', '请先填写回购函号');
                        return false;
                    }
            
                    var leasebgndt = record.get("leasebgndt");
                    if (Ext.isEmpty(leasebgndt)) {
                        Leaf.showMessage('提示信息', '请先填写租赁开始日');
                        return false;
                    }
            
                    var result_boolean = false;
                    Leaf.request({
                        url: '${/request/@context_path}/autocrud/agent.bgt.bgt_calculate_rent_validate_repur_times/execute',
                        para: {
                            repurno: repurno,
                            leasebgndt: leasebgndt,
                            leaseprd: leaseprd
                        },
                        success: function(rst) {
                            var resultcd = rst.result.resultcd;
                            //if (resultcd == 1) {
                                result_boolean = true;
                            //} else {
                            //    Aurora.showMessage('提示信息', '租赁期数与原合同足额支付期数之和超过二次租赁最大期数');
                            //    result_boolean = false;
                            //}
                        },
                        scope: this,
                        sync: true
                    });
                    return result_boolean;
            
                }
                // else {
                // if ((leaseprd < 6) || (leaseprd > 60)) {
                // stdintrrate = null;
                // Aurora.showMessage('提示信息', '租赁期间必须在6到60个月之间');
                // return false;
                // }
                // }
            
                return true;
            }
            
            /**
             * 校验首付款比率
             *
             * @param temp_pay_rate
             *            临时计算出的首付款比率
             * @param init_downpayrate
             *            页面加载时从数据库读取的首付款比率
             * @returns {Boolean} 通过true,非法false
             */
            
            function verify_payRate(temp_pay_rate, init_downpayrate) {
                if ((temp_pay_rate < init_downpayrate) && (init_downpayrate > 0)) {
                    Aurora.showMessage('提示信息', '首付款比率不足');
                    return false;
                }
                return true;
            }
            
            /**
             * 校验租赁起始日期
             *
             * @param leasebgndt
             *            租赁起始日
             * @returns {Boolean}
             */
            
            function verify_leasebgndt(leasebgndt) {
            
                var result_boolean = false;
                if (leasebgndt != null) {
                    Leaf.request({
                        url: "${/request/@context_path}/autocrud/agent.bgt.bgt_calculate_rent_validate_leasebgndt/execute",
                        para: {
                            leasebgndt: leasebgndt,
                            operator_id: "${/session/@operator_id}"
                        },
                        success: function(result) {
                            result_boolean = true;
                        },
                        error: function() {
                            result_boolean = false;
                        },
                        scope: this,
                        sync: true
                    });
                }
                return result_boolean;
            }
            
            /**
             * 判断不均等付款时,校验支付计划表中是否所有的记录都被选中
             *
             * @returns {Boolean} 全选则不符合规则,返回false;没全选符合规则,返回true;
             */
            
            function verify_isAllDetailRecordSelected() {
                var ds = $("detail_ds");
                var allRecords = ds.getAll();
            
                if (Ext.isEmpty(allRecords)) {
                    // 结果表为空,说明还没有进行试算,返回true
                    return true;
                }
            
                var allLength = allRecords.length;
                var selectedLength = 0;
            
                for (var i = 0;i < allRecords.length;i++) {
                    if (allRecords[i].get('manualflag') == '1') selectedLength++;
                }
            
                if (allLength == selectedLength) {
                    Aurora.showMessage('提示信息', "不能修改所有回数的支付金额!");
                    return false;
                }
                return true;
            }
            
            /**
             * 校验基准利率
             *
             * @param stdintrrate
             *            取利率
             * @param interest
             *            用户输入的利率
             * @returns {Boolean} 通过true,非法false
             */
            
            function verify_interest(stdintrrate, errcode, interest) {
            
                var head_record = $("ord_contract_ds").getCurrentRecord();
                errcode = head_record.get("_stdinterest_errorcode");
            
                if (Ext.isEmpty(errcode)) {
                    getBaseIntr();
                }
                errcode = head_record.get("_stdinterest_errorcode");
            
                if (errcode == -1) {
                    Leaf.showMessage('提示信息', "未取到合适的利率表");
                    return false;
                } else if (errcode == -2) {
                    Leaf.showMessage('提示信息', "未取到合适的利率");
                    return false;
                } else if (errcode == -9) {
                    Leaf.showMessage('提示信息', "取利率过程发生错误");
                    return false;
                } else if (errcode == 0) {
            
            
                    if (stdintrrate > interest) {
                        Leaf.showMessage('提示信息', "利率不允许小于基准利率!");
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    return false;
                }
            }
            
            /**
             * 头信息更新时触发
             *
             * @param ds
             * @param record
             * @param name
             * @param value
             * @param oldValue
             */
            
            function formUpdate(ds, record, name, value, oldValue) {
            
                if (name != "printflg") {
                    isSaved = false;
                }
            
                if (name == "webcustomercd") {
                    if ((value != null) && (value != '')) {
                        var ctitype = record.get('ctitype');
                        var ctino = record.get('ctino');
                        record.set('ctitype_ctino', ctitype + "/" + ctino);
            
                        var branchcd = record.get('branchcd');
                        var dealercd = record.get('dealercd');
                        record.set('dealercd_dis', dealercd + "-" + branchcd);
            
                        var hometel = record.get("homtel");
                        var offtel = record.get("offtel");
                        var mobtel = record.get("mobtel");
                        if (hometel) {
                            record.set("customtel", hometel);
                        } else if (offtel) {
                            record.set("customtel", offtel);
                        } else if (mobtel) {
                            record.set("customtel", mobtel);
                        }
            
                        if (Ext.isEmpty(record.get("score"))) {
                            Leaf.showMessage('提示信息', "该客户没有评分,请进行客户信息更新或选择其他客户");
                        }
            
                    } else {
                        record.set('ctitype_ctino', null);
                        record.set('dealercd_dis', null);
                        record.set('branchcd', null);
                        record.set('dealercd', null);
                        record.set('customtel', null);
                    }
            
                    mdf_array[CUSTOMER_NAME_INDEX] = 1; // 设置修改标记
                } else if (name == "hclc_budget_type") {
                    var ob = document.getElementById('old_box');
                    var rb = document.getElementById('release_box');
            
                    record.set('dp_interfree_paydt', null);
                    record.set('dp_cash_amt', null);
                    record.set('hclc_repur_number', null);
                    record.set('dp_interfree_amt', null);
            
                    var repurno_field = record.getMeta().getField("hclc_repur_number");
                    var dp_cash_amt_field = record.getMeta().getField("dp_cash_amt");
                    var serialno_field = record.getMeta().getField("serialno");
                    var modelcd_field = record.getMeta().getField('modelcd');
                    var pattern_field = record.getMeta().getField('pattern');
                    var dp_interfree_paydt_field = record.getMeta().getField("dp_interfree_paydt");
            
                    repurno_field.setRequired(false);
                    dp_cash_amt_field.setRequired(false);
                    modelcd_field.setRequired(true);
                    pattern_field.setRequired(true);
                    dp_interfree_paydt_field.setRequired(false);
            
                    serialno_field.setReadOnly(false);
                    modelcd_field.setReadOnly(false);
                    pattern_field.setReadOnly(false);
            
                    if (value == "NORMAL") {
                        ob.style.display = "none";
                        rb.style.display = "none";
                    } else if (value == "OLD") {
                        dp_cash_amt_field.setRequired(true);
                        dp_interfree_paydt_field.setRequired(true);
                        ob.style.display = "block";
                        rb.style.display = "none";
                    } else if (value == "RELEASE") {
                        repurno_field.setRequired(true);
                        modelcd_field.setRequired(false);
                        pattern_field.setRequired(false);
            
                        ob.style.display = "none";
                        rb.style.display = "block";
            
                        serialno_field.setReadOnly(true);
                        modelcd_field.setReadOnly(true);
                        pattern_field.setReadOnly(true);
                    }
            
                    mdf_array[BUDGET_TYPE_INDEX] = 1;
                } else if (name == "budget_category") {
                    // 百元取整和不均等付款复选组
                    var calculateOptionsBox = document.getElementById('try_calculat_box');
                    // 试算结果中的浮动利率框
                    var resultRatebox = document.getElementById('result_fRate_box');
            
                    record.set('rtnway', 1);
                    record.set('roundcalcflag', 1);
            
                    if (value == "FIXED") {
                        calculateOptionsBox.style.display = "block";
                        resultRatebox.style.display = "none";
                    } else if (value == "FLOATING") {
                        // calculateOptionsBox.style.display = "block";
                        calculateOptionsBox.style.display = "none";
                        resultRatebox.style.display = "block";
                    }
            
                    mdf_array[BUDGET_CATEGORY_INDEX] = 1;
                }
            
                if ((name == "machamt") || (name == "optionsamt") || (name == "downpayment")) {
                    var machamt = parseFloat(record.get('machamt')) || 0;
                    var optionsamt = parseFloat(record.get('optionsamt')) || 0;
                    var downpayment = parseFloat(record.get('downpayment')) || 0;
            
                    if (name == "optionsamt") {
                        if (Ext.isEmpty(oldValue) && value == 0) {
                            return;
                        }
                        var saleamt = parseFloat((machamt + optionsamt) || 0).toFixed(2);
                        record.set('saleamt', saleamt);
            
                        mdf_array[OPTIONSAMT_INDEX] = 1;
            
                        // record.set('leaseprnc', leaseprnc);
                    } else if (name == "machamt") {
                        var saleamt = parseFloat((machamt + optionsamt) || 0).toFixed(2);
                        record.set('saleamt', saleamt);
            
                        mdf_array[MACHAMT_INDEX] = 1;
                    } else if (name == "downpayment") {
                        var saleamt = parseFloat(record.get('saleamt')) || 0;
                        var leaseprnc = parseFloat((saleamt - downpayment) || 0).toFixed(2);
                        record.set('leaseprnc', leaseprnc);
            
                        mdf_array[DOWNPAYMENT_INDEX] = 1;
                    }
                } else if (name == "saleamt") {
                    var downpayment = parseFloat(record.get('downpayment')) || 0;
                    var leaseprnc = parseFloat((value - downpayment) || 0).toFixed(2);
                    record.set('leaseprnc', leaseprnc);
                } else if (name == "modelcd") {
                    var pattern_field = record.getMeta().getField('pattern');
                    if (value) {
                        pattern_field.setLovPara('modelcd', record.get('modelcd'));
                        if (oldValue != value) {
                            record.set("pattern", null);
                        }
                    } else {
                        pattern_field.setLovPara('modelcd', null);
                    }
            
                    mdf_array[MODELCD_INDEX] = 1;
            
                } else if (name == "leasebgndt") {
                    // 校验租赁开始日期
                    if (!verify_leasebgndt(value)) return;
                    if (record.get("hclc_budget_type") == "OLD") {
                        var dpInterfreePaydt = Aurora.dateFormat.parseDate(get_dp_interfree_paydt(value,record.get('dp_interfree_prd')), 'yyyy-mm-dd');
                        record.set("dp_interfree_paydt", dpInterfreePaydt);
                    } else {
                        record.set("dp_interfree_paydt", null);
                    }
                    mdf_array[LEASEBGNDT_INDEX] = 1;
                }else if (name == "dp_interfree_prd") {
                    // 校验租赁开始日期
                    if (!verify_leasebgndt(record.get('leasebgndt'))) return;
                    if (record.get("hclc_budget_type") == "OLD") {
                        var dpInterfreePaydt = Aurora.dateFormat.parseDate(get_dp_interfree_paydt(record.get('leasebgndt'),value), 'yyyy-mm-dd');
                        record.set("dp_interfree_paydt", dpInterfreePaydt);
                    } else {
                        record.set("dp_interfree_paydt", null);
                    }
                    mdf_array[LEASEBGNDT_INDEX] = 1;
                } else if (name == "rtnway") {
                    var result_grid = $("result_table");
                    if (value == 1) {
                        result_grid.hideColumn('manualflag');
                    } else {
                        result_grid.showColumn('manualflag');
                    }
                    mdf_array[RTNWAY_INDEX] = 1;
                } else if (name == "serialno") {
                    if (record.get("hclc_budget_type") != "RELEASE") {
                        //updated by ouyangzhaochang 2012/02/27 start
                        //verify_serialno(record.get("serialno"), record.get("modelcd"));
                        verify_serialno(head_record.get("serialno"), head_record.get("modelcd"), head_record.get("budgetno"));
                        //updated by ouyangzhaochang 2012/02/27 end
                    }

                } else if (name == "roundcalcflag") {
                    mdf_array[ROUNDCALCFLAG_INDEX] = 1;
                } else if (name == "paybgndt") {
                    mdf_array[PAYBGNDT_INDEX] = 1;
                } else if (name == "leaseprd") {
                    mdf_array[LEASEPRD_INDEX] = 1;
                } else if (name == "interest") {
                    validte_interest(value);
                    mdf_array[INTEREST_INDEX] = 1;
                } else if (name == "ovhdexpenses") {
                    if (Ext.isEmpty(oldValue) && value == 0) {
                        return;
                    }
                    mdf_array[OVHDEXPENSES_INDEX] = 1;
                } else if (name == "margin") {
                    if (Ext.isEmpty(oldValue) && value == 0) {
                        return;
                    }
                    mdf_array[MARGIN_INDEX] = 1;
                }
            }
            
            function get_dp_interfree_paydt(leasebgndt,dp_interfree_prd) {
                var p_result_dt = null;
                Aurora.request({
                    url: "${/request/@context_path}/autocrud/agent.bgt.bgt_calculate_rent_get_dp_interfree_paydt/execute",
                    para: {
                        leasebgndt: leasebgndt,
                        dp_interfree_prd:dp_interfree_prd
                    },
                    success: function(rst) {
                        p_result_dt = rst.result.dp_interfree_paydt;
                    },
                    scope: this,
                    sync: true
                });
                return p_result_dt;
            }
            
            function validte_interest(interest) {
                if (interest >= 99.999) {
                    Leaf.showMessage('提示信息', '利率应介于“0”至“99.999”之间');
                    return false;
                }
                return true;
            }
            
            /**
             * 以旧换新 校验现金支付金额
             *
             * @param downpayment
             *            主机金额
             * @param dp_cash_amt
             *            现金支付金额
             * @returns {Boolean} 通过true,非法false
             */
            
            function validate_dp_cash_amt(downpayment, dp_cash_amt, dp_interfree_paydt) {
                if (dp_cash_amt > downpayment) {
                    Aurora.showMessage('提示信息', '现金支付金额不能大于首付款金额');
                    return false;
                }
            
                var p_resultcd = null;
                Leaf.request({
                    url: "${/request/@context_path}/autocrud/agent.bgt.bgt_calculate_rent_validate_dp_cash_amt/execute",
                    para: {
                        dealercd: '${/session/@dealer_cd}',
                        dp_cash_amt: dp_cash_amt
                    },
                    success: function(rst) {
                        p_resultcd = rst.result.p_resultcd;
                    },
                    scope: this,
                    sync: true
                });
                if (p_resultcd == 0) {
                    return true;
                } else if (p_resultcd == 1) {
                    Aurora.showMessage('提示信息', '没有维护可用额度,不可创建');
                    return false;
                } else if (p_resultcd == 2) {
                    Aurora.showMessage('提示信息', '超过可用额度,不可创建!请修改现金支付额度!');
                    return false;
                }
            }
            
            
            /**
             * 校验回购业务是否完成
             *
             * @param serialNo
             * @param repurno
             * @param modelcd
             * @returns {Boolean}
             */
            
            function verify_repur() {
                var check_repur = true;
                var head_record = $("ord_contract_ds").getCurrentRecord();
            
                var repurno = head_record.get("hclc_repur_number");
                if (Ext.isEmpty(repurno)) return;

                Leaf.request({
                    url: "${/request/@context_path}/autocrud/agent.bgt.bgt_calculate_rent_validate_repur_serialno/execute",
                    para: {
                        repurno: repurno,
                        budgetno: head_record.get("budgetno")
                    },
                    success: function(rst) {
                        var resultcd = rst.result.resultcd;
                        if (resultcd < 0) {
                            Aurora.showMessage('提示信息', rst.result.message);
                            /*
                             * head_record.set("modelcd", null);
                             * head_record.set("serialno", null);
                             * head_record.set("pattern", null);
                             * head_record.set("modelname", null);
                             * head_record.set("detention", null);
                             * head_record.set("spec", null);
                             */
                            check_repur = false;
                        } else {
                            check_repur = true;
                            head_record.set("modelcd", rst.result.modelcd);
                            head_record.set("serialno", rst.result.serialno);
                            head_record.set("pattern", rst.result.pattern);
                            head_record.set("modelname", rst.result.modelname);
                            head_record.set("detention", rst.result.detention);
                            head_record.set("spec", rst.result.name_c);
            
                        }
                    },
                    scope: this,
                    sync: true
                });
                return check_repur;
            }
            
            /**
             * 检查客户分数
             *
             * @param score
             * @returns
             */
            
            function verify_customer_score(score) {
                var result_boolean = Ext.isEmpty(score);
                if (result_boolean) {
                    Leaf.showMessage('提示信息', '该客户没有评分,请进行客户信息更新或选择其他客户');
                }
                return !result_boolean;
            }
            
            /**
             * 检查不均等付款时,每期金额是否小于 表 ord_floating_interest_para.lowest_unequal_payment 定义的值
             *
             * @returns true:校验通过  false:不通过
             */
            
            function verify_rtnway_amount(headRecord) {
                var ds = $("detail_ds");
                var records = ds.getAll(); //取出明细的所有数据
            
                if ((Ext.isEmpty(records)) || (records.length == 0) || (headRecord.get("rtnway") == "1")) {
                    //明细为空,或数据条数为空,说明还没有进行试算,无法填写数值,不做校验;
                    //均等付款不做检测
                    return true;
                }
            
                //取出 lowest_unequal_payment 数值
                var lowest_unequal_payment = "${/model/floating_interest_para_model/record/@lowest_unequal_payment}";
                for (var i = 0;i < records.length;i++) {
                    if ((parseFloat(records[i].get("payamt")) < parseFloat(lowest_unequal_payment)) && (records[i].get("manualflag") == "1")) {
                        //找到比系统数值小的,并且被选中的
                        Leaf.showMessage('提示信息', '第' + records[i].get("times") + "期: 支付金额不允许小于“" + lowest_unequal_payment + "”");
                        return false;
                    }
                }
            
                return true;
            }
            
            function detailUpdate(ds, record, name, value, oldValue) {
                if (name == "manualflag") {
                    if (value == 0) {
                        var location = ds.indexOf(record);
                        if ((record.get("payamt")) != back_data_array[location]) { // 对比是否改变了数值
                            /*
                             * 如改变,恢复原值(理由是:如果简单的将原值直接覆盖上去, 当出现“用户勾选了某一行,没有改变其值后又取消勾选”的情况时,
                             * 就会造成误判,认为用户改变了关键值);
                             */
                            record.set("payamt", back_data_array[location]);
                        }
                    }
                } else if (name == "payamt") {
                    mdf_array[RESULT_PAYAMT_INDEX] = 1;
                }
            }
            
            /**
             * 校验试算前数据是否符合要求
             *
             * @returns {Boolean}
             */
            
            function validate_calculate_data() {
            
                var head_record = $("ord_contract_ds").getCurrentRecord();
                var stdintrrate = parseFloat(head_record.get("stdintrrate") || (-1));
                var interest = parseFloat(head_record.get("interest"));
                var stdinterest_errorcd = head_record.get("_stdinterest_errorcode");
                var hclc_budget_type = head_record.get("hclc_budget_type");
            
                //add by ouyangzhaochang 2012/05/23 start 校验支付开始日必须在租赁开始日的下个月内
                var paybgndt = head_record.get("paybgndt");
                var leasebgndt = head_record.get("leasebgndt");
                if (!verify_paydate(paybgndt, leasebgndt)) {
                    return;
                }
                //add by ouyangzhaochang 2012/05/23 end
            
                // 利率校验结果
                var check_interest = verify_interest(stdintrrate, stdinterest_errorcd, interest);
                if (!check_interest) return false;
            
                if (hclc_budget_type == "OLD") {
                    var dpInterfreePaydt = Aurora.dateFormat.parseDate(get_dp_interfree_paydt(head_record.get("leasebgndt"),head_record.get("dp_interfree_prd")), 'yyyy-mm-dd');
                    if (Ext.isEmpty(dpInterfreePaydt)) {
                        Leaf.showMessage('提示信息', '取得“免息支付日”出错');
                        return false;
                    }
                    head_record.set("dp_interfree_paydt", dpInterfreePaydt);
                } else {
                    head_record.set("dp_interfree_paydt", null);
                }
            
                if (head_record.get("dp_cash_amt") > head_record.get("downpayment")) {
                    Leaf.showMessage('提示信息', '现金支付金额大于首付款');
                    return false;
                }
            
                // 以旧换新校验结果
                var check_dp_cash_amt = true;
                if ((hclc_budget_type) == "OLD") {
                    head_record.set("dp_interfree_amt", head_record.get("downpayment") - head_record.get("dp_cash_amt"));
            
            
                    check_dp_cash_amt = validate_dp_cash_amt(head_record.get("downpayment") || 0, head_record.get("dp_interfree_amt") || 0, head_record.get("dp_interfree_paydt"));
            
            
                }
                if (!check_dp_cash_amt) return false;
            
                // 二次租赁校验结果
                var check_repur = true;
                if ((hclc_budget_type) == "RELEASE") {
                    check_repur = verify_repur();
                }
                if (!check_repur) return false;
            
                // 校验机号(普通)
                if ((hclc_budget_type) != "RELEASE") {
                    //updated by ouyangzhaochang 2012/02/27 start
                    //var check_serialno = verify_serialno(head_record.get("serialno"), head_record.get("modelcd"));
                    var check_serialno = verify_serialno(head_record.get("serialno"), head_record.get("modelcd"), head_record.get("budgetno"));
                    //updated by ouyangzhaochang 2012/02/27 end
                    if (!check_serialno) return false;
                }
            
                // 检查租赁起始日
                var check_leasebgdt = verify_leasebgndt(head_record.get("leasebgndt"));
                if (!check_leasebgdt) return false;
            
                // 检查客户评分
                var check_customerscore = verify_customer_score(head_record.get("score"));
                if (!check_customerscore) return false;
            
                // 检查利率范围
                var check_interest = validte_interest(head_record.get("interest"));
                if (!check_interest) return false;
            
                var check_selectAll = verify_isAllDetailRecordSelected();
                if (!check_selectAll) return false;
            
                var check_rtnway_amount = verify_rtnway_amount(head_record);
                if (!check_rtnway_amount) return false;
            
                return true;
            
            }
            
            /*
             * 试算过程开始
             */
            
            function try_calculate() {
                //add by ouyangzhaochang 2012/05/01 start
                var saveButton = $('saveButton');
                saveButton.disable();
                //add by ouyangzhaochang 2012/05/11 end
                if (!$('ord_contract_ds').validate()) {
                    return;
                }
                if (!validate_calculate_data()) {
                    return;
                }
            
                var record = $('ord_contract_ds').getCurrentRecord();
            
                record.set("margin", record.get("margin") || 0);
                record.set("ovhdexpenses", record.get("ovhdexpenses") || 0);
                record.set("optionsamt", record.get("optionsamt") || 0);
            
                var roundcalcflag = record.get("roundcalcflag"); // 百元取整
                var rtnway = record.get("rtnway"); // 不均等付款
            
                // 试算调用过程地址
                var destination_bm_url = "";
                if (roundcalcflag == '1') {
                    // 非百元取整
                    destination_bm_url = "${/request/@context_path}/autocrud/agent.bgt.bgt_pab001_lease_calculation/execute";
                } else if (roundcalcflag == '2') {
                    // 百元取整
                    destination_bm_url = "${/request/@context_path}/autocrud/agent.bgt.bgt_pab002_lease_calculation/execute";
                }
            
                // 获取每期付款字符串
                var paymentSeq = generateSequence();
                Leaf.request({
                    url: destination_bm_url,
                    para: {
                        saleamt: record.get("saleamt"),
                        leaseprnc: record.get("leaseprnc"),
                        interest: (parseFloat(record.get("interest")) / 100),
                        leasebgndt: record.get("leasebgndt").format('yyyymmdd'),
                        paybgndt: record.get("paybgndt").format('yyyymmdd'),
                        leaseprd: record.get("leaseprd"),
                        downpayment: record.get("downpayment"),
                        detention: record.get("detention") || 0,
                        i_baoxianfei: 0,
                        ovhdexpenses: record.get("ovhdexpenses") || 0,
                        i_dingjin: 0,
                        margin: record.get("margin") || 0,
                        rtnway: rtnway,
                        i_editserial: paymentSeq,
                        dealercd: '${/session/@dealer_cd}',
                        modelcd: record.get("modelcd"),
                        budget_category: record.get("budget_category")
                    },
                    success: function(result) {
                        isRecalculatFlg = '1'; // 将试算标记标1
                        var errorcd = result.result.errcode;
                        if (errorcd == 0) {
                            // alert("成功");
                            record.set("seq", result.result.seq);
            
                            // 查询数据到结果表中
                            var detail_ds = $("detail_ds");
                            detail_ds.setQueryParameter("seq", result.result.seq); // 设置查询条件
            
                            var floatingCalculatSuccess = true;
                            if (record.get("budget_category") == 'FLOATING') {
                                Leaf.request({
                                    url: "${/request/@context_path}/autocrud/agent.bgt.bgt_calculate_rent_calc_adjust_interest_amount/execute",
                                    para: {
                                        principal: record.get("leaseprnc"),
                                        interest: (parseFloat(record.get("stdintrrate")) / 100),
                                        leasing_period: record.get("leaseprd")
                                    },
                                    success: function(args) {
                                        record.set("delay_execute_period", args.result.delay_execute_period);
                                        record.set("adj_step", args.result.adj_step);
                                        record.set("adj_range", args.result.adj_range);
                                        record.set("unit_adjust_amount", args.result.result);
                                        floatingCalculatSuccess = true;
                                    },
                                    error: function(args) {
                                        floatingCalculatSuccess = false;
                                    },
                                    scope: this,
                                    sync: true
                                });
                            }
            
                            if (floatingCalculatSuccess) {
                                // 指定查询路径,试算均需从TEMP_KINRI表中查数据
                                detail_ds.setQueryUrl("${/request/@context_path}/autocrud/agent.bgt.TEMP_KINRI/query");
                                detail_ds.query(); // 查询数据
            
                                // 将验证数组恢复初始化
                                initValidArray();
                            }
            
                        } else {
                            Leaf.showMessage('提示信息', result.result.error_message);
                            //add by ouyangzhaochang 2012/05/11 start
                            var saveButton = $('saveButton');
                            saveButton.enable();
                            //add by ouyangzhaochang 2012/05/11 end
                        }
                    },
                    scope: this,
                    sync: true
                });
            }
            
            function afterLoadData(ds) {
                var record = $('ord_contract_ds').getCurrentRecord();
                var records = ds.getAll(); // 得到加载的全部数据
                back_data_array = new Array(records.length);
            
                var totalSalestax = parseFloat(0); // 营业税总和
                var totalpaytimes = parseFloat(0);
                var totalPayment = parseFloat(0);
                var totalInt = parseFloat(0); // 利息总和
                var totalPrn = parseFloat(0); // 本金总和
                var totalCsgchg = parseFloat(0);
            
                var find_min_paytime = false;
            
                // 将初始数据写入备份数组中,同时,计算每行的营业税和营业税总和
                for (var i = 0;i < back_data_array.length;i++) {
                    var current_payamt = parseFloat(records[i].get("payamt")); // 得到当前付款金额
                    back_data_array[i] = current_payamt; // 写入备份数组
            
                    totalPayment += current_payamt; // 计算付款总和
            
                    var current_int = parseFloat(records[i].get("interest"));
                    totalInt += current_int;
            
                    var current_tax = (current_int * 0.05).toFixed(2); // 计算当前行营业税
                    totalSalestax += parseFloat(current_tax); // 计算营业税总和
                    records[i].set("salestax", current_tax); // 设置当前行营业税
            
                    if (current_payamt > 0) {
                        totalpaytimes += 1; // 计算支付回数
                        if (!find_min_paytime) {
                            record.set("perlchg_fir", records[i].get("payamt")); // 取第一期支付金额>0的,作为“每月租金(第一期)”
                            find_min_paytime = true;
                        }
                    }
            
            
            
                    var current_csgchg = parseFloat(records[i].get("csgchg"));
                    totalCsgchg += current_csgchg;
            
                    var current_prn = parseFloat(records[i].get("principal"));
                    totalPrn += current_prn;
                }
            
                // 设置第二期租金
                var rtnway = record.get("rtnway");
                record.set("perlchg_sec", null);
                if (rtnway == 1) {
                    if (records.length > 1) { //add by shuangyi.li 去除只有1期的情况
                        record.set("perlchg_sec_dis", parseFloat(records[1].get("payamt")));
                        record.set("perlchg_sec", parseFloat(records[1].get("payamt")));
                        (document.getElementById('perlchg_sec_number')).style.display = "block";
                        (document.getElementById('perlchg_sec_text')).style.display = "none";
                        Ext.get("result_table").child('td.table_title').update("预定支付表(均等)");
                    }
                    // zhangyi@2012/02/21
                    if (record.get("budget_category") == 'FLOATING') {
                        //如果是浮动利率并且是均等付款,显示“调整租金(每0.1%)”界面字段
                        (document.getElementById('result_fRate_box')).style.display = "block";
                    }
                } else {
                    record.set("perlchg_sec_dis", "详细付款状况参见下列的租金支付计划表");
                    record.set("perlchg_sec", parseFloat(0));
                    (document.getElementById('perlchg_sec_text')).style.display = "block";
                    (document.getElementById('perlchg_sec_number')).style.display = "none";
                    Ext.get("result_table").child('td.table_title').update("预定支付表(不均等)");
            
                    // zhangyi@2012/02/21
                    if (record.get("budget_category") == 'FLOATING') {
                        //如果是浮动利率并且是不均等付款,隐藏“调整租金(每0.1%)”界面字段
                        (document.getElementById('result_fRate_box')).style.display = "none";
                    }
                }
            
                record.set("tolleasechg", totalPayment.toFixed(2));
            
                record.set("paytimes", totalpaytimes);
                record.set("tolsaltax", (parseFloat(totalPayment.toFixed(2)) * 0.05).toFixed(2));
                record.set("tolconschg", totalCsgchg.toFixed(2));
                record.set("tolintamt", totalInt.toFixed(2));
                record.set("paysum", record.get("downpayment"));
                record.set("totalPrn", totalPrn.toFixed(2));
            
                // 动态设置grid大小
                var result_table = $("result_table");
                var height = 60 + (back_data_array.length) * 25;
                result_table.setHeight(height);
            
                // 显示下半部分
                var result_div = document.getElementById('calculate_result_div');
                result_div.style.display = "block";
            
                // 设置隐藏列
                var result_grid = $("result_table");
                if (rtnway == 1) {
                    result_grid.hideColumn('manualflag');
                } else {
                    result_grid.showColumn('manualflag');
                }
            
                if (isAdd == 0 && loadDetailCount == 0) isSaved = true;
            
                loadDetailCount++;
                //add by ouyangzhaochang 2012/05/11 start
                var saveButton = $('saveButton');
                saveButton.enable();
                //add by ouyangzhaochang 2012/05/11 end
            }
            
            // 生成不均等付款的标识序列
            
            function generateSequence() {
            
                var records = $("detail_ds").getAll();
                if (records.length == 0) {
                    return '-1';
                }
            
                var sequenceStr = "";
                for (var i = 0;i < records.length;i++) {
                    if (records[i].get("manualflag") == 0) {
                        sequenceStr += -1;
                    } else {
                        sequenceStr += (records[i].get("payamt"));
                    }
                    sequenceStr += "^";
                }
                return sequenceStr;
            }
            
            /**
             * 检测是否有关键数据被更改
             */
            
            function checkIfKeyDataUpdated() {
                var index = -1;
                for (var i = 0;i < mdf_array.length;i++) {
                    if (mdf_array[i] == 1) {
                        index = i;
                        break;
                    }
                }
                return index;
            }
            
            /**
             * 保存结果
             */
            
            function saveResult() {
                var head_record = $("ord_contract_ds").getCurrentRecord();
                var form_ds = $("ord_contract_ds");
            
                if (!form_ds.validate()) {
                    return;
                }
            
                //add by ouyangzhaochang 2012/05/11 start 以旧换新的现金支付额不能为空
                var hclc_budget_type = head_record.get('hclc_budget_type');
                if (hclc_budget_type == 'OLD') {
                    var dp_cash_amt = head_record.get('dp_cash_amt');
                    if (typeof(dp_cash_amt) == "undefined" || (dp_cash_amt === '')) {
                        Leaf.showMessage('提示信息', '现金支付金额不能为空');
                        return;
                    }
                }
                //add by ouyangzhaochang 2012/05/11 end
            
                var check_index = checkIfKeyDataUpdated();
                if (check_index != -1) {
                    Leaf.showMessage('提示信息', "“" + mdf_message_array[check_index] + '”数据已改变,请在重新试算后再保存');
                    return;
                }
            
            
                if (!validate_calculate_data()) {
                    return;
                }
            
            
                var tolleasechg = parseFloat(head_record.get("tolleasechg") || 0);
                var downpayment = parseFloat(head_record.get("downpayment") || 0);
                var detention = parseFloat(head_record.get("detention") || 0);
                head_record.set('contractamt', (tolleasechg + downpayment + detention).toFixed(2)); // 合同总金额
            
                head_record.set('companycd', "${/session/@companyCd}");
                head_record.set('userid', "${/session/@user_id}");
                head_record.set('org_cd', "${/session/@org_id}");
                head_record.set('recalculat_flg', isRecalculatFlg);
                // 如果是新增状态
                if (isAdd == 1) {
                    var comfirm = Aurora.showConfirm('${l:JAVASCRIPT_MESSAGE}', '确定提交?', function() {
                        comfirm.close();
                        form_ds.setSubmitParameter('dealercd', head_record.get('dealercd'));
                        form_ds.setSubmitParameter('branchcd', '00');
                        form_ds.setSubmitUrl("bgt_trial_balance_insert.svc");
                        form_ds.submit();
                    });
                } else {
                    var comfirm = Aurora.showConfirm('${l:JAVASCRIPT_MESSAGE}', '确定修改?', function() {
                        comfirm.close();
                        // alert(result.result.p_bugetno);
            
                        // 设置提交地址
                        form_ds.setSubmitUrl("${/request/@context_path}/autocrud/agent.bgt.bgt_calculate_rent_update_ld004_05/batch_update");
                        form_ds.submit();
                    }, null, null, 100);
                }
            
            }
            
            function saveSuccess(dataSet, datas) {
            
                if (isAdd == 1) {
                    budgetno = datas.result.budgetno_temp;
                    $("ord_contract_ds").getCurrentRecord().set("budgetno_temp", budgetno);
                    $("ord_contract_ds").getCurrentRecord().set("budgetno", budgetno);
                    Leaf.showMessage('提示信息', '新增成功,概算书编号为:' + budgetno);
                    isAdd = 0;
                } else {
                    Leaf.showMessage('提示信息', '修改成功');
                }
                $("ord_contract_ds").getCurrentRecord().set("status", 0);
                isSaved = true;
            }
            
            function opt1Validator(record, name, value) {
                if (Ext.isEmpty(value)) {
                    return true;
                }
            
                if (value.length > 20) {
                    return '最多输入600字';
                }
            
                return true;
            }
            
            
            
            function back() {
                window.history.go(-1);
            }
            
            function paydtRenderer(value, record, name) {
                if (record) {
                    var str = value.substring(0, 4) + "/" + value.substring(4, 6) + "/" + value.substring(6, 8);
                    return str;
                }
                return '';
            }
            
            function numberRenderer(value, record, name) {
                return Leaf.formatNumber(value, 2);
            }
            
            function interestRenderer(value, record, name) {
                return Leaf.formatNumber(value, 3);
            }
            
            function footTitle(data, name) {
                return "合计";
            }
            
            function footPayAmt(data, name) {
                var value = $("ord_contract_ds").getCurrentRecord().get("tolleasechg");
                return Leaf.formatNumber(value, 2);
            }
            
            function footPrn(data, name) {
                var value = $("ord_contract_ds").getCurrentRecord().get("totalPrn");
                return Leaf.formatNumber(value, 2);
            }
            
            function footInt(data, name) {
                var value = $("ord_contract_ds").getCurrentRecord().get("tolintamt");
                return Leaf.formatNumber(value, 2);
            }
            
            function footConschg(data, name) {
                var value = $("ord_contract_ds").getCurrentRecord().get("tolconschg");
                return Leaf.formatNumber(value, 2);
            }
            
            function payamtEditFunction(record, name) {
                var manualflag = record.get("manualflag");
                if (manualflag == 0) {
                    return '';
                } else {
                    return 'grid_nf';
                }
            }
            
            function print() {
                if (!isSaved) {
                    Leaf.showMessage('提示信息', '数据已修改,请先保存再打印');
                    return;
                }
            
                var record = $("ord_contract_ds").getCurrentRecord();
                var currentStatus = record.get("status");
                var printflg = record.get("printflg");
            
                if (Ext.isEmpty(printflg)) return;
            
                var requestSuccess = false;
                var requestStatus = "";
                Leaf.request({
                    url: '${/request/@context_path}/autocrud/agent.bgt.bgt_budgetapprove_get_status/execute',
                    para: {
                        budgetno: record.get("budgetno")
                    },
                    success: function(result) {
                        requestSuccess = true;
                        requestStatus = result.result.status;
            
                    },
                    scope: this,
                    sync: true
                });
            
                if (requestSuccess) {
            
                    if (requestStatus != currentStatus) {
                        Aurora.showMessage('提示信息', '该概算书信息已被其他用户更改,请重新查询!');
                        return;
                    }
            
                    if (requestStatus == 7) {
                        Aurora.showMessage('提示信息', '该概算书已被删除!');
                        return;
                    }
            
                    var msg = "";
                    if (printflg == 1) {
                        msg = "是否打印概算书(客户用)?";
                    } else if (printflg == 2) {
                        msg = "是否打印概算书(代理店用)?";
                    } else {
                        return;
                    }
            
                    var comfirm = Aurora.showConfirm('${l:JAVASCRIPT_MESSAGE}', msg, function() {
                        comfirm.close();
                        var success2 = false;
                        Aurora.request({
                            url: '${/request/@context_path}/autocrud/agent.bgt.bgt_budgetedit_print/execute',
                            para: {
                                budgetno: record.get("budgetno"),
                                status: currentStatus,
                                printflg: printflg
                            },
                            success: function(rst) {
                                record.set("status", rst.result.newstatus);
            
                                isSaved = true;
                                success2 = true;
                            },
                            scope: this,
                            sync: true
                        });
                        if (success2) {
                            printRep(printflg, record.get("customerflg"), record.get("budgetno"));
                        }
                    }, null, null, 100);
                }
            }
            
            // 打印帐票
            
            function printRep(publishType, custFlg, budgetno) {
                var obj = new FineReport();
                obj.ReportTemplate = "";
            
                // var url1 = '${/request/@context_path}/preview?__format=';
                // var url2 = '&__report=modules/agent/report/';
                // 概算书(本纸)
                if (publishType == "1") {
                    // var reportURL = url1 + "pdf" + url2 + "RA07.rptdesign" +
                    // "&budgetno="+budgetno;
                    // window.open(reportURL);
            
                    obj.ReportTemplate = "PAR007.cpt";
                }
                // 概算书(代理店控)
                else if (publishType == "2") {
                    // var reportURL = url1 + "pdf" + url2 + "RA08.rptdesign" +
                    // "&budgetno="+budgetno;
                    // window.open(reportURL);
            
                    obj.ReportTemplate = "PAR008.cpt";
                }
            
                obj.setParameter("BUDGETNO", budgetno);
                obj.setParameter("format", "PDF");
                obj.openReport();
            }
        ]]></script>

        <a:screenBody>
            <div/>
            <table border="0" cellpadding="0" cellspacing="0" width="766">
                <tr align="right">
                    <td width="71">
                        <span><![CDATA[概算书编号]]></span>
                    </td>
                    <td width="112">
                        <a:textField name="budgetno" bindTarget="ord_contract_ds" readOnly="true" width="105"/>
                    </td>
                    <td width="81">
                        <span><![CDATA[概算书打印日]]></span>
                    </td>
                    <td width="112">
                        <a:textField name="estisudate" bindTarget="ord_contract_ds" readOnly="true" renderer="Aurora.formatDate" width="105"/>
                    </td>
                    <td width="92">
                        <span><![CDATA[概算书类别]]></span>
                    </td>
                    <td width="102">
                        <a:comboBox name="hclc_budget_category_dis" bindTarget="ord_contract_ds" width="95"/>
                    </td>
                    <td width="72">
                        <span><![CDATA[概算书类型]]></span>
                    </td>
                    <td width="124">
                        <a:comboBox name="hclc_budget_type_dis" bindTarget="ord_contract_ds" width="115"/>
                    </td>
                </tr>
            </table>
            <table id="old_box" border="0" cellpadding="0" cellspacing="0" style="display:none" width="766">
                <tr align="right">
                    <td width="71">
                        <span><![CDATA[现金支付额]]></span>
                    </td>
                    <td width="112">
                        <a:numberField name="dp_cash_amt" allowFormat="true" allowNegative="false" bindTarget="ord_contract_ds" width="105"/>
                    </td>
                    <td width="92">
                        <span><![CDATA[免息首付款额度]]></span>
                    </td>
                    <td width="102">
                        <a:numberField name="dp_interfree_amt" allowFormat="true" allowNegative="false" bindTarget="ord_contract_ds" readOnly="true" width="95"/>
                    </td>
                    <td width="92">
                        <span><![CDATA[免息周期]]></span>
                    </td>
                    <td width="104">
                        <a:comboBox name="dp_interfree_prd_dis" bindTarget="ord_contract_ds" width="95"/>
                    </td>
                    <td width="81">
                        <span><![CDATA[免息支付日]]></span>
                    </td>
                    <td width="112">
                        <a:datePicker name="dp_interfree_paydt" bindTarget="ord_contract_ds" width="115"/>
                    </td>
                </tr>
            </table>
            <table id="release_box" border="0" cellpadding="0" cellspacing="0" style="display:none" width="766">
                <tr align="right">
                    <td width="642">
                        <span><![CDATA[回购函号]]></span>
                    </td>
                    <td width="124">
                        <a:textField name="hclc_repur_number" bindTarget="ord_contract_ds" width="115">
                            <a:events>
                                <a:event name="blur" handler="verify_repur"/>
                            </a:events>
                        </a:textField>
                    </td>
                </tr>
            </table>
            <table>
                <tr>
                    <td>
                        <a:form labelWidth="100" showmargin="false" title="客户信息" width="290">
                            <a:lov name="customername" bindTarget="ord_contract_ds" prompt="客户名称" width="170"/>
                            <a:textField name="customtel" bindTarget="ord_contract_ds" prompt="电话" width="170"/>
                            <a:textField name="ctitype_ctino" bindTarget="ord_contract_ds" prompt="证件类型/号码" width="170"/>
                            <a:textField name="delvinaddr" bindTarget="ord_contract_ds" prompt="交货地址" width="170"/>
                        </a:form>
                    </td>
                    <td>
                        <a:form labelWidth="90" showmargin="false" title="评分信息" width="207">
                            <a:textField name="basic_score" bindTarget="ord_contract_ds" prompt="基本分" readOnly="true" width="100"/>
                            <a:textField name="trade_score" bindTarget="ord_contract_ds" prompt="交易系数" readOnly="true" width="100"/>
                            <a:textField name="guarantor_score" bindTarget="ord_contract_ds" prompt="担保人系数" readOnly="true" width="100"/>
                            <a:textField name="score" bindTarget="ord_contract_ds" prompt="综合分" readOnly="true" width="100"/>
                        </a:form>
                    </td>
                    <td>
                        <a:form labelWidth="90" showmargin="false" title="代理店信息" width="257">
                            <a:textField name="dealercd_dis" bindTarget="ord_contract_ds" prompt="代理店代码" width="150"/>
                            <a:textField name="branchname" bindTarget="ord_contract_ds" prompt="分公司名称" width="150"/>
                            <a:textField name="tel" bindTarget="ord_contract_ds" prompt="电话" width="150"/>
                            <a:lov name="regionname" bindTarget="ord_contract_ds" prompt="发往地" width="150"/>
                        </a:form>
                    </td>
                </tr>
            </table>
            <table>
                <tr>
                    <td>
                        <a:form height="290" padding="0" showmargin="false" title="租赁详细信息" width="210">
                            <a:box column="1" labelWidth="70">
                                <a:numberField name="saleamt" allowFormat="true" allowNegative="false" bindTarget="ord_contract_ds" prompt="销售金额" width="120"/>
                            </a:box>
                            <a:box column="1" labelWidth="70">
                                <a:numberField name="machamt" allowFormat="true" allowNegative="false" bindTarget="ord_contract_ds" prompt="主机金额" width="120">
                                    <a:events>
                                        <a:event name="blur" handler="getBaseIntr"/>
                                    </a:events>
                                </a:numberField>
                            </a:box>
                            <a:box column="1" labelWidth="70">
                                <a:numberField name="optionsamt" allowFormat="true" allowNegative="false" bindTarget="ord_contract_ds" prompt="附件金额" width="120">
                                    <a:events>
                                        <a:event name="blur" handler="getBaseIntr"/>
                                    </a:events>
                                </a:numberField>
                            </a:box>
                            <a:box column="1" labelWidth="70">
                                <a:numberField name="downpayment" allowFormat="true" allowNegative="false" bindTarget="ord_contract_ds" prompt="首付款" width="120">
                                    <a:events>
                                        <a:event name="blur" handler="getBaseIntr"/>
                                    </a:events>
                                </a:numberField>
                            </a:box>
                            <a:box column="1" labelWidth="70">
                                <a:numberField name="ovhdexpenses" allowFormat="true" allowNegative="false" bindTarget="ord_contract_ds" prompt="管理费" width="120"/>
                            </a:box>
                            <a:box column="1" labelWidth="70">
                                <a:numberField name="margin" allowFormat="true" allowNegative="false" bindTarget="ord_contract_ds" prompt="保证金" width="120"/>
                            </a:box>
                            <a:box column="1" labelWidth="70">
                                <a:numberField name="detention" allowFormat="true" allowNegative="false" bindTarget="ord_contract_ds" prompt="留购金" width="120"/>
                            </a:box>
                            <a:box column="2" labelWidth="70">
                                <a:numberField name="stdintrrate" bindTarget="ord_contract_ds" prompt="基准利率" readOnly="true" renderer="interestRenderer" width="100"/>
                                <label><![CDATA[%]]></label>
                            </a:box>
                            <a:box column="1" labelWidth="70">
                                <span><![CDATA[&nbsp;]]></span>
                            </a:box>
                        </a:form>
                    </td>
                    <td>
                        <a:form height="290" padding="0" showmargin="false" title="物件名称" width="287">
                            <a:box labelWidth="90">
                                <a:textField name="modelname" bindTarget="ord_contract_ds" prompt="机种名称" width="180"/>
                            </a:box>
                            <a:box labelWidth="90">
                                <a:lov name="modelcd" bindTarget="ord_contract_ds" prompt="机型" width="180">
                                    <a:events>
                                        <a:event name="select" handler="getBaseIntr"/>
                                    </a:events>
                                </a:lov>
                            </a:box>
                            <a:box labelWidth="90">
                                <a:lov name="pattern" bindTarget="ord_contract_ds" prompt="型号" width="180"/>
                            </a:box>
                            <a:box labelWidth="90">
                                <a:textField name="serialno" bindTarget="ord_contract_ds" prompt="机号" width="180"/>
                            </a:box>
                            <a:box column="1" labelWidth="90">
                                <a:datePicker name="leasebgndt" bindTarget="ord_contract_ds" prompt="租赁开始日" width="180">
                                    <a:events>
                                        <a:event name="select" handler="getBaseIntr"/>
                                    </a:events>
                                </a:datePicker>
                            </a:box>
                            <a:box labelWidth="90">
                                <a:datePicker name="paybgndt" bindTarget="ord_contract_ds" prompt="支付开始日" width="180">
                                    <a:events>
                                        <a:event name="select" handler="getBaseIntr"/>
                                    </a:events>
                                </a:datePicker>
                            </a:box>
                            <a:box labelWidth="90">
                                <a:numberField name="leaseprnc" bindTarget="ord_contract_ds" prompt="租赁本金" renderer="numberRenderer" width="180"/>
                            </a:box>
                            <a:box column="2" labelWidth="90">
                                <a:numberField name="leaseprd" allowDecimals="false" allowNegative="false" bindTarget="ord_contract_ds" prompt="租赁期间" width="180">
                                    <a:events>
                                        <a:event name="blur" handler="getBaseIntr"/>
                                    </a:events>
                                </a:numberField>
                            </a:box>
                            <a:box column="2" labelWidth="90">
                                <a:numberField name="interest" bindTarget="ord_contract_ds" decimalPrecision="3" prompt="利率" width="160"/>
                                <label><![CDATA[%]]></label>
                            </a:box>
                        </a:form>
                    </td>
                    <td>
                        <a:form padding="0" showmargin="false" title="配置">
                            <a:textArea name="spec" bindTarget="ord_contract_ds" height="161" padding="0" width="249"/>
                        </a:form>
                        <a:form padding="0" showmargin="false" title="附属品">
                            <a:textArea name="opt1" bindTarget="ord_contract_ds" height="60" padding="0" width="250"/>
                        </a:form>
                    </td>
                </tr>
            </table>
            <table border="0" cellpadding="0" cellspacing="0" width="766">
                <tr>
                    <td width="220">
                        <!--style="display:none;" -->
                        <div>
                            <a:hBox>
                                <a:checkBox name="rtnway" bindTarget="ord_contract_ds" style="margin-right:0;"/>
                                <label><![CDATA[不均等付款]]></label>
                                <div><![CDATA[&nbsp;&nbsp;&nbsp;]]></div>
                                <div id="try_calculat_box">
                                    <table>
                                        <tr>
                                            <td>
                                                <a:checkBox name="roundcalcflag" bindTarget="ord_contract_ds" style="margin-right:0;"/>
                                            </td>
                                            <td>
                                                <label><![CDATA[百元取整]]></label>
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                            </a:hBox>
                        </div>
                    </td>
                    <td align="center" width="576">
                        <div style="width:100%">
                            <a:hBox showmargin="false">
                                <a:button name="try_btn" click="try_calculate" text="租金试算"/>
                                <div><![CDATA[&nbsp;&nbsp;&nbsp;]]></div>
                                <a:button name="back_btn" id="reset_btn" click="reset_form" text="清除"/>
                            </a:hBox>
                        </div>
                    </td>
                </tr>
            </table>
            <div id="calculate_result_div" style="display:none">
                <!-- style="display:none"-->
                <a:form padding="0" showmargin="false" title="试算结果" width="768">
                    <table border="0" cellpadding="0" cellspacing="0" width="100%">
                        <tr>
                            <td width="50%">
                                <a:box column="1" labelWidth="120">
                                    <a:numberField name="tolleasechg" bindTarget="ord_contract_ds" prompt="租金合计" readOnly="true" renderer="numberRenderer" width="220"/>
                                </a:box>
                            </td>
                            <td>
                                <a:box column="1" labelWidth="120">
                                    <a:numberField name="perlchg_fir" bindTarget="ord_contract_ds" prompt="每月租金(第一期)" readOnly="true" renderer="numberRenderer" width="220"/>
                                </a:box>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <a:box column="1" labelWidth="120">
                                    <a:numberField name="paysum" bindTarget="ord_contract_ds" prompt="签约时支付款" readOnly="true" renderer="numberRenderer" width="220"/>
                                </a:box>
                            </td>
                            <td>
                                <div id="perlchg_sec_number" style="display:none">
                                    <a:box column="1" labelWidth="120">
                                        <a:numberField name="perlchg_sec_dis" bindTarget="ord_contract_ds" prompt="每月租金(第二期)" readOnly="true" renderer="numberRenderer" width="220"/>
                                    </a:box>
                                </div>
                                <div id="perlchg_sec_text" style="display:none">
                                    <a:box column="1" labelWidth="120">
                                        <a:textField name="perlchg_sec_dis" bindTarget="ord_contract_ds" prompt="每月租金(第二期)" readOnly="true" width="220"/>
                                    </a:box>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <a:box column="1" labelWidth="120">
                                    <a:numberField name="paytimes" allowDecimals="false" allowFormat="false" allowNegative="false" bindTarget="ord_contract_ds" prompt="支付总回数(回)" readOnly="true" width="220"/>
                                </a:box>
                            </td>
                            <td>
                                <div id="result_fRate_box" style="display:block">
                                    <a:box column="1" labelWidth="120">
                                        <a:numberField name="unit_adjust_amount" bindTarget="ord_contract_ds" prompt="调整租金(每0.1%)" readOnly="true" width="220"/>
                                    </a:box>
                                </div>
                            </td>
                        </tr>
                    </table>
                </a:form>
                <a:box padding="0" style="margin-top:10px" width="768">
                    <a:table id="result_table" bindTarget="detail_ds" canWheel="false" percentwidth="100" title="  ">
                        <a:columns>
                            <a:column name="manualflag" editor="grid_cb"/>
                            <a:column name="times" prompt="回数"/>
                            <a:column name="paydt" footerRenderer="footTitle" prompt="支付日"/>
                            <a:column name="payamt" align="right" editorFunction="payamtEditFunction" footerRenderer="footPayAmt" prompt="支付金额" renderer="numberRenderer"/>
                            <a:column prompt="明细(合同利息)">
                                <a:column name="principal" align="right" footerRenderer="footPrn" prompt="本金" renderer="numberRenderer"/>
                                <a:column name="interest" align="right" footerRenderer="footInt" prompt="利息" renderer="numberRenderer"/>
                            </a:column>
                            <a:column name="prncbalance" align="right" prompt="本金余额" renderer="numberRenderer"/>
                        </a:columns>
                        <a:editors>
                            <a:checkBox id="grid_cb"/>
                            <a:numberField id="grid_nf" allowDecimals="true" allowFormat="true" allowNegative="false"/>
                        </a:editors>
                    </a:table>
                    <table border="0" cellpadding="0" cellspacing="0" style="margin-top:10px;margin-bottom:25px" width="100%">
                        <tr>
                            <td>
                                <a:radio name="printflg" bindTarget="ord_contract_ds" layout="horizontal" width="400">
                                    <a:items>
                                        <a:item label="概算书(客户用)" value="1"/>
                                        <a:item label="概算书(代理店用)" value="2"/>
                                    </a:items>
                                </a:radio>
                            </td>
                            <td align="right">
                                <a:switch test="/parameter/@isAdd">
                                    <a:case value="0">
                                        <a:button click="back" text="HAP_BACK"/>
                                    </a:case>
                                </a:switch>
                            </td>
                            <td align="right">
                                <a:button id="saveButton" click="saveResult" text="保存结果"/>
                            </td>
                            <td align="right">
                                <a:button click="print" text="打印"/>
                            </td>
                        </tr>
                    </table>
                </a:box>
            </div>
        </a:screenBody>
        <script><![CDATA[
        
            //initPageView();
        
        ]]></script>
    </a:view>
</a:screen>