define('FinancialAffairs',
    ['modelFactory', 'plugins', 'json', 'Qpin', 'common', 'leftMenu', 'kindedit', 'jqselect'],
    function (modelFactory, plugins) {
        //下拉配置过滤数据 只可选员工
        var notMemberFilter = function (treeId, parentNode, responseData) {
            var CBCRM = avalon.vmodels.CBCRM
            var ret = [], len = 0, curr, hasEmp = false
            if (responseData.data && responseData.data.groups.length)
                len = responseData.data.groups.length
            while (len) {
                curr = responseData.data.groups[--len]
                curr.nocheck = true
                hasEmp = false
                curr.Posts.forEach(function (p, i) {
                    curr.Posts[i].ParentId = p.Boss ? p.Boss.Id : p.Group
                    curr.Posts[i].nocheck = true
                    p.Users.forEach(function (u, i) {
                        var u = p.Users[i]
                        if (u.Id === CBCRM.memberShip.Id) return true
                        u.ParentId = u.PositionId
                        u.Name = u.FullName
                        ret.push(u)
                    })
                    if (!hasEmp) {
                        hasEmp = p.Users.length > 0
                    }
                    if (hasEmp) {
                        ret.push(p)
                    }
                })
                if (hasEmp) ret.push(curr)
            }
            return ret
        }
        //只要部门和用户
        notPostFilter = function (treeId, parentNode, responseData) {
            var CBCRM = avalon.vmodels.CBCRM
            var ret = [], len = 0, curr, hasEmp = false
            if (responseData.data && responseData.data.groups.length)
                len = responseData.data.groups.length
            while (len) {
                curr = responseData.data.groups[--len]
                //curr.nocheck = true
                hasEmp = false
                curr.Posts.forEach(function (p, i) {
                    p.Users.forEach(function (u, i) {
                        if (u.Id === CBCRM.memberShip.Id) return true
                        u.ParentId = p.Boss ? p.Boss.Id : p.Group
                        u.Post = p.Name;
                        u.Name = u.FullName + "(" + u.Post + ")";
                        ret.push(u)
                    })
                    if (!hasEmp) {
                        hasEmp = p.Users.length > 0
                    }
                })
                ret.push(curr);
            }
            return ret
        }
        var Financial = {
            //财务概况
            Index: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM
                var mvvm = avalon.define('Index', function (vm) {
                    vm.account = {}
                    vm.accountList = []
                    vm.top = {}
                    vm.sTime = CBCRM.sTime;
                })
                function initWithData() {
                    mvvm.accountList = [
                        { id: 0, title: '现金账户', open: true, change: itemClick, items: [] },
                        { id: 1, title: '银行账户', open: false, change: itemClick, items: [] },
                        { id: 2, title: '虚拟账户', open: false, change: itemClick, items: [] },
                        { id: 3, title: '负债账户', open: false, change: itemClick, items: [] },
                        { id: 4, title: '债权账户', open: false, change: itemClick, items: [] }
                    ]
                    $.get('/FinancialAffairs/Accounting/', {}, function (ret) {
                        mvvm.account = ret.data.total;
                        mvvm.top = ret.data.top;
                        if (ret.data.list) {
                            mvvm.accountList.forEach(function (item, i) {
                                ret.data.list.forEach(function (account) {
                                    if (account.AccountTypeId == i) {
                                        item.items.push(account);
                                        item.open = true;
                                    }
                                })
                            });
                        }

                        createJQLinear("#linechart", mvvm.sTime.year + '收支走势图', ret.data.chartLine);
                        createJQPieChart("#comechart", mvvm.sTime.year + '收入构成图', ret.data.chartIn);
                        createJQPieChart("#paychart", mvvm.sTime.year + '支出去向图', ret.data.chartOut);
                    });
                }
                
                function itemClick() {
                    var index = parseInt($(this).attr('index'));
                    mvvm.accountList[index].open = !mvvm.accountList[index].open;
                }

                //JQ 油表图
                function createJQDashboard(chartId, title, value, max) {
                    $(chartId).empty();
                    data = [value];
                    try{
                        $(chartId).jqplot([data], {
                            title:title,
                            seriesDefaults: {
                                renderer: $.jqplot.MeterGaugeRenderer,
                                rendererOptions: {
                                    min: 0,
                                    max: max,
                                    ticks :[],
                                    showTicks: true,
                                    showTickLabels: true,
                                    intervals: [max / 4, max / 2, max * 3 / 4, max],
                                    intervalInnerRadius: 50,
                                    label: value,
                                    labelHeightAjust: 0,
                                    labelPosition: 'inside',
                                    hubRadius:5
                                }
                            }
                        });
                    }
                    catch (ex) {
                        $(chartId).html("<p class='nodata'>" + ex.message + "</p>");
                    }
                }
                //JQuery 饼图
                function createJQPieChart(chartId, title, chartData) {
                    var pieData = [];
                    $(chartId).empty();
                    try{
                        if (chartId == '#chart_pie') {
                            chartData.forEach(function (item) {
                                var name = item.seriesname;
                                var total = 0;
                                var itemData = item.data;
                                itemData.forEach(function (idata) {
                                    total += parseInt(idata.value);
                                });

                                name += " " + total + '家';
                                pieData.push([name, total])
                            });
                        }
                        else {
                            chartData.forEach(function (item) {
                                pieData.push([item.label + ' ' + item.value, parseInt(item.value)]);
                            });
                        }
                        //console.log(pieData);
                        $(chartId).jqplot([pieData], {
                            title: title,
                            pointLabels: { show: true },
                            seriesDefaults: {
                                fill: true,
                                showMarker: false,
                                shadow: false,
                                renderer: $.jqplot.PieRenderer,
                                rendererOptions: {
                                    diameter: undefined,
                                    padding: 10,
                                    sliceMargin: 2,
                                    fill: true,
                                    shadow: true,
                                    shadowOffset: 2,
                                    shadowDepth: 5,
                                    shadowAlpha: 0.07,
                                    showDataLabels: true
                                },
                                pointLabels: { //数值点标签属性设置，该属性来自于jqplot.pointLabels.min.js
                                    show: true, //是否在图表上显示数值点标签
                                    location: 'e' //标签显示的方位
                                }
                            },
                            legend: {
                                show: true,
                                location: 'ne',
                                xoffset: 12,
                                yoffset: 12
                            }
                        });
                    }
                    catch (ex) {
                        $(chartId).html("<p class='nodata'>" + ex.message + "</p>");
                    }
                }

                //JQuery 线性图
                function createJQLinear(chartId, title, chartData) {
                    var linearData = [];
                    var labels = [];
                    $(chartId).empty();
                    try{
                        chartData.forEach(function (item) {
                            var a = [];
                            labels.push(item.seriesname);
                            item.data.forEach(function (node, i) {
                                a.push([(i + 1) + "月", node.value]);
                            })
                            linearData.push(a);
                        });
                        //console.log(linearData);
                        $(chartId).jqplot(linearData, {
                            title: title,
                            animate: true,
                            animateReplot: true,
                            /*cursor: {
                                show: true,
                                showTooltip: true,
                                followMouse: true,
                                zoom: true,
                                looseZoom: true,
                                showTooltip: true,
                                tooltipOffset: 6,
                                showTooltipUnitPosition: true,
                                ooltipFormatString:'%.2f'
                            }, */
                            series: [
                                {
                                    label: labels[0] || '',
                                    showHighlight: true,
                                    pointLabels: {
                                        show: true
                                    },
                                    rendererOptions: {
                                        animation: {
                                            speed: 2000
                                        }
                                    }
                                }, {
                                    label: labels[1] || '',
                                    showHighlight: true,
                                    pointLabels: {
                                        show: true
                                    },
                                    rendererOptions: {
                                        animation: {
                                            speed: 2000
                                        }
                                    }
                                },
                            
                            ],
                            axes: {
                                xaxis: {
                                    renderer: $.jqplot.CategoryAxisRenderer
                                },
                                yaxis: {
                                    label: '',
                                    tickOptions: {
                                        formatString: '%.1f'
                                    },
                                    rendererOptions: {
                                        forceTickAt0: true
                                    },
                                    lableRenderer: $.jqplot.CanvasAxisLabelRenderer,
                                }
                            },
                            highlighter: {
                                show: true,
                                showLabel: true,
                                tooltipAxes: 'y',
                                sizeAjust: 7.5,
                                tooltipLocation: 'ne'
                            },
                            legend: {
                                renderer: $.jqplot.EnhancedLegendRenderer,
                                show: true,
                                location: 'ne',
                                // placement:'outsideGrid'
                            }
                        });
                    }
                    catch (ex) {
                        $(chartId).html("<p class='nodata'>" + ex.message + "</p>");
                    }
                }

                //JQuery 线性图
                function createJQBar(chartId, title, chartData) {
                    var barData = [];
                    var labels = [];
                    var a = [];
                    $(chartId).empty();
                    try{
                        console.log(chartData);
                        chartData.forEach(function (item) {
                            labels.push(item.label);
                            a.push(item.value);
                        });
                        barData.push(a);
                        //console.log(barData);
                        if (a.length > 0) {
                            $(chartId).jqplot(barData, {
                                title: title,
                                series: [
                                   {
                                       //color: '#5FAB78',
                                       renderer: jQuery.jqplot.BarRenderer,
                                       rendererOptions: {
                                           barDirection: 'vertical',
                                           barMargin: 15,
                                           barWidth: 50
                                       }
                                   }
                                ],
                                seriesDefaults: {
                                    renderer: $.jqplot.BarRenderer,
                                    rendererOptions: { fillToZero: true },
                                    pointLabels: { //数值点标签属性设置，该属性来自于jqplot.pointLabels.min.js
                                        show: true, //是否在图表上显示数值点标签
                                        location: 'n', //标签显示的方位 'se', 's', 'sw', 'w', 'nw'
                                        edgeTolerance: -15
                                    },
                                    // Rotate the bar shadow as if bar is lit from top right.
                                    shadowAngle: 135
                                },
                                cursor: {
                                    show: true, //是否显示提示信息
                                    zoom: true, //是否启用变焦，鼠标左键选中图表去拖动可放大图标
                                    looseZoom: true //扩展变焦范围，提供更全面的刻度值信息，目前仅对有时间轴和线性轴的图表有效
                                },

                                axesDefaults: {
                                    tickRenderer: $.jqplot.CanvasAxisTickRenderer,
                                    tickOptions: {
                                        fontFamily: 'Georgia',
                                        angle: -30,
                                        fontSize: '10pt'
                                    }
                                },
                                axes: {
                                    xaxis: {
                                        renderer: $.jqplot.CategoryAxisRenderer,
                                        ticks: labels,
                                    },
                                },
                            });
                        }
                    }
                    catch (ex) {
                        $(chartId).html("<p class='nodata'>" + ex.message + "</p>");
                    }

                    //p.replot();
                }

                require("jqPlotPie,jqBar,jqPointLabels,jqCategory,jqCanvasText,jqCanvasAxisLabel,jqEnhancedLegend,jqPointLabel,jqCursor,jqHighlighter,jqMeterGauge",
                function () {
                    initWithData();
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                });

                CBCRM.onLoadModuleBefore = function () { avalon.vmodels.Index = null }
            },
            //收支记账
            Accounting: function (tmpl, lang, contentId, module,paramData) {
                var CBCRM = avalon.vmodels.CBCRM, that = this, detail, contract, meun
                var reLoadProject = function () {
                    if (avalon.vmodels.belongToTree) {
                        var treeVm = avalon.vmodels.belongToTree,

                            tree = $.fn.zTree.getZTreeObj(treeVm.treeId)
                        if (tree)
                            tree.reAsyncChildNodes(null, "refresh")
                    }
                    /*赋值对应客户*/
                    if (action=="customer") {
                        var cu = paramData.entity;
                        avalon.vmodels.setParetCustomer.q = cu.Name
                        mvvm.accounting.CustomId = cu.Id
                        mvvm.accounting.CustomName = cu.Name
                    }
                }
                var action = that.params.action, paramid = that.params.id, mid = this.params.mid;
                var vmid='Accounting';
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.$skipArray = ["lang"];
                    vm.lang = lang;
                    vm.destroy = function () {
                        destroyui(["belongToTree", "belongToTree2", "businessTreeid"]);
                    }
                    vm.tag = 'list'
                    vm.tagChange = function () {
                        mvvm.tag = $(this).attr('tag');
                        if (mvvm.tag == 'in') {
                            mvvm.accounting = modelFactory.create('AccountBook');
                            mvvm.accounting.Category = '收入';
                            InCometWindow("新增收入记账");
                        }
                        if (mvvm.tag == 'out') {
                            mvvm.accounting = modelFactory.create('AccountBook');
                            mvvm.accounting.Category = '支出';
                            InCometWindow("新增支出记账");
                            //reLoadProject()
                        }
                        if (mvvm.tag == 'tr') {//转账
                            mvvm.accounting = modelFactory.create('AccountBook');
                            PayOutWindow("新增转账");
                        }
                        mvvm.contactArray = [];
                        mvvm.accountingOutBill = [];


                        /*赋值对应客户*/
                        if (action=="customer") {
                            var cu = paramData.entity;
                            mvvm.accounting.CustomId = cu.Id
                            mvvm.accounting.CustomName = cu.Name
                        }
                    }
                    vm.account = {}
                    vm.accountList = []
                    vm.noDeleteList = []
                    vm.showItem = {}
                    vm.accounting = {}
                    //查询条件
                    initQuerys(vm, function (data, name, val, type) {
                        if (name == "datespan") {
                            {
                                if (val == "c") {
                                    if (type == "remove") {
                                        mvvm.removeQuery("begindate", true);
                                        mvvm.removeQuery("enddate", true);
                                    } else {
                                        mvvm.queryData.datespan.valLabel = ""
                                        if (mvvm.hasLength == 1) {
                                            mvvm.hasQuery = false;
                                        }
                                        return false;
                                    }
                                } else {
                                    mvvm.removeQuery("begindate", true);
                                    mvvm.removeQuery("enddate", true);
                                }
                            }
                        } else if (name == "appointUser") {
                            if (type == "remove") mvvm.removeQuery("employees",true)
                        }
                        var data = mvvm.createQuery();
                        mvvm.grid1.loadData(data);
                    });
                    vm.createQueryData = function () {
                        return {
                            category: {
                                label: "记账类别", val: "", valLabel: "",
                                items: [
                                    { label: "不限", val: "", curr: true },
                                    { label: "收入", val: "收入", curr: false },
                                    { label: "支出", val: "支出", curr: false },
                                    { label: "转账", val: "转账", curr: false }
                                ]
                            },
                            assetsid: {
                                label: "收支帐户", val: "", valLabel: "",
                                items: [
                                    { label: "不限", val: "", curr: true }
                                ]
                            },
                            datespan: {
                                label: "时间范围", val: "", valLabel: "",
                                items: [
                                    { label: "不限", val: "", curr: true },
                                    { label: "本月", val: "m", curr: false },
                                    { label: "上月", val: "m_-1", curr: false },
                                    { label: "本年", val: "y", curr: false },
                                    { label: "自定义", val: "c", curr: false, type: "date", d1: "begindate", d2: "enddate", format: "%Y-%m-%d" },
                                ]
                            },
                            appointUser: {
                                label: "业务归属", val: "", valLabel: "",
                                items: [
                                    { label: "不限", val: "", curr: true },
                                    { label: "指定部门员工", val: "appointUser", curr: false, type: "selectUser" }
                                ]
                            },
                            keyword: { label: "关键词", val: "", valLabel: "" },
                            begindate: { label: "起始时间", val: "" },
                            enddate: { label: "结束时间", val: "" },
                            employees: { label: "员工id", val: '', valLabel: "" },
                            receiptid: { label: "收款单id", val: '', noRemove: true },
                            customerid: { label: "客户id", val: '', noRemove: true },
                            contractid: { label: "合同id", val: '', noRemove: true }
                        };
                    }
                    vm.createGrid1 = function () {
                        return createGrid({
                            url: "/FinancialAffairs/AccountList",
                            pageid: vmid + "_page_grid1",
                            modelFactory: modelFactory,
                            $lang: lang,
                            createQuery: function () {
                                var data = mvvm.createQuery();
                                return data;
                            },
                            onLoadData: function (ret, list) {
                                mvvm.ADD = ret.data.ADD;
                                mvvm.DELETE = ret.data.DELETE;
                                mvvm.totalmoney = 0
                                mvvm.initNoDeleteList(); //检查记账的项不能删除
                                list.forEach(function (item, i) {
                                    var money = parseFloat(item.Amount)
                                    if (money)
                                        if (item.Category == '收入')
                                            mvvm.totalmoney += money
                                        else
                                            mvvm.totalmoney -= money
                                })
                                return ret.data;
                            },
                            onRemove: function (deleteIds) {
                                delete deleteIds.length;
                                $.post("/FinancialAffairs/AccountAllDelete", deleteIds, function (ret) {
                                    var ok = CBCRM.showResult(ret);
                                    if (ok) {
                                        mvvm.grid1.reloadData();
                                        if (action == "Contract" && paramData) paramData.reloadEntity();
                                    }
                                })
                            }
                        });
                    }
                    vm.queryData = vm.createQueryData();
                    vm.grid1 = vm.createGrid1();
                    vm.appointUser = function () {
                        var emps = mvvm.queryData.employees.val.split(",")
                        var ops = {
                            listData: emps,
                            required: true,
                            multiple:true,
                            callback: function (us) {
                                if (emps.length == 0 && us.length == 0) return false;
                                if (us.length == 0) {
                                    mvvm.removeQuery("employees");
                                    return false;
                                }
                                emps = where(us, true, "Id");
                                mvvm.addQuery("employees", emps.join(","));
                                return true;
                            }
                        }
                        return ops;
                    }
                    vm.selectUser = function (key,r) {
                        var ops,type=r.val;
                        switch (type) {
                            case "appointUser":
                                ops = mvvm.appointUser();
                                break;
                            default:
                                messageBox.alert("无效类型：" + type);
                                return;
                        }
                        plugins.selectUser({
                            dataAuth:7020001,
                            listData: ops.listData,
                            multiple: true,
                            required: ops.required,
                            callback: function (us) {
                                if (ops.callback.apply(this, arguments))
                                    mvvm.addQuery(key, r.val, r.label, true);
                                else
                                    mvvm.removeQuery(key,true);
                            }
                        });
                    }
                    vm.accountingList = []
                    vm.accountingContact = []
                    vm.fullName = CBCRM.memberShip.FullName;

                    vm.accountingSubmit = function () {
                        var relevance = []
                        mvvm.contactArray.forEach(function (item) {
                            relevance.push({ AccountBookId: '', BillId: '', ContactId: item.Id, PlanOfPayId: '' });
                            if (item.PlanOfPayList && item.PlanOfPayList.length > 0) {
                                item.PlanOfPayList.forEach(function (child) {
                                    relevance.push({ AccountBookId: '', BillId: '', ContactId: item.Id, PlanOfPayId: child.Id });
                                })
                            }
                        });
                        mvvm.accountingOutBill.forEach(function (item) {
                            relevance.push({ AccountBookId: '', BillId: item.Id, ContactId: '', PlanOfPayId: '' });
                        })
                        var model = mvvm.accounting.$model;
                        if (model.Id != 0)
                            delete model.RelevanceList;
                        relevance.forEach(function (item, i) {
                            model['RelevanceList[' + i + '].AccountBookId'] = item.AccountBookId;
                            model['RelevanceList[' + i + '].BillId'] = item.BillId;
                            model['RelevanceList[' + i + '].ContactId'] = item.ContactId;
                            model['RelevanceList[' + i + '].PlanOfPayId'] = item.PlanOfPayId;
                        });

                        model.IsTransfer = (mvvm.tag == 'in' || mvvm.tag == 'out') ? 0 : 1;
                        if (model.ProjectId && model.AccountId) {
                            if (model.Amount) {
                                if (mvvm.contactArray.length > 0) {
                                    var url = model.Id == 0 ? "/FinancialAffairs/AccountAdd/" : "/FinancialAffairs/AccountEdit/" + model.Id;
                                    $.post(url, model, function (ret) {
                                        CBCRM.showResult(ret, function () {
                                            var indialog = art.dialog.list['incomeForm']
                                            if (indialog) indialog.close()
                                            mvvm.tag = 'list';
                                            mvvm.grid1.reloadData();
                                        });
                                    });
                                }
                                else
                                    messageBox.warning('请选择合同订单');
                            }
                            else messageBox.warning('请填写正确的收支金额');
                        }
                        else messageBox.warning('请选择收支项目以及收支账户!');
                    }
                    vm.trSubmit = function () {//转账
                        var model = mvvm.accounting.$model;

                        if (!model.OutAccountId) {
                            messageBox.warning('请选择转出账户'); return;
                        }
                        if (!model.AccountId) {
                            messageBox.warning('请选择转入账户'); return;
                        }
                        if (!model.Amount) {
                            messageBox.warning('请填写转账金额'); return;
                        }
                        var url = model.Id == 0 ? "/FinancialAffairs/TransferAdd/" : "/FinancialAffairs/TransferEdit/" + model.Id;
                        $.post(url, model, function (ret) {
                            CBCRM.showResult(ret, function () {
                                var pdialog = art.dialog.list['PayOutMoney']
                                if (pdialog) pdialog.close()
                                mvvm.tag = 'list';
                                mvvm.grid1.reloadData();
                            })
                        })
                    }
                    vm.showDetail = false;
                    vm.showClick = function () {
                        mvvm.showDetail = !mvvm.showDetail;
                    }
                    vm.ADD = false
                    vm.DELETE = false

                    vm.totalmoney = 0
                    vm.totalrptmoney = 0

                    //资产账户
                    vm.belongToOpts2 = {
                        q: '请输入资产账户名称',
                        treeopts: {
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    mvvm.accounting.AccountId = treeNode.Id;
                                    mvvm.accounting.AccountName = treeNode.Name;
                                }
                            },
                            async: {
                                url: function (treeId, treeNode) { return '/FinancialAffairs/AssetsDrodown/' },
                                dataFilter: function (treeId, parentNode, responseData) {
                                    var result = [];
                                    if (responseData.data) {
                                        responseData.data.forEach(function (item) {
                                            result.push({ Id: item.Id, Name: item.AccountName });
                                        })
                                    }
                                    return result;
                                }
                            }
                        }
                    }
                    //转出账户
                    vm.belongToOpts3 = {
                        q: '请输入资产账户名称',
                        treeopts: {
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    mvvm.accounting.OutAccountId = treeNode.Id;
                                    mvvm.accounting.OutAccountName = treeNode.Name;
                                }
                            },
                            async: {
                                url: function (treeId, treeNode) { return '/FinancialAffairs/AssetsDrodown/' },
                                dataFilter: function (treeId, parentNode, responseData) {
                                    var result = [];
                                    if (responseData.data) {
                                        responseData.data.forEach(function (item) {
                                            result.push({ Id: item.Id, Name: item.AccountName });
                                        })
                                    }
                                    return result;
                                }
                            }
                        }
                    }
                    //转入账户
                    vm.belongToOpts4 = {
                        q: '请输入资产账户名称',
                        treeopts: {
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    mvvm.accounting.AccountId = treeNode.Id;
                                    mvvm.accounting.AccountName = treeNode.Name;
                                }
                            },
                            async: {
                                url: function (treeId, treeNode) { return '/FinancialAffairs/AssetsDrodown/' },
                                dataFilter: function (treeId, parentNode, responseData) {
                                    var result = [];
                                    if (responseData.data) {
                                        responseData.data.forEach(function (item) {
                                            result.push({ Id: item.Id, Name: item.AccountName });
                                        })
                                    }
                                    return result;
                                }
                            }
                        }
                    }
                    //部门员工
                    
                    
                    //日期
                    vm.birthdayOpts = {
                        format: '%Y-%m-%d %H:%M',
                        onSelect: function (date, formatDate, format) {
                            mvvm.accounting.BookDate = formatDate
                        }
                    }

                    vm.showOnlyList = false

                    vm.RECEIPTSADD = false
                    vm.RECEIPTSDELETE = false
                    vm.receiptList = [] //收款单
                    vm.receiptDetailList = [] //收款业务明细
                    vm.receiptDetailDelList = [] //存删除的业务明细
                    vm.receiptPayOfPlanList = [] //收款计划
                    vm.receiptpaging = {
                        paging: function () {
                            var that = this
                            var query = {
                                pageIndex: that.currentindex + 1,
                                pageSize: that.pagesize,
                                customerId: mvvm.accounting.CustomId,
                                categroy: 0
                            }
                            initReceiptBill(queryBillData);
                        }
                    }

                    //应收应付
                    //tab切换
                    vm.tab = 'tab1'
                    vm.tabChange = function () {
                        var tabid = $(this).attr("val")
                        mvvm.tab = tabid
                    }
                    vm.arapList = [];
                    vm.selArapList = [];
                    vm.arapKey = '';
                    vm.arapCategory = 'contract';
                    vm.arapCategoryDisplay = "应收款编号"
                    vm.arapTitle = "应收款"
                    vm.arapType = '';
                    vm.arapAmount = 0;
                    vm.arapSelected = [];
                    vm.writeOffList = [];
                    vm.delWriteOffList = [];
                    vm.arapRelList = [];

                    vm.initNoDeleteList = function () {
                        mvvm.noDeleteList = [];
                        $.get('/FinancialAffairs/GetARAPWriteOff/', {
                        }, function (ret) {
                            if (ret.data.woList && ret.data.woList.length > 0) {
                                ret.data.woList.forEach(function (item) {
                                    mvvm.noDeleteList.push(item.AccountingNo);
                                });
                            };
                        })
                    }
                    vm.isDeletable = function (accountingNo) {
                        var deletable = true;
                        mvvm.noDeleteList.forEach(function (item) {
                            if (accountingNo == item) {
                                deletable = false;
                                return;
                            }
                        });
                        return deletable;
                    }
                    vm.sumWriteOffAmt = function () {
                        var amt = 0;
                        mvvm.arapRelList.$model.forEach(function (item) {
                            var v = parseFloat(item.SettleMoney);
                            if (v && v > 0) {
                                item.NotSettleMoney = item.Money - item.SettleMoney;
                                amt += v;
                            }
                        });
                        mvvm.arapAmount = amt;
                    }
                    
                  
                    /*vm.selectSettleCustomer = function (item) {
                        plugins.selectCustomer({
                            callback: function (cus) {
                                var cu = cus[0];
                                item.SettleCustomerId = cu.Name;
                                item.SettleCustomerName = cu.Name;
                            }
                        });
                    }*/
                    /*vm.selectDutyPerson = function (item) {
                        plugins.selectUser({
                            dataAuth: 7051001,
                            callback: function (us) {
                                var u = us[0];
                                item.DutyPersonId = u.Id;
                                item.DutyPersonName = u.FullName;
                            }
                        })
                    }
                    vm.settleWays = []; */
                    vm.getDicts = function () {
                        getDicts({ settleWays: 100056 }, mvvm);
                    }
                    vm.initRelArap = function (type, contractId) {
                        if (!contractId)
                            return;
                        mvvm.arapRelList = [];
                        mvvm.writeOffList = [];
                        mvvm.delWriteOffList = [];
                        mvvm.arapAmount = 0;
                        $.get('/FinancialAffairs/GetARAPList/', {
                            'type': type,
                            'contractId': contractId,
                            'isSettled':false
                        }, function (ret) {
                            ret.data.Source.forEach(function (item) {
                                var d = $.extend({}, item);
                                d.SettleMoney = d.NotSettleMoney; //显示未收金额
                                mvvm.arapRelList.push(d);
                                var amt = parseFloat(d.SettleMoney)
                                if (amt && amt > 0)
                                    mvvm.arapAmount += amt;
                                //watchMoney(mvvm.arapRelList[mvvm.arapRelList.length - 1]);
                            });
                        })
                    }
                    vm.GetRelArapDetail = function (type, accountingNo) {
                        mvvm.delWriteOffList = [];
                        if (!accountingNo)
                            return;
                        $.get('/FinancialAffairs/GetARAPWriteOff/', {
                            'type': type,
                            'accountingNo': accountingNo
                        }, function (ret) {
                            mvvm.arapRelList = ret.data.arapList;
                            mvvm.writeOffList = ret.data.woList;
                            mvvm.arapRelList.forEach(function (item) {
                                mvvm.writeOffList.forEach(function (woItem) {
                                    if (item.Id == woItem.ARAPId) {
                                        item.Remark = woItem.Remark;
                                        return;
                                    }
                                });
                                var amt = parseFloat(item.SettleMoney);
                                if (amt)
                                    mvvm.arapAmount += amt;
                            });
                        })
                    }
                    vm.addArap = function (onLoad) {
                        var arapKey = ''
                        mvvm.selArapList = []
                        mvvm.searchArap(mvvm.arapType, mvvm.arapCategory, mvvm.arapKey, onLoad)

                        var dialog = mvvm.openTmpl({
                            multiple: true,
                            title: mvvm.arapType ==1 ?"选择应付款":"选择应收款", w:800, h:300, padding:"def2",
                            url:"/FinancialAffairs/SelectARAPTemplate.html", tmpl:tmpl,
                            pageid: vmid + "_gridm_page",
                            pageOps: { enablesetsize: false, showtotal: true },
                            createQuery: function () {
                                // return mvvm.createQuery(); 
                            },
                            button:[{
                                name: '确定',
                                focus: true,
                                callback: function () {
                                    mvvm.selArapList.forEach(function (item) {
                                        var isInList = false;
                                        mvvm.arapRelList.forEach(function (m) {
                                            if (item.Id === m.Id){
                                                isInList = true;
                                                return;
                                            }
                                        });
                                        if (!isInList) {
                                            var relArap = $.extend({}, item);
                                            relArap.SettleMoney = relArap.NotSettleMoney;
                                            mvvm.arapRelList.push(relArap);
                                            var amt = parseFloat(relArap.SettleMoney);
                                            if (amt)
                                                mvvm.arapAmount += amt;
                                            //watchMoney(mvvm.arapRelList[mvvm.arapRelList.length-1]);
                                        }
                                    });
                                    if (dialog) dialog.close();
                                    return false;
                                }
                            }]
                        });          
                    }
                    vm.searchArap = function (type,category,key,onLoad) {
                        $.get('/FinancialAffairs/GetARAPList/', {
                            'type': type,
                            'category':category,
                            'key': key,
                            'isSettled': false,
                            'pageSize':100
                        }, function (ret) {
                            if (typeof (onLoad) == "function")
                                onLoad(ret.data.Source);
                            ret.data.Source.forEach(function (item) {
                                item.checked = false;
                                item.chkDisabled = false;
                                //禁止选添加的应收应付
                                mvvm.arapRelList.forEach(function (d) {
                                    if (d.Id == item.Id) {
                                        item.chkDisabled = true;
                                        return;
                                    }
                                });
                            });
                            mvvm.arapList = ret.data.Source;
                            mvvm.arapList.forEach(function (item) {
                                mvvm.watchArapItem(item);
                            });
                        })
                    }
                    vm.watchArapItem = function (item) {
                        item.$watch("checked", function (n, o) {
                            if (n) {
                                mvvm.arapList.forEach(function (m) {
                                    if (item.Id == m.Id)
                                        m.checked = n;
                                });
                            }
                            mvvm.onSelectArap(item, item.checked);
                        });
                    }
                    vm.onSelectArap = function (item, checked) {
                        if (checked)
                            mvvm.selArapList.push(item);
                        else
                            for (var i = 0; i < mvvm.selArapList.length; i++) {
                                if (mvvm.selArapList[i].Id === item.Id)
                                    mvvm.selArapList.splice(i, 1);
                            }
                    }
                    // 删除列表中的关联应收应付
                    vm.dodelArapWriteOff = function (index, arapId) {
                        if (!mvvm.arapRelList.length) {
                            messageBox.warning("请重新选择合同订单！")
                            return false;
                        }
                        mvvm.writeOffList.forEach(function (item) {
                            if (item.ARAPId == arapId) {
                                mvvm.delWriteOffList.push(item.Id);
                                var amt = parseFloat(item.WriteOffAmount);
                                if(amt)
                                   mvvm.arapAmount -= amt;
                            }
                        });
                        mvvm.arapRelList.splice(index, 1);
                    }
                    
                    //收款明细新增
                    vm.doadd = function () {
                        mvvm.accounting = modelFactory.create('AccountBook')
                        mvvm.tag = 'in'
                        var dIndex = 0
                        mvvm.unitsData.forEach(function (item, i) { if (item.IsDefault) { dIndex = i } })
                        mvvm.accounting.Unit = mvvm.unitsData.length > 0 ? mvvm.unitsData[dIndex].Id : ''
                        mvvm.accounting.AccountId = mvvm.assetsData.length > 0 ? mvvm.assetsData[0].Id : ''
                        mvvm.accounting.AccountName = mvvm.assetsData.length > 0 ? mvvm.assetsData[0].AccountName : ''
                        var currUser = CBCRM.memberShip
                        mvvm.accounting.SalesmanId = currUser.Id
                        mvvm.accounting.Salesman = currUser.FullName
                        mvvm.accounting.ReceiptmanId = currUser.Id
                        mvvm.accounting.Receiptman = currUser.FullName
                        mvvm.accounting.ReceiptDate = GetDateTime()
                        mvvm.accounting.BookDate = GetDateTime()
                        mvvm.accounting.IsTransfer = 0;
                        mvvm.accounting.Category = '收入';
                        switch (action) {
                            case "customer":
                                mvvm.accounting.CustomId = paramid
                                mvvm.accounting.CustomName = paramData.entity.Name
                                break;
                            case "Contract":
                                var ct = paramData.entity;
                                mvvm.accounting.Contract = ct.Id
                                mvvm.accounting.ContractNum = ct.ContractNum
                                mvvm.mulSelect = false
                                mvvm.setCustomerInfo(ct.Customer)
                                break;
                        }
                        mvvm.accountingSave('新增收款明细')
                        if (action == "Contract") {
                            mvvm.selectContract(false, function (list) {
                                if (list.length) list[0].checked = true;
                                mvvm.getProductList();
                            });
                        }
                    }
                    //编辑
                    vm.doedit = function (billId, billNo) {
                        //查看收/付款明细
                        var id = $(this).attr('val')
                        mvvm.accounting = modelFactory.create('AccountBook')
                        $.get('/FinancialAffairs/AccountDetail/' + id, {}, function (ret) {
                            mvvm.accounting = ret.data

                            mvvm.accounting.BefoceAmount = ret.data.Amount
                            mvvm.accounting.BeforeProductId = ret.data.Product
                            mvvm.accounting.BeforeAccountId = ret.data.AccountId
                            mvvm.accounting.BeforeContractId = ret.data.Contract

                            if (billNo) { //查看收/付款单
                                mvvm.writeOffList = [];
                                mvvm.arapRelList = [];
                                mvvm.delWriteOffList = [];
                                if (mvvm.accounting.Category == '收入') {
                                    mvvm.arapType = 0;
                                    mvvm.tag = 'in';
                                    mvvm.doeditReceipts(billId);
                                }
                                else if (mvvm.accounting.Category == '支出') {
                                    mvvm.arapType = 1;
                                    mvvm.tag = 'out';
                                    mvvm.doeditPayBill(billId);
                                }

                            }
                            else if (!mvvm.accounting.IsTransfer) {
                                if (mvvm.accounting.Category == '收入') {
                                    mvvm.tag = 'in'
                                    mvvm.accountingSave('编辑收款明细')
                                }
                                if (mvvm.accounting.Category == '支出') {
                                    mvvm.tag = 'out'
                                    mvvm.dosavePay('编辑支出明细')
                                }
                            } else {
                                mvvm.tag = 'tr'
                                PayOutWindow("修改转账")
                            }
                        })

                    }
                    //查看
                    vm.doview = function (id) {
                        $.get('/FinancialAffairs/AccountDetail/' + id, {}, function (ret) {
                            mvvm.accounting = ret.data
                            var title, tmplId;
                            if (mvvm.accounting.IsTransfer == 1) {
                                title = "转账信息详情";
                                tmplId = "viewTemplate";
                                //viewWindow('查看转账信息')
                            }
                            else if (mvvm.accounting.Category == '收入') {
                                mvvm.arapType = 0;
                                title = "收款明细详情";
                                tmplId = "accountingViewTemplate";
                                //var dialog = messageBox.openHtml('收款明细详细', '880px', '300px', '');
                                //var content = $(dialog.content())
                                ////content.attr('ms-include', 'accountingViewTemplate')
                                //var inputTmpl = $(tmpl).find("#accountingViewTemplate").text()
                                //content.html(inputTmpl)
                                //avalon.scan(content[0], mvvm)
                            } else if (mvvm.accounting.Category == '支出') {
                                mvvm.arapType = 1;
                                title = "支出明细详情";
                                tmplId = "accountingViewTemplate2";
                                //var dialog = messageBox.openHtml('支出明细详细', '880px', '228px', '');
                                //var content = $(dialog.content())
                                //var inputTmpl = $(tmpl).find("#accountingViewTemplate2").text()
                                //content.html(inputTmpl)
                                //avalon.scan(content[0], mvvm)
                            }
                            var dialog = mvvm.openTmpl({
                                title: title, w: 880,padding:"def2",
                                tmplId: tmplId, tmpl: tmpl
                            });
                        })
                    }

                    //明细保存
                    vm.accountingSave = function (title) {
                        var dialog = mvvm.openTmpl({
                            title: title, w: 830, h: 400,
                            tmplId: "accountingFormTemplate", tmpl: tmpl,
                            button:[{
                                name: '确定',
                                focus: true,
                                callback: function () {
                                    var model = mvvm.accounting.$model
                                    var msg = ''
                                    if (!model.Product) {
                                        msg = msg + '请选择产品名称<br/>'
                                    }
                                    if (!model.AccountId) {
                                        msg = msg + '请选择收费账户<br/>'
                                    }
                                    if (!model.ProjectName) {
                                        msg = msg + '请选择收费项目<br/>'
                                    }
                                    var amount = parseFloat(mvvm.accounting.Amount)
                                    if (!amount || amount < 0) {
                                        msg = msg + '请输入正确的金额<br/>'
                                    }
                                    if (msg) {
                                        messageBox.warning(msg)
                                        return false
                                    }
                                    var url = model.Id == 0 ? "/FinancialAffairs/AccountAdd/" : "/FinancialAffairs/AccountEdit/" + model.Id;
                                    $.post(url, model, function (ret) {
                                        CBCRM.showResult(ret, function () {
                                            mvvm.tag = 'list'
                                            mvvm.grid1.reloadData();
                                            dialog.close()
                                            if (paramData) {
                                                if (paramData.reloadEntity) paramData.reloadEntity();
                                                if (paramData.reloadList) paramData.reloadList();
                                            }
                                        });
                                    });

                                    return false
                                }
                            }],
                            onClose:function () {
                                mvvm.destroyui(["salesmanid", "receiptmanid", "accountingbelongToTree", "customerTreeId"]);
                            }
                        });
                    }
                    //自动编号 
                    vm.autoCode = function () {
                        $.get('/FinancialAffairs/GetReceiptsAutoCode', {}, function (ret) {
                            mvvm.accounting.No = ret.data.autoCode
                        })
                    }
                    vm.watchBill = function () {
                        mvvm.accounting.$watch("Receiptdate", function (n, o) {
                            mvvm.receiptDetailList.forEach(function (item) {
                                item.ReceiptDate = n;
                            })
                        });
                        mvvm.accounting.$watch("BillDate", function (n, o) {
                            mvvm.receiptDetailList.forEach(function (item) {
                                item.BillDate = n;
                            })
                        });
                    }
                    //收款单新增
                    vm.doaddReceipts = function () {
                        mvvm.accounting = modelFactory.create('ReceiptsBill') //收款单 
                        mvvm.receiptDetailList = []
                        mvvm.receiptDetailDelList = []
                        mvvm.receiptPayOfPlanList = []
                        mvvm.watchBill();
                        mvvm.tag = 'in'
                        mvvm.arapRelList = [];
                        mvvm.writeOffList = [];
                        mvvm.delWriteOffList = [];
                        mvvm.arapType = 0;
                        mvvm.arapCategoryDisplay = "应收款编号";
                        mvvm.arapKey = '';
                        mvvm.arapAmount = 0;
                        mvvm.arapCategory = 'contract';
                        mvvm.autoCode()
                        //if (that.params.id && detail) {
                        //    mvvm.mulSelect = true
                        //    mvvm.setCustomerInfo(that.params.id)
                        //    mvvm.setCustomerContacts(that.params.id)
                        //}
                        switch (action) {
                            case "customer":
                                mvvm.mulSelect = true
                                mvvm.setCustomerInfo(that.params.id)
                                //mvvm.setCustomerContacts(that.params.id)
                                break;
                            case "Contract":
                                var ct = paramData.entity;
                                mvvm.accounting.Contract = ct.Id
                                mvvm.accounting.ContractNum = ct.ContractNum
                                mvvm.mulSelect = true
                                mvvm.setCustomerInfo(ct.Customer)
                                $.get('/Market/ProductList', {
                                    'contractid': ct.Id,
                                    'pageSize': 10000
                                }, function (ret) {
                                    //mvvm.setCustomerContacts(con.Customer)
                                    var assetsid = mvvm.assetsData.length > 0 ? mvvm.assetsData[0].Id : ''
                                    mvvm.receiptDetailList = []
                                    mvvm.receiptPayOfPlanList = []
                                    ret.data.Source.forEach(function (pro) {
                                        var detail = mvvm.productToAccountBook(pro);
                                        detail.AccountId = assetsid
                                        detail.Contract = ct.Id;
                                        mvvm.receiptDetailList.push(detail)
                                    })
                                    //取付款计划
                                    //mvvm.getPlanPay(ct.Id);
                                    //合计
                                    mvvm.sumProductAmt()
                                })
                                break;
                            case "ARAPCollectAdd":
                                var arap = paramData.entity;
                                mvvm.accounting.Contract = arap.Contract.Id
                                mvvm.accounting.ContractNum = arap.Contract.ContractNum
                                mvvm.mulSelect = true
                                mvvm.setCustomerInfo(arap.CustomerId)
                                $.get('/Market/ProductList', {
                                    'contractid': arap.Contract.Id,
                                    'pageSize': 10000
                                }, function (ret) {
                                    //mvvm.setCustomerContacts(con.Customer)
                                    var assetsid = mvvm.assetsData.length > 0 ? mvvm.assetsData[0].Id : ''
                                    mvvm.receiptDetailList = []
                                    mvvm.receiptPayOfPlanList = []
                                    ret.data.Source.forEach(function (pro) {
                                        if (pro && pro != '') {
                                            var detail = mvvm.productToAccountBook(pro);
                                            detail.AccountId = assetsid
                                            detail.Contract = arap.Contract.Id;
                                            mvvm.receiptDetailList.push(detail)
                                        }
                                    })
                                    //合计
                                    mvvm.sumProductAmt()

                                    $.get('/FinancialAffairs/GetARAPList/', {
                                        'type': mvvm.arapType,
                                        'contractId': arap.Contract.Id,
                                        'isSettled': false
                                    }, function (ret) {
                                        ret.data.Source.forEach(function (item) {
                                            if (arap.Id == item.Id) {
                                                var d = $.extend({}, item);
                                                d.SettleMoney = d.NotSettleMoney; //显示未收金额
                                                mvvm.arapRelList.push(d);
                                                var amt = parseFloat(d.SettleMoney)
                                                if (amt && amt > 0)
                                                    mvvm.arapAmount += amt;
                                                //watchMoney(mvvm.arapRelList[mvvm.arapRelList.length - 1]);
                                            }     
                                        });
                                    })
                                    mvvm.sumWriteOffAmt();
                                })
                                break;
                        }

                        var curr = CBCRM.memberShip
                        mvvm.accounting.SalesmanId = curr.Id;
                        mvvm.accounting.Salesman = curr.FullName
                        mvvm.accounting.ReceiptmanId = curr.Id
                        mvvm.accounting.Receiptman = curr.FullName
                        mvvm.accounting.AddBy = curr.Id
                        mvvm.accounting.AddByName = curr.FullName
                        mvvm.accounting.AddTime = GetDateTime()

                        mvvm.dosaveReceipts('新增收款单')
                    }
                    //收款单编辑
                    vm.doeditReceipts = function (id) {
                        if (!id) {
                            messageBox.warning("单据记录不存在");
                            return;
                        }
                        var path = '/FinancialAffairs/ReceiptsBill/'
                        $.get(path, { 'id': id }, function (ret) {
                            if (!ret || !ret.data) return CBCRM.showResult(ret);
                            var data = ret.data.Source
                            mvvm.accounting = data[0]
                            var title, tmplId;
                            if (mvvm.accounting.Category == 0) {
                                mvvm.arapType = 0
                                mvvm.arapCategoryDisplay = "应收款编号";
                                mvvm.getReceiptDetail(id)
                                mvvm.GetRelArapDetail(mvvm.arapType, mvvm.accounting.No);
                                mvvm.dosaveReceipts('编辑收款单');
                                mvvm.arapKey = '';
                                mvvm.arapAmount = 0;
                                mvvm.arapCategory = 'contract';
                            }
                        })
                    }
                    //收款单查看
                    vm.doviewReceipts = function (id, val) {
                        var path = '/FinancialAffairs/ReceiptsBill/'
                        $.get(path, { 'id': id }, function (ret) {
                            if (!ret || !ret.data) return CBCRM.showResult(ret);
                            var data = ret.data.Source
                            mvvm.accounting = data[0]
                            var title, tmplId;
                            mvvm.arapAmount = 0;
                            if (mvvm.accounting.Category != 1) {
                                mvvm.getReceiptDetail(id)
                                mvvm.arapType = 0;
                                mvvm.GetRelArapDetail(mvvm.arapType, mvvm.accounting.No);
                                //mvvm.getReceiptPayOfPlan(id)
                                title = "收款单详情";
                                tmplId = "receiptsViewTemplate";
                            } else {
                                mvvm.getReceiptDetail(id)
                                mvvm.arapType = 1;
                                mvvm.GetRelArapDetail(mvvm.arapType, mvvm.accounting.No);
                                title = "支出单详情";
                                tmplId = "receiptsViewTemplate2";
                            }
                            mvvm.openTmpl({
                                title: title, w: 950, h: 300,padding: "def2",
                                tmplId: tmplId, tmpl: tmpl
                            })
                        })
                    }
                    //取收款关联业务明细
                    vm.getReceiptDetail = function (receiptid) {

                        var val = null
                        if (action == 'get') {
                            val = ''
                        }
                        else if (that.params.id && !that.params.action) {
                            val = (that.params && that.params.id) ? that.params.id : ''
                        }

                        $.get('/FinancialAffairs/AccountList/', { "receiptid": receiptid, 'customerid': val }, function (ret) {
                            mvvm.receiptDetailList = ret.data.Source
                            if (mvvm.receiptDetailList != null && mvvm.receiptDetailList.length > 0) {
                                mvvm.receiptDetailList.forEach(function (item, i) {
                                    mvvm.receiptDetailList[i].BefoceAmount = item.Amount
                                    mvvm.receiptDetailList[i].BeforeProductId = item.Product
                                    mvvm.receiptDetailList[i].BeforeAccountId = item.AccountId
                                    mvvm.receiptDetailList[i].BeforeContractId = item.Contract
                                })
                            }
                        })
                    }
                    //取收款关联付款计划
                    vm.getReceiptPayOfPlan = function (receiptid) {
                        $.get('/FinancialAffairs/GetReceiptPayOfPlan/', { "receiptid": receiptid }, function (ret) {
                            mvvm.receiptPayOfPlanList = ret.data.Source
                        })
                    }

                    //收款单删除
                    vm.doDelReceipts = function () {
                        var id = $(this).attr('val');
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.get('/FinancialAffairs/ReceiptsDel/' + id, {}, function (ret) {
                                CBCRM.showResult(ret, function () {
                                    initReceiptBill(queryBillData);
                                    mvvm.grid1.reloadData();
                                    if (action == "Contract" && paramData) paramData.reloadEntity();
                                })
                            })
                        });
                    }
                    vm.doAllDelReceipts = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.post('/FinancialAffairs/ReceiptsAllDelete/', deleteIds, function (ret) {
                                CBCRM.showResult(ret, function () {
                                    initReceiptBill(queryBillData);
                                    mvvm.grid1.reloadData();
                                    if (action == "Contract" && paramData) paramData.reloadEntity();
                                });
                            });
                        });
                    }
                    //收款业务明细单删除
                    vm.dodelReceiptDetials = function () {
                        var index = parseInt($(this).attr('index'))
                        mvvm.receiptDetailDelList.push(mvvm.receiptDetailList[index].$model)
                        mvvm.receiptDetailList.removeAt(index)
                        var amt = 0
                        mvvm.receiptDetailList.$model.forEach(function (item, i) {
                            var amount = parseFloat(item.Amount)
                            if (amount) {
                                amt = amt + amount
                            }
                        })
                        mvvm.accounting.Amount = amt

                    }
                    //收款计划删除
                    vm.dodelPayOfPlan = function () {
                        var index = parseInt($(this).attr('index'))
                        mvvm.receiptPayOfPlanList.removeAt(index)
                    }
                    //收款单保存
                    vm.dosaveReceipts = function (title) {
                        var dialog = mvvm.openTmpl({
                            title: title, w: 900, h: 400,padding:"def2",
                            tmplId: "receiptsFormTemplate", tmpl: tmpl,
                            button: [{
                                name: '确定',
                                focus: true,
                                callback: function () {
                                    var msg = ''
                                    var writeOffAmount = 0;
                                    if (!mvvm.accounting.No) {
                                        msg = '收款单号不能为空<br/>'
                                    }
                                    if (!mvvm.accounting.CustomerDisplay) {
                                        msg = msg + '客户名称不能为空<br/>'
                                    }
                                    if (mvvm.receiptDetailList.$model.length == 0) {
                                        msg = msg + '收费明细无任何数据<br/>'
                                    }
                                    var amount = parseFloat(mvvm.accounting.Amount)
                                    if (!amount || amount < 0) {
                                        msg = msg + '请输入正确的金额<br/>'
                                    }
                                    for (var i = 0; i < mvvm.arapRelList.length; i++) {
                                        var arapRel = mvvm.arapRelList[i];
                                        var amount = parseFloat(arapRel.SettleMoney);
                                        if (isNaN(amount) || amount < 0 || amount > arapRel.Money) {
                                            msg = msg + '请输入正确销账的金额<br/>';
                                            break;
                                        }
                                        else
                                            writeOffAmount += amount;
                                    }
                                    if (writeOffAmount != 0 && writeOffAmount != mvvm.accounting.Amount) {
                                        msg = msg + '收款金额跟销账总金额必须相等<br/>'
                                    }
                                    if (msg) {
                                        messageBox.warning(msg)
                                        return false
                                    }
                                    //保存、更新、删除应收应付销账
                                    mvvm.arapRelList.forEach(function (item) {
                                        var isExist = false;
                                        // 更新应收应付销账
                                        mvvm.writeOffList.forEach(function (woItem) {
                                            if (woItem.ARAPId == item.Id) {
                                                woItem.WriteOffAmount = item.SettleMoney;
                                                woItem.Remark = item.Remark;
                                                isExist = true;
                                                return;
                                            }
                                        });
                                        // 新增应收应付销账
                                        if (!isExist) { 
                                            var arapWO = modelFactory.create("ARAPWriteOff");
                                            arapWO.ARAPId = item.Id;
                                            arapWO.AccountingNo = mvvm.accounting.No;
                                            arapWO.Type = item.Type;
                                            arapWO.WriteOffAmount = item.SettleMoney;
                                            arapWO.Remark = item.Remark == '' ? '' : item.Remark;
                                            mvvm.writeOffList.push(arapWO);
                                        }
                                    });
                                    //var url = "/FinancialAffairs/ARAPWriteOffUpdateList/"
                                    //var data = { "models": mvvm.writeOffList.$model, "delIds": mvvm.delWriteOffList.$model };
                                    //jsonPost(url, data, function (ret) {
                                    //})

                                    var model = mvvm.accounting.$model
                                    mvvm.receiptDetailList.forEach(function (item, i) {
                                        item.Category = '收入';
                                        item.IsTransfer = 0;
                                        item.CustomId = model.Customer;
                                        item.CustomName = model.CustomerDisplay;
                                        item.Contract = model.Contract;
                                        item.Telphone = model.CustomerTel;
                                        item.Address = model.CustomerAddr;
                                        item.SalesmanId = model.SalesmanId;
                                        item.Salesman = model.Salesman;
                                        item.ReceiptmanId = model.ReceiptmanId;
                                        item.Receiptman = model.Receiptman;
                                    });
                                    var data = {
                                        model: model,
                                        ReceiptsDetailList: mvvm.receiptDetailList.$model,
                                        ReceiptsDetailDelList: where(mvvm.receiptDetailDelList.$model, true, "Id"),
                                        writeOffList: mvvm.writeOffList.$model,
                                        delWOIdList: mvvm.delWriteOffList.$model
                                    };
                                    //$.extend(model, jsonToSubmit("ReceiptsDetailList", mvvm.receiptDetailList));
                                    //mvvm.receiptDetailDelList.$model.forEach(function (item, i) {
                                    //    model['ReceiptsDetailDelList[' + i + '].Id'] = item.Id
                                    //})
                                    //if (mvvm.accounting.IsPayOfPlan) {
                                    //    mvvm.receiptPayOfPlanList.$model.forEach(function (item, i) {
                                    //        model['PayOfPlanList[' + i + '].PlanOfPayId'] = item.Id
                                    //    })
                                    //}
                                    var url = model.Id == 0 ? "/FinancialAffairs/ReceiptsAdd/" : "/FinancialAffairs/ReceiptsUpdate/" + model.Id;
                                    jsonPost(url, data, function (ret) {
                                        CBCRM.showResult(ret, function () {
                                            if (action == "customer" || action == "Contract") {
                                                initReceiptBill(queryBillData)
                                            }
                                            mvvm.grid1.reloadData();
                                            mvvm.initNoDeleteList();//检查列表项是否可删除
                                            if (paramData) {
                                                if (paramData.reloadEntity) paramData.reloadEntity();
                                                if (paramData.reloadList) paramData.reloadList();
                                            }
                                            dialog.close()
                                        })
                                    });

                                    return false
                                }                    
                            }],
                            onClose: function () {
                                if (action == "ARAPCollectAdd") {
                                    paramData.reloadList();
                                }
                            }
                        });
                    }

                    //支出明细新增
                    vm.doaddPay = function () {
                        mvvm.accounting = modelFactory.create('AccountBook')
                        mvvm.tag = 'out'
                        mvvm.accounting.AccountId = mvvm.assetsData.length > 0 ? mvvm.assetsData[0].Id : ''
                        mvvm.accounting.AccountName = mvvm.assetsData.length > 0 ? mvvm.assetsData[0].AccountName : ''
                        var currUser = CBCRM.memberShip
                        mvvm.accounting.Salesman = currUser.FullName
                        mvvm.accounting.Receiptman = currUser.FullName
                        mvvm.accounting.AddBy.Id = currUser.Id
                        mvvm.accounting.AddBy.FullName = currUser.FullName
                        mvvm.accounting.ReceiptDate = GetDateTime()
                        mvvm.accounting.BookDate = GetDateTime()
                        mvvm.accounting.IsTransfer = 0;
                        mvvm.accounting.Category = '支出'
                        switch (action) {
                            case "customer":
                                mvvm.accounting.CustomId = paramid
                                mvvm.accounting.CustomName = paramData.entity.Name
                                break;
                            case "Contract":
                                mvvm.accounting.ContractNum = paramid
                                mvvm.accounting.Contract = mid;
                                mvvm.setCustomerInfo(that.params.cid)
                                break;
                        }
                        mvvm.dosavePay("支出明细")

                    }
                    vm.setFromCustomer = function () {
                        if (action != "customer") return;
                        var c = paramData.entity;
                        mvvm.accounting.CustomId = c.Id;
                        mvvm.accounting.CustomName = c.Name;
                    }
                    //支出明细保存
                    vm.dosavePay = function (title) {
                        var dialog = mvvm.openTmpl({
                            title: title, w: 745, h: 300,padding:"def2",
                            tmplId: "accountingFormTemplate2", tmpl: tmpl,
                            button: [{
                                name: '确定',
                                focus: true,
                                callback: function () {
                                    var model = mvvm.accounting.$model
                                    var msg = ''
                                    var amount = parseFloat(model.Amount)
                                    if (!amount || amount < 0) {
                                        msg = msg + '请输入正确的付款金额<br/>'
                                    }
                                    if (!model.ProjectName) {
                                        msg = msg + '请选择付款项目<br/>'
                                    }
                                    if (!model.Receiptman) {
                                        msg = msg + '请输入领款人<br/>'
                                    }
                                    if (msg) {
                                        messageBox.warning(msg)
                                        return false
                                    }
                                    var url = model.Id == 0 ? "/FinancialAffairs/AccountAdd/" : "/FinancialAffairs/AccountEdit/" + model.Id;
                                    $.post(url, model, function (ret) {
                                        CBCRM.showResult(ret, function () {
                                            mvvm.tag = 'list'
                                            mvvm.grid1.reloadData();
                                            dialog.close()
                                            if (paramData) {
                                                if (paramData.reloadEntity) paramData.reloadEntity();
                                                if (paramData.reloadList) paramData.reloadList();
                                            }
                                        });
                                    });

                                    return false
                                }
                            }],
                            onClose: function () {
                                mvvm.destroyui(["customerTreeId", "receiptmanid", "accountingbelongToTree"]);
                            }
                        });
                    }

                    //支出单新增
                    vm.doaddPayBill = function () {
                        mvvm.accounting = modelFactory.create('ReceiptsBill')
                        mvvm.receiptDetailList = []
                        mvvm.receiptDetailDelList = []
                        mvvm.doaddReceiptDetials()
                        mvvm.tag = 'out'
                        mvvm.arapRelList = [];
                        mvvm.writeOffList = [];
                        mvvm.delWriteOffList = [];
                        mvvm.arapType = 1;
                        mvvm.arapCategoryDisplay = "应付款编号";
                        mvvm.arapKey = '';
                        mvvm.arapCategory = 'contract';
                        mvvm.autoCode()

                        var curr = CBCRM.memberShip
                        mvvm.accounting.SalesmanId = curr.Id;
                        mvvm.accounting.Salesman = curr.FullName
                        mvvm.accounting.ReceiptmanId = curr.Id
                        mvvm.accounting.Receiptman = curr.FullName
                        mvvm.accounting.AddBy = curr.Id
                        mvvm.accounting.AddByName = curr.FullName
                        mvvm.accounting.AddTime = GetDateTime()
                        mvvm.accounting.Receiptdate = GetDateTime()
                        mvvm.accounting.Category = 1
                        switch (action) {
                            case 'add':
                                mvvm.accounting.IsOrder = true
                                mvvm.accounting.OrderId = paramid
                                break;
                            case 'ARAPPayAdd':
                                var arap = paramData.entity;
                                mvvm.accounting.Contract = arap.Contract.Id
                                mvvm.accounting.ContractNum = arap.Contract.ContractName
                                mvvm.mulSelect = true
                                mvvm.setCustomerInfo(arap.CustomerId)
                                $.get('/FinancialAffairs/GetARAPList/', {
                                    'type': mvvm.arapType,
                                    'contractId': arap.Contract.Id,
                                    'isSettled': false
                                }, function (ret) {
                                    ret.data.Source.forEach(function (item) {
                                        if (arap.Id == item.Id) {
                                            var d = $.extend({}, item);
                                            d.SettleMoney = d.NotSettleMoney; //显示未收金额
                                            mvvm.arapRelList.push(d);
                                            var amt = parseFloat(d.SettleMoney)
                                            if (amt && amt > 0)
                                                mvvm.arapAmount += amt;
                                            //watchMoney(mvvm.arapRelList[mvvm.arapRelList.length - 1]);
                                        } 
                                    });
                                })
                                break;
                        }
                            mvvm.dosavePayBill('新增支出单')
                    }

                    //支出单编辑
                    vm.doeditPayBill = function (id) {
                        if (!id) {
                            messageBox.warning("支出单据记录不存在");
                            return;
                        }
                        var path = '/FinancialAffairs/ReceiptsBill/'
                        $.get(path, { 'id': id }, function (ret) {
                            if (!ret || !ret.data) return CBCRM.showResult(ret);
                            var data = ret.data.Source
                            mvvm.accounting = data[0]
                            //mvvm.receiptDetailList = mvvm.accounting.ReceiptsDetail
                            var title, tmplId;
                            if (mvvm.accounting.Category == 1) {
                                mvvm.arapType = 1;
                                mvvm.arapCategoryDisplay = "应付款编号";
                                mvvm.arapAmount = 0;
                                mvvm.getReceiptDetail(id)
                                mvvm.GetRelArapDetail(mvvm.arapType, mvvm.accounting.No);
                                mvvm.dosavePayBill('支出单')
                                mvvm.arapKey = '';
                                mvvm.arapCategory = 'contract';
                            }
                        })
                    }

                    //支出单保存
                    vm.dosavePayBill = function (title) {
                        var dialog = mvvm.openTmpl({
                            title: title, w: 900, h: 400, padding: "def2",
                            tmplId: "receiptsFormTemplate2", tmpl: tmpl,
                            button: [{
                                name: '确定',
                                focus: true,
                                callback: function () {
                                    var msg = ''
                                    var writeOffAmount = 0;
                                    if (!mvvm.accounting.No) {
                                        msg = '付款单号不能为空<br/>'
                                    }
                                    if (!mvvm.accounting.CustomerDisplay) {
                                        msg = msg + '客户名称不能为空<br/>'
                                    }
                                    if (mvvm.receiptDetailList.$model.length == 0) {
                                        msg = msg + '付款明细无任何数据<br/>'
                                    }
                                    var amount = parseFloat(mvvm.accounting.Amount)
                                    if (!amount || amount < 0) {
                                        msg = msg + '请输入正确的付款金额<br/>'
                                    }
                                    for (var i = 0; i < mvvm.arapRelList.length; i++) {
                                        var arapRel = mvvm.arapRelList[i];
                                        var amt = parseFloat(arapRel.SettleMoney);
                                        if (isNaN(amt) || amt < 0 || amt > arapRel.Money) {
                                            msg = msg + '请输入正确销账的金额<br/>';
                                            break;
                                        }
                                        else
                                            writeOffAmount += amt;
                                    }
                                    if (writeOffAmount != mvvm.accounting.Amount) {
                                        msg = msg + '支出金额跟销账总金额必须相等<br/>'
                                    }
                                    if (msg) {
                                        messageBox.warning(msg)
                                        return false
                                    }

                                    //保存、更新、删除应收应付销账
                                    mvvm.arapRelList.forEach(function (item) {
                                        var isExist = false;
                                        // 更新应收应付销账
                                        mvvm.writeOffList.forEach(function (woItem) {
                                            if (woItem.ARAPId == item.Id) {
                                                woItem.WriteOffAmount = item.SettleMoney;
                                                woItem.Remark = item.Remark;
                                                isExist = true;
                                                return;
                                            }
                                        });
                                        // 新增应收应付销账
                                        if (!isExist) {
                                            var arapWO = modelFactory.create("ARAPWriteOff");
                                            arapWO.ARAPId = item.Id;
                                            arapWO.AccountingNo = mvvm.accounting.No;
                                            arapWO.Type = item.Type;
                                            arapWO.WriteOffAmount = item.SettleMoney;
                                            arapWO.Remark = item.Remark == '' ? '' : item.Remark;
                                            mvvm.writeOffList.push(arapWO);
                                        }
                                    });
                                    //var url = "/FinancialAffairs/ARAPWriteOffUpdateList/"
                                    //var data = { "models": mvvm.writeOffList.$model, "delIds": mvvm.delWriteOffList.$model };
                                    //jsonPost(url, data, function (ret) {
                                    //})

                                    var model = mvvm.accounting.$model
                                    mvvm.receiptDetailList.$model.forEach(function (item, i) {
                                        item.IsTransfer = 0;
                                        item.Category = '支出';
                                        item.CustomId = model.Customer
                                        item.CustomName = model.CustomerDisplay
                                        item.Receiptman = model.Receiptman
                                        item.ReceiptmanId = model.ReceiptmanId
                                        item.Address = model.CustomerAddr
                                        item.Accounting = model.Accounting
                                        item.Checker = model.Checker
                                        item.Teller = model.Teller
                                        item.Broker = model.Broker
                                        item.Examiner = model.Examiner
                                    });
                                    //$.extend(model, jsonToSubmit("ReceiptsDetailList", mvvm.receiptDetailList));
                                    //mvvm.receiptDetailDelList.$model.forEach(function (item, i) {
                                    //    model['ReceiptsDetailDelList[' + i + '].Id'] = item.Id
                                    //})
                                    var data = {
                                        model: model,
                                        ReceiptsDetailList: mvvm.receiptDetailList.$model,
                                        ReceiptsDetailDelList: where(mvvm.receiptDetailDelList.$model, true, "Id"),
                                        writeOffList: mvvm.writeOffList.$model,
                                        delWOIdList: mvvm.delWriteOffList.$model
                                    };
                                    var url = model.Id == 0 ? "/FinancialAffairs/ReceiptsAdd/" : "/FinancialAffairs/ReceiptsUpdate/" + model.Id;
                                    jsonPost(url, data, function (ret) {
                                        CBCRM.showResult(ret, function () {
                                            if (detail) {
                                                //initReceiptBill(queryBillData)
                                            } else {
                                                if (action == 'add') {
                                                    meun = avalon.vmodels.PurchasePay
                                                    meun.paymet(mvvm.accounting.Amount, paramid, 0)
                                                } else if (action == 'edit') {
                                                    meun = avalon.vmodels.PurchasePay
                                                    meun.doeditview(model.OrderId)
                                                    meun.paymet(mvvm.accounting.Amount, model.OrderId, 1)
                                                } else {
                                                    mvvm.grid1.reloadData();
                                                }
                                            }
                                            if (paramData) {
                                                if (paramData.reloadEntity) paramData.reloadEntity();
                                                if (paramData.reloadList) paramData.reloadList();
                                            }
                                            mvvm.initNoDeleteList();//检查列表项是否可删除
                                            dialog.close()

                                        });
                                    });

                                    return false
                                }
                            }]
                            /*, function () {
                                if (avalon.vmodels.receiptmanid) avalon.vmodels.receiptmanid.destroy()
                                if (avalon.vmodels.setParetCustomerId) avalon.vmodels.setParetCustomerId.destroy()
                                if (avalon.vmodels.employeeTree)
                                    avalon.vmodels.employeeTree.destroy() 
                            })
    
                            var content = $(dialog.content())
                            //content.attr('ms-include', 'receiptsFormTemplate2')
                            var inputTmpl = $(tmpl).find("#receiptsFormTemplate2").text()
                            content.html(inputTmpl)
                            avalon.scan(content[0], mvvm) */
                        });
                    }
                    //支出单明细新增
                    vm.doaddReceiptDetials = function () {
                        mvvm.receiptDetailList.push(modelFactory.create('AccountBook'))
                    }
                    //支出单合计
                    vm.sumPayAmt = function () {
                        var amt = 0
                        mvvm.receiptDetailList.$model.forEach(function (item, i) {
                            var amount = parseFloat(item.Amount)
                            if (amount) {
                                amt = amt + amount
                            }
                        })
                        mvvm.accounting.Amount = amt
                    }


                    //客户的联系人拉下列表数据
                    vm.customerContactData = []
                    vm.setCustomerContacts = function (customerid) {
                        $.get('/Customer/Contacts', { 'customerId': customerid }, function (ret) {
                            mvvm.customerContactData = ret.data.contacts.Source
                        })
                    }
                    vm.contactsChange = function () {
                        var option = $(this).find('option:selected')
                        if (option.val()) {
                            mvvm.accounting.Contacts = option.val()
                            mvvm.accounting.ContactsDisplay = option.text()
                        } else {
                            mvvm.accounting.Contacts = ''
                            mvvm.accounting.ContactsDisplay = ''
                        }
                    }
                    //取客户其它信息
                    vm.setCustomerInfo = function (customerid) {
                        $.get('/Customer/DetailCustomer/' + customerid, {}, function (ret) {
                            var customer = ret.data
                            mvvm.customerContactData = ret.data.Contacts;
                            if (mvvm.mulSelect) {
                                mvvm.accounting.Customer = customerid
                                mvvm.accounting.CustomerDisplay = customer.Name
                                mvvm.accounting.CustomerTel = customer.CompanyTel1
                                mvvm.accounting.CustomerAddr = customer.CompanyProvinceDisplay + customer.CompanyCityDisplay + customer.CompanyAreaDisplay + customer.CompanyAddress
                            } else {
                                mvvm.accounting.CustomId = customerid
                                mvvm.accounting.CustomName = customer.Name
                            }
                        })
                    }

                    //收款明细、支出明细选择客户
                    vm.selectDetailCustomer = function () {
                        plugins.selectCustomer({
                            callback: function (cus) {
                                var cu = cus[0];
                                mvvm.accounting.CustomId = cu.Id
                                mvvm.accounting.CustomName = cu.Name;
                            }
                        })
                    }
                    //收款单、支出单 选客户/联系人
                    vm.selectBillCustomer = function () {
                        plugins.selectCustomer({
                            type: "contacts",
                            callback: function (cus, cons) {
                                var cu = cus[0], con = cons.length > 0 ? cons[0] : {Id:"",Name:""};
                                mvvm.accounting.Customer = cu.Id
                                mvvm.accounting.CustomerDisplay = cu.Name
                                mvvm.accounting.Contacts = con.Id
                                mvvm.accounting.ContactsDisplay = con.Name

                                mvvm.mulSelect = true
                                //mvvm.setCustomerContacts(mvvm.accounting.Customer)
                                mvvm.customerContactData = cu.Contacts;
                                //mvvm.setCustomerInfo(mvvm.accounting.Customer)
                                mvvm.accounting.CustomerTel = cu.CompanyTel1
                                mvvm.accounting.CustomerAddr = cu.CompanyProvinceDisplay + cu.CompanyCityDisplay + cu.CompanyAreaDisplay + cu.CompanyAddress
                            }
                        });
                    }

                    //选择合同或产品
                    vm.mulSelect = false  //是否多选业务明细
                    vm.selProductList = []
                    vm.selContactList = []
                    vm.contractKey = ''


                    //款项流水选择合同订单
                    vm.selectContract = function (mulSelect,onLoad) {
                        //是否多选业务明细
                        mvvm.mulSelect = mulSelect
                        mvvm.contractKey = ''
                        var dialog=mvvm.openTmpl({
                            title: "选择合同业务明细", w: 800, h: 300,padding:"def2",
                            tmplId: "ContractListTemplate", tmpl: tmpl,
                            button:[{
                                name: '确定',
                                focus: true,
                                callback: function () {
                                    var contractChk = $("input[name='selectContract']:checked")
                                    if (contractChk.length == 0) {
                                        messageBox.warning('请选择合同订单')
                                    } else {
                                        var con = mvvm.selContactList[parseInt(contractChk.eq(0).attr('index'))]
                                        mvvm.accounting.Contract = con.Id
                                        mvvm.accounting.ContractNum = con.ContractNum
                                        mvvm.setCustomerInfo(con.Customer)
                                        var assetsid = mvvm.assetsData.length > 0 ? mvvm.assetsData[0].Id : ''
                                        if (mvvm.mulSelect) {//收付款单
                                            mvvm.accounting.Customer = con.Customer
                                            mvvm.accounting.CustomerDisplay = con.CustomerDisplay
                                            mvvm.setCustomerContacts(con.Customer)
                                            if (mvvm.accounting.Id == 0) {
                                                mvvm.receiptDetailList = []
                                                mvvm.receiptPayOfPlanList = []
                                            }
                                            var productChk = $("input[name='selectProduct']:checked")
                                            productChk.each(function (i, item) {
                                                var pro = mvvm.selProductList[parseInt(productChk.eq(i).attr('index'))]
                                                var detail = mvvm.productToAccountBook(pro);
                                                detail.AccountId = assetsid
                                                detail.Contract = con.Id;
                                                mvvm.receiptDetailList.push(detail)
                                            })
                                            //取付款计划
                                            //mvvm.getPlanPay(con.Id);
                                            //合计
                                            mvvm.sumProductAmt();
                                            //应收应付记账
                                            mvvm.initRelArap(mvvm.arapType, mvvm.accounting.Contract);
                                            mvvm.sumWriteOffAmt();
                                        }
                                        else {//收入/支出明细
                                            var productChk = $("input[name='selectProduct']:checked")
                                            if (productChk.length > 0) {
                                                var pro = mvvm.selProductList[parseInt(productChk.eq(0).attr('index'))]
                                                var detail = mvvm.productToAccountBook(pro);
                                                detail.AccountId = assetsid
                                                detail.Contract = con.Id;
                                                extendValue(mvvm.accounting, detail, "Product,ProductDisplay,ProductAlias,ProductBrand,ProductStandard,ProductPrice,DealPrice,ProductNum,Unit,Amount");
                                            }
                                        }
                                        if (dialog) dialog.close()
                                    }
                                    return false;
                                }
                            }]
                        })
                        mvvm.searchContract(onLoad)
                        vm.selProductList = []
                    }
                    vm.selectedContract = function () {
                        var contractid = $(this).attr('contractid')
                        $(this).find('input').eq(0).attr('checked', 'checked')
                        switch (action) {
                            case "customer":
                                $.get('/Market/ProductList/', { 'contractid': contractid, 'customerid': (that.params && that.params.id) ? that.params.id : '', 'pageSize': 1000 }, function (ret) {
                                    mvvm.selProductList = ret.data.Source
                                })
                                break;
                            case "Contract":
                            default:
                                $.get('/Market/ProductList/', { 'contractid': contractid, 'pageSize': 1000 }, function (ret) {
                                    var list = ret.data.Source
                                    mvvm.selProductList = list;
                                })
                                break;
                        }


                    }
                    vm.searchContract = function (onLoad) {
                        switch (action) {
                            case "customer":
                                mvvm.getContractList(onLoad)
                                break;
                            case "Contract":
                                mvvm.getContractListByContract(onLoad)
                                break;
                            default:
                                mvvm.getContractList(onLoad)
                                break;
                        }
                    }
                    vm.getContractList = function (onLoad) {
                        var customerid = ''
                        if (mvvm.accounting.Customer && mvvm.accounting.CustomerDisplay) {
                            customerid = mvvm.accounting.Customer
                        } else if (mvvm.accounting.CustomId && mvvm.accounting.CustomName) {
                            customerid = mvvm.accounting.CustomId
                        }
                        $.get('/Market/Contract/', {
                            'key': mvvm.contractKey,
                            //'paystate': 1,
                            'customerid': paramid ? paramid : customerid
                        }, function (ret) {
                            if (typeof(onLoad)=="function") onLoad(ret.data.Source);
                            mvvm.selContactList = ret.data.Source
                        })
                    }
                    vm.getContractListByContract = function (onLoad) {
                        var contractNum = ''
                        if (mvvm.accounting.ContractNum) {
                            contractNum = mvvm.accounting.ContractNum
                        }
                        $.get('/Market/Contract/', {
                            'key': mvvm.contractKey,
                            'paystate': 1,
                            'contractNum': contractNum
                        }, function (ret) {
                            if (onLoad) onLoad(ret.data.Source);
                            mvvm.selContactList = ret.data.Source
                        })
                    }
                    vm.productToAccountBook = function (pro) {
                        var detail = modelFactory.create('AccountBook')
                        detail.Product = pro.Id
                        detail.ProductDisplay = pro.ProductName
                        detail.ProductAlias = pro.ProductAlias
                        detail.ProductBrand = pro.BrandDisplay
                        detail.ProductStandard = pro.Standard
                        detail.ProductPrice = pro.StandardPrice
                        detail.DealPrice = pro.Price
                        detail.ProductNum = pro.Num
                        detail.Unit = pro.Unit
                        var currReturnAmount = 0
                        if (pro.ReturnAmount)
                            currReturnAmount = pro.Money - pro.ReturnAmount
                        else
                            currReturnAmount = pro.Money
                        detail.Amount = currReturnAmount
                        return detail;
                    }
                    //取付款计划
                    vm.getPlanPay = function (id) {
                        $.get('/Market/GetContractRelevance/', { "Id": id }, function (ret) {
                            mvvm.receiptPayOfPlanList = ret.data.planOfPayList
                        })
                    }
                    
                    //款项流水选择产品
                    vm.productListKey = ''
                    vm.selectProduct = function () {
                        mvvm.contractKey = ''
                        mvvm.productListKey = ''
                        //是否多选业务明细
                        var mul = $(this).attr('val')
                        if (mul == 'mul')
                            mvvm.mulSelect = true
                        else
                            mvvm.mulSelect = false
                        var dialog = messageBox.openHtml('选择业务明细', '800px', '300px', '', [{
                            name: '确定',
                            focus: true,
                            callback: function () {
                                var productChk = $("input[name='selectProduct']:checked")
                                var assetsid = mvvm.assetsData.length > 0 ? mvvm.assetsData[0].Id : ''
                                if (productChk.length > 0) {
                                    if (mvvm.mulSelect) {
                                        productChk.each(function (i, item) {
                                            var detail = modelFactory.create('AccountBook')
                                            var pro = mvvm.selProductList[parseInt(productChk.eq(i).attr('index'))]
                                            detail.Product = pro.Id
                                            detail.ProductDisplay = pro.ProductName
                                            detail.ProductAlias = pro.ProductAlias
                                            detail.ProductBrand = pro.BrandDisplay
                                            detail.ProductStandard = pro.Standard
                                            detail.ProductPrice = pro.Price
                                            detail.ProductNum = pro.Num
                                            detail.Unit = pro.Unit
                                            detail.Amount = pro.Money
                                            detail.AccountId = assetsid
                                            detail.BookDate = GetDateTime()
                                            detail.ReceiptDate = GetDateTime()
                                            mvvm.receiptDetailList.push(detail)
                                        })
                                        mvvm.sumProductAmt()
                                    } else {
                                        var pro = mvvm.selProductList[parseInt(productChk.eq(0).attr('index'))]
                                        mvvm.accounting.Product = pro.Id
                                        mvvm.accounting.ProductDisplay = pro.ProductName
                                        mvvm.accounting.ProductAlias = pro.ProductAlias
                                        mvvm.accounting.ProductBrand = pro.BrandDisplay
                                        mvvm.accounting.ProductStandard = pro.Standard
                                        mvvm.accounting.ProductPrice = pro.Price
                                        mvvm.accounting.ProductNum = pro.Num
                                        mvvm.accounting.Unit = pro.Unit
                                        var currReturnAmount = 0
                                        if (pro.ReturnAmount)
                                            currReturnAmount = pro.Money - pro.ReturnAmount
                                        else
                                            currReturnAmount = pro.Money
                                        mvvm.accounting.Amount = currReturnAmount
                                        //mvvm.accounting.BookDate = GetDateTime()
                                        //mvvm.accounting.ReceiptDate = GetDateTime()

                                        if (!mvvm.accounting.ContractNum && pro.Contract) {
                                            mvvm.accounting.Contract = pro.Contract
                                            mvvm.accounting.ContractNum = pro.ContractNum
                                        }
                                        if (!mvvm.accounting.CustomName && pro.Customer) {
                                            mvvm.accounting.CustomId = pro.Customer
                                            mvvm.setCustomerInfo(pro.Customer)
                                        }
                                    }
                                }
                                if (dialog) dialog.close()
                                return false;
                            }
                        }]);
                        var content = $(dialog.content())
                        //content.attr('ms-include', 'ProductListTemplate')
                        var inputTmpl = $(tmpl).find("#ProductListTemplate").text()
                        content.html(inputTmpl)
                        avalon.scan(content[0], mvvm)
                        mvvm.getProductList()
                    }
                    vm.getProductList = function () {
                        switch (action) {
                            case "customer":
                                $.get('/Market/ProductList/',
                                    { 'key': mvvm.productListKey, 'contractid': mvvm.accounting.Contract, 'customerid': paramid, 'pageSize': 1000 },
                                    function (ret) {
                                    if(ret && ret.result)mvvm.selProductList = ret.data.Source
                                })
                                break;
                            case "Contract":
                                $.get('/Market/ProductList/', { 'contractid': mid,ifPayOk:false, 'pageSize': 1000 }, function (ret) {
                                    if(ret && ret.result)mvvm.selProductList = ret.data.Source
                                })

                                break;
                        }
                    }             
                    vm.selectedProduct = function () {
                        var payState = $(this).attr('val')
                        if (!mvvm.mulSelect && payState != '2')
                            $(this).find('input').eq(0).attr('checked', 'checked')
                    }
                    vm.sumProductAmt = function () {
                        var amt = 0
                        mvvm.receiptDetailList.$model.forEach(function (item, i) {
                            var amount = parseFloat(mvvm.receiptDetailList[i].Amount)
                            if (amount)
                                amt = amt + amount
                        })
                        mvvm.accounting.Amount = amt
                    }
                    vm.sumProductAmt2 = function () {
                        var index = $(this).attr('index')
                        var amt = 0
                        mvvm.receiptDetailList.$model.forEach(function (item, i) {
                            if (i == index) {
                                var price = parseFloat(item.ProductPrice)
                                var num = parseFloat(item.ProductNum)
                                if (price && num) {
                                    var amount2 = price * num
                                    mvvm.receiptDetailList[i].Amount = amount2
                                }
                            }
                            var amount = parseFloat(mvvm.receiptDetailList[i].Amount)
                            if (amount)
                                amt = amt + amount
                        })
                        mvvm.accounting.Amount = amt
                    }
         


                    //选择收款单
                    vm.receiptsKey = ''
                    vm.selReceiptsList = []
                    vm.selectReceipts = function () {
                        mvvm.receiptsKey = ''
                        var dialog = messageBox.openHtml('选择收款单', '800px', '300px', '', [{
                            name: '确定',
                            focus: true,
                            callback: function () {
                                var productChk = $("input[name='selectReceipts']:checked")
                                if (productChk.length > 0) {
                                    var pro = mvvm.selReceiptsList[parseInt(productChk.eq(0).attr('index'))]
                                    mvvm.accounting.ReceiptBill = pro.Id
                                    mvvm.accounting.ReceiptBillDisplay = pro.No
                                }
                                if (dialog) dialog.close()
                                return false;
                            }
                        }]);
                        var content = $(dialog.content())
                        //content.attr('ms-include', 'ReceiptsListTemplate')
                        var inputTmpl = $(tmpl).find("#ReceiptsListTemplate").text()
                        content.html(inputTmpl)
                        avalon.scan(content[0], mvvm)
                        mvvm.getReceipts()
                    }
                    vm.getReceipts = function () {
                        $.get('/FinancialAffairs/ReceiptsBill/', {
                            'keyword': mvvm.receiptsKey,
                            'customerid': (that.params && that.params.id) ? that.params.id : ''
                        }, function (ret) {
                            mvvm.selReceiptsList = ret.data.Source
                        })
                    }
                    vm.selectedReceipts = function () {
                        $(this).find('input').eq(0).attr('checked', 'checked')
                    }

                    vm.getReceipts = function () {
                        $.get('/FinancialAffairs/ReceiptsBill/', {
                            'keyword': mvvm.receiptsKey,
                            'customerid': (that.params && that.params.id) ? that.params.id : ''
                        }, function (ret) {
                            mvvm.selReceiptsList = ret.data.Source
                        })
                    }
                    vm.selectedReceipts = function () {
                        $(this).find('input').eq(0).attr('checked', 'checked')
                    }
                    //选择票据凭证
                    vm.billKey = ''
                    vm.selBillsList = []
                    vm.selectBill = function () {
                        mvvm.billKey = ''
                        mvvm.selBillsList = []
                        var dialog = messageBox.openHtml('选择开票记录', '800px', '300px', '', [{
                            name: '确定',
                            focus: true,
                            callback: function () {
                                var billChk = $("input[name='selectBill']:checked")
                                if (billChk.length > 0) {
                                    var pro = mvvm.selBillsList[parseInt(billChk.eq(0).attr('index'))]
                                    mvvm.accounting.Bill = pro.Id
                                    mvvm.accounting.BillDisplay = pro.BillCode
                                    mvvm.accounting.BillType = pro.BillType
                                    mvvm.accounting.BillTypeDisplay = pro.BillTypeDisplay
                                    mvvm.accounting.BillDate = pro.CreateDate
                                }
                                if (dialog) dialog.close()
                                return false;
                            }
                        }
                        , {
                            name: '新增开票',
                            callback: function () {
                                goto('/FinancialAffairs/Bill/0/add')
                                return false;
                            }
                        }
                        ]);
                        var content = $(dialog.content())
                        //content.attr('ms-include', 'BillTemplate')
                        var inputTmpl = $(tmpl).find("#BillTemplate").text()
                        content.html(inputTmpl)
                        avalon.scan(content[0], mvvm)
                        mvvm.getBills()
                    }
                    vm.getBills = function () {
                        $.get('/FinancialAffairs/Bill/', {
                            'key': mvvm.billKey,
                            'customerid': mvvm.accounting.CustomId
                        }, function (ret) {
                            mvvm.selBillsList = ret.data.Source
                        })
                    }
                    vm.selectedBill = function () {
                        $(this).find('input').eq(0).attr('checked', 'checked')
                    }

                    //取字典
                    vm.unitsData = []
                    vm.receiptsData = []
                    vm.getDictData = function () {
                        $.get('/FinancialAffairs/GetAccountingDict', {}, function (ret) {
                            mvvm.unitsData = ret.data.unitsData
                            mvvm.receiptsData = ret.data.receiptsData
                        })
                    }
                    //常用说明
                    vm.selectreceiptsData = function () {
                        mvvm.accounting.Remark = $(this).find('option:selected').val()
                    }
                    //取账号
                    vm.assetsData = []
                    vm.getAssets = function () {
                        $.get('/FinancialAffairs/AssetsList', {}, function (ret) {
                            mvvm.assetsData = ret.data.Source
                            mvvm.queryData.assetsid.concat(where(ret.data.Source, true, { val: "Id", label: "AccountName", curr: false }));
                        })
                    }
                    //业务员，收款人
                    vm.selectMan = function (type) {
                        plugins.selectUser({
                            dataAuth: 7020000,
                            callback: function (us) {
                                var u = us[0];
                                switch (type) {
                                    case "salesman":
                                        mvvm.accounting.SalesmanId = u.Id;
                                        mvvm.accounting.Salesman = u.FullName
                                        break;
                                    case "receiptman":
                                        mvvm.accounting.ReceiptmanId = u.Id;
                                        mvvm.accounting.Receiptman = u.FullName
                                        break;
                                }
                            }
                        })
                    }
                    //收支项目 
                    vm.currEmpIndex = 0
                    vm.setEmps = function () {
                        var curItem = this.$vmodel,
                            index = curItem.$index,
                            panel = avalon.vmodels.employeeTreepanel,
                            tree = avalon.vmodels.employeeTree
                        mvvm.currEmpIndex = index
                        if (!panel) {
                            avalon.ui.dropDownGroupPostUserTree(this, {
                                dropDownGroupPostUserTreeId: 'employeeTree',
                                dropDownGroupPostUserTreeOptions: {
                                    q: '请输入收支项目名称',
                                    treeopts: {
                                        callback: {
                                            onClick: function (e, treeId, treeNode) {
                                                var detail = mvvm.receiptDetailList[mvvm.currEmpIndex]
                                                detail.ProjectId = treeNode.Id
                                                detail.ProjectName = treeNode.Name
                                            }
                                        },
                                        async: {
                                            url: function (treeId, treeNode) {
                                                var res = '';
                                                switch (mvvm.tag) {
                                                    case 'in': res = '/FinancialAffairs/PorjectDrodonwn/?type=0'; break;
                                                    case 'out': res = '/FinancialAffairs/PorjectDrodonwn/?type=1'; break;
                                                }
                                                return res;
                                            },
                                            dataFilter: function (treeId, parentNode, responseData) {
                                                var result = [];
                                                if (responseData.data) {
                                                    responseData.data.forEach(function (item) {
                                                        result.push({ Id: item.Id, Name: item.Name, ParentId: item.Parent });
                                                    })
                                                }
                                                return result;
                                            }
                                        }
                                    }
                                },
                                initevent: false
                            }, this.$vmodels)
                            panel = avalon.vmodels.employeeTreepanel
                            tree = avalon.vmodels.employeeTree
                        } else {
                            panel.target = this
                        }
                        panel.toggle(true)
                    }
                    vm.belongToOpts = {
                        q: '请输入收支项目名称',
                        treeopts: {
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    mvvm.accounting.ProjectId = treeNode.Id
                                    mvvm.accounting.ProjectName = treeNode.Name
                                }
                            },
                            async: {
                                url: function (treeId, treeNode) {
                                    var res = '';
                                    switch (mvvm.tag) {
                                        case 'in': res = '/FinancialAffairs/PorjectDrodonwn/?type=0'; break;
                                        case 'out': res = '/FinancialAffairs/PorjectDrodonwn/?type=1'; break;
                                    }
                                    return res;
                                },
                                dataFilter: function (treeId, parentNode, responseData) {
                                    var result = [];
                                    if (responseData.data) {
                                        responseData.data.forEach(function (item) {
                                            result.push({ Id: item.Id, Name: item.Name, ParentId: item.Parent });
                                        })
                                    }
                                    return result;
                                }
                            }
                        }
                    }
                    //新增下拉菜单
                    vm.IsShowAddList = false
                    vm.showAddList = function () {
                        mvvm.IsShowAddList = !mvvm.IsShowAddList
                    }
                    vm.IsShowAddList2 = false
                    vm.showAddList2 = function () {
                        mvvm.IsShowAddList2 = !mvvm.IsShowAddList2
                    }

                    //会计、出纳等快速选择
                    vm.examinerData = []
                    vm.accountingData = []
                    vm.checkerData = []
                    vm.tellerData = []
                    vm.brokerData = []
                    vm.accountGetMans = function () {
                        $.get('/FinancialAffairs/AccountGetMans/', {}, function (ret) {
                            mvvm.examinerData = ret.data.examiner
                            mvvm.accountingData = ret.data.accounting
                            mvvm.checkerData = ret.data.checker
                            mvvm.tellerData = ret.data.teller
                            mvvm.brokerData = ret.data.broker
                        });
                    }
                    vm.getManVal = function (mantype) {
                        var val = $(this).text()
                        switch (mantype) {
                            case 'examiner':
                                mvvm.accounting.Examiner = val
                                break
                            case 'accounting':
                                mvvm.accounting.Accounting = val
                                break
                            case 'checker':
                                mvvm.accounting.Checker = val
                                break
                            case 'teller':
                                mvvm.accounting.Teller = val
                                break
                            case 'broker':
                                mvvm.accounting.Broker = val
                                break
                        }
                    }
                    vm.manshow = function (mantype) {
                        switch (mantype) {
                            case 'examiner':
                                $('#examiner').show()
                                break
                            case 'accounting':
                                $('#accounting').show()
                                break
                            case 'checker':
                                $('#checker').show()
                                break
                            case 'teller':
                                $('#teller').show()
                                break
                            case 'broker':
                                $('#broker').show()
                                break
                        }
                    }
                    vm.manhide = function (mantype) {
                        var val = $(this).text()
                        switch (mantype) {
                            case 'examiner':
                                $('#examiner').hide()
                                break
                            case 'accounting':
                                $('#accounting').hide()
                                break
                            case 'checker':
                                $('#checker').hide()
                                break
                            case 'teller':
                                $('#teller').hide()
                                break
                            case 'broker':
                                $('#broker').hide()
                                break
                        }
                    }
                })
                mvvm.grid1.init();
                mvvm.queryData.begindate.$watch("val", watchTime);
                mvvm.queryData.enddate.$watch("val", watchTime);
                function watchMoney(item) {
                    item.$watch("SettleMoney", function (n, o) {
                        if (n && n != o) {
                            var m = parseFloat(n);
                            item.NotSettleMoney = item.Money - item.SettleMoney;
                            var ovalue = parseFloat(o);
                            if (ovalue) {
                                mvvm.arapAmount += m - ovalue;
                            }
                        }
                    })
                }
                function watchTime(v1, v2) {
                    if (v1 && v1 != v2) {
                        var data = mvvm.createQuery();
                        mvvm.grid1.loadData(data);
                    }
                }
                mvvm.getDictData()
                //mvvm.getAssets()
                mvvm.accountGetMans()
                //取收款单
                function initReceiptBill(data) {
                    var path = ''
                    if (that.params.id)
                        if (action == "customer")
                            path = '/FinancialAffairs/ReceiptsBill/?customerid=' + that.params.id
                        else if (action == "Contract") {
                            path = '/FinancialAffairs/ReceiptsBill/?contractid=' + that.params.mid
                        } else {
                            path = '/FinancialAffairs/ReceiptsBill/'
                        }
                    else
                        path = '/FinancialAffairs/ReceiptsBill/'
                    $.get(path, data, function (ret) {
                        mvvm.receiptList = ret.data.Source
                        avalon.vmodels.receiptpaging.total = ret.data.RecordTotal
                        mvvm.RECEIPTSADD = ret.data.RECEIPTSADD
                        mvvm.RECEIPTSDELETE = ret.data.RECEIPTSDELETE
                        mvvm.totalrptmoney = 0
                        mvvm.receiptList.forEach(function (item, i) {
                            var money = parseFloat(item.Amount)
                            if (money)
                                mvvm.totalrptmoney += money
                        })
                    })
                }
                var queryBillData = {
                    pageIndex: 1,
                    pageSize: 20,
                    customerId: '',
                    categroy: 0
                }

                function _init() {
                    mvvm.accountList = [
                        { id: 0, title: '现金账户', open: true, change: itemClick, items: [] },
                        { id: 1, title: '银行账户', open: false, change: itemClick, items: [] },
                        { id: 2, title: '虚拟账户', open: false, change: itemClick, items: [] },
                        { id: 3, title: '负债账户', open: false, change: itemClick, items: [] },
                        { id: 4, title: '债权账户', open: false, change: itemClick, items: [] }
                    ]
                    $.get('/FinancialAffairs/Accounting/', {}, function (ret) {
                        if (!ret || !ret.result) return CBCRM.showResult(ret);
                        mvvm.account = ret.data.total;
                        mvvm.assetsData = ret.data.list;
                        var arr = mvvm.queryData.assetsid.items.$model.concat(where(ret.data.list, true, { val: "Id", label: "AccountName", curr: false }));
                        mvvm.queryData.assetsid.items = arr;
                        var val = mvvm.queryData.assetsid.val;
                        if (val) mvvm.addQuery("assetsid", val, null,true);
                        if (ret.data.list) {
                            mvvm.accountList.forEach(function (item, i) {
                                ret.data.list.forEach(function (account) {
                                    if (account.AccountTypeId == i) {
                                        item.items.push(account);
                                        item.open = true;
                                    }
                                })
                            });

                        }
                    });
                    $.get('/FinancialAffairs/AccountGetDic/', {}, function (ret) { mvvm.accountingBillType = ret.data; })
                }
                function itemClick() {
                    var index = parseInt($(this).attr('index'));
                    mvvm.accountList[index].open = !mvvm.accountList[index].open;
                }
                function PayOutWindow(title) {
                    var dialog = mvvm.openTmpl({
                        title: "", w: 750, h: 200,
                        tmplId: "PayOutMoney", tmpl: tmpl,
                        button: [{
                            name: '确定',
                            focus: true,
                            callback: function () {
                                mvvm.trSubmit();
                                return false;
                            }
                        }],
                        onClose: function () {
                            mvvm.destroyui(["belongToTree3", "belongToTree4"]);
                        }
                    });
                }
                function viewWindow(title) {
                    var dialog = messageBox.openHtml(title, '800px', '200px', '');
                    var content = $(dialog.content())
                    content.attr('ms-include', 'viewTemplate')
                    content.parent().css('vertical-align', 'top');
                    avalon.scan(content[0], mvvm)
                }
                function viewIncomeWindow(title) {
                    var dialog = messageBox.openHtml(title, '800px', '200px', '');
                    var content = $(dialog.content())
                    content.attr('ms-include', 'viewIncome')
                    content.parent().css('vertical-align', 'top');
                    avalon.scan(content[0], mvvm)
                }
                avalon.filters.GetSample = function (sample) {
                    return sample ? '(简)' : '(全)';
                }
                avalon.filters.CreateId = function () {

                }
                avalon.filters.GetBillType = function (id) {
                    var res = ''
                    mvvm.accountingBillType.forEach(function (item) {
                        if (item.Id == id) res = item.Data;
                    })
                    return res;
                }
                function fill() {
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
                }
                _init();
                switch (action) {
                    case "customer"://客户信息中，款项流水调用
                        mvvm.queryData.customerid.val = paramid;
                        /*隐藏其它，只显示列表块*/
                        mvvm.showOnlyList = true
                        paramData.viewOther(tmpl, mvvm);
                        break;
                    case "add":
                        //逐步改为使用doadd
                        mvvm.doaddPayBill()
                        break;
                    case "doadd":
                        //带参数添加
                        var pd = paramData || {};
                        var entity = pd.entity || {};
                        switch (pd.type) {
                            case "addDetailReceipts":
                                mvvm.doadd();
                                break;
                        }
                        avalon.mix(mvvm.accounting, entity);
                        break;
                    case "ARAPCollectAdd":
                        //mvvm.doadd();
                        //var arap = paramData.entity;
                        mvvm.doaddReceipts("ARAPCollectAdd");
                        break;
                    case "ARAPPayAdd":
                        mvvm.doaddPayBill("ARAPPayAdd");
                        break;
                    case "get":
                        mvvm.doviewReceipts(paramid)
                        break;
                    case "edit":
                        mvvm.doeditPayBill(paramid)
                        break;
                    case "view":
                        mvvm.doview(paramid);
                        break;
                    case "Contract"://合同订单中调用
                        var entity = paramData.entity;
                        mvvm.queryData.contractid.val = entity.Id;
                        mvvm.showOnlyList = true
                        paramData.viewOther(tmpl, mvvm, "#viewDiv");
                        break;
                    default:
                        if (paramData) {
                            for (var key in paramData) {
                                if (mvvm.queryData.hasOwnProperty(key))
                                    mvvm.addQuery(key, paramData[key], null, true);
                            }
                        }
                        fill();
                        break;
                }
                mvvm.getDicts();
            },

            //基本设置
            Settings: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this
                var mvvm = CBCRM.define('Settings', function (vm) {
                    vm.index = ''
                    vm.change = function () {
                        mvvm.index = avalon(this).data('index')
                    }

                    /* 以下为收支项目相关 */
                    vm.project = {}
                    vm.projectList = []
                    vm.projectPList = []
                    vm.watchType = function () {
                        mvvm.project.$watch("Type", function (n,o) {
                            var plist = where(projectList, function (item) { return (!item.Parent || item.Parent==1) && item.Type==n });
                            mvvm.projectPList = plist;
                            mvvm.Parent = n;
                        });
                    }
                    vm.projectAdd = function (type,pid,pname) {
                        mvvm.project = modelFactory.create('Project');
                        mvvm.watchType();
                        mvvm.project.Type = type.toString();

                        if (pid) {
                            mvvm.project.Parent = pid.toString();
                            mvvm.project.PName = pname
                        }
                        projectWindow('新增收支项目');
                    }
                    vm.projectEdit = function () {
                        var id = $(this).attr('id');
                        $.get('/FinancialAffairs/ProjectDetail/' + id, {}, function (ret) {
                            if (!ret || !ret.result) return CBCRM.showResult(ret);
                            mvvm.project = ret.data;
                            var pid = ret.data.Parent, type = ret.data.Type;
                            mvvm.watchType();
                            mvvm.project.Type = "";
                            mvvm.project.Type = type;
                            mvvm.project.Parent = pid;
                            if (ret.data.Super)
                                mvvm.project.PName = ret.data.Super.Name;

                        })
                        projectWindow('编辑收支项目');
                    }
                    vm.projectDel = function () {
                        var id = $(this).attr('val');
                        var index = parseInt($(this).attr('index'));
                        messageBox.confirm('确定删除吗？', function () {
                            mvvm.projectList.removeAt(index);
                            $.get('/FinancialAffairs/ProjectDelete/' + id, {}, function () { });
                        });
                    }
                    vm.projectAllDel = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.post('/FinancialAffairs/ProjectAllDelete/', deleteIds, function (ret) {
                                if (ret.result) {
                                    initWithProject();
                                    messageBox.succeed(ret.message);
                                }
                            });
                        });
                    }
                    vm.projectHide = function (hide) {
                        var ids = checkAll(null, true), act = hide ? "隐藏" : "显示";
                        if (ids.length == 0) {
                            messageBox.warning("未选择任何数据！");
                            return;
                        }
                        messageBox.confirm('确定'+act+'选中的数据吗？', function () {
                            $.post('/FinancialAffairs/ProjectHide', {ids:ids.join(","),hide:hide}, function (ret) {
                                CBCRM.showResult(ret);
                                if (ret.result) {
                                    initWithProject();
                                }
                            });
                        });
                    }
                    vm.changeProjectHide = function (entity,submit) {
                        if (submit) {
                            var act = entity.Hide ? "显示" : "隐藏";
                            messageBox.confirm2("确定要" + act + "该项目吗？", function () {
                                entity.Hide = !entity.Hide;
                                $.post('/FinancialAffairs/ProjectHide', { ids: entity.Id, hide: entity.Hide }, function (ret) {
                                    CBCRM.showResult(ret);
                                    if (!ret.result) {
                                        entity.Hide = !entity.Hide;
                                    }
                                });
                            });
                        } else {
                            entity.Hide = !entity.Hide;
                        }
                    }
                    vm.projectShowItem = {}
                    vm.projectKeyword = ''
                    vm.projectSearch = function () {
                        mvvm.projectShowItem.keyword = mvvm.projectShowItem.keywordName = mvvm.projectKeyword;
                        initWithProject(mvvm.projectShowItem.$model);
                    }
                    vm.projectClear = function () {
                        mvvm.projectKeyword = mvvm.projectShowItem.keyword = '';
                        mvvm.projectShowItem.type = mvvm.projectShowItem.typeName = '';
                        initWithProject(mvvm.projectShowItem.$model)
                    }
                    vm.projectRemove = function () {
                        var tag = $(this).attr('val');
                        switch (tag) {
                            case 'keyword':
                                mvvm.projectKeyword = '';
                                mvvm.projectShowItem.keyword = mvvm.projectShowItem.keywordName = '';
                                break;
                            case 'type':
                                mvvm.projectShowItem.type = mvvm.projectShowItem.typeName = ''; break;
                                break;
                        }
                        initWithProject(mvvm.projectShowItem.$model);
                    }
                    vm.projectItem = function () {
                        var val = $(this).attr('val');
                        var na = $(this).attr('na');
                        mvvm.projectShowItem.type = val ? parseInt(val) : val;
                        mvvm.projectShowItem.typeName = na;
                        initWithProject(mvvm.projectShowItem.$model);
                    }
                    //vm.projectpaing = {//分页
                    //    paging: function () {
                    //        var that = this
                    //        var query = { pageIndex: that.currentindex + 1, pageSize: that.pagesize }
                    //        initWithProject(query);
                    //    }
                    //}
                    vm.PROJECTADD = false
                    vm.PROJECTDELETE = false

                    //展开收缩树
                    vm.doNode = function () {
                        var id = $(this).attr('id')
                        if (id == '0' || id == '1') {
                            var stu = parseInt($(this).attr('stu'))
                            if (stu == 1) {
                                $(this).removeClass('tablelevel0')
                                $(this).addClass('tablelevel0_exp')
                                if (id == '0')
                                    $('.typein').hide()
                                else
                                    $('.typeout').hide()
                                $(this).attr('stu', 2)
                            } else if (stu == 2) {
                                $(this).removeClass('tablelevel0_exp')
                                $(this).addClass('tablelevel0')
                                if (id == '0')
                                    $('.typein').show()
                                else
                                    $('.typeout').show()
                                $(this).attr('stu', 1)
                            }
                        }
                    }

                    /* 以下为资产账户相关 */
                    vm.assets = {}
                    vm.assetsKeyword = ''
                    vm.assetsSearch = function () {
                        mvvm.assetsShowItem.keyword = mvvm.assetsShowItem.keywordName = mvvm.assetsKeyword;
                        initWithAssets(mvvm.assetsShowItem.$model);
                    }
                    vm.assetsClear = function () {
                        mvvm.assetsShowItem.keyword = mvvm.assetsShowItem.keywordName = '';
                        mvvm.assetsShowItem.type = mvvm.assetsShowItem.typeName = '';
                        initWithAssets(mvvm.assetsShowItem.$model);
                    }
                    vm.assetsRemove = function () {
                        var val = $(this).attr('val');
                        switch (val) {
                            case "keyword": mvvm.assetsShowItem.keyword = mvvm.assetsShowItem.keywordName = ''; break;
                            case "type": mvvm.assetsShowItem.type = mvvm.assetsShowItem.typeName = ''; break;
                        }
                        initWithAssets(mvvm.assetsShowItem.$model);
                    }
                    vm.assetsShowItem = {}
                    vm.assetsCategory = []
                    vm.assetsCategorySimple = []
                    vm.assetsCurrency = []
                    vm.assetsList = []
                    vm.assetsAdd = function () {
                        mvvm.assets = modelFactory.create('Assets')
                        mvvm.assets.AccountTypeId += '';
                        mvvm.assets.CurrencyId = mvvm.currencyList.$model.length ? mvvm.currencyList.$model[0].Id : 0
                        assetsWindow('新增资产账户');
                    }
                    vm.assetsEdit = function (id) {
                        $.get('/FinancialAffairs/AssetsDetail/' + id, {}, function (ret) {
                            mvvm.assets = ret.data;
                            mvvm.assets.AccountTypeId += '';
                            assetsWindow('编辑资产账户');
                        });
                    }
                    vm.assetsDel = function () {
                        var id = $(this).attr('val');
                        var index = parseInt($(this).attr('index'));
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.get('/FinancialAffairs/AssetsDel/' + id, {}, function (ret) {
                                mvvm.assetsList.removeAt(index);
                            })
                        });
                    }
                    vm.assetsAllDel = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.post('/FinancialAffairs/AssetsAllDelete/', deleteIds, function (ret) {
                                if (ret.result) {
                                    initWithAssets();
                                    messageBox.succeed(ret.message);
                                }
                            });
                        });
                    }
                    vm.assetspaing = {
                        paging: function () {
                            var that = this
                            var query = { pageIndex: that.currentindex + 1, pageSize: that.pagesize }
                            initWithAssets(query);
                        }
                    }
                    vm.assetslisttab = '';
                    vm.assetslistTabs = [
                        { label: "全部账户", val: '' }
                    ]
                    vm.assetslisttabChange = function (tabid) {
                        if (tabid === mvvm.assetslisttab) return;
                        mvvm.assetslisttab = tabid;
                        assetsQuery.type = tabid;
                        initWithAssets(assetsQuery);
                    }
                    vm.changeAssetsHide = function (entity,submit) {
                        if (submit) {
                            var act = entity.Hide ? "显示" : "隐藏";
                            messageBox.confirm2("确定要"+ act +"该账户吗？", function () {
                                entity.Hide = !entity.Hide;
                                $.post('/FinancialAffairs/AssetsHide/', { id: entity.Id, hide: entity.Hide }, function (ret) {
                                    CBCRM.showResult(ret);
                                    if (!ret.result) {
                                        entity.Hide = !entity.Hide;
                                    }
                                });
                            });
                        } else {
                            entity.Hide = !entity.Hide;
                        }
                    }
                    vm.ASSETSADD = false
                    vm.ASSETSDELETE = false
                    vm.ACCOUNTINGVIEW = false;

                    /* 以下为汇率相关 */
                    vm.currency = {}
                    vm.currencyList = []
                    vm.currencyAdd = function () {
                        mvvm.currency = modelFactory.create('Currency');
                        currencyWindow('新增汇率');
                    }
                    vm.currencyEdit = function () {
                        var index = $(this).attr('index');
                        mvvm.currency = mvvm.currencyList.$model[index];
                        currencyWindow('编辑汇率');
                    }
                    vm.currencyDel = function () {
                        var id = $(this).attr('val');
                        var index = parseInt($(this).attr('index'));
                        messageBox.confirm('确定删除此数据吗？', function () {
                            mvvm.currencyList.removeAt(index);
                            $.get('/FinancialAffairs/CurrencyDel/' + id, {}, function () { })
                        })
                    }
                    vm.currencyAllDel = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.post('/FinancialAffairs/CurrencyAllDelete/', deleteIds, function (ret) {
                                if (ret.result) {
                                    initWithCurrency();
                                    messageBox.succeed(ret.message);
                                }
                            });
                        });
                    }
                    vm.currencypaing = {
                        paging: function () {
                            var that = this
                            var query = { pageIndex: that.currentindex + 1, pageSize: that.pagesize }
                            initWithCurrency(query);
                        }
                    }
                    vm.backlist = function () {
                        vm.index = ''
                    }
                    vm.EXCHANGEADD = false
                    vm.EXCHANGEDELETE = false
                })

                /*-------------------------------------------------收支项目-----------------------------------------------*/
                var projectQuery = {
                    keyword: '', keywordName: '',
                    type: '', typeName: '',
                    pageIndex: 1, pageSize: 20
                }
                mvvm.projectShowItem = avalon.mix({}, projectQuery);
                function projectWindow(title) {
                    var dialog = messageBox.openHtml(title, '400px', '200px', '', [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            var model = mvvm.project.$model;
                            if (model.Name) {
                                var url = model.Id == 0 ? "/FinancialAffairs/ProjectAdd/" : "/FinancialAffairs/ProjectEdit/" + model.Id;
                                $.post(url, model, function (ret) {
                                    if (ret.result)
                                        messageBox.ok(ret.message, function () { initWithProject(); dialog.close(); });
                                    else
                                        messageBox.error(ret.message);
                                })
                            }
                            else messageBox.error('请填写收支项目的名称!');
                            return false;
                        }
                    }]);

                    var content = $(dialog.content())
                    content.attr('ms-include', 'projectTemplate')
                    avalon.scan(content[0], mvvm)
                }
                var projectList = [];
                function initWithProject(data) {
                    $.get('/FinancialAffairs/ProjectList/', data || {}, function (ret) {
                        if (!ret || !ret.result) return CBCRM.showResult(ret);
                        projectList = ret.data.list;
                        mvvm.projectList = [].concat(projectList);
                        mvvm.PROJECTADD = ret.data.ADD
                        mvvm.PROJECTDELETE = ret.data.DELETE
                        //avalon.vmodels.upaing.total = ret.data.RecordTotal
                    });
                }
                initWithProject()
                function getDetailById(id) {
                    $.get('/FinancialAffairs/ProjectDetail/', { id: id }, function (ret) { mvvm.project = ret.data; });
                }

                /*-------------------------------------------------资产账户----------------------------------------------*/
                var assetsQuery = {
                    keyword: '', keywordName: '',
                    type: '', typeName: '',
                    pageIndex: 1, pageSize: 20
                }
                mvvm.assetsShowItem = avalon.mix({}, assetsQuery);
                function initAssets() {
                    var arr = [
                        { value: 0, key: '现金账户', selected: false, click: itemClick, helpTip: '' },
                        { value: 1, key: '银行账户', selected: false, click: itemClick, helpTip: '' },
                        { value: 2, key: '虚拟账户', selected: false, click: itemClick, helpTip: '主要指网络类账户，它不是银行类账户，但有资金沉积其中，如：网银，支付宝，财付通等账户' },
                        { value: 3, key: '负债账户', selected: false, click: itemClick, helpTip: '负债账户也叫债务结算账户,它是用来核算和监督企业与各个债权单位或个人在经济往来中发生的各种应付款项，直白点讲欠别人的，要应付的。' },
                        { value: 4, key: '债权账户', selected: false, click: itemClick, helpTip: '债权账户也称债权结算账户（资产结算账户）用来核算监督企业同各个债务单位或个人之间债权结算业务的账户，直白点讲别人欠我们的，应收回的，如“应收账款”“应收票据”“预付账款”“其他应收款”等' }
                    ];
                    //mvvm.assetsCategory = [{ value: '', key: '不限', selected: true, click: itemClick }].concat(arr);
                    mvvm.assetsCategorySimple = [].concat(arr);
                    arr.forEach(function (item) {
                        mvvm.assetslistTabs.push({ val: item.value, label: item.key });
                    });
                }
                initAssets();
                function initWithAssets(data) {
                    
                    $.get('/FinancialAffairs/AssetsList/', data || {}, function (ret) {
                        mvvm.assetsList = ret.data.Source;
                        mvvm.ASSETSADD = ret.data.ASSETSADD
                        mvvm.ASSETSDELETE = ret.data.ASSETSDELETE
                        mvvm.ACCOUNTINGVIEW = ret.data.ACCOUNTINGVIEW;
                        avalon.vmodels.assetsupaing.total = ret.data.RecordTotal
                    });
                }
                function assetsWindow(title) {
                    var btns= [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            var model = mvvm.assets.$model;
                            if (model.AccountName) {
                                var url = model.Id == 0 ? "/FinancialAffairs/AssetsAdd/" : "/FinancialAffairs/AssetsEdit/" + model.Id;
                                $.post(url, model, function (ret) {
                                    if (ret.result) {
                                        initWithAssets();
                                        messageBox.ok(ret.message, function () { dialog.close(); });
                                    }
                                    else messageBox.error(ret.message);
                                });
                            }
                            else messageBox.warning('请填写资产账户名称!');
                            return false;
                        }
                    }]
                    var dialog = openTmpl({
                        vm: mvvm, title: title, w: 770, h: 210,
                        tmpl: tmpl, tmplid: "assetsTemplate",
                        btns:btns
                    });
                }
                function itemClick() {
                    var index = parseInt($(this).attr('index'));
                    mvvm.assetsCategory.forEach(function (item) { item.selected = false; })
                    var model = mvvm.assetsCategory[index]
                    model.selected = true;
                    mvvm.assetsShowItem.type = model.value;
                    mvvm.assetsShowItem.typeName = (model.key == '不限') ? '' : model.key;
                    initWithAssets(mvvm.assetsShowItem.$model);
                }
                avalon.filters.GetCurrency = function (id) {
                    var result = '';
                    mvvm.currencyList.forEach(function (item) { if (item.Id == id) { result = item.Data; } });
                    return result;
                }
                avalon.filters.GetType = function (id) {
                    var result = '';
                    mvvm.assetsCategorySimple.forEach(function (item) { if (item.value == id) { result = item.key; } });
                    return result;
                }

                /*-------------------------------------------------设置汇率----------------------------------------------*/
                mvvm.currency = modelFactory.create('Currency');
                function initWithCurrency(data) {
                    $.get('/FinancialAffairs/CurrencyList', data || {}, function (ret) {
                        mvvm.currencyList = ret.data.Source;
                        mvvm.EXCHANGEADD = ret.data.EXCHANGEADD;
                        mvvm.EXCHANGEDELETE = ret.data.EXCHANGEDELETE;
                        avalon.vmodels.currencyupaing.total = ret.data.RecordTotal
                    })
                }
                function currencyWindow(title) {
                    var dialog = messageBox.openHtml(title, '700px', '160px', '', [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            var model = mvvm.currency.$model;
                            if (model.Data) {
                                var url = model.Id == 0 ? "/FinancialAffairs/CurrencyAdd/" : "/FinancialAffairs/CurrencyEdit/" + model.Id;
                                $.post(url, model, function (ret) {
                                    if (ret.result)
                                        messageBox.ok(ret.message, function () { messageBox.close(); initWithCurrency(); })
                                    else
                                        messageBox.error(ret.message);
                                })
                            }
                            else messageBox.warning('请填写币别名称!');
                            return false;
                        }
                    }]);

                    var content = $(dialog.content())
                    content.attr('ms-include', 'currencyTemplate')
                    avalon.scan(content[0], mvvm)
                }
                initWithCurrency();

                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)

                if (that.params.action && that.params.action == 'list' && that.params.id == 3) {
                    mvvm.index = 'assetes'
                }
            },

            //票据凭证
            Bill: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this
                var mvvm = CBCRM.define('financialaffairsbill', function (vm) {
                    vm.lang = lang
                    vm.entity = {}
                    vm.billList = []
                    vm.billpaing = {
                        paging: function () {
                            var that = this
                            queryData.pageIndex = that.currentindex + 1
                            queryData.pageSize = that.pagesize
                            GetBillList(queryData);
                        }
                    }
                    vm.accountpaing = {
                        pagesize: 10,
                        pagesizeopts: [10],
                        paging: function () {
                            var that = this
                            initWithAccounting({
                                pageSize: that.pagesize,
                                pageIndex: that.currentindex + 1
                            });
                        }
                    }

                    vm.keyword = ''
                    vm.history = []
                    vm.showItem = {}
                    vm.has = false

                    vm.billTypeData = []
                    vm.unitData = []

                    //统计金额
                    vm.TotalAmount1 = 0
                    vm.TotalAmount2 = 0

                    vm.ADD = true
                    vm.DELETE = true

                    //开票日期
                    vm.createdateOpts = {
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.CreateDate = formatDate
                        }
                    }

                    //选客户/联系人
                    vm.selectCustomer = function () {
                        plugins.selectCustomer({
                            type: "contacts",
                            callback: function (cus,cons) {
                                var cu = cus[0], con = cons.length ? cons[0] : { Id: "", Name: "" };
                                mvvm.entity.CustomId = cu.Id
                                mvvm.entity.CustomName = cu.Name
                                mvvm.entity.CustomMan = con.Name

                                mvvm.customerContactData = cu.Contacts || [];
                                mvvm.entity.Telphone = cu.CompanyTel1
                                mvvm.entity.Address = cu.CompanyProvinceDisplay + cu.CompanyCityDisplay + cu.CompanyAreaDisplay + cu.CompanyAddress
                            }
                        });
                    };
                    //客户联系人
                    vm.customerContactData = []
                    vm.setCustomerContacts = function (customerid) {
                        $.get('/Customer/Contacts', { 'customerId': customerid }, function (ret) {
                            mvvm.customerContactData = ret.data.contacts.Source
                        })
                    }
                    vm.customerContactsChange = function () {
                        var option = $(this).find('option:selected')
                        if (option.val()) {
                            mvvm.entity.CustomMan = option.text()
                        } else {
                            mvvm.entity.CustomMan = ''
                        }
                    }
                    //取客户其它信息
                    vm.setCustomerInfo = function (customerid) {
                        $.get('/Customer/DetailCustomer/' + customerid, {}, function (ret) {
                            var customer = ret.data
                            mvvm.entity.Telphone = customer.CompanyTel1
                            mvvm.entity.Address = customer.CompanyProvinceDisplay + customer.CompanyCityDisplay + customer.CompanyAreaDisplay + customer.CompanyAddress
                        })
                    }

                    //关键字搜索
                    vm.search = function () {
                        if (mvvm.keyword) {
                            queryData.key = mvvm.keyword;
                            GetBillList(queryData);
                            if (mvvm.history.length = 3)
                                mvvm.history.removeAt(2);
                            mvvm.history.unshift(mvvm.keyword);
                        }
                    }
                    //历史搜索
                    vm.historyClick = function () {
                        mvvm.keyword = $(this).val();
                        queryData.key = mvvm.keyword;
                        GetBillList(queryData);
                    }
                    //移除单个快速筛选
                    vm.remove = function () {
                        var searchKey = this.$vmodel.$key;
                        mvvm.showItem[searchKey] = '';
                        $(".quickword a[key='" + searchKey + "']").eq(0).addClass('selected').siblings().removeClass('selected');
                        mvvm.has = false;
                        for (var item in mvvm.showItem.$model) {
                            if (mvvm.showItem.$model[item]) {
                                mvvm.has = true;
                                break;
                            }
                        }
                        queryData[searchKey] = ''
                        GetBillList(queryData);
                    }
                    //清空
                    vm.clear = function () {
                        mvvm.keyword = '';
                        mvvm.showItem = avalon.mix({}, searchItem);
                        mvvm.has = false;
                        $(".quickword a").removeClass('selected');
                        $(".quickword a[value='0']").addClass('selected');
                        queryData = avalon.mix({}, createDate);
                        GetBillList(queryData);
                    }
                    //快速筛选 
                    vm.itemClick = function () {
                        $(this).addClass('selected').siblings().removeClass('selected');
                        var key = $(this).attr("key");
                        var value = $(this).attr("value");
                        var name = $("#" + key).html() + "：";
                        var display = $(this).text();
                        queryData[key] = value;
                        if (value != "0" && value != "") {
                            mvvm.showItem[key] = ''
                            mvvm.showItem[key] = name + display;
                            mvvm.has = true;
                        } else {
                            mvvm.showItem[key] = ''
                            mvvm.has = false;
                            for (var item in mvvm.showItem.$model) {
                                if (mvvm.showItem.$model[item]) {
                                    mvvm.has = true;
                                    break;
                                }
                            }
                        }
                        GetBillList(queryData);
                    }
                    //新增
                    vm.doadd = function () {
                        mvvm.entity = modelFactory.create('Bill')
                        var dindex = 0
                        mvvm.billTypeData.forEach(function (item, i) { if (item.IsDefault) { dindex = i } })
                        mvvm.entity.BillType = mvvm.billTypeData.length > 0 ? mvvm.billTypeData[dindex].Id : ''
                        mvvm.billProjectList = []
                        mvvm.billProjectDelList = []
                        mvvm.billProjectList.push(avalon.mix({}, billProjectData))
                        var currUser = CBCRM.memberShip
                        mvvm.entity.Creator = currUser.FullName
                        mvvm.entity.CreateDate = GetDateTime()
                        mvvm.formSubmit('新增开票记录')

                    }
                    //编辑
                    vm.doedit = function () {
                        var id = $(this).val()

                        mvvm.billList.forEach(function (item) {
                            if (item.Id == id) {
                                mvvm.billProjectDelList = []
                                mvvm.entity = item
                                if (mvvm.entity.CustomId) {
                                    mvvm.setCustomerContacts(mvvm.entity.CustomId)
                                }
                                GetBillProjectList(id)
                                mvvm.formSubmit('编辑开票记录')
                            }
                        })

                    }
                    //查看
                    vm.doview = function () {
                        var id = $(this).val()
                        mvvm.billList.$model.forEach(function (item) {
                            if (item.Id == id) {
                                mvvm.entity = item
                                GetBillProjectList(id)
                                var dialog = mvvm.openTmpl({
                                    title: "查看开票记录详细", w: 880, h: 300, padding: "def2",
                                    tmplId: "viewTemplate", tmpl: tmpl
                                });
                            }
                        })
                    }
                    //删除
                    vm.dodel = function () {
                        var index = parseInt($(this).attr('index'));
                        var id = $(this).val();
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/FinancialAffairs/BillDel/' + id, {}, function (ret) {
                                if (ret.result)
                                    mvvm.campaignList.removeAt(index);
                                messageBox.succeed(ret.message);
                            })
                        });
                    }
                    //批量删除
                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.post('/FinancialAffairs/BillAllDel/', deleteIds, function (ret) {
                                if (ret.result) {
                                    GetBillList(queryData);
                                    messageBox.succeed(ret.message);
                                }
                            });
                        });
                    }

                    vm.formSubmit = function (title) {
                        var dialog = mvvm.openTmpl({
                            title: title, w: 819, h: 397, padding: "def2",
                            tmplId: "formTemplate", tmpl: tmpl,
                            button: [{
                                name: '确定',
                                focus: true,
                                callback: function () {
                                    var model = avalon.mix({}, mvvm.entity.$model)
                                    var msg = ''
                                    if (!model.BillCode) {
                                        msg = msg + '票据编号不能为空<br/>'
                                    }
                                    if (msg) {
                                        messageBox.warning(msg)
                                        return false
                                    }
                                    if (model.hasOwnProperty)
                                        delete model.hasOwnProperty
                                    if (model.IsBillProject) {
                                        mvvm.billProjectList.$model.forEach(function (item, index) {
                                            model["BillProjectList[" + index + "].Id"] = item.Id
                                            model["BillProjectList[" + index + "].PrejectName"] = item.PrejectName
                                            model["BillProjectList[" + index + "].Standard"] = item.Standard
                                            model["BillProjectList[" + index + "].Unit"] = item.Unit
                                            model["BillProjectList[" + index + "].Price"] = item.Price
                                            model["BillProjectList[" + index + "].Number"] = item.Number
                                            model["BillProjectList[" + index + "].Amount"] = item.Amount
                                            model["BillProjectList[" + index + "].TaxRate"] = item.TaxRate
                                            model["BillProjectList[" + index + "].TaxAmt"] = item.TaxAmt
                                        })
                                    }
                                    var url = model.Id == 0 ? "/FinancialAffairs/BillAdd/" : "/FinancialAffairs/BillUpdate/" + model.Id;
                                    $.post(url, model, function (ret) {
                                        CBCRM.showResult(ret, function () {
                                            if (that.params.action == 'add') {
                                                var accountmodel = avalon.vmodels.Accounting
                                                if (accountmodel) accountmodel.getBills()
                                            } else {
                                                GetBillList(queryData)
                                            }
                                            if(dialog)dialog.close()
                                        })
                                    });
                                    return false
                                }
                            }]
                        });
                    }
                    vm.billProjectList = [] //项目表
                    vm.billProjectDelList = [] //项目表临时存放删除的数据
                    vm.projectSum = 0
                    //计算合计
                    vm.setAmt = function () {
                        var cost = 0
                        mvvm.billProjectList.$model.forEach(function (item, index) {
                            var currCost = 0
                            if (item.Price && item.Number) {
                                var amount = parseFloat(item.Price) * parseFloat(item.Number)
                                if (amount) {
                                    mvvm.billProjectList[index].Amount = amount
                                    cost += amount
                                    if (item.TaxRate) {
                                        var taxAmt = amount * parseFloat(item.TaxRate) / 100
                                        if (taxAmt) {
                                            mvvm.billProjectList[index].TaxAmt = taxAmt
                                            cost += taxAmt
                                        }
                                    }
                                }
                            }
                        })
                        //mvvm.entity.Amount1 = cost
                        //mvvm.entity.Amount2 = cost
                    }
                    //编辑界面列表全选
                    vm.doChkAll = function () {
                        var chkVal = $(this).attr("checked");
                        $("input[name='checkitem']").each(function (index, item) {
                            item.checked = chkVal
                        })
                    }
                    //新加一行
                    vm.doBillProjectAdd = function () {
                        mvvm.billProjectList.push(avalon.mix({}, billProjectData))
                    }
                    //删除一行
                    vm.doBillProjectDel = function () {
                        var bid = parseInt($(this).attr('index'))
                        var list = mvvm.billProjectList
                        mvvm.billProjectDelList.push(list[bid])
                        list.removeAt(bid)

                    }

                    //选择合同订单
                    vm.selContractList = []
                    vm.contractKey = ''
                    vm.getContractData = function () {
                        $.get('/Market/Contract/', {
                            'key': mvvm.contractKey,
                            'paystate': 1
                        }, function (ret) {
                            mvvm.selContractList = ret.data.Source
                        })
                    }
                    vm.selectContract = function () {
                        mvvm.selContractList = []
                        mvvm.contractKey = ''
                        var dialog = mvvm.openTmpl({
                            title: "选择合同订单", w: 800, h: 400,
                            tmplId: "ContractListTemplate", tmpl: tmpl,
                            dialogId: "billSelectContract",
                            button: [{
                                name: '确定',
                                focus: true,
                                callback: function () {
                                    mvvm.setContractVal()
                                }
                            }]
                        });
                        mvvm.getContractData()
                    }
                    vm.selectedContract = function () {
                        $(this).find('input').eq(0).attr('checked', 'checked')
                    }
                    vm.setContractVal = function () {
                        var contractChk = $("input[name='selectContract']:checked")
                        if (contractChk.length == 0) {
                            messageBox.warning('请选择合同订单')
                        } else {
                            var index = parseInt(contractChk.attr('index'))
                            var contract = mvvm.selContractList[index]
                            mvvm.entity.Contract = contract.Id
                            mvvm.entity.ContractNum = contract.ContractNum
                            var billSelectContractDialog = art.dialog.list['billSelectContract']
                            if (billSelectContractDialog) {
                                billSelectContractDialog.close()
                            }
                        }
                    }
                    //选择收款单或收款明细
                    vm.rbtab = 'tab1'
                    vm.rbtabChange = function () {
                        var tab = $(this).attr('val')
                        mvvm.rbtab = tab
                    }
                    vm.selReceiptsList = []
                    vm.selProductList = []
                    vm.selectReceipts = function () {
                        mvvm.selReceiptsList = []
                        mvvm.selProductList = []
                        var dialog = mvvm.openTmpl({
                            title: "选择收款单或者收款明细", w: 800, h: 400,
                            tmplId: "ReceiptsListTemplate", tmpl: tmpl,
                            dialogId:"billSelectReceipts",
                            button: [{
                                name: '确定',
                                focus: true,
                                callback: function () {
                                    mvvm.setReceiptsVal()
                                }
                            }]
                        });
                        mvvm.getReceipts()
                    }
                    vm.setReceiptsVal = function () {
                        var contractChk = ''
                        if (mvvm.rbtab == 'tab1') {
                            mvvm.entity.IsReceipts = true
                            contractChk = $("input[name='selectReceipts']:checked")
                        } else {
                            mvvm.entity.IsReceipts = false
                            contractChk = $("input[name='selectProduct']:checked")
                        }
                        if (contractChk.length == 0) {
                            var msg = mvvm.entity.IsReceipts ? '请选择收款单' : '请选择收款明细'
                            messageBox.warning(msg)
                        } else {
                            var index = parseInt(contractChk.attr('index'))
                            var receipts = mvvm.entity.IsReceipts ? mvvm.selReceiptsList[index] : mvvm.selProductList[index]
                            mvvm.entity.ReceiptsBill = receipts.Id
                            mvvm.entity.ReceiptsBillDisplay = receipts.No
                            mvvm.entity.IsPay = true
                            var billSelectReceiptsDialog = art.dialog.list['billSelectReceipts']
                            if (billSelectReceiptsDialog) {
                                billSelectReceiptsDialog.close()
                            }
                        }
                    }
                    vm.getReceipts = function () {
                        $.get('/FinancialAffairs/ReceiptsBill/', {
                            'contractid': mvvm.entity.Contract > 0 ? mvvm.entity.Contract : ''
                        }, function (ret) {
                            mvvm.selReceiptsList = ret.data.Source
                        })
                        $.get('/FinancialAffairs/AccountList/', {
                            "contractid": mvvm.entity.Contract > 0 ? mvvm.entity.Contract : ''
                        }, function (ret) {
                            mvvm.selProductList = ret.data.Source
                        })
                    }
                    vm.selectedReceipts = function () {
                        $(this).find('input').eq(0).attr('checked', 'checked')
                    }
                })

                //创建查询对象并提交
                var createDate = {
                    billtype: 0,
                    key: '',
                    pageSize: 20,
                    pageIndex: 1
                }
                //创建筛选对象
                var searchItem = {
                    billtype: '',
                }
                //创建编辑界面关联表数据对象
                var billProjectData = { Id: 0, BillId: '', PrejectName: '', Standard: '', Unit: '', Price: '', Number: '', Amount: '', TaxRate: '', TaxAmt: '' }

                var queryData = avalon.mix({}, createDate)
                mvvm.showItem = avalon.mix({}, searchItem)
                InitDictItem()
                mvvm.entity = modelFactory.create('Bill')

                function GetBillList(data) {
                    $.get('/FinancialAffairs/Bill/', data || {}, function (ret) {
                        mvvm.billList = ret.data.Source;
                        avalon.vmodels.upaing.total = ret.data.RecordTotal;
                        //统计
                        mvvm.billList.forEach(function (item, i) {
                            var money1 = parseFloat(item.Amount1)
                            var money2 = parseFloat(item.Amount2)
                            if (money1)
                                mvvm.TotalAmount1 += money1
                            if (money2)
                                mvvm.TotalAmount2 += money2
                        })

                        mvvm.ADD = ret.data.ADD
                        mvvm.DELETE = ret.data.DELETE
                    })
                }

                //从字典取数据
                function InitDictItem() {
                    $.get('/FinancialAffairs/GetBillDict', {}, function (ret) {
                        mvvm.billTypeData = ret.data.BillTypeData
                        mvvm.billTypeData.forEach(function (item, i) {
                            if (item.Id == 102417)
                                mvvm.billTypeData.removeAt(i)
                        })
                        mvvm.unitData = ret.data.UnitData
                    })
                }
                //获取开票明细
                function GetBillProjectList(Id) {
                    $.get('/FinancialAffairs/BillProduct/', { "Id": Id }, function (ret) {
                        mvvm.billProjectList = ret.data
                    })
                }

                avalon.filters.GetBillType = function (id) {
                    var res = ''
                    mvvm.accountingBillType.forEach(function (item) {
                        if (item.Id == id) res = item.Data;
                    })
                    return res;
                }

                if (that.params.action == 'add') {
                    avalon.nextTick(function () {
                        mvvm.doadd()
                    })
                } else {
                    require('commonui', function () {
                        CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                    })
                }
                CBCRM.onLoadModuleBefore = function () {
                    if (avalon.vmodels.setParetCustomerId)
                        avalon.vmodels.setParetCustomerId.destroy()
                    avalon.vmodels.Bill = null
                }
            },

            //财务-应收应付
            ARAPCollect: function (tmpl, lang, contentId, module, paramData) {
                var CBCRM = avalon.vmodels.CBCRM,
                    that = this, detail, vmid = "ARAPCollect"
                var action = that.params.action, paramid = that.params.id;
                //var oldvm = avalon.vmodels[vmid];
                //if (oldvm != null) delete avalon.vmodels[vmid];
                //if (mvvm == null) {
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.init = false;
                    vm.lang = lang
                    vm.entity = {}
                    vm.arapList = []
                    vm.delList = []
                    vm.dateformat = "%Y-%m-%d"
                    vm.destroy = function () {
                        mvvm.grid1.destroy();
                    }
                    initQuerys(vm, function (data, name, val, type) {
                        if (name == "datespan") {
                            {
                                if (val == "c") {
                                    if (type == "remove") {
                                        mvvm.removeQuery("begindate", true);
                                        mvvm.removeQuery("enddate", true);
                                    } else {
                                        mvvm.queryData.datespan.valLabel = ""
                                        if (mvvm.hasLength == 1) {
                                            mvvm.hasQuery = false;
                                        }
                                        return false;
                                    }
                                } else {
                                    mvvm.removeQuery("begindate", true);
                                    mvvm.removeQuery("enddate", true);
                                }
                            }
                        } else if (name == "appointUser") {
                            if (type == "remove") mvvm.removeQuery("employees", true)
                        }
                        var data = mvvm.createQuery();
                        mvvm.grid1.loadData(data);
                    });
                    vm.queryMore = false;
                    vm.createQueryData = function () {
                        var d = new Date();
                        return {
                            datespan: {
                                label: "计划日期", val: "", valLabel: "", 
                                items: [
                                    { label: "不限", val: "", curr: true },
                                    { label: d.getMonth() - 1 + '月', val: "m_-2", curr: false },
                                    { label: d.getMonth() + '月', val: "m_-1", curr: false },
                                    { label: d.getMonth() + 1 + '月', val: "m", curr: false },
                                    { label: d.getMonth() + 2 + '月', val: "m_+1", curr: false },
                                    { label: d.getMonth() + 3 + '月', val: "m_+2", curr: false },
                                    { label: d.getFullYear() + '年', val: "y", curr: false },
                                    { label: "自定义", val: "c", curr: false, type: "date", d1: "begindate", d2: "enddate", format: "%Y-%m-%d" }
                                ]
                            },
                            settleStatus: {
                                label: "结算状态", val: "", valLabel: "",
                                items: [{ label: "不限", val: '', curr: true }, { label: "已结清", val: '0', curr: false }, { label: "未结清", val: '1', curr: false }]
                            },
                            appointUser: {
                                label: "业务归属", val: "", valLabel: "",
                                items: [
                                    { label: "不限", val: "", curr: true },
                                    { label: "我的应收", val: "1", curr: false },
                                    { label: "下属应收", val: "2", curr: false },
                                    { label: "指定部门员工", val: "appointUser", curr: false, type: "selectUser" }
                                ]
                            },
                            contractId: { label: "合同Id", val: "", valLabel: "" },
                            begindate: {label: "起始时间", val: "", valLabel: ""},
                            enddate: { label: "截止时间", val: "", valLabel: "" },
                            employees: { label: "员工id", val: '', valLabel: "" },
                            type: { label: "收付类型", val: '0', valLabel: "", noRemove: true },
                            key: { label: "关键词", val: "", valLabel: "" }
                        }
                    }
                    vm.queryData = vm.createQueryData();
                    vm.createGrid1 = function () {
                        return createGrid({
                            url: "/FinancialAffairs/ARAPCollect",
                            modelFactory: modelFactory,
                            $lang: lang,
                            entityId: "ARAP",
                            pageid: vmid + "_grid1_page",
                            createQuery: function () {
                                var data = mvvm.createQuery();
                                return data;
                            },
                            onLoadData: function (ret) {
                                if (!ret.result) return CBCRM.showResult(ret);
                                mvvm.ADD = ret.data.ADD
                                mvvm.DELETE = ret.data.DELETE
                            },
                            onRemove: function (deleteIds,ids) {
                                var gvm = this;
                                var checkedItems = mvvm.grid1.getChecked();
                                for(var i = 0; i < checkedItems.length; i++){
                                    if (checkedItems[i].Money != checkedItems[i].NotSettleMoney) {
                                        messageBox.error('无法删除已结算项目<br/>')
                                        return false
                                    }
                                }
                                $.post('/FinancialAffairs/ARAPAllDelete', deleteIds, function (ret) {
                                    CBCRM.showResult(ret);
                                    if (ret.result) {
                                        gvm.reloadData();
                                    }
                                });
                            }
                        });
                    }
                    vm.grid1 = vm.createGrid1();

                    vm.typedata = []
                    
                    vm.settleStatusdata = []

                    vm.ADD = true
                    vm.DELETE = true

                    //选择合同
                    vm.selectContract = function () {
                        plugins.selectContract({
                            type: "contract",
                            dataAuth: 7050001,
                            multiple:{con:false, det:true},
                            callback: function (con,detail) {
                                mvvm.entity.Contract.Id = con[0].Id;
                                mvvm.entity.Contract.ContractName = con[0].ContractName;
                                mvvm.entity.CustomerId = con[0].Customer;
                                mvvm.entity.CustomerName = con[0].CustomerDisplay;
                                mvvm.arapList = [];
                                detail.forEach(function (item) {
                                    var arap = modelFactory.create("ARAP");
                                    arap.PlanDate = item.AddTime;
                                    arap.Money = item.Money;
                                    arap.Batch = item.Num;
                                    arap.SettleMoney = 0;
                                    arap.NotSettleMoney = item.Money;
                                    arap.Remark = item.Remark;
                                    mvvm.arapList.push(arap);
                                    watchMoney(mvvm.arapList[mvvm.arapList.length - 1]);
                                });
                            }
                        });
                    }
                    vm.setContractSelect = function (contractId) {
                        if (!contractId)
                            return;
                        $.post("/FinancialAffairs/GetPlanOfPays", { 'contractid': contractId }, function (ret) {
                            if (!ret || !ret.result)
                                return CBCRM.showResult(ret);
                            ret.data.Source.forEach(function (item) {
                                var arap = modelFactory.create("ARAP");
                                arap.PlanDate = item.AddTime;
                                arap.Money = item.Money;
                                arap.Batch = item.Num;
                                arap.SettleMoney = 0;
                                arap.NotSettleMoney = item.Money;
                                arap.Remark = item.Remark;
                                mvvm.arapList.push(arap);
                                watchMoney(mvvm.arapList[mvvm.arapList.length - 1]);
                            });
                        });
                    }
                    //选客户,结算单位
                    vm.selectCustomer = function (type) {
                        plugins.selectCustomer({
                            dataAuth: 7050001,
                            callback: function (cus, cons) {
                                var cu = cus[0];
                                switch (type) {
                                    case "settleCustomer":
                                        mvvm.entity.SettleCustomerName = cu.Name
                                        mvvm.entity.SettleCustomerId = cu.Id
                                        break;
                                    case "customer":
                                        mvvm.entity.CustomerName = cu.Name
                                        mvvm.entity.CustomerId = cu.Id
                                        break;
                                }
                            }
                        });
                    }
                    //业务员，负责人
                    vm.selectUser = function (type, r) {
                        var ops, mul;
                        switch (type) {
                            case "salesman":
                                mul = false;
                                break;
                            case "dutyPerson":
                                mul = false
                                break;
                            case "addBy":
                                mul = false;
                                break;
                            case "appointUser":
                                mul = true;
                                break;
                        }
                        plugins.selectUser({
                            dataAuth: 7050001,
                            multiple: mul,
                            callback: function (us) {
                                var u = us[0];
                                switch (type) {
                                    case "salesman":
                                        mvvm.entity.SalesmanId = u.Id;
                                        mvvm.entity.SalesmanName = u.FullName
                                        break;
                                    case "dutyPerson":
                                        mvvm.entity.DutyPersonId = u.Id;
                                        mvvm.entity.DutyPersonName = u.FullName
                                        break;
                                    case "addBy":
                                        mvvm.entity.AddBy.Id = u.id;
                                        mvvm.entity.AddBy.UserName = u.FullName;
                                        break;
                                    case "appointUser":
                                        var emps = mvvm.queryData.employees.val.split(",");
                                        if (emps.length == 0 && us.length == 0) return false;
                                        if (us.length == 0) {
                                            mvvm.removeQuery("employees");
                                            return false;
                                        }
                                        emps = where(us, true, "Id");
                                        mvvm.addQuery("employees", emps.join(","));
                                        mvvm.addQuery(type, r.val, r.label, true);
                                        break;
                                }
                            }
                        })
                    }
                    //费用日期
                    vm.costdateOpts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.CostDate = formatDate
                        }
                    }
                    //计划日期
                    vm.plandateOpts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.PlanDate = formatDate
                        }
                    }
                    vm.project = {}
                    vm.ARAPOpts = {
                        q: '请输入收支项目名称',
                        treeopts: {
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    mvvm.entity.ProjectId = treeNode.Id
                                    mvvm.entity.Project = treeNode.Name
                                }
                            },
                            async: {
                                url: function (treeId, treeNode) {
                                    var res  = '/FinancialAffairs/PorjectDrodonwn';
                                    return res;
                                },
                                dataFilter: function (treeId, parentNode, responseData) {
                                    var result = [];
                                    if (responseData.data) {
                                        responseData.data.forEach(function (item) {
                                            result.push({ Id: item.Id, Name: item.Name, ParentId: item.Parent });
                                        })
                                    }
                                    return result;
                                }
                            }
                        }
                    }
                    //新增
                    vm.doadd = function () {
                        mvvm.grid1.getEntity(null, function (entity) {
                            mvvm.entity = entity;
                            var currUser = CBCRM.memberShip
                            mvvm.entity.SalesmanId = currUser.Id
                            mvvm.entity.SalesmanName = currUser.FullName
                            mvvm.entity.DutyPersonId = currUser.Id
                            mvvm.entity.DutyPersonName = currUser.FullName
                            mvvm.entity.Type = 0
                            mvvm.entity.AddBy.Id = currUser.Id;
                            mvvm.entity.AddBy.UserName = currUser.FullName;
                            mvvm.arapAmount = 0;
                            mvvm.arapList = []
                            mvvm.delList = []
                        });
                        if (action == "Contract") {
                            mvvm.entity.Contract.Id = paramData.entity.Id;
                            mvvm.entity.Contract.ContractName = paramData.entity.ContractName;
                            mvvm.entity.CustomerId = paramData.entity.Customer;
                            mvvm.entity.CustomerName = paramData.entity.CustomerDisplay;
                            mvvm.setContractSelect(paramData.entity.Id);
                        }
                        mvvm.formSubmit('新增应收款')
                    }
                    //编辑
                    vm.doedit = function (id, contractId) {
                        mvvm.grid1.getEntity(id, function (entity) {
                            mvvm.entity = entity;
                            mvvm.entity.AddBy.UserName = entity.AddBy.FullName;
                            mvvm.formSubmit('编辑应收款')
                        }, true);
                        mvvm.initArapList(contractId, 0);
                    }
                    //删除
                    vm.doremove = function (item, index) {
                        var model = item.$model;
                        if (model.Money != model.NotSettleMoney) {
                           messageBox.error('无法删除已结算项目<br/>')
                           return false
                        }
                        mvvm.grid1.remove(item, index);
                    }

                    vm.formSubmit = function (title) {
                        var editor;
                        var btns = [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                mvvm.entity.$model.NotSettleMoney = mvvm.entity.$model.Money;
                                var model = avalon.mix({}, mvvm.entity.$model);
                                var msg = ''
                                if (!model.Contract.ContractName) {
                                    msg = msg + '请选择归属合同<br/>'
                                }
                                if (!model.CustomerName) {
                                    msg = msg + '请选择客户名称<br/>'
                                }
                                if (!mvvm.arapList.length) {
                                    msg = msg + '请添加应收款计划<br/>'
                                }
                                else {
                                    for (var i = 0; i < mvvm.arapList.length; i++) {
                                        var arap = mvvm.arapList[i];
                                        var amount = parseFloat(arap.Money);
                                        if (!amount || amount < 0) {
                                            msg = msg + '请输入正确的金额<br/>';
                                            break;
                                        }
                                        if (!arap.PlanDate) {
                                            msg = msg + '请选择计划日期<br/>';
                                            break;
                                        }

                                    }
                                }
                                if (msg) {
                                    messageBox.warning(msg)
                                    return false
                                }
                                // 复制公共参数到列表
                                mvvm.arapList.forEach(function (arap) {
                                    arap.Type = 0;
                                    arap.Contract.Id = mvvm.entity.Contract.Id
                                    //arap.Contract.ContractName = mvvm.entity.ContractName;
                                    arap.CustomerId = mvvm.entity.CustomerId;
                                    arap.CustomerName = mvvm.entity.CustomerName;
                                    arap.SalesmanId = mvvm.entity.SalesmanId;
                                    arap.SalesmanName = mvvm.entity.SalesmanName;
                                    arap.DutyPersonId = mvvm.entity.DutyPersonId;
                                    arap.DutyPersonName = mvvm.entity.DutyPersonName;
                                    //arap.AddTime = mvvm.entity.AddTime;
                                    //arap.AddBy.Id = mvvm.entity.AddBy.Id;
                                    //arap.AddBy.UserName = mvvm.entity.AddBy.UserName;
                                });
                                /*
                                $.extend(model, jsonToSubmit("Contract", model.Contract));
                                delete model.Contract;
                                delete model.AddBy;
                                var url = (model.Id == 0 ? "/FinancialAffairs/ARAPAdd/" : "/FinancialAffairs/ARAPEdit/");
                                */
                                var url = "/FinancialAffairs/ARAPUpdateList/"
                                var data = { "models": mvvm.arapList.$model, "delIds":mvvm.delList.$model };
                                jsonPost(url, data, function (ret) {
                                    CBCRM.showResult(ret, function () {
                                        if (ret.result) {
                                            mvvm.grid1.reloadData();
                                            if (dialog) dialog.close()
                                        }
                                    })
                                })
                                mvvm.arapList = [];
                                return false;
                            }
                        }] 
                        var dialog = mvvm.openTmpl({
                            title: title, w: 700, h: 300, padding: "def2",
                            btns: btns,
                            url:"/FinancialAffairs/ARAPCollectForm.html",
                            afterscan: function () {
                                
                            },
                            onclose: function () {
                                mvvm.destroyui(["ARAPTree"]);
                            }
                        });
                    }
                    //查看
                    vm.doview = function (id, contractId) {
                        mvvm.grid1.getEntity(id, function (entity) {
                            mvvm.entity = entity;
                            mvvm.entity.AddBy.UserName = entity.AddBy.FullName;
                            mvvm.initArapList(contractId, 0);
                            var dialog = mvvm.openTmpl({
                                title: "查看应收款", w: 700, h: 300, padding: "def2",
                                url: "/FinancialAffairs/ARAPView.html"
                            });
                        }, true)
                    }
                    // 删除列表中的Arap
                    vm.dodelDetail = function (index) {
                        if (!mvvm.arapList.length) {
                            messageBox.warning("请重新选择合同订单！")
                            return false;
                        }
                        if (mvvm.arapList[index].Id)
                            mvvm.delList.push(mvvm.arapList[index].Id);
                        mvvm.arapList.splice(index, 1);

                    }
                    // 添加应收应付到列表
                    vm.addArap = function () {
                        var arap = modelFactory.create("ARAP");
                        arap.Batch = mvvm.arapList.length +1;
                        mvvm.arapList.push(arap);
                        watchMoney(mvvm.arapList[mvvm.arapList.length - 1]);
                    }
                    vm.initArapList = function (contractId, type) {
                        if (!contractId)
                            return;
                        mvvm.arapList = []
                        mvvm.delList = []
                        $.get('/FinancialAffairs/GetARAPList/', {
                            'contractId': contractId,
                            'type':type
                        }, function (ret) {
                            ret.data.Source.forEach(function (item) {
                                var arap = modelFactory.create("ARAP");
                                arap.Id = item.Id;
                                arap.PlanDate = item.PlanDate;
                                arap.CustomerId = item.CustomerId;
                                arap.CustomerName = item.CustomerName;
                                arap.Money = item.Money;
                                arap.Batch = item.Batch;
                                arap.SettleMoney = item.SettleMoney;
                                arap.NotSettleMoney = item.NotSettleMoney;
                                arap.SalesmanId = item.SalesmanId
                                arap.SalesmanName = item.SalesmanName
                                arap.DutyPersonId = item.DutyPersonId
                                arap.DutyPersonName = item.DutyPersonName
                                arap.Type = item.Type;
                                arap.Remark = item.Remark;
                                arap.AddBy.Id = item.AddBy.Id;
                                arap.AddBy.UserName = item.AddBy.FullName;
                                mvvm.arapList.push(arap);

                                watchMoney(mvvm.arapList[mvvm.arapList.length - 1]);
                            });
                        });
                    }

                    //记账
                    vm.addAccountBook = function (item) {
                        var url = '/FinancialAffairs/Accounting/' + item.Id + '/ARAPCollectAdd';
                        mvvm.gotourl(url, true, {
                            entity: item.$model,
                            reloadList: function () { mvvm.grid1.reloadData() }
                        });
                    }

                    vm.settleWayData = [];
                    vm.getDicts = function () {
                        /*getDicts({ settleWayData: 100056 }, mvvm, function () {
                            mvvm.settleWayData.forEach(function(item,i)
                            {
                                mvvm.queryData.settleWay.items.push({ label: item.Data, val: item.Data, curr: false })
                            })
                            mvvm.settleWayData.unshift({ Data: '请选择', Id: 0 }); //添加‘请选择’到付款方式下拉框
                        }); */
                    }
                })
                mvvm.grid1.init();
                mvvm.queryData.begindate.$watch("val", watchTime);
                mvvm.queryData.enddate.$watch("val", watchTime); 
                function watchMoney(item) {
                    item.$watch("Money", function (n, o) {
                        if (n && n != o) {
                            var m = parseFloat(n);
                            item.NotSettleMoney = item.Money - item.SettleMoney;
                        }
                    })
                }
                function watchTime(v1, v2) {
                    if (v1 && v1 != v2) {
                        var data = mvvm.createQuery();
                        mvvm.grid1.loadData(data);
                    }
                }
                mvvm.getDicts();
                switch (action) {
                    case "Contract":
                        mvvm.addQuerys({ contractId: paramData.entity.Id }, true);
                        paramData.viewOther(tmpl, mvvm, "#tableList");
                        break;
                    default:
                        CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                }
            },

            //财务-应收应付
            ARAPPay: function (tmpl, lang, contentId, module, paramData) {
                var CBCRM = avalon.vmodels.CBCRM,
                    that = this, detail, vmid = "ARAPPay"
                var action = that.params.action, paramid = that.params.id;
                //var oldvm = avalon.vmodels[vmid];
                //if (oldvm != null) delete avalon.vmodels[vmid];
                //if (mvvm == null) {
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.init = false;
                    vm.lang = lang
                    vm.entity = {}
                    vm.arapList = []
                    vm.delList = []
                    vm.dateformat = "%Y-%m-%d"
                    vm.destroy = function () {
                        mvvm.grid1.destroy();
                    }
                    initQuerys(vm, function (data, name, val, type) {
                        if (name == "datespan") {
                            {
                                if (val == "c") {
                                    if (type == "remove") {
                                        mvvm.removeQuery("begindate", true);
                                        mvvm.removeQuery("enddate", true);
                                    } else {
                                        mvvm.queryData.datespan.valLabel = ""
                                        if (mvvm.hasLength == 1) {
                                            mvvm.hasQuery = false;
                                        }
                                        return false;
                                    }
                                } else {
                                    mvvm.removeQuery("begindate", true);
                                    mvvm.removeQuery("enddate", true);
                                }
                            }
                        } else if (name == "appointUser") {
                            if (type == "remove") mvvm.removeQuery("employees", true)
                        }
                        var data = mvvm.createQuery();
                        mvvm.grid1.loadData(data);
                    });
                    vm.queryMore = false;
                    vm.createQueryData = function () {
                        var d = new Date();
                        return {
                            datespan: {
                                label: "计划日期", val: "", valLabel: "",
                                items: [
                                    { label: "不限", val: "", curr: true },
                                    { label: d.getMonth() - 1 + '月', val: "m_-2", curr: false },
                                    { label: d.getMonth() + '月', val: "m_-1", curr: false },
                                    { label: d.getMonth() + 1 + '月', val: "m", curr: false },
                                    { label: d.getMonth() + 2 + '月', val: "m_+1", curr: false },
                                    { label: d.getMonth() + 3 + '月', val: "m_+2", curr: false },
                                    { label: d.getFullYear() + '年', val: "y", curr: false },
                                    { label: "自定义", val: "c", curr: false, type: "date", d1: "begindate", d2: "enddate", format: "%Y-%m-%d" }
                                ]
                            },
                            settleStatus: {
                                label: "结算状态", val: "", valLabel: "",
                                items: [{ label: "不限", val: '', curr: true }, { label: "已付清", val: '0', curr: false }, { label: "未付清", val: '1', curr: false }]
                            },
                            appointUser: {
                                label: "业务归属", val: "", valLabel: "",
                                items: [
                                    { label: "不限", val: "", curr: true },
                                    { label: "我的应付", val: "1", curr: false },
                                    { label: "下属应付", val: "2", curr: false },
                                    { label: "指定部门员工", val: "appointUser", curr: false, type: "selectUser" }
                                ]
                            },
                            contractId: { label: "合同Id", val: "", valLabel: "" },
                            begindate: { label: "起始时间", val: "", valLabel: "" },
                            enddate: { label: "截止时间", val: "", valLabel: "" },
                            employees: { label: "员工id", val: '', valLabel: "" },
                            type:{ label: "收付类型", val: '1', valLabel: "", noRemove: true},
                            key: { label: "关键词", val: "", valLabel: "" }
                        }
                    }
                    vm.queryData = vm.createQueryData();
                    vm.createGrid1 = function () {
                        return createGrid({
                            url: "/FinancialAffairs/ARAPPay",
                            modelFactory: modelFactory,
                            $lang: lang,
                            entityId: "ARAP",
                            pageid: vmid + "_grid1_page",
                            createQuery: function () {
                                var data = mvvm.createQuery();
                                return data;
                            },
                            onLoadData: function (ret) {
                                if (!ret.result) return CBCRM.showResult(ret);
                                mvvm.ADD = ret.data.ADD
                                mvvm.DELETE = ret.data.DELETE
                            },
                            onRemove: function (deleteIds, ids) {
                                var gvm = this;
                                var checkedItems = mvvm.grid1.getChecked();
                                for (var i = 0; i < checkedItems.length; i++) {
                                    if (checkedItems[i].Money != checkedItems[i].NotSettleMoney) {
                                        messageBox.error('无法删除已结算项目<br/>')
                                        return false
                                    }
                                }
                                $.post('/FinancialAffairs/ARAPAllDelete', deleteIds, function (ret) {
                                    CBCRM.showResult(ret);
                                    if (ret.result) {
                                        gvm.reloadData();
                                    }
                                });
                            }
                        });
                    }
                    vm.grid1 = vm.createGrid1();

                    vm.typedata = []

                    vm.settleStatusdata = []

                    vm.ADD = true
                    vm.DELETE = true

                    //选择合同
                    vm.selectContract = function () {
                        plugins.selectContract({
                            type: "contract",
                            dataAuth: 7050001,
                            multiple: { con: false, det: true },
                            callback: function (con, detail) {
                                mvvm.entity.Contract.Id = con[0].Id;
                                mvvm.entity.Contract.ContractName = con[0].ContractName;
                                mvvm.entity.CustomerId = con[0].Customer;
                                mvvm.entity.CustomerName = con[0].CustomerDisplay;
                                mvvm.arapList = [];
                                detail.forEach(function (item) {
                                    var arap = modelFactory.create("ARAP");
                                    arap.PlanDate = item.AddTime;
                                    arap.Money = item.Money;
                                    arap.Batch = item.Num;
                                    arap.SettleMoney = 0;
                                    arap.NotSettleMoney = item.Money;
                                    arap.Remark = item.Remark;
                                    mvvm.arapList.push(arap);
                                    watchMoney(mvvm.arapList[mvvm.arapList.length - 1]);
                                });
                            }
                        });
                    }

                    vm.setContractSelect = function (contractId) {
                        if (!contractId)
                            return;
                        $.post("/FinancialAffairs/GetPlanOfPays", { 'contractid': contractId }, function (ret) {
                            if (!ret || !ret.result)
                                return CBCRM.showResult(ret);
                            ret.data.Source.forEach(function (item) {
                                var arap = modelFactory.create("ARAP");
                                arap.PlanDate = item.AddTime;
                                arap.Money = item.Money;
                                arap.Batch = item.Num;
                                arap.SettleMoney = 0;
                                arap.NotSettleMoney = item.Money;
                                arap.Remark = item.Remark;
                                mvvm.arapList.push(arap);
                                watchMoney(mvvm.arapList[mvvm.arapList.length - 1]);
                            });
                        });
                    }
                    //选客户,结算单位
                    vm.selectCustomer = function (type) {
                        plugins.selectCustomer({
                            dataAuth: 7050001,
                            callback: function (cus, cons) {
                                var cu = cus[0];
                                switch (type) {
                                    case "settleCustomer":
                                        mvvm.entity.SettleCustomerName = cu.Name
                                        mvvm.entity.SettleCustomerId = cu.Id
                                        break;
                                    case "customer":
                                        mvvm.entity.CustomerName = cu.Name
                                        mvvm.entity.CustomerId = cu.Id
                                        break;
                                }
                            }
                        });
                    }
                    //业务员，负责人
                    vm.selectUser = function (type, r) {
                        var ops, mul;
                        switch (type) {
                            case "salesman":
                                mul = false;
                                break;
                            case "dutyPerson":
                                mul = false
                                break;
                            case "addBy":
                                mul = false;
                                break;
                            case "appointUser":
                                mul = true;
                                break;
                        }
                        plugins.selectUser({
                            dataAuth: 7050001,
                            multiple: mul,
                            callback: function (us) {
                                var u = us[0];
                                switch (type) {
                                    case "salesman":
                                        mvvm.entity.SalesmanId = u.Id;
                                        mvvm.entity.SalesmanName = u.FullName
                                        break;
                                    case "dutyPerson":
                                        mvvm.entity.DutyPersonId = u.Id;
                                        mvvm.entity.DutyPersonName = u.FullName
                                        break;
                                    case "addBy":
                                        mvvm.entity.AddBy.Id = u.id;
                                        mvvm.entity.AddBy.UserName = u.FullName;
                                        break;
                                    case "appointUser":
                                        var emps = mvvm.queryData.employees.val.split(",");
                                        if (emps.length == 0 && us.length == 0) return false;
                                        if (us.length == 0) {
                                            mvvm.removeQuery("employees");
                                            return false;
                                        }
                                        emps = where(us, true, "Id");
                                        mvvm.addQuery("employees", emps.join(","));
                                        mvvm.addQuery(type, r.val, r.label, true);
                                        break;
                                }
                            }
                        })
                    }
                    //费用日期
                    vm.costdateOpts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.CostDate = formatDate
                        }
                    }
                    //计划日期
                    vm.plandateOpts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.PlanDate = formatDate
                        }
                    }
                    vm.project = {}
                    vm.ARAPOpts = {
                        q: '请输入收支项目名称',
                        treeopts: {
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    mvvm.entity.ProjectId = treeNode.Id
                                    mvvm.entity.Project = treeNode.Name
                                }
                            },
                            async: {
                                url: function (treeId, treeNode) {
                                    var res = '/FinancialAffairs/PorjectDrodonwn';
                                    return res;
                                },
                                dataFilter: function (treeId, parentNode, responseData) {
                                    var result = [];
                                    if (responseData.data) {
                                        responseData.data.forEach(function (item) {
                                            result.push({ Id: item.Id, Name: item.Name, ParentId: item.Parent });
                                        })
                                    }
                                    return result;
                                }
                            }
                        }
                    }
                    //查看
                    vm.doview = function (id, contractId) {
                        mvvm.grid1.getEntity(id, function (entity) {
                            mvvm.entity = entity;
                            mvvm.entity.AddBy.UserName = entity.AddBy.FullName;
                            mvvm.initArapList(contractId, 1);
                            var dialog = mvvm.openTmpl({
                                title: "查看应付款", w: 700, h: 300, padding: "def2",
                                url: "/FinancialAffairs/ARAPView.html"
                            });
                        }, true)
                    }
                    //新增
                    vm.doadd = function () {
                        mvvm.grid1.getEntity(null, function (entity) {
                            mvvm.entity = entity;
                            var currUser = CBCRM.memberShip
                            mvvm.entity.SalesmanId = currUser.Id
                            mvvm.entity.SalesmanName = currUser.FullName
                            mvvm.entity.DutyPersonId = currUser.Id
                            mvvm.entity.DutyPersonName = currUser.FullName
                            mvvm.entity.Type = 1
                            mvvm.entity.AddBy.Id = currUser.Id;
                            mvvm.entity.AddBy.UserName = currUser.FullName;
                            mvvm.arapList = []
                            mvvm.delList = []
                        });
                        if (action == "Contract") {
                            mvvm.entity.Contract.Id = paramData.entity.Id;
                            mvvm.entity.Contract.ContractName = paramData.entity.ContractName;
                            mvvm.entity.CustomerId = paramData.entity.Customer;
                            mvvm.entity.CustomerName = paramData.entity.CustomerDisplay;
                            mvvm.setContractSelect(paramData.entity.Id);
                        }
                        mvvm.formSubmit('新增应付款')
                    }
                    //编辑
                    vm.doedit = function (id, contractId) {
                        mvvm.grid1.getEntity(id, function (entity) {
                            mvvm.entity = entity;
                            mvvm.entity.AddBy.UserName = entity.AddBy.FullName;
                            mvvm.formSubmit('编辑应付款')
                        }, true);
                        mvvm.initArapList(contractId, 1);
                    }
                    //删除
                    vm.doremove = function (item, index) {
                        var model = item.$model;
                        if (model.Money != model.NotSettleMoney) {
                            messageBox.error('无法删除已结算项目<br/>')
                            return false
                        }
                        mvvm.grid1.remove(item, index);
                    }

                    vm.formSubmit = function (title) {
                        var editor;
                        var btns = [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                mvvm.entity.$model.NotSettleMoney = mvvm.entity.$model.Money;
                                var model = avalon.mix({}, mvvm.entity.$model);
                                var msg = ''
                                if (!model.Contract.ContractName) {
                                    msg = msg + '请选择归属合同<br/>'
                                }
                                if (!model.CustomerName) {
                                    msg = msg + '请选择客户名称<br/>'
                                }
                                if (!mvvm.arapList.length) {
                                    msg = msg + '请添加应付款计划<br/>'
                                }
                                else {
                                    for (var i = 0; i < mvvm.arapList.length; i++) {
                                        var arap = mvvm.arapList[i];
                                        var amount = parseFloat(arap.Money);
                                        if (!amount || amount < 0) {
                                            msg = msg + '请输入正确的金额<br/>';
                                            break;
                                        }
                                        if (!arap.PlanDate) {
                                            msg = msg + '请选择计划日期<br/>';
                                            break;
                                        }

                                    }
                                }
                                if (msg) {
                                    messageBox.warning(msg)
                                    return false
                                }
                                // 复制公共参数到列表
                                mvvm.arapList.forEach(function (arap) {
                                    arap.Type = 1;
                                    arap.Contract.Id = mvvm.entity.Contract.Id
                                    //arap.Contract.ContractName = mvvm.entity.ContractName;
                                    arap.CustomerId = mvvm.entity.CustomerId;
                                    arap.CustomerName = mvvm.entity.CustomerName;
                                    arap.SalesmanId = mvvm.entity.SalesmanId;
                                    arap.SalesmanName = mvvm.entity.SalesmanName;
                                    arap.DutyPersonId = mvvm.entity.DutyPersonId;
                                    arap.DutyPersonName = mvvm.entity.DutyPersonName;
                                    //arap.AddTime = mvvm.entity.AddTime;
                                    //arap.AddBy.Id = mvvm.entity.AddBy.Id;
                                    //arap.AddBy.UserName = mvvm.entity.AddBy.UserName;
                                });
                                /*
                                $.extend(model, jsonToSubmit("Contract", model.Contract));
                                delete model.Contract;
                                delete model.AddBy;
                                var url = (model.Id == 0 ? "/FinancialAffairs/ARAPAdd/" : "/FinancialAffairs/ARAPEdit/");
                                */
                                var url = "/FinancialAffairs/ARAPUpdateList/"
                                var data = {"type": 1, "models": mvvm.arapList.$model, "delIds": mvvm.delList.$model };
                                jsonPost(url, data, function (ret) {
                                    CBCRM.showResult(ret, function () {
                                        if (ret.result) {
                                            mvvm.grid1.reloadData();
                                            if (dialog) dialog.close()
                                        }
                                    })
                                })
                                mvvm.arapList = [];
                                return false;
                            }
                        }]
                        var dialog = mvvm.openTmpl({
                            title: title, w: 700, h: 300, padding: "def2",
                            btns: btns,
                            url: "/FinancialAffairs/ARAPPayForm.html",
                            afterscan: function () {

                            },
                            onclose: function () {
                                mvvm.destroyui(["ARAPTree"]);
                            }
                        });
                    }
                    
                    // 删除列表中的Arap
                    vm.dodelDetail = function (index) {
                        if (!mvvm.arapList.length) {
                            messageBox.warning("请重新选择合同订单！")
                            return false;
                        }
                        if (mvvm.arapList[index].Id)
                            mvvm.delList.push(mvvm.arapList[index].Id);
                        mvvm.arapList.splice(index, 1);

                    }
                    // 添加应收应付到列表
                    vm.addArap = function () {
                        var arap = modelFactory.create("ARAP");
                        arap.Batch = mvvm.arapList.length +1;
                        mvvm.arapList.push(arap);
                        watchMoney(mvvm.arapList[mvvm.arapList.length - 1]);
                    }
                    vm.initArapList = function (contractId,type) {
                        if (!contractId)
                            return;
                        mvvm.arapList = []
                        mvvm.delList = []
                        $.get('/FinancialAffairs/GetARAPList/', {
                            'contractId': contractId,
                            'type':type
                        }, function (ret) {
                            ret.data.Source.forEach(function (item) {
                                var arap = modelFactory.create("ARAP");
                                arap.Id = item.Id;
                                arap.PlanDate = item.PlanDate;
                                arap.CustomerId = item.CustomerId;
                                arap.CustomerName = item.CustomerName;
                                arap.Money = item.Money;
                                arap.Batch = item.Batch;
                                arap.SettleMoney = item.SettleMoney;
                                arap.NotSettleMoney = item.NotSettleMoney;
                                arap.SalesmanId = item.SalesmanId
                                arap.SalesmanName = item.SalesmanName
                                arap.DutyPersonId = item.DutyPersonId
                                arap.DutyPersonName = item.DutyPersonName
                                arap.Type = item.Type;
                                arap.Remark = item.Remark;
                                arap.AddBy.Id = item.AddBy.Id;
                                arap.AddBy.UserName = item.AddBy.FullName;
                                mvvm.arapList.push(arap);
                                watchMoney(mvvm.arapList[mvvm.arapList.length - 1]);
                            });
                        });
                    }

                    //记账
                    vm.addAccountBook = function (item) {
                        var url = '/FinancialAffairs/Accounting/' + item.Id + '/ARAPPayAdd';
                        mvvm.gotourl(url, true, {
                            entity: item.$model,
                            reloadList: function () { mvvm.grid1.reloadData() }
                        });
                    }

                    vm.settleWayData = [];
                    vm.getDicts = function () {
                        /*getDicts({ settleWayData: 100056 }, mvvm, function () {
                            mvvm.settleWayData.forEach(function(item,i)
                            {
                                mvvm.queryData.settleWay.items.push({ label: item.Data, val: item.Data, curr: false })
                            })
                            mvvm.settleWayData.unshift({ Data: '请选择', Id: 0 }); //添加‘请选择’到付款方式下拉框
                        }); */
                    }
                })
                mvvm.grid1.init();
                mvvm.queryData.begindate.$watch("val", watchTime);
                mvvm.queryData.enddate.$watch("val", watchTime);
                function watchMoney(item) {
                    item.$watch("Money", function (n, o) {
                        if (n && n != o) {
                            var m = parseFloat(n);
                            item.NotSettleMoney = item.Money - item.SettleMoney;
                        }
                    })
                }
                function watchTime(v1, v2) {
                    if (v1 && v1 != v2) {
                        var data = mvvm.createQuery();
                        mvvm.grid1.loadData(data);
                    }
                }
                mvvm.getDicts();
                switch (action) {
                    case "Contract":
                        mvvm.addQuerys({ contractId: paramData.entity.Id }, true);
                        paramData.viewOther(tmpl, mvvm, "#tableList");
                        break;
                    default:
                        CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                }
            },

            ARAP: function (tmpl, lang, contentId, module, paramData) {
                var CBCRM = avalon.vmodels.CBCRM, vmid = "ARAP";
                var params = this.params || {}, action = params.action, paramid = params.id;
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.lang = lang;
                    initQuerys(vm, function (data,name,val,type) {
                        mvvm.grid1.loadData(data);
                    });
                    vm.queryData = {
                        contractId: { label: "合同id", val: "" }
                    };
                    vm.createGrid1 = function () {
                        var grid = createGrid({
                            url: "/FinancialAffairs/ARAP",
                            pageid: vmid + "_grid1_page",
                            createQuery: function () {
                                return mvvm.createQuery();
                            }
                        });
                        return grid;
                    }
                    vm.grid1 = vm.createGrid1();
                });
                mvvm.grid1.init();
                console.log(action)
                switch (action) {
                    case "Contract":
                        mvvm.addQuerys({ contractId: paramid }, true);
                        paramData.viewOther(tmpl,mvvm);
                        break;
                    default:
                        CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                        break;
                }
                
            }, 
        }
        return Financial;
    })