<?xml version="1.0" encoding="UTF-8"?>
<!--
    2019-9-6  Spencer 3893  合同回购申请创建明细
 -->
<a:screen xmlns:a="http://www.leaf-framework.org/application" customizationEnabled="true" dynamiccreateenabled="true" trace="true">
    <a:init-procedure/>
    <a:view>
        <a:link id="con_repo_submit_link" model="cont.CON_REPO001.submit_change_req" modelaction="execute"/>
        <a:link id="con_repo001_cancel_link" model="cont.CON731.cancel_change_req" modelaction="execute"/>
        <a:link id="con_repo001_calc_cashflow_link" model="cont.CON_REPO001.calc_cashflow" modelaction="execute"/>
        <a:link id="con_repo001_calc_repo_date_amount_link" model="cont.CON_REPO001.calc_repo_date_amount" modelaction="execute"/>
        <a:link id="${/parameter/@layout_code}${/parameter/@tree_code}_hls_fin_calculator_update_link_id"
                url="${/request/@context_path}/modules/cont/CON_REPO001/hls_fin_calculator_update_n.lview"/>
        <a:link id="con_update_record_link_id" model="cont.CON_REPO001.save_calc_from_con" modelaction="execute"/>
        <a:link id="con_update_record_link1_id" model="cont.CON_REPO001.con_change_calc_from_con" modelaction="execute"/>

        <script type="text/javascript"><![CDATA[
        var calc_flag = false;
        var maunal_calc_flag = false;
        Leaf.onReady(function() {
            var ds_id = get_dsid_by_tabcode_basetable(window['${/parameter/@layout_code}_layoutDataSetList'],'F_BASE_01', 'con_contract');
            if ($(ds_id)) {
                $(ds_id).setQueryParameter('contract_id','${/parameter/@contract_id}');
                $(ds_id).query();
            }
        });
        function open_contract_win(ds_id, record_id) {
            var record = $(ds_id).findById(record_id);
            var param = record.data;
            param['function_code'] = 'CON301';
            param['function_usage'] = 'QUERY';
            param['download'] = 'Y';
            param['maintain_type'] = 'UPDATE';
            param['url_title'] = '${l:CON301.CONTRACT_DETAIL}';
            hls_doc_get_layout_code('con_contract_get_layout_code_link_id', param, 'con_contract_modify_link', ds_id);
        }
        //新增和加载时调用form
        window['${/parameter/@bp_seq}${/parameter/@layout_code}_on_layout_dynamic_form_add_and_load'] = function(ds, record, config_records, bp_seq) {
            var repurchase_types = record.get('repurchase_types');
            if (repurchase_types == 'ONE_TIME_REPURCHASE') {
                record.getField('payment_frequency_n').setRequired(false);
                record.getField('payment_frequency').setRequired(false);
                record.getField('payment_period').setRequired(false);
                record.getField('payment_frequency_n').setReadOnly(true);
                record.getField('payment_period').setReadOnly(true);
                record.set('payment_period', 1);
                record.set('payment_frequency', null);
                record.set('payment_frequency_n', null);
            }
        };
        // window['${/parameter/@layout_code}_SAVE_LAYOUT_DYNAMIC_CLICK'] = function () {
        //     $('${/parameter/@layout_code}_save').disable(); //按钮不可用
        //     window['${/parameter/@bp_seq}${/parameter/@layout_code}_lock_layout_dynamic_window']();
        //     if (calc_flag) {
        //         maunal_calc_flag = true;
        //     }else{
        //         window['${/parameter/@bp_seq}${/parameter/@layout_code}_unlock_layout_dynamic_window']();
        //         Leaf.showMessage('${l:HLS.PROMPT}', '请先计算，再保存！');
        //         $('${/parameter/@layout_code}_save').enable(); //按钮可用
        //         return;
        //     }
        // };
        window['${/parameter/@bp_seq}${/parameter/@layout_code}_on_layout_dynamic_update'] = function(ds, record, name, value, old_value, bp_seq) {
            var ds_id = get_dsid_by_tabcode_basetable(window['${/parameter/@layout_code}_layoutDataSetList'],'F_BASE_01', 'con_contract');
            if (ds == $(ds_id)) {
                var repurchase_types = record.get('repurchase_types');
                if (name != 'repurchase_types_n') {
                    if (repurchase_types == null || repurchase_types == undefined) {
                        Leaf.showMessage('${l:HLS.PROMPT}', '请先维护基本信息中的回购类型！');
                        return;
                    }
                }
                // 一次性回购
                if (repurchase_types == 'ONE_TIME_REPURCHASE') {
                    // 回购价款总额 = 逾期租金 + 逾期罚息（调整后）+ 剩余本金 + 留购价 + 手续费 + 资金占用费
                    // sum_overdue_amount+ccr_due_amount+sum_unreceived_principal+residual_value+repurchase_service_charges+fund_possession_cost
                    // 回购价款计算基数 = 逾期租金 + 逾期罚息（调整后）+ 剩余本金 + 留购价
                    // 逾期罚息（调整后）
                    record.getField('payment_frequency_n').setRequired(false);
                    record.getField('payment_frequency').setRequired(false);
                    record.getField('payment_period').setRequired(false);
                    record.getField('payment_frequency_n').setReadOnly(true);
                    record.getField('payment_period').setReadOnly(true);
                    record.set('payment_period', 1);
                    record.set('payment_frequency', null);
                    record.set('payment_frequency_n', null);
                    if (name == 'ccr_due_amount') {
                        var due_amount = record.get('due_amount') || 0;
                        if (due_amount < value) {
                            Leaf.showMessage('${l:HLS.PROMPT}', '调整后的罚息必须小于等于逾期罚息！');
                        }
                        var repurchase_count_amount = plus(plus(plus(record.get('sum_overdue_amount') || 0, value || 0), record.get('sum_unreceived_principal') || 0)
                            , record.get('residual_value') || 0);
                        var repurchase_tatal_amount = plus(plus(repurchase_count_amount, record.get('repurchase_service_charges') || 0), record.get('fund_possession_cost') || 0);
                        record.set('repurchase_tatal_amount', repurchase_tatal_amount);
                        record.set('repurchase_count_amount', repurchase_count_amount);
                    }
                    // 手续费
                    if (name == 'repurchase_service_charges') {
                        var repurchase_count_amount = plus(plus(plus(record.get('sum_overdue_amount') || 0, record.get('ccr_due_amount') || 0), record.get('sum_unreceived_principal') || 0)
                            , record.get('residual_value') || 0);
                        var repurchase_tatal_amount = plus(plus(repurchase_count_amount, value || 0), record.get('fund_possession_cost') || 0);
                        record.set('repurchase_tatal_amount', repurchase_tatal_amount);
                        record.set('repurchase_count_amount', repurchase_count_amount);
                    }
                    // 资金占用费value
                    if (name == 'fund_possession_cost') {
                        var repurchase_count_amount = plus(plus(plus(record.get('sum_overdue_amount') || 0, record.get('ccr_due_amount') || 0), record.get('sum_unreceived_principal') || 0)
                            , record.get('residual_value') || 0);
                        var repurchase_tatal_amount = plus(plus(repurchase_count_amount, record.get('repurchase_service_charges') || 0), value || 0);
                        record.set('repurchase_tatal_amount', repurchase_tatal_amount);
                        record.set('repurchase_count_amount', repurchase_count_amount);
                    }
                    // 分期回购
                } else if (repurchase_types == 'STAGE_REPURCHASE') {
                    record.getField('payment_frequency_n').setRequired(true);
                    record.getField('payment_frequency').setRequired(true);
                    record.getField('payment_period').setRequired(true);
                    record.getField('payment_frequency_n').setReadOnly(false);
                    record.getField('payment_period').setReadOnly(false);
                    // 回购价款总额 = 逾期租金 + 逾期罚息（调整后）+ 剩余本金 + 留购价 + 手续费 + 资金占用费
                    // sum_overdue_amount+ccr_due_amount+sum_unreceived_principal+residual_value+repurchase_service_charges+fund_possession_cost
                    // 回购价款计算基数 = 逾期租金 + 逾期罚息（调整后）+ 剩余本金 + 留购价
                    // 逾期罚息（调整后）
                    if(name == 'payment_period'){
                        if(value <= 0 || value == NaN || value == undefined){
                            Leaf.showMessage('${l:HLS.PROMPT}', '支付期数请填写大于0的整数！');
                            return;
                        }
                    }
                    if (name == 'ccr_due_amount') {
                        var due_amount = record.get('due_amount') || 0;
                        if (due_amount < value) {
                            Leaf.showMessage('${l:HLS.PROMPT}', '调整后的罚息必须小于等于逾期罚息！');
                            return;
                        }
                        var repurchase_count_amount = plus(plus(plus(record.get('sum_overdue_amount') || 0, value || 0), record.get('sum_unreceived_principal') || 0)
                            , record.get('residual_value') || 0);
                        var repurchase_tatal_amount = plus(plus(repurchase_count_amount, record.get('repurchase_service_charges') || 0), record.get('fund_possession_cost') || 0);
                        record.set('repurchase_tatal_amount', repurchase_tatal_amount);
                        record.set('repurchase_count_amount', repurchase_count_amount);
                    }
                    // 手续费
                    if (name == 'repurchase_service_charges') {
                        var repurchase_count_amount = plus(plus(plus(record.get('sum_overdue_amount') || 0, record.get('ccr_due_amount') || 0), record.get('sum_unreceived_principal') || 0)
                            , record.get('residual_value') || 0);
                        var repurchase_tatal_amount = plus(plus(repurchase_count_amount, value || 0), record.get('fund_possession_cost') || 0);
                        record.set('repurchase_tatal_amount', repurchase_tatal_amount);
                        record.set('repurchase_count_amount', repurchase_count_amount);
                    }
                    // 资金占用费value
                    if (name == 'fund_possession_cost') {
                        var repurchase_count_amount = plus(plus(plus(record.get('sum_overdue_amount') || 0, record.get('ccr_due_amount') || 0), record.get('sum_unreceived_principal') || 0)
                            , record.get('residual_value') || 0);
                        var repurchase_tatal_amount = plus(plus(repurchase_count_amount, record.get('repurchase_service_charges') || 0), value || 0);
                        record.set('repurchase_tatal_amount', repurchase_tatal_amount);
                        record.set('repurchase_count_amount', repurchase_count_amount);
                    }
                }
            }
            if(name == 'sum_overdue_amount'){
                var repurchase_count_amount = plus(plus(plus(value || 0, record.get('ccr_due_amount') || 0), record.get('sum_unreceived_principal') || 0)
                    , record.get('residual_value') || 0);
                var repurchase_tatal_amount = plus(plus(repurchase_count_amount, record.get('repurchase_service_charges') || 0), record.get('fund_possession_cost') || 0);
                record.set('repurchase_tatal_amount', repurchase_tatal_amount);
                record.set('repurchase_count_amount', repurchase_count_amount);
            }
            if(name == 'sum_unreceived_principal'){
                var repurchase_count_amount = plus(plus(plus(record.get('sum_overdue_amount') || 0, record.get('ccr_due_amount') || 0), value || 0)
                    , record.get('residual_value') || 0);
                var repurchase_tatal_amount = plus(plus(repurchase_count_amount, record.get('repurchase_service_charges') || 0), record.get('fund_possession_cost') || 0);
                record.set('repurchase_tatal_amount', repurchase_tatal_amount);
                record.set('repurchase_count_amount', repurchase_count_amount);
            }
            if (name == 'repurchase_date') {
                // last_rent_due_date 前期租金支付约定日：自动带出原合同报价现金流中，回购解约日上一期应收租金的日期。
                Leaf.request({
                    url: $('con_repo001_calc_repo_date_amount_link').getUrl(),
                    para: {
                        contract_id: record.get('contract_id'),
                        repurchase_date: value
                    },
                    success: function (res) {
                        record.set('last_rent_due_date', res.result.last_rent_due_date);
                        record.set('sum_received_rent_amount', res.result.sum_received_rent_amount);
                        record.set('sum_unreceived_rent_amount', res.result.sum_unreceived_rent_amount);
                        record.set('sum_overdue_amount', res.result.sum_overdue_amount);
                        record.set('sum_unreceived_principal', res.result.sum_unreceived_principal);
                        record.set('due_amount', res.result.due_amount);
                        record.set('ccr_due_amount', res.result.due_amount);
                    },
                    failure: function () {

                    },
                    error: function () {

                    },
                    scope: this
                });
            }
        };

        window['${/parameter/@layout_code}_submit_approval_layout_dynamic_click'] = function() {
                $('${/parameter/@layout_code}_submit_approval').disable();
                var req_ds_id = get_dsid_by_tabcode_basetable(window['${/parameter/@layout_code}_layoutDataSetList'], 'F_BASE_01', 'con_contract');
                var req_record = $(req_ds_id).getAt(0);
                var case_type = '';
                var document_type = '${/parameter/@document_type}';
                var calc_session_id = req_record.get('calc_session_id');

                window['${/parameter/@bp_seq}${/parameter/@layout_code}_lock_layout_dynamic_window']();
                if ($(req_ds_id).validate($('${/parameter/@layout_code}_submit_approval').enable())) {
                    // if (req_record.dirty) {
                    //     Leaf.showMessage('${l:HLS.PROMPT}', '${l:HLS.EXECUTE_AFTER_SAVE}');
                    //     window['${/parameter/@bp_seq}${/parameter/@layout_code}_unlock_layout_dynamic_window']();
                    //     return;
                    // }
                    $('${/parameter/@layout_code}_submit_approval').disable();
                    $('${/parameter/@layout_code}_save').disable();
                    $('${/parameter/@layout_code}_user_button1').disable();
                    $('${/parameter/@layout_code}_user_button3').disable();
                    setTimeout(window['${/parameter/@layout_code}_SAVE_LAYOUT_DYNAMIC_CLICK'](con_repo001_submit), 2000);
                } else {
                    window['${/parameter/@bp_seq}${/parameter/@layout_code}_unlock_layout_dynamic_window']();
                }

        };
        function con_repo001_submit() {
            var req_ds_id = get_dsid_by_tabcode_basetable(window['${/parameter/@layout_code}_layoutDataSetList'], 'F_BASE_01', 'con_contract');
            var req_record = $(req_ds_id).getAt(0);
            window['${/parameter/@bp_seq}${/parameter/@layout_code}_lock_layout_dynamic_window']();
            Leaf.request({
                url: $('con_repo_submit_link').getUrl(),
                para: {
                    change_req_id:' ${/parameter/@change_req_id}',
                    layout_code: '${/parameter/@layout_code}'
                },
                success: function(res) {
                    $('${/parameter/@layout_code}_submit_approval').enable();
                    $('${/parameter/@layout_code}_save').enable();
                    $('${/parameter/@layout_code}_user_button1').enable();
                    $('${/parameter/@layout_code}_user_button3').enable();
                    $('${/parameter/@winid}').close();
                    window['${/parameter/@bp_seq}${/parameter/@layout_code}_unlock_layout_dynamic_window']();
                },
                failure: function() {
                    $('${/parameter/@layout_code}_submit_approval').enable();
                    $('${/parameter/@layout_code}_save').enable();
                    $('${/parameter/@layout_code}_user_button1').enable();
                    $('${/parameter/@layout_code}_user_button3').enable();
                    window['${/parameter/@bp_seq}${/parameter/@layout_code}_unlock_layout_dynamic_window']();
                },
                error: function() {
                    $('${/parameter/@layout_code}_submit_approval').enable();
                    $('${/parameter/@layout_code}_save').enable();
                    $('${/parameter/@layout_code}_user_button1').enable();
                    $('${/parameter/@layout_code}_user_button3').enable();
                    window['${/parameter/@bp_seq}${/parameter/@layout_code}_unlock_layout_dynamic_window']();
                },
                scope: this
            });
        }

        //报价计算
        window['${/parameter/@layout_code}_user_button1_layout_dynamic_click'] = function() {
            window['${/parameter/@bp_seq}${/parameter/@layout_code}_lock_layout_dynamic_window']();
            var ds_id_head = get_dsid_by_basetable(window['${/parameter/@layout_code}_layoutDataSetList'],'con_contract');
            var cashflow_ds_id = get_dsid_by_basetable(window['${/parameter/@layout_code}_layoutDataSetList'], 'con_contract_cashflow');
            var record = $(ds_id_head).getCurrentRecord();
            var price_list = record.get('price_list');
                var calc_session_id = record.get('calc_session_id');
                var parent_pk_value = record.get('contract_id');
                var calc_type = '${/parameter/@calc_type}' || 'CLASSIC_CALCULATOR';
               if (record.dirty == true) {
                Leaf.showMessage('${l:PROMPT}', '${l:HLS.EXECUTE_AFTER_SAVE}');
                   window['${/parameter/@bp_seq}${/parameter/@layout_code}_unlock_layout_dynamic_window']();
                   return;
               }
               if($(ds_id_head).validate()){
                   if(record.get('repurchase_types') == 'ONE_TIME_REPURCHASE'){
                       Leaf.request({
                           url: $('con_repo001_calc_cashflow_link').getUrl(),
                           para: {
                               contract_id: record.get('contract_id'),
                           },
                           success: function(res) {
                               calc_flag = true;
                               Leaf.SideBar.enable = true;
                               Leaf.SideBar.show({msg: '计算成功!',duration: 2000});
                               var ca_ds_id = get_dsid_by_tabcode_basetable(window['${/parameter/@layout_code}_layoutDataSetList'],'G_QUOTATION_04', 'con_contract_cashflow');
                               if (ca_ds_id) {
                                   $(ca_ds_id).query();
                               }
                               window['${/parameter/@bp_seq}${/parameter/@layout_code}_unlock_layout_dynamic_window']();
                               $('${/parameter/@layout_code}_user_button1').enable();
                           },
                           failure: function() {
                               window['${/parameter/@bp_seq}${/parameter/@layout_code}_unlock_layout_dynamic_window']();
                               $('${/parameter/@layout_code}_user_button1').enable();
                           },
                           error: function() {
                               window['${/parameter/@bp_seq}${/parameter/@layout_code}_unlock_layout_dynamic_window']();
                               $('${/parameter/@layout_code}_user_button1').enable();
                           },
                           scope: this
                       });
                   }else {
                       Leaf.request({
                           url: $('con_update_record_link1_id').getUrl(),
                           para: {
                               'contract_id': record.get('contract_id')
                           },
                           success: function(res) {
                               if (calc_session_id) {
                                   //直接进入报价页面
                                   var win = new Leaf.Window({
                                       id: 'hls_fin_calc_quotation_update_link_winid',
                                       params: {
                                           document_id: parent_pk_value,
                                           price_list: price_list,
                                           document_category: 'CONTRACT',
                                           contract_status:record.get('contract_status'),
                                           maintain_type: 'MODIFY',
                                           calc_session_id: record.get('calc_session_id'),
                                           quotation_id: record.get('quotation_id'),
                                           dsId: cashflow_ds_id,
                                           winId: 'hls_fin_calc_quotation_update_link_winid',
                                           global_flag: 'Y',
                                           id_num: 1,
                                           calc_type: calc_type,
                                           recreate_L_formula: 'N'
                                       },
                                       url: $('${/parameter/@layout_code}${/parameter/@tree_code}_hls_fin_calculator_update_link_id').getUrl(),
                                       fullScreen: true,
                                       draggable: true
                                   });
                                   win.on('close', function () {
                                       $(cashflow_ds_id).query();
                                       $(ds_id_head).query();
                                   });
                                   window['${/parameter/@bp_seq}${/parameter/@layout_code}_unlock_layout_dynamic_window']();
                               }
                           },
                           failure: function() {
                               window['${/parameter/@bp_seq}${/parameter/@layout_code}_unlock_layout_dynamic_window']();
                           },
                           error: function() {
                               window['${/parameter/@bp_seq}${/parameter/@layout_code}_unlock_layout_dynamic_window']();
                           },
                           scope: this
                       });
                   }
               }else{
                   window['${/parameter/@bp_seq}${/parameter/@layout_code}_unlock_layout_dynamic_window']();

               }


        };
        //取消变更
        window['${/parameter/@layout_code}_user_button3_layout_dynamic_click'] = function() {
            $('${/parameter/@layout_code}_user_button3').disable(); //按钮不可用
            Leaf.showConfirm('${l:HLS.PROMPT}', '是否确认取消变更？', function() {
                window['${/parameter/@bp_seq}${/parameter/@layout_code}_lock_layout_dynamic_window']();
                Leaf.request({
                    url: $('con_repo001_cancel_link').getUrl(),
                    para: {
                        change_req_id: ${/parameter/@change_req_id}
                    },
                    success: function(res) {
                        $('${/parameter/@layout_code}_user_button3').enable(); //按钮启用
                        window['${/parameter/@bp_seq}${/parameter/@layout_code}_unlock_layout_dynamic_window']();
                        $('${/parameter/@winid}').close();
                    },
                    failure: function() {
                        $('${/parameter/@layout_code}_user_button3').enable(); //按钮启用
                        window['${/parameter/@bp_seq}${/parameter/@layout_code}_unlock_layout_dynamic_window']();
                    },
                    error: function() {
                        $('${/parameter/@layout_code}_user_button3').enable(); //按钮启用
                        window['${/parameter/@bp_seq}${/parameter/@layout_code}_unlock_layout_dynamic_window']();
                    },
                    scope: this
                });
            });
        };
        window['${/parameter/@layout_code}_on_layout_dynamic_grid_load'] = function (ds, qpara, bp_seq) {

        };
        window['${/parameter/@layout_code}_dynamic_link_renderer'] = function(value, record, name, config_record, bp_seq) {
            window['${/parameter/@layout_code}_hls_link_render_record'][record.id + '---' + name] = record;
            if (name == 'contract_number' && value) {
                return '<a href="javascript:open_contract_win(\'' + record.ds.id + '\',\'' + record.id + '\')">' + value + '</a>';
            }else if (name == 'description') {
                if (record.get('important_flag') == 'Y') {
                    return '<span style="color: RED; ">' + value + '</span>';
                }
                return value;
            }
        }
        //图片渲染
        window['${/parameter/@bp_seq}${/parameter/@layout_code}_dynamic_pic_renderer'] = function(record, name, bp_seq) {
            var result = name.match(/(.*)_pic$/);
            if (result) {
                var pic_value = record.get(result[1]);
                if (pic_value == 'OUTFLOW') {
                    return '<img src="${/request/@context_path}/images/outflow.png" style="margin-top:4px"/>';
                } else if (pic_value == 'INFLOW') {
                    return '<img src="${/request/@context_path}/images/inflow.png" style="margin-top:4px"/>';
                } else if (pic_value == 'NONCASH') {
                    return '<img src="${/request/@context_path}/images/noncash.png" style="margin-top:4px"/>';
                } else if (pic_value == 'CASH') {
                    return '<img src="${/request/@context_path}/images/cash.png" style="margin-top:4px"/>';
                }
            }
        };
        //查询时调用(grid,table,gridBox)
        window['${/parameter/@bp_seq}${/parameter/@layout_code}_on_layout_dynamic_grid_query'] = function(ds, qpara, bp_seq) {
            var ds_us_id = get_dsid_by_tabcode_basetable(window['${/parameter/@layout_code}_layoutDataSetList'],'F_BASE_03', 'hls_document_use_seal');
            if (ds == $(ds_us_id)) {
                ds.setQueryParameter('document_table','CON_CONTRACT_CHANGE_REQ');
                ds.setQueryParameter('change_req_id','${/parameter/@change_req_id}');
                ds.query();
            }
        };
        ]]></script>
        <a:screen-include screen="modules/cont/CON500/con_contract_get_layout_code.lview"/>
    </a:view>
</a:screen>