<?xml version="1.0" encoding="UTF-8"?>
<bm:model xmlns:o="leaf.database.local.oracle" xmlns:e="leaf.service.exception" xmlns:s="leaf.plugin.script" xmlns:f="leaf.database.features" xmlns:bm="http://www.leaf-framework.org/schema/bm" alias="t1">
    <bm:fields/>
    <bm:primary-key/>
    <bm:features>
        <o:sequence-pk/>
        <f:standard-who/>
        <!-- make sure bm-script must be the LAST feature -->
        <s:bm-script><![CDATA[
            function new_bm_map(name) {
                return new CompositeMap("bm", 'http://www.leaf-framework.org/schema/bm', name);
            }
            
            function create_query_field(query_field, queryoperator) {
                if (query_field) {
                    var qf = new_bm_map('query-field');
                    qf.field = query_field;
                    qf.queryoperator = queryoperator; //attribute name must in lowercase
                    $this.addQueryField(qf.getData()); //get it's java type...
                }
            }
            
            function create_order_by_fields() {
                var robf = $ctx.model.getChild('rootpath_order_by_fields');
                var order_by_fields_path = ( !! robf) ? robf.getChildren() : [];
                var order_by_fields = '';
                if (order_by_fields_path.length) {
                    for (var i = 0;i < order_by_fields_path.length;i++) {
                        var order_by_field_result = order_by_fields_path[i];
                        var order_type = '';
                        if (order_by_field_result.grid_order_type == 'DESCENDING') {
                            order_type = 'desc';
                        } else {
                            order_type = 'asc';
                        }
                        var temp_field_name = '';
                        if (order_by_field_result.data_type == 'NUMBER') {
                            temp_field_name = 'to_number(' + order_by_field_result.column_name + ')';
                        } else {
                            temp_field_name = order_by_field_result.column_name;
                        }
                        if (order_by_fields) {
                            order_by_fields = order_by_fields + ',' + temp_field_name + ' ' + order_type;
                        } else {
                            order_by_fields = temp_field_name + ' ' + order_type;
                        }
                    }
                    $this.setDefaultOrderby(order_by_fields);
                }
            }
            
            function override() {
                var qf_root = $this.getObjectContext().getChild("query-fields");
                for (var i = 0;i < override_queryfields.length;i++) {
                    var override_queryfield = override_queryfields[i];
                    importClass(Packages.uncertain.composite.CompositeUtil);
                    var field_name = '';
                    var query_handle = '';
                    if (override_queryfield['name']) {
                        field_name = 'name';
                        query_handle = 'queryexpression';
                    } else if (override_queryfield['field']) {
                        field_name = 'field';
                        query_handle = 'queryoperator';
                    }
                    var query_field = CompositeUtil.findChild(qf_root, "query-field", "field", override_queryfield[field_name]);
                    if (query_field) {
                        query_field.remove('field');
                        query_field.remove('queryoperator');
                        query_field.put(field_name, override_queryfield[field_name]);
                        query_field.put(query_handle, override_queryfield[query_handle]);
                    } else {
                        var qf = new_bm_map('query-field');
                        qf[field_name] = override_queryfield[field_name];
                        qf[query_handle] = override_queryfield[query_handle];
                        $this.addQueryField(qf.getData());
                    }
                }
            }
            
            function add_datafilter() {
                if (add_datafilters.length) {
                    var model = new CompositeMap($this.getObjectContext());
                    var datafilters = model.getChild('data-filters');
                    if (!datafilters) {
                        datafilters = model.createChildNS('data-filters');
                    }
                    for (var i = 0;i < add_datafilters.length;i++) {
                        var add_datafilter = add_datafilters[i];
                        var dataf = datafilters.createChildNS('data-filter');
                        dataf.name = add_datafilter.name;
                        dataf.enforceoperations = 'query';
                        dataf.expression = add_datafilter.expression;
                    }
                }
            }
            
            function remove_datafilter(name) {
                var datafilters = $this.getObjectContext().getChild("data-filters");
                importClass(Packages.uncertain.composite.CompositeUtil);
                if (datafilters) {
                    var dataf = CompositeUtil.findChild(datafilters, "data-filter", "name", name);
                    if (dataf) {
                        datafilters.removeChild(dataf);
                    }
                    var dataf1 = CompositeUtil.findChild(datafilters, "data-filter");
                    if (!dataf1) {
                        $this.getObjectContext().removeChild(datafilters);
                    }
                }
            }

            function remove_query_field(name) {
                importClass(Packages.uncertain.composite.CompositeUtil);
                var qf_root = $this.getObjectContext().getChild("query-fields");
                var query_field = CompositeUtil.findChild(qf_root, "query-field", "field", name);
                if (query_field) {
                    qf_root.removeChild(query_field);
                }
            }
            
            function import_server_bm_tplt() {
                var cx = Packages.leaf.javascript.Context.getCurrentContext();
                try {
                    if ($ctx.tab_code) {
                        Packages.leaf.plugin.script.engine.ScriptImportor.defineExternScript(cx, this, $ctx.getData(), 'layoutconfig/' + $ctx.parameter.layout_code.toLowerCase() + '_' + $ctx.tab_code.toLowerCase() + '_queryfields.js');
                    }
                    if ($ctx.parameter.authority_flag == 'Y' && $ctx.query_tab_code) {
                        Packages.leaf.plugin.script.engine.ScriptImportor.defineExternScript(cx, this, $ctx.getData(), "aut_authority_bm_validate.js");
                    }
                } catch (e) {
            
                    var je = e.javaException;
                    while (je && je.getCause())
                    je = je.getCause();
                    if (je && je.getClass() == java.io.FileNotFoundException) {
                        if ($ctx.parameter.authority_flag == 'Y' && $ctx.query_tab_code) {
                            Packages.leaf.plugin.script.engine.ScriptImportor.defineExternScript(cx, this, $ctx.getData(), "aut_authority_bm_validate.js");
                        }
                    } else {
                        throw e;
                    }
            
                }
            }
            //去除数据空格
            function remove_space(table_name,field_name,aurora_bm_field){
               //租赁项目信息,客户类型,催收手机号,交货地址,租赁物安置地点,合同签订地
               if(table_name.toUpperCase()=='PRJ_PROJECT'){
                    if(field_name.toUpperCase()=='BP_CLASS' || field_name.toUpperCase()=='CELL_PHONE'
                    || field_name.toUpperCase()=='DELIVERY_ADDRESS' || field_name.toUpperCase()=='LEASE_ITEM_LOCATION'
                    || field_name.toUpperCase()=='SIGNING_CITY'){
                        f.setInsertExpression('hlc_remove_space(${@'+field_name+'})');
                        f.setUpdateExpression('hlc_remove_space(${@'+field_name+'})');
                    }
               }

              //项目报告_租赁物信息,序号,品牌名称,租赁物,机型,机号,使用小时,留购价,二手机评估价,台数
              if(table_name.toUpperCase()=='PRJ_PROJECT_LEASE_ITEM'){
                     if(field_name.toUpperCase()=='LEASE_ITEM_SEQ' || field_name.toUpperCase()=='BRAND_VALUE' ||
                     field_name.toUpperCase()=='LEASE_ITEM_ID' || field_name.toUpperCase()=='MODELCD' ||
                     field_name.toUpperCase()=='MACHINE_NUMBER' || field_name.toUpperCase()=='MACHINE_NUMBER_70' ||
                     field_name.toUpperCase()=='USING_HOUR' || field_name.toUpperCase()=='DETENTION_AMOUNT' ||
                     field_name.toUpperCase()=='DETENTION_AMOUNT' || field_name.toUpperCase()=='SET_NUMBER'){
                         f.setInsertExpression('hlc_remove_space(${@'+field_name+'})');
                         f.setUpdateExpression('hlc_remove_space(${@'+field_name+'})');
                    }
               }

               //承租人评分明细表,房产价值,家庭平均月收入,工程平均月收入,工程合同金额,第三方担保附件份数,年龄,铁甲评分
               if(table_name.toUpperCase()=='BP_TENANT_RATE_DETAIL'){
                 if(field_name.toUpperCase()=='HOUSE_VALUE' || field_name.toUpperCase()=='FAMILY_AVG_INCOME' ||
                 field_name.toUpperCase()=='WORK_AVG_MONTH_INCOME' || field_name.toUpperCase()=='E_CONTRACT_AMOUNT' ||
                 field_name.toUpperCase()=='THIRD_GUAR_SCORE' || field_name.toUpperCase()=='BP_AGE' ||
                 field_name.toUpperCase()=='TJ_SCORE'){
                     f.setInsertExpression('hlc_remove_space(${@'+field_name+'})');
                     f.setUpdateExpression('hlc_remove_space(${@'+field_name+'})');
                    }
                }

               //hls_bp_master和hls_bp_master_req,商业伙伴名称,简称,统一社会信用代码,中征码,注册资本,法人代表姓名,主营业务,法人代表身份证号,电话,手机,注册地址,邮政编码,证件号码,电话(住宅),电话
               //职业信息,入职年份,单位名称,单位详细地址,单位电话,单位邮编
               //配偶信息,配偶姓名,证件号码,联系电话,单位电话,工作单位,单位地址
               //开票信息,发票抬头,开票地址,电话,开户行,账号,纳税人识别号,备注,接收发票邮箱
               if(table_name.toUpperCase()=='HLS_BP_MASTER' || table_name.toUpperCase()=='HLS_BP_MASTER_REQ'){
                    if(field_name.toUpperCase()=='BP_NAME' || field_name.toUpperCase()=='EXTRA_NAM'
                    || field_name.toUpperCase()=='SOCIAL_CODE' || field_name.toUpperCase()=='CREDIT_CODE'
                    || field_name.toUpperCase()=='REGISTERED_CAPITAL' || field_name.toUpperCase()=='LEGAL_PERSON'
                    || field_name.toUpperCase()=='MAIN_BUSINESS' || field_name.toUpperCase()=='ID_CARD_NO_LEG'
                    || field_name.toUpperCase()=='PHONE' || field_name.toUpperCase()=='CELL_PHONE'
                    || field_name.toUpperCase()=='REGISTERED_PLACE' || field_name.toUpperCase()=='ZIPCODE'
                    || field_name.toUpperCase()=='ID_CARD_NO' || field_name.toUpperCase()=='HOME_PHONE'
                    || field_name.toUpperCase()=='EMAIL' || field_name.toUpperCase()=='FAX'
                    || field_name.toUpperCase()=='LIVING_ADDRESS' || field_name.toUpperCase()=='ENTRY_DATE'
                    || field_name.toUpperCase()=='WORK_UNIT' || field_name.toUpperCase()=='WORK_UNIT_ADDRESS'
                    || field_name.toUpperCase()=='WORK_UNIT_PHONE' || field_name.toUpperCase()=='WORK_UNIT_ZIP'
                    || field_name.toUpperCase()=='BP_NAME_SP' || field_name.toUpperCase()=='ID_NO_SP'
                    || field_name.toUpperCase()=='CELL_PHONE_SP' || field_name.toUpperCase()=='WORK_UNIT_PHONE_SP'
                    || field_name.toUpperCase()=='WORK_UNIT_NAME_SP' || field_name.toUpperCase()=='WORK_UNIT_ADDRESS_SP'
                    || field_name.toUpperCase()=='INVOICE_TITLE' || field_name.toUpperCase()=='INVOICE_BP_ADDRESS'
                    || field_name.toUpperCase()=='INVOICE_BP_PHONE_NUM' || field_name.toUpperCase()=='INVOICE_BP_BANK'
                    || field_name.toUpperCase()=='INVOICE_BP_BANK_ACCOUNT' || field_name.toUpperCase()=='TAX_REGISTRY_NUM'
                    || field_name.toUpperCase()=='REF_V07' || field_name.toUpperCase()=='RECEPTION_MAILE'
                    || field_name.toUpperCase()=='ID_CARD_NO_AG'){
                        f.setInsertExpression('hlc_remove_space(${@'+field_name+'})');
                        f.setUpdateExpression('hlc_remove_space(${@'+field_name+'})');
                    }
               }

              //经办人信息,姓名,身份证号,手机号
              if(table_name.toUpperCase()=='HLS_BP_MASTER_SIGNER' || table_name.toUpperCase()=='HLS_BP_MASTER_SIGNER_REQ'){
                    if(field_name.toUpperCase()=='NAME' || field_name.toUpperCase()=='ID_CARD'
                    || field_name.toUpperCase()=='CELL_PHONE'){
                        f.setInsertExpression('hlc_remove_space(${@'+field_name+'})');
                        f.setUpdateExpression('hlc_remove_space(${@'+field_name+'})');
                    }
               }

               //银行信息,账户名称,银行账号,银行全称,支行名称
               //hls_bp_master_bank_acc_req
               if(table_name.toUpperCase()=='HLS_BP_MASTER_BANK_ACCOUNT' || table_name.toUpperCase()=='HLS_BP_MASTER_BANK_ACC_REQ'){
                    if(field_name.toUpperCase()=='BANK_ACCOUNT_NAME' || field_name.toUpperCase()=='BANK_ACCOUNT_NUM'
                    || field_name.toUpperCase()=='BANK_FULL_NAME' || field_name.toUpperCase()=='BANK_BRANCH_NAME'){
                        f.setInsertExpression('hlc_remove_space(${@'+field_name+'})');
                        f.setUpdateExpression('hlc_remove_space(${@'+field_name+'})');
                    }
               }

               //地址信息,详细地址,邮政编码,电话
               if(table_name.toUpperCase()=='HLS_BP_MASTER_ADDRESS' || table_name.toUpperCase()=='HLS_BP_MASTER_ADDRESS_REQ'){
                    if(field_name.toUpperCase()=='ADDRESS' || field_name.toUpperCase()=='ZIPCODE'
                    || field_name.toUpperCase()=='PHONE'){
                        f.setInsertExpression('hlc_remove_space(${@'+field_name+'})');
                        f.setUpdateExpression('hlc_remove_space(${@'+field_name+'})');
                    }
               }

               //联系人信息,联系人名称,职位,电话,传真,E-mail,地址,邮政编码,支付负责人
               if(table_name.toUpperCase()=='HLS_BP_MASTER_CONTACT_INFO'){
                    if(field_name.toUpperCase()=='CONTACT_PERSON' || field_name.toUpperCase()=='POSITION'
                    || field_name.toUpperCase()=='PHONE' || field_name.toUpperCase()=='FAX'
                    || field_name.toUpperCase()=='EMAIL' || field_name.toUpperCase()=='CONTACT_INFO'
                    || field_name.toUpperCase()=='REF_V01' || field_name.toUpperCase()=='PAYMENT_OWNER'){
                        f.setInsertExpression('hlc_remove_space(${@'+field_name+'})');
                        f.setUpdateExpression('hlc_remove_space(${@'+field_name+'})');
                    }
               }

               //企业关联信息,身份类型,名称,证件号码,出资比例
               //hls_bp_master_com_req,法人
               if(table_name.toUpperCase()=='HLS_BP_MASTER_COMPANY_INFO' || table_name.toUpperCase()=='HLS_BP_MASTER_COM_REQ'){
                    if(field_name.toUpperCase()=='IDENTITY_TYPE' || field_name.toUpperCase()=='PERSON_NAME'
                    || field_name.toUpperCase()=='ASSOCIATE_ID_NO' || field_name.toUpperCase()=='CAPITAL_KEY'){
                        f.setInsertExpression('hlc_remove_space(${@'+field_name+'})');
                        f.setUpdateExpression('hlc_remove_space(${@'+field_name+'})');
                    }
               }
            }
            
            var table_name = $ctx.dynamic_base_table;
            // println("table_name:"+table_name);
            if (!table_name) raise_app_error("table name not found");
            $this.setBaseTable(table_name); //get base table from somewhere...
            var dsf = $instance('leaf.database.service.DatabaseServiceFactory');
            var it = new Packages.leaf.plugin.entity.OracleTableFields();
            var tableName = $this.getBaseTable();
            var fMap = new CompositeMap(it.getTableFields(dsf, tableName));
            // println(fMap.toXML());
            if (fMap.msg) raise_app_error('error while get table fields:' + fMap.msg + " :" + table_name);
            var flds = fMap.getChildren();
            var bp_seq_flag = 'N',
                bp_category = 'N';
            for (var i = 0;i < flds.length;i++) {
                var r = flds[i];
                if (r.name == 'BP_SEQ') {
                    bp_seq_flag = 'Y';
                } else if (r.name == 'BP_CATEGORY') {
                    bp_category = 'Y';
                }
                var f = Packages.leaf.bm.Field().createField(r.name.toLowerCase());
                f.setPhysicalName(r.name);
                if (r.dbtype == 'NUMBER') {
                    f.setDataType('java.lang.Double');
                } else if (r.dbtype == 'CLOB') {
                    f.setDataType('java.sql.Clob');
                } else {
                    if (!r.javatype) {
                        f.setDataType('java.lang.String');
                    } else {
                        f.setDataType(r.javatype);
                    }
                }
                f.setDatabaseType(r.dbtype);
                remove_space(tableName,r.name.toLowerCase(),f);
                f.setPrompt(r.prompt);
                $this.addField(f);
                if (r.ispk) {
                    //dynamic primary-key
                    if (!$ctx.pkmap) $ctx.pkmap = {};
                    $ctx.pkmap[table_name] = r.name.toLowerCase();
                    var pk = new_bm_map('pk-field');
                    // println("pk:" + r.toXML());
                    //f.setInsertExpression(table_name+'_s.nextval');
                    pk.name = r.name.toLowerCase();
                    if ($ctx.excelSaveFlag == 'Y') {
                        var model = new CompositeMap($this.getObjectContext());
                        var datafilters = model.getChild('data-filters');
                        if (!datafilters) {
                            datafilters = model.createChildNS('data-filters');
                        }
                        dataf = datafilters.createChildNS('data-filter');
                        dataf.name = pk.name;
                        dataf.enforceoperations = 'query';
                        dataf.expression = pk.name.toLowerCase() + '=${@' + pk.name.toLowerCase() + '}';
                    }
                    $this.getObjectContext().getChild('primary-key').addChild(pk.getData()); //get it's java type...
                }
                if ($ctx.query_tab_code) {
                    if (r.dbtype != 'DATE' && r.name.toLowerCase() != 'bp_seq' && r.name.toLowerCase() != 'bp_category' && r.name.toLowerCase() != 'copy_contract_id') {
                        create_query_field(r.name.toLowerCase(), 'like');
                    }
                }
            }
            if (!$ctx.query_tab_code) {
                var qf_root = $ctx.model.getChild('rootpath_query_field');
                // println("pk:" + qf_root.toXML());
                var qfs = ( !! qf_root) ? qf_root.getChildren() : [];
                var model = new CompositeMap($this.getObjectContext());
                var datafilters = model.getChild('data-filters');
                if (!datafilters) {
                    datafilters = model.createChildNS('data-filters');
                }
                // if (bp_seq_flag == 'Y' && $ctx.dynamic_parent_table == 'prj_project') {
                // qfs.push({
                // query_field1: '',
                // query_field2: 'BP_SEQ'
                // });
                // }
                if (bp_category == 'Y' && $ctx.dynamic_parent_table == 'prj_project') {
                    qfs.push({
                        query_field1: '',
                        query_field2: 'BP_CATEGORY'
                    });
                }
                for (var i = 0;i < qfs.length;i++) {
                    //dynamic query field
                    var temp_qf = qfs[i];
                    create_query_field(temp_qf.query_field1, '=');
                    create_query_field(temp_qf.query_field2, '=');
                    if (temp_qf.query_field2) {
                        var query_field2 = temp_qf.query_field2;
                        if (($ctx.parameter.tree_code || $ctx.dynamic_tab_type == 'GRIDBOX') && query_field2.toLowerCase() == 'bp_seq') {
                            continue;
                        }
                        var dataf = datafilters.createChildNS('data-filter');
                        dataf.name = query_field2.toLowerCase();
                        dataf.enforceoperations = 'query';
                        if ($ctx.query_bp_category) {
                            if (temp_qf.query_field2 == 'BP_CATEGORY') {
                                if ($ctx.parameter.bp_category == 'TENANT') {
                                    dataf.expression = query_field2.toLowerCase() + ' in (' + "'" + "TENANT" + "'," + "'" + "TENANT_SEC" + "'" + ')';
                                } else {
                                    dataf.expression = query_field2.toLowerCase() + '=${@' + query_field2.toLowerCase() + '}';
                                }
                            } else {
                                dataf.expression = query_field2.toLowerCase() + '=${@' + query_field2.toLowerCase() + '}';
                            }
                        } else if (!$ctx.query_bp_category && (temp_qf.query_field2 == 'BP_CATEGORY' || temp_qf.query_field2 == 'BP_SEQ')) {
                            dataf.expression = '1=1';
                        } else {
                            dataf.expression = query_field2.toLowerCase() + '=${@' + query_field2.toLowerCase() + '}';
                        }
                    }
                }
            }
            import_server_bm_tplt();
            create_order_by_fields();
            /*   println('===============================');
             println($ctx.parameter.authority_flag);
             println('===============================');
             println($this.getObjectContext().toXML()); */
        ]]></s:bm-script>
    </bm:features>
    <bm:relations/>
    <bm:query-fields/>
</bm:model>