/// <reference path="../../Content/Themes/Base/Template/Product/PriceList.html" />
define('Market', ['modelFactory', 'plugins', 'json', 'dialog', 'common', 'leftMenu', 'jscal2', 'kindedit', 'Jpin', 'upload', 'fusionCharts', "floatCalc", "cookie", "filters"], function (modelFactory, plugins) {
    var publicFn = {
        //查看营销战役
        campaigndoview: function (id) {
            var path = '/Market/Campaign/' + id + '/view';
            goto(path,true)
        },
        //查看市场活动
        activitydoview: function (id) {
            var path = '/Market/Activity/' + id + '/view';
            goto(path,true)
        },
        //查看合同订单
        contractdoview: function (id) {
            var path = '/Market/Contract/' + id + '/view';
            goto(path,true)
        },
        //查看销售机会
        salesOpportunitiesdoview: function (id) {
            var path = '/Market/SalesOpportunities/' + id + '/view';
            goto(path,true)
        },
        //查看客户
        customerdoview: function (id) {
            var path = "/Customer/DetailCustomer/" + id;
            goto(path, true);
        }

    },

    //只要部门和用户
    notPostFilter =function(groupCheck){
        return 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 = !groupCheck
                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
        }
    },
    //产品特殊价格
    formatPriceList = function (product) {
        var a = [];
        product.PriceList.forEach(function (item) {
            a.push(item.MemberGradeDisplay + ":" + (item.Prints ? item.Prints : "无"));
        });
        a.push("最低价：" + product.LowestPrice);
        return a.join(",");
    }
    //销售目标
    var SalesTarget = function () {

        var $a = avalon;
        var dateLen = 5;
        var mydepartments = [];
        var loadMyDeparts = function () {
            //$.get('/Market/GetSaleTargetDepartment', {}, function (ret) {
            //    mydepartments = ret.data;
            //})
        }
        loadMyDeparts();
        var keyIndexMaps = {};
        var dateIndexMaps = {};
        var departments = mydepartments;
        var isNum = /^\d+(\.{1}\d+)?$/;
        var fulld;
        var time = "";
        var treeAsyncSuccess = function (event, treeId, treeNode, msg) {
            var tree = $.fn.zTree.getZTreeObj(treeId);
            var node;
            if (mydepartments.length) {
                $a.each(mydepartments, function (i, t) {
                    node = tree.getNodeByParam("id", t, null);
                    tree.checkNode(node, true, true);
                });
            } else {
                tree.checkAllNodes(true);
            }
        };
        var $saleTarget = $a.define("market.targets", function ($v) {
            $v.users = [];
            $v.dates = [];
            $v.btns = [];
            $v.columns = [];
            $v.checkNum = function (e) {
                var $el = $a(e.target);
                if (!isNum.test($el.val())) {
                    messageBox.error('请输入数字')
                    $(e.target).focus();
                    return false;
                }
            }
            $v.expandRow = function () {
                var $vm = this.$vmodel;
                var users = this.$vmodels[1].users;
                var index = $vm.$index;
                var depth = $vm.item.Depth;
                var current;
                var showDetails = $vm.item.showDetails = !$vm.item.showDetails;
                while (true) {
                    current = users[++index];
                    if (!current || current.Depth <= depth) break;
                    current.show = current.showDetails = showDetails;
                }
            }
            $v.toChart = function () {
                var $vm = this.$vmodel;
                var users = this.$vmodels[1].users;
                var index = $vm.$index;
                toChart(users[index]);
            }
            $v.doEdit = ''
            $v.doCancel = ''
            $v.doSave = ''
        });
        var $totalChart = $a.define("market.totalChart", function ($v) {
            $v.changeChartType = function (e) {
                var $self = $a(e.target),
                type = $self.data("type");
                if (type) {
                    createChart("chart", null, type);
                }
            }
        });
        var $search = $a.define("search", function ($v) {
            $v.startDate = '';
            $v.endDate = '';
            $v.doShow = function () {
                $saleTarget.users = [];
                $saleTarget.dates = [];
                $saleTarget.btns = [];
                $saleTarget.columns = [];
                setDateRange();
                loadUsers();
            }

            $v.startDateOPts = {
                format: '%Y-%m',
                onSelect: function (date, formatDate, format) {
                    $search.startDate = formatDate
                }
            }

            $v.endDateOPts = {
                format: '%Y-%m',
                onSelect: function (date, formatDate, format) {
                    $search.endDate = formatDate
                }
            }
        });
        $search.$watch("startDate", function (c, o) {
            if (c !== o) {
                $search.startDate = c;
                $.cookie('ssd', c);
            }
        });
        $search.$watch("endDate", function (c, o) {
            if (c !== o) {
                $search.endDate = c;
                $.cookie('sed', c);
            }
        });
        var $doption = $a.define("doption", function ($v) {
            $v.treeopts = {
                treeopts: {
                    check: {
                        enable: true,
                        chkStyle: 'checkbox'
                    },
                    callback: {
                        onCheck: function (event, treeId, treeNode) {
                            var treeObj = $.fn.zTree.getZTreeObj(treeId);
                            var nodes = treeObj.getCheckedNodes(true);
                            var hasCheck = nodes.length > 0;
                            var users = $saleTarget.users;

                            var uIds = ''
                            for (var n = 0 ; n < nodes.length; n++) {
                                uIds += nodes[n].Id + ','
                            }

                            for (var j = 1, uLen = users.length; j < uLen; j++) {
                                g = users[j];
                                if (uIds.indexOf(g.Id) > -1) {
                                    g.show = true;
                                    g.showDetails = g.show;
                                } else {
                                    g.show = false;
                                }
                            }
                        }
                    },
                    async: {
                        url: function (treeId, treeNode) {
                            return "/Settings/GetGroupPostUser/2020901"
                        }
                        ,
                        dataFilter: 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 = false
                                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]
                                        u.ParentId = u.PositionId
                                        u.Name = u.FullName
                                        ret.push(u)
                                    })
                                    if (!hasEmp) {
                                        hasEmp = p.Users.length > 0
                                    }
                                    if (hasEmp) {
                                        ret.push(p)
                                    }
                                })
                                ret.push(curr)
                            }
                            return ret
                        }
                    }
                }
            }
        });
        var now = new Date();
        var editIndex;
        var getChildren = function (arr, index, depth) {
            var current,
                 ret = [];
            for (var i = index + 1, len = arr.length; i < len; i++) {
                current = arr[i];
                if (current.Depth <= depth) {
                    break;
                } else {
                    $a.log("current：" + (current.GroupName || current.Name) + " Depth：" + current.Depth);
                    ret.push(current);
                }
            }
            return ret;
        }
        var targetCheck = function (row, column) {
            var users = $saleTarget.users;
            var root = users[0];
            var i = row || 1;
            var len = users.length;
            var stack = [root];
            var cur;
            var filter = ['show', 'toEdit', 'hasOwnProperty', 'SignAContractMoneyNotEq',
                    'ReturnedMoneyNotEq', 'CustomerNumNotEq', 'SignAContractNotEq'];
            var empty = {
                SignAContract: 0,
                SignAContractTotal: 0,
                CompleteSignAContract: 0,
                SignAContractMoney: 0,
                SignAContractMoneyTotal: 0,
                CompleteSignAContractMoney: 0,
                ReturnedMoney: 0,
                ReturnedMoneyTotal: 0,
                CompleteReturnedMoney: 0,
                CustomerNum: 0,
                CustomerNumTotal: 0,
                CompleteCustomerNum: 0
            };
            var start = $a.mix({}, empty);
            var depth = 0;
            var ret = {};
            var target;
            var el;
            var x = 0;
            var y = 0;
            var p = '';
            var calc = function (i, t) {
                var s = ret[i];
                for (var key in s) {
                    p = key + "NotEq";
                    if (t.hasOwnProperty(p)) {
                        x = parseInt(t[key], 10);
                        y = parseInt(s[key], 10);
                        x = isNaN(x) ? 0 : x;
                        y = isNaN(y) ? 0 : y;
                        /*if (x || y) {
                        $a.log("name:" + el.GroupName + "key:" + key + " x:" + x + " y:" + y);
                        }*/
                        t[p] = x < y;
                    }
                }
            }
            for (; i < len; i++) {
                cur = users[i];
                if (cur.Depth === depth && stack.length) {
                    //下一个部门时先计算压入堆栈里的部门
                    var ts;
                    while (el = stack.pop()) {
                        ts = el.Targets;
                        if (!column) {
                            $a.each(ts, calc);
                        } else {
                            calc(column, ts[column]);
                        }
                    }
                    ret = {};
                    stack.push(root);
                    stack.push(cur);
                    start = $a.mix({}, empty);
                }
                if (!cur.show) continue;
                if (!cur.IsGroup) {
                    if (column) {
                        target = cur.Targets[column];
                        $a.each(target, function (i, t) {
                            if ($.inArray(i, filter) === -1) {
                                start = ret[column] || $a.mix({}, empty);
                                ret[column] = start;
                                x = parseInt(start[i], 10);
                                y = parseInt(target[i], 10);
                                if ($a.type(x) === "number" && $a.type(y) === "number") {
                                    x = isNaN(x) ? 0 : x;
                                    y = isNaN(y) ? 0 : y;
                                    //$a.log("key:"+j + " x:"+x + " y:"+y );
                                    start[i] = x.add(y);
                                }
                            }
                        });
                    } else {
                        $a.each(cur.Targets, function (i, t) {
                            start = ret[i] || $a.mix({}, empty);
                            ret[i] = start;
                            $a.each(t, function (j, item) {
                                if ($.inArray(j, filter) === -1) {
                                    x = parseInt(start[j], 10);
                                    y = parseInt(t[j], 10);
                                    if ($a.type(x) === "number" && $a.type(y) === "number") {
                                        x = isNaN(x) ? 0 : x;
                                        y = isNaN(y) ? 0 : y;
                                        //$a.log("key:"+j + " x:"+x + " y:"+y );
                                        start[j] = x.add(y);
                                    }
                                }
                            });
                        });
                    }
                } else {
                    depth = Math.max(depth, cur.Depth);
                    stack.push(cur);
                }
            }
        }
        var targetTotal = function (row) {
            var users = $saleTarget.users;
            var i = row || 0;
            var len = users.length;
            var cur;
            var ct;
            var tlen = 0;
            var empty = {
                SignAContractMoneyTotal: 0,
                CompleteSignAContractMoneyTotal: 0,
                ReturnedMoneyTotal: 0,
                CompleteReturnedMoneyTotal: 0,
                CustomerNumTotal: 0,
                CompleteCustomerNumTotal: 0,
                SignAContractTotal: 0,
                CompleteSignAContractTotal: 0
            };
            var keyMap = {
                SignAContractMoneyTotal: "SignAContractMoney",
                CompleteSignAContractMoneyTotal: "CompleteSignAContractMoney",
                ReturnedMoneyTotal: "ReturnedMoney",
                CompleteReturnedMoneyTotal: "CompleteReturnedMoney",
                CustomerNumTotal: "CustomerNum",
                CompleteCustomerNumTotal: "CompleteCustomerNum",
                SignAContractTotal: "SignAContract",
                CompleteSignAContractTotal: "CompleteSignAContract"
            };
            var rowTotal = $a.mix({}, empty);
            var x = 0;
            var y = 0;
            for (; i < len; i++) {
                cur = users[i];
                tlen = cur.Targets.length;
                while (tlen) {
                    tlen--;
                    ct = cur.Targets[tlen];
                    for (var key in rowTotal) {
                        x = parseInt(ct[keyMap[key]], 10);
                        y = parseInt(rowTotal[key], 10);
                        x = isNaN(x) ? 0 : x;
                        y = isNaN(y) ? 0 : y;
                        rowTotal[key] = x.add(y);
                    }
                }
                for (var key in rowTotal) {
                    //$a.log("rowindex:"+i + " key:"+key + " val:"+rowTotal[key]);
                    cur[key] = rowTotal[key];
                }
                rowTotal = $a.mix({}, empty);
            }
        }
        var doCall = function (isEdit) {
            var $vmm = this.$vmodel;
            var $pvm = this.$vmodels[1];
            var index = $vmm.$index;
            var i = 0;
            var j = 0;
            var len = $pvm.users.length;
            var tLen;
            var current;
            var show;
            var t;
            var copy;
            $vmm.item.canCancel = $vmm.item.canSave = isEdit;
            $vmm.item.editing = !isEdit;
            editIndex = index;
            $a.log("当前编辑项索引:" + editIndex);
            for (; i < len; i++) {
                current = $pvm.users[i];
                if (!current.show) continue;
                tLen = current.Targets.length;
                for (; j < tLen; j++) {
                    t = current.Targets[j];
                    if (isEdit) {
                        show = j === index;
                        t.toEdit = true;
                        t.show = show;
                        $pvm.columns[j].show = show;
                        $pvm.dates[j].show = show;
                        $pvm.btns[j].show = show;
                    } else {
                        t.show = true;
                        t.toEdit = false;
                        $pvm.columns[j].show = true;
                        $pvm.dates[j].show = true;
                        $pvm.btns[j].show = true;
                    }
                }
                j = 0;
            }
        }
        var doCancel = function () {
            doCall.call(this, false);
        }
        var doEdit = function () {
            doCall.call(this, true);
        }
        var doSave = function () {
            if (!editIndex && editIndex !== 0) return;
            var users = $saleTarget.users;
            var dates = $saleTarget.dates;
            var i = 0, j = 0;
            var len = users.length;
            var current;
            var target;
            var d = dates[editIndex].date + "-01";
            var ret = [];
            var model = {};
            var self = this;
            var tmp;
            var departmentss = [];
            for (i = 0; i < len; i++) {
                current = users[i];
                if (!current.show) continue;
                target = current.Targets[editIndex];
                $a.log("Employee：" + current.Id + " Department：" + current.GroupId + " Date：" + d);
                //if (current.IsGroup) { 
                //    model["departments[" + j + "].Id"] = current.Id;
                //    j++
                //}
                tmp = $a.mix({}, target.$model, {
                    Employee: current.Id || ""
                            , Department: current.GroupId || ""
                            , CompleteDate: d
                });

                //delete tmp.Id;
                delete tmp.EmployeeDisplay;
                delete tmp.SignAContractNotEq;
                delete tmp.SignAContractMoneyNotEq;
                delete tmp.ReturnedMoneyNotEq;
                delete tmp.CustomerNumNotEq;
                delete tmp.show;
                delete tmp.toEdit;
                //ret.push(tmp);
                model["targets[" + i + "].Id"] = tmp.Id
                model["targets[" + i + "].SignAContract"] = tmp.SignAContract
                model["targets[" + i + "].ReturnedMoney"] = tmp.ReturnedMoney
                model["targets[" + i + "].CustomerNum"] = tmp.CustomerNum
                model["targets[" + i + "].Employee"] = current.Id
                model["targets[" + i + "].Department"] = current.GroupId
                model["targets[" + i + "].SignAContractMoney"] = tmp.SignAContractMoney
                model["targets[" + i + "].CompleteDate"] = d
            }
            //if (ret.length === 0) {
            //    $a.log("没有销售目标值可保存。");
            //    return;
            //}

            $.post("/Market/SaleTargetSave/", model, function (res) {
                if (res.result) {
                    time = new Date();
                    messageBox.ok('数据保存成功')
                    doCall.call(self, false);
                    $a.nextTick(function () {
                        targetTotal();
                        targetCheck(0, editIndex);
                    });
                } else {
                    messageBox.error('数据保存失败')
                }
            });
        }
        var monthCalc = function (startDate, endDate) {
            var number = 0;
            var yearToMonth = (endDate.getFullYear() - startDate.getFullYear()) * 12;
            number += yearToMonth;
            monthToMonth = endDate.getMonth() - startDate.getMonth();
            number += monthToMonth;
            return number + 1;
        }
        var createDate = function (len, month) {
            var d;
            for (var i = 0; i < len; i++) {
                d = new Date();
                d.setMonth(month + i + 1, 0);
                fulld = d.getFullYear() + "-" + (d.getMonth() + 1);
                dateIndexMaps[fulld] = i;
                $saleTarget.dates.push({
                    date: fulld,
                    show: true
                });
                $saleTarget.columns.push({
                    show: true
                });
                $saleTarget.btns.push({
                    canCancel: false,
                    canSave: false,
                    show: true,
                    editing: true
                });
            }
        }
        var dateFormat = function (val) {
            return typeof val.getFullYear !== "undefined" ? val.getFullYear() + "-" + (val.getMonth() + 1)
             : "";
        }
        var setDateRange = function () {
            var start = new Date($search.startDate.replace("-", "/") + "/01");
            var end = new Date($search.endDate.replace("-", "/") + "/01");
            var month = monthCalc(start, end);
            dateLen = month;
            createDate(month, start.getMonth());
        }
        var createChart = function (id, charts, charttype) {
            var myChart = new FusionCharts("/Scripts/Charts/Charts/" + (charttype || "MSColumn3D")
             + ".swf", "totalChart", "990", "350");
            myChart.setTransparent(true);
            myChart.setJSONData(charts || createChart.ret);
            myChart.render(id);
            if (charts) {
                createChart.ret = charts;
            }
        }
        var toChart = function (user) {
            var id = "chart", $chart = $("#" + id);
            if (!$chart.length) {
                $a.log("没有找到统计图表区域，停止执行。");
            }
            var data = $chart.data();
            if (!data) return;
            var column = data.column,
                completeColumn = "Complete" + column,
                 charts = {
                     "chart": {
                         "caption": (user.GroupName || user.Name) + " 的 " + data.caption + "完成情况统计图",
                         "xaxisname": "时间范围",
                         "yaxisname": data.caption,
                         "yaxisminvalue": 0,
                         "yaxismaxvalue": 0,
                         "showcolumnshadow": "1",
                         "showvalues": "0",
                         "decimals": "0",
                         "numbersuffix": data.units,
                         "alternatevgridcolor": "f7f7f7",
                         "basefontcolor": "114B78",
                         "tooltipbordercolor": "114B78",
                         "tooltipbgcolor": "E7EFF6",
                         "plotborderdashed": "0",
                         "plotborderdashlen": "2",
                         "plotborderdashgap": "2",
                         "useroundedges": "1",
                         "showborder": "0",
                         "bgColor": "#e6e6e6",
                         "canvasBorderColor": "#e6e6e6",
                         "canvasBgColor": "#FFFFFF",
                         "canvasBgAlpha": "50",
                         "bgAlpha": "0",
                         "basefontsize": "12"
                     },
                     "categories": [{
                         "category": []
                     }],
                     "dataset": []
                 },
            ymax = 0,
            targets = user.Targets,
            dates = $saleTarget.dates,
            targetVals = [],
            completeVals = [];
            $a.each(dates, function (i, item) {
                charts.categories[0].category.push({ "label": item.date });
            });
            $a.each(targets, function (i, item) {
                var val = item[column];
                ymax = Math.max(ymax, val);
                targetVals.push({
                    "value": val
                });
            });
            $a.each(targets, function (i, item) {
                completeVals.push({
                    "value": item[completeColumn]
                });
            });
            charts.dataset.push({
                "seriesname": "目标值",
                "color": "AFD8F8",
                "data": targetVals
            });
            charts.dataset.push({
                "seriesname": "完成值",
                "color": "F6BD0F",
                "data": completeVals
            });
            if (ymax < 10) {
                charts.chart.yaxismaxvalue = 10;
            }
            createChart(id, charts);
            if ($chart.scrollIntoView) $chart.scrollIntoView();
        }
        $search.startDate = $.cookie('ssd');
        $search.endDate = $.cookie('sed');
        if (!$search.startDate) {
            $search.startDate = dateFormat(now);
        }
        if (!$search.endDate) {
            var nd = new Date();
            nd.setMonth(nd.getMonth() + dateLen);
            $search.endDate = dateFormat(nd);
        }
        $saleTarget.doEdit = function () {
            //this.$vmodels.unshift(entity)
            doEdit.call(this)
            //doCall(true,entity,this.$vmodel,index)
        }
        $saleTarget.doSave = function () {
            doSave.call(this)
        }
        $saleTarget.doCancel = function () {
            doCall.call(this)
        }
        setDateRange();
        var loadUsers = function () {
            $.get('/Settings/GetGroupPostUser/2020901', {}, function (result) {
                var empty = {
                    SignAContractMoneyTotal: '',
                    CompleteSignAContractMoneyTotal: '',
                    ReturnedMoneyTotal: '',
                    CompleteReturnedMoneyTotal: '',
                    CustomerNumTotal: '',
                    CompleteCustomerNumTotal: '',
                    SignAContractTotal: '',
                    CompleteSignAContractTotal: '',
                    show: true,
                    showDetails: true,
                    IsGroup: true,
                    Targets: [],
                    Depth: 0
                };
                var data = []   //[$a.mix({}, empty, { GroupName: "公司", Id: 0 })];
                var elen = result.data.groups.length;
                var depthMap = {};
                var current;
                var employees = [];
                var employee;
                var i = 0;
                var ds = mydepartments;
                var hasDepartment = mydepartments.length > 0;
                while (i < elen) {
                    var group = result.data.groups[i]
                    curr = $a.mix(group, empty);
                    if (!curr.ParentId) {
                        depthMap[curr.Id] = depth = 0;
                    } else {
                        depth = depthMap[curr.ParentId];
                        if (!depth) {
                            depthMap[curr.Id] = depth = 1;
                        } else {
                            depth += 1;
                            depthMap[curr.Id] = depth;
                        }
                    }
                    curr.Targets = [];
                    curr.Depth = depth;
                    curr.IsGroup = true;
                    if (hasDepartment) {
                        curr.show = $.inArray(parseInt(curr.Id, 10), ds) > -1;
                    } else {
                        curr.show = true;
                    }
                    curr.show = true;
                    curr.showDetails = curr.show;
                    data.push(curr);

                    curr.Posts.forEach(function (p, i) {
                        curr.Posts[i].ParentId = p.Boss ? p.Boss.Id : p.Group
                        p.Users.forEach(function (u, i) {
                            var u = p.Users[i]
                            var employee = $a.mix(u, empty);
                            delete employee.showDetails;
                            employee.IsGroup = false;
                            employee.ParentId = u.PositionId
                            employee.Name = u.FullName
                            if (!employee.BossIds) {
                                employee.Depth = curr.Depth + 1;
                            } else {
                                employee.Depth = employee.BossIds.split(",").length;
                            }
                            data.push(employee)
                        })
                    })
                    i++;
                }
                //employees = employees.sort(empSort);
                //groupCall(result.data.groups);
                $saleTarget.users = data;
                loadTargets();
            });
        }
        var createEmptyTargets = function (len) {
            var empty = {
                SignAContract: '',
                SignAContractTotal: '',
                SignAContractMoney: '',
                SignAContractMoneyTotal: '',
                ReturnedMoney: '',
                ReturnedMoneyTotal: '',
                CustomerNum: '',
                CustomerNumTotal: '',
                CompleteSignAContract: '',
                CompleteCustomerNum: '',
                CompleteSignAContractMoney: '',
                CompleteReturnedMoney: '',
                CompleteReturnedMoneyTotal: '',
                CompleteSignAContractMoneyTotal: '',
                CompleteSignAContractTotal: '',
                CompleteCustomerNumTotal: '',
                SignAContractMoneyNotEq: false,
                ReturnedMoneyNotEq: false,
                CustomerNumNotEq: false,
                SignAContractNotEq: false,
                show: true,
                toEdit: false
            };
            var ret = [];
            while (len) {
                len--;
                ret.push($a.mix({}, empty));
            }
            return ret;
        }
        var loadTargets = function () {
            var sd = $saleTarget.dates[0].date;
            var ed = $saleTarget.dates[dateLen - 1].date;
            var users = $saleTarget.users;
            var userLen = $saleTarget.users.length;
            $a.nextTick(function () {
                for (var g = 0; g < userLen; g++) {
                    var c = users[g];
                    keyIndexMaps[c.Id] = g;
                    c.Targets = createEmptyTargets(dateLen);
                }
            });
            $.get('/Market/GetSaleTarget', {
                StartDate: sd, EndDate: ed, t: time
            }, function (result) {
                var datas = result.data;
                if (!datas.length) {
                    $a.log("没有" + sd + " 至 " + ed + " 销售目标数据……");
                    setTimeout(function () {
                        var $el = $(".exmployee_saletarget");
                        $el.width($el.parent().width());
                    }, 500);
                    return;
                }
                time = "";
                var indexMaps = keyIndexMaps;
                var index;
                var d;
                var rd;
                var dindex;
                var t;
                $a.each(datas, function (index, item) {
                    index = indexMaps[item.Employee];
                    d = item.CompleteDate.split("-");
                    rd = d[0] + "-" + parseInt(d[1], 10);
                    dindex = dateIndexMaps[rd];

                    if (index >= 0) {
                        delete item.Id;
                        delete item.CompleteDate;
                        delete item.Employee;
                        delete item.EmployeeDisplay;
                        delete item.Department;
                        t = users[index].Targets[dindex];
                        var tmp,
                        model = t.$model
                        for (var prop in model) {
                            tmp = item[prop]
                            if (typeof tmp !== 'undefined')
                                t[prop] = tmp
                        }
                        users[index].Targets[dindex] = t
                    }
                });
                $a.nextTick(function () {
                    targetTotal();
                    targetCheck();
                    toChart($saleTarget.users[0]);
                    var $el = $(".exmployee_saletarget");
                    $el.width($el.parent().width());
                });
            });
        }
        loadUsers();
        $a.scan();

        $(function () {
            setTimeout(function () {
                var $nodes = $(".setdepartment");
                $nodes.attr("ms-ui-treeopts", "dropDownDepartmentTree");
                $a.scan($nodes[0], $doption);
            }, 2000);
            //$a.log("userAgent：" + navigator.userAgent);
            if (navigator.userAgent.indexOf("MSIE 8.0") > 0) {
                $("#right").css("padding-right", 6);
            } else {
                $("#right").css("padding-right", 8);
            }
        });

        $a.filters.percents = function (str, val, fixed) {
            if (!str || !val) {
                return "";
            }
            var ret = str / val;
            if (isNaN(ret) || ret === 0) {
                return "0 %";
            }
            return (parseFloat((ret + "").substr(0, 4)) * 100) + "%"
        }

        
    }

    //下拉配置过滤数据 只可选员工
    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
    }

    //市场模块
    var Market = {
        ///工作台
        Index: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM;
            var Mvvm = avalon.define('marketdesktop', function (vm) {
                vm.lang = lang
                vm.searchFieldList = {}
                vm.key = ''
                vm.path = ''
                vm.searchtype = 'Campaign'
                vm.onSetPath = function () {
                    Mvvm.path = '#/Market/' + Mvvm.searchtype + '/' + encodeURI(Mvvm.key) + "/key"
                    //if (Mvvm.searchtype != 'Contract')
                    //    Mvvm.path = '#/Market/' + Mvvm.searchtype + '/' + encodeURI(Mvvm.key)
                    //else
                    //    Mvvm.path = '#/Market/Contract/' + encodeURI(Mvvm.key)+'/0/key'
                }
                vm.onEnter = function (e) {
                    if (e.keyCode == 13) {
                        Mvvm.onSetPath();
                        var url = '/Market/' + Mvvm.searchtype + '/' + encodeURI(Mvvm.key) + "/key";
                        goto(url);
                    }
                }
            })

            Mvvm.searchFieldList = {
                Campaign: '营销战役',
                ProbeFeedback: '调查反馈',
                Activity: '市场活动',
                SalesOpportunities: '销售机会',
                DocumentaryOffer: '跟单报价',
                Contract: '合同订单',
                ProductList:'业务明细',
                //key7: '渠道政策',
                //key8: '广告素材',
                //key9: '礼品/赠品'
            }

            require('commonui', function () {
                CBCRM.fillContent(tmpl, lang, contentId, module, Mvvm)
            })

            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.Index = null
            }
        }

        ///销售管理工作台
        , Sales: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM,vmid="marketingsales";

            var mvvm = CBCRM.define(vmid, function (vm) {
                vm.$skipArray = ['lang']
                vm.menus = []
                vm.lang = lang
                vm.destroy = function () {
                    destroyui(["employeeTreeId"])
                }
                vm.campaigns = [] //战役
                vm.activities = [] //活动
                vm.feedbacks = []  //反馈
                vm.customers = []  //目标客户 
                vm.customcount = 0  //跟单客户数
                vm.oldcustomer = 0 //老客户
                vm.newcustomer = 0 //新客户
                vm.signcustomer = 0 //已签单客户
                vm.successrate = 0 //成功率
                vm.salesopportunities = [] //销售机会
                vm.documentaryoffers = []  //跟单报价
                vm.marketcontracts = []   //合同订单
                vm.marketproducts = []   //业务明细

                vm.MarketingCampaign = {}//阶段战役
                vm.customerControllerList = []
                //查看OK
                vm.doviews = function () {
                    var path = $(this).attr('path')
                    goto(path, true)
                }

                //选择所属战役
                vm.campaignList = []
                vm.campaignPanel = false
                vm.campaignKey = ''
                vm.selectCampaign = function () {
                    $('body').bind('mousedown', function () {
                        mvvm.campaignPanel = false
                        $('body').unbind('mousedown')
                    })

                    getCampaignList();
                    mvvm.campaignPanel = true;
                }
                vm.searchCampaign = function () {
                    getCampaignList();
                }
                vm.closeCampaignPanel = function () {
                    mvvm.campaignPanel = false;
                }
                vm.clickCampaign = function () {
                    var campaign = $(this);
                    GetCampaignById(campaign.attr("key"))
                    mvvm.campaignPanel = false;
                    mvvm.showCampaign = true
                }
                vm.mousedownstop = function (e) {
                    e.stopPropagation()
                }

                vm.customerIds = ""
                vm.clickCustomer = function (item) {
                    mvvm.customerIds = item.Id == mvvm.customerIds ? "" : item.Id;
                    GetSalesCustomer(mvvm.customerIds)
                }

                vm.selectedId = 0
                vm.getCustomer = function (val) {
                    mvvm.selectedId = val
                    GetCustomer(val, 0)
                }
                //员工
                vm.employeeTreeOpts = {
                    showBtnBar: true,
                    okCall: function (tree, pannel) {
                        var nodes=tree.getCheckedNodes()
                        var uids = where(nodes, function (item) { return item.iconSkin == "emp" }, "Id");
                        if (uids.length == 0) {
                            messageBox.warning("请选择员工！");
                            return false;
                        }
                        var type = 2;
                        mvvm.selectedId = type
                        var isAll = findArr(nodes, 1);
                        GetCustomer(type, isAll ? null : uids);
                    },
                    treeopts: {
                        check: {
                            enable: true,
                            chkStyle: "checkbox",
                            chkboxType: { "Y": "ps", "N": "ps" }
                        },
                        async: {
                            url: function (treeId, treeNode) {
                                var url = '/Settings/GetGroupPostUser/1020101'//
                                vmtree = avalon.vmodels.employeeTreeId
                                if (vmtree && vmtree.q && vmtree.q !== vmtree.qcopy) {
                                    url += '?empName=' + vmtree.q
                                }
                                return url
                            },
                            dataFilter: notPostFilter(true)
                        }
                    }
                }
                //左边导航子项显示隐藏
                vm.ShowSubNav = ''
                vm.onSubNav = function (subname) {
                    if (mvvm.ShowSubNav == subname)
                        mvvm.ShowSubNav = ''
                    else
                        mvvm.ShowSubNav = subname
                }

                vm.onSelectCampaign = function () {
                    var campaignid = $(this).attr("campaignsId")
                    queryData.campaignId = campaignid

                    GetBelongToData(campaignid)
                    GetTargetCustoms(queryData)
                }

                vm.customerkey = ''
                vm.onCustomerSearch = function () {
                    queryData.key = mvvm.customerkey
                    GetTargetCustoms(queryData)
                }
                vm.viewCustomer = function (cid) {
                    goto('/Customer/DetailCustomer/' + cid, true);
                }


                vm.tabNum = 1
                vm.tabPath = '#/Market/SalesOpportunities'
                vm.onShowTab = function (tab) {
                    if (tab == 1) {
                        mvvm.tabPath = '#/Market/SalesOpportunities'
                    } else {
                        mvvm.tabPath = '#/Market/DocumentaryOffer'
                    }
                    mvvm.tabNum = tab
                }
                vm.tabNum2 = 1
                vm.tabPath2 = '#/Market/Contract'
                vm.onShowTab2 = function (tab) {
                    if (tab == 1) {
                        mvvm.tabPath2 = '#/Market/Contract'
                    } else {
                        mvvm.tabPath2 = '#/Market/ProductList'
                    }
                    mvvm.tabNum2 = tab
                }

                vm.onSearchCustomer = function () {
                    var customerid = $(this).attr("customerId")
                    GetSalesData(customerid)
                }

                vm.chkdepart = false
                vm.chktimespan = false

                vm.showCampaign = false
                vm.departId = 0
                vm.employeeId = 0
                vm.startdate = ''
                vm.enddate = ''
                vm.onSearchSaleData = function () {
                    if (!mvvm.chkdepart) {
                        queryData.departId = 0
                        queryData.employeeId = 0
                    }
                    else {
                        queryData.departId = mvvm.departId
                        queryData.employeeId = mvvm.employeeId
                    }
                    mvvm.showItem.dateSpan = ''
                    if (mvvm.chktimespan) {
                        queryData.sdate = ''
                        queryData.ddate = ''
                    } else {
                        queryData.sdate = mvvm.startdate
                        queryData.ddate = mvvm.enddate
                        if (queryData.sdate != '')
                            mvvm.showItem.dateSpan = "时间段：" + mvvm.startdate + "~" + mvvm.enddate + ""
                    }
                    GetTargetCustoms(queryData)
                }

                vm.showItem = {}
                vm.remove = function () {
                    var searchKey = this.$vmodel.$key;
                    mvvm.showItem[searchKey] = ''
                    if (searchKey == 'departName') {
                        mvvm.chkdepart = false

                    } else if (searchKey == 'dateSpan') {
                        queryData.sdate = ''
                        queryData.ddate = ''
                        mvvm.chktimespan = false


                    }
                    GetTargetCustoms(queryData)
                }

                vm.stradateOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        mvvm.startdate = formatDate
                        mvvm.chktimespan = true
                        GetTargetCustoms(queryData)

                    }
                }

                vm.enddateOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        mvvm.enddate = formatDate
                        mvvm.chktimespan = true
                        GetTargetCustoms(queryData)
                    }
                }

            })

            //取所属战役
            function getCampaignList() {
                var key = mvvm.campaignKey;
                $.get('/Market/Campaign/', { "key": key }, function (ret) {
                    mvvm.campaignList = ret.data.Source;
                })
            }

            //取战役
            function GetBelongToData(campaignid) {
                $.get('/Market/BelongToData/', { "top": 10, "campaignId": campaignid }, function (ret) {
                    if (campaignid == 0) {
                        mvvm.showCampaign = false;
                        GetSalesData(0);
                    } else {
                        mvvm.showCampaign = true;
                        mvvm.MarketingCampaign = ret.data.campaignlist[0]
                        GetSalesData(ret.data.campaignlist[0].Id);
                    }
                })
            }
            //选中战役
            function GetCampaignById(campaignid) {
                $.get('/Market/GetCampaignById/', { "campaignId": campaignid }, function (ret) {
                    mvvm.MarketingCampaign = ret.data
                    GetSalesData(campaignid);
                })
            }

            //取跟中客户
            function GetCustomer(type, ids) {
                var data = { type: type };
                if (ids) data.ids = ids.join(",")
                $.get('/Customer/GetCustomerByType/', data, function (ret) {
                    if (ret.data)
                        mvvm.customerControllerList = ret.data
                })
            }


            //创建筛选对象
            var searchItem = {
                departName: '',
                employeeName: '',
                dateSpan: '',
            }
            mvvm.showItem = avalon.mix({}, searchItem);
            //取目标客户
            var customsCondition = {
                "campaignId": 0,
                "departId": 0,
                "employeeId": 0,
                "sdate": '',
                "edate": '',
                "key": '',
                "pageIndex": 1,
                "pageSize": 20
            }
            var queryData = avalon.mix({}, customsCondition);
            function GetTargetCustoms(Data) {

            }
            //取销售机会，跟单报价，合同订单，业务明细
            function GetSalesData(marketingcampaignid) {
                $.get('/Market/SalesOpportunities/', { "marketingcampaignid": marketingcampaignid, "pageIndex": 1, "pageSize": 20,onlyMe:true }, function (ret1) {
                    mvvm.salesopportunities = ret1.data.Source //销售机会 
                    $.get('/Market/DocumentaryOffer/', { "marketingcampaignid": marketingcampaignid, "pageIndex": 1, "pageSize": 20,onlyMe:true }, function (ret2) {
                        mvvm.documentaryoffers = ret2.data.Source //跟单报价 
                        $.get('/Market/Contract/', { "marketingcampaignid": marketingcampaignid, "orderValue": 1, "pageIndex": 1, "pageSize": 20,onlyMe:true }, function (ret3) {
                            mvvm.marketcontracts = ret3.data.Source   //合同订单 
                            $.get('/Market/ProductList/', { "marketingcampaignid": marketingcampaignid, "pageIndex": 1, "pageSize": 20,onlyMe:true }, function (ret4) {
                                mvvm.marketproducts = ret4.data.Source  //业务明细
                            })
                        })
                    })
                })
            }
            //取销售机会，跟单报价，合同订单，业务明细
            function GetSalesCustomer(customerId) {
                $.get('/Market/SalesOpportunities/', { "customerid": customerId, "pageIndex": 1, "pageSize": 20, onlyMe: true }, function (ret1) {
                    mvvm.salesopportunities = ret1.data.Source //销售机会 
                    $.get('/Market/DocumentaryOffer/', { "customerid": customerId, "pageIndex": 1, "pageSize": 20, onlyMe: true }, function (ret2) {
                        mvvm.documentaryoffers = ret2.data.Source //跟单报价 
                        $.get('/Market/Contract/', { "customerid": customerId, "orderValue": 1, "pageIndex": 1, "pageSize": 20, onlyMe: true }, function (ret3) {
                            mvvm.marketcontracts = ret3.data.Source   //合同订单 
                            $.get('/Market/ProductList/', { "customerid": customerId, "pageIndex": 1, "pageSize": 20, onlyMe: true }, function (ret4) {
                                mvvm.marketproducts = ret4.data.Source  //业务明细
                            })
                        })
                    })
                })
            }

            GetBelongToData(0)
            GetCustomer(0, 0)
            var root = CBCRM.gps[1]
            CBCRM.getChildMenus(root, 1, true).forEach(function (m) {
                var children = CBCRM.getChildMenus(m, 1, true)
                    , menu
                if (m.isAction)
                    return true
                menu = avalon.mix({}, m)
                if (children.length) {
                    menu.children = children
                }
                mvvm.menus.push(menu)
            })
            CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
        }

        ///销售管理-营销战役
        , Campaign: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM, that = this, init = false;
            var kind1;
            var mvvm = CBCRM.define('marketingcampaign', function (vm) {
                vm.destroy = function () {
                    mvvm.destroyui(["campaignSponsorTree"]);
                }
                vm.lang = lang
                vm.entity = {}
                vm.action = 'list'
                vm.title = ''
                vm.describe = ''
                vm.tab = "tab1";
                vm.campaignList = []
                vm.campaignpaing = {
                    paging: function () {
                        if (!init) {
                            init = true;
                            return;
                        }
                        var thatpage = this
                        queryData.pageSize = thatpage.pagesize
                        queryData.pageIndex = thatpage.currentindex + 1
                        getCampaignList(queryData);
                    }
                }

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

                vm.ADD = true
                vm.DELETE = true

                //左边导航子项显示隐藏
                vm.ShowSubNav = ''
                vm.onSubNav = function (subname) {
                    if (mvvm.ShowSubNav == subname)
                        mvvm.ShowSubNav = ''
                    else
                        mvvm.ShowSubNav = subname
                }

                //下拉发起人配置
                vm.selectSponsor = function () {
                    plugins.selectUser({
                        dataAuth: 2020101,
                        callback: function (us) {
                            var u = us[0];
                            mvvm.entity.CampaignSponsor = u.Id;
                            mvvm.entity.CampaignSponsorDisplay = u.FullName;
                        }
                    });
                }

                //时间范围配置
                vm.startdateOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        mvvm.entity.StartDate = formatDate
                    }
                }
                vm.enddateOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        mvvm.entity.EndDate = formatDate
                    }
                }
                //执行开始时间，执行结束时间  
                vm.currIndex = 0
                vm.setIndex = function () {
                    var curItem = this.$vmodel,
                        index = curItem.$index
                    mvvm.currIndex = index
                }
                vm.executionstartdateOpts = {
                    format: '%Y-%m-%d %H:%M',
                    onSelect: function (date, formatDate, format) {
                        var combatmmissions = mvvm.combatmmissionsList[mvvm.currIndex]
                        combatmmissions.ExecutionStartTime = formatDate
                    }
                }
                vm.executionenddateOpts = {
                    format: '%Y-%m-%d %H:%M',
                    onSelect: function (date, formatDate, format) {
                        var combatmmissions = mvvm.combatmmissionsList[mvvm.currIndex]
                        combatmmissions.ExecutionEndTime = formatDate
                    }
                }
                vm.setEmps = function (item) {
                    dataAuth: 2020101,
                    plugins.selectUser({
                        callback: function (us) {
                            var u = us[0];
                            item.EmployeeName = u.FullName;
                            item.EmployeeId = u.Id;
                        }
                    });
                }
                vm.setCons = function (item) {
                    dataAuth: 2020101,
                    plugins.selectUser({
                        callback: function (us) {
                            var u = us[0];
                            item.ConscientiousPersonDisplay = u.FullName;
                            item.ConscientiousPerson = u.Id;
                        }
                    });
                }

                //关键字搜索
                vm.search = function () {
                    if (mvvm.keyword) {
                        queryData.key = mvvm.keyword;
                        getCampaignList(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;
                    getCampaignList(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] = ''
                    getCampaignList(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);
                    getCampaignList(queryData);
                }
                //快速筛选 
                vm.itemClick = function () {
                    $(this).attr('class', '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;
                            }
                        }
                    }
                    getCampaignList(queryData);
                }

                //新增
                vm.doadd = function () {
                    mvvm.action = 'add'
                    //mvvm.title = '新增营销战役'
                    //mvvm.describe = '新增一条营销机会'

                    mvvm.entity = modelFactory.create('Campaign')
                    mvvm.entity.CampaignType = mvvm.campaignTypeData.length > 0 ? mvvm.campaignTypeData[0].Id : ''
                    /*赋值发起人*/
                    var currUser = CBCRM.memberShip
                    mvvm.entity.CampaignSponsor = currUser.Id;
                    mvvm.entity.CampaignSponsorDisplay = currUser.FullName;
                    /*字典*/
                    InitDataForAdd()
                    InCometWindow("新增营销战役");
                }
                //编辑
                vm.doedit = function () {
                    mvvm.action = 'edit'
                    mvvm.title = '编辑营销战役'
                    mvvm.describe = '编辑一条营销机会'
                    var id = $(this).val()
                    mvvm.campaignList.$model.forEach(function (item) {
                        if (item.Id == id) {
                            mvvm.entity = item
                            GetRelevanceData(id)

                        }
                    })

                    InCometWindow("编辑销售战役");


                }
                //查看
                vm.doview = function (id) {
                    mvvm.campaignList.$model.forEach(function (item) {
                        if (item.Id == id) {
                            mvvm.entity = item
                            GetRelevanceData(id)
                            mvvm.action = "view"
                        }
                    })
                    viewWindow("查看营销战役");
                }
                //删除
                vm.dodel = function () {
                    var index = parseInt($(this).attr('index'));
                    var id = $(this).val();
                    messageBox.confirm('确定删除此数据吗？', function () {
                        $.post('/Market/CampaignDel/' + id, {}, function (ret) {
                            if (ret.result)
                                mvvm.campaignList.removeAt(index);
                            messageBox.succeed(ret.message);
                        })
                    });
                }
                //批量删除
                vm.doalldel = function () {
                    var deleteIds = checkAll();
                    messageBox.confirm('确定删除选中的数据吗？', function () {
                        $.post('/Market/CampaignAllDel/', deleteIds, function (ret) {
                            if (ret.result) {
                                getCampaignList(queryData);
                                messageBox.succeed(ret.message);
                            }
                        });
                    });
                }
                //取消
                vm.onCancel = function () {
                    mvvm.action = "list"
                }
                //保存
                vm.onSubmit = function () {
                    var model = mvvm.entity.$model;

                    mvvm.resandeqList.$model.forEach(function (item, index) {
                        model["REList[" + index + "].Id"] = item.Id
                        model["REList[" + index + "].JobTitle"] = item.JobTitle
                        model["REList[" + index + "].EmployeeId"] = item.EmployeeId
                        model["REList[" + index + "].EmployeeName"] = item.EmployeeName
                        model["REList[" + index + "].MainTasks"] = item.MainTasks
                        model["REList[" + index + "].AddBy"] = item.AddBy
                        model["REList[" + index + "].MarketingCampaign"] = item.MarketingCampaign
                    })
                    mvvm.materialgearList.$model.forEach(function (item, index) {
                        model["MGList[" + index + "].Id"] = item.Id
                        model["MGList[" + index + "].MaterialName"] = item.MaterialName
                        model["MGList[" + index + "].Num"] = item.Num
                        model["MGList[" + index + "].Price"] = item.Price
                        model["MGList[" + index + "].Remark"] = item.Remark
                        model["MGList[" + index + "].MarketingCampaign"] = item.MarketingCampaign
                    })
                    mvvm.matingtrainList.$model.forEach(function (item, index) {
                        model["MTList[" + index + "].Id"] = item.Id
                        model["MTList[" + index + "].MatingTrainName"] = item.MatingTrainName
                        model["MTList[" + index + "].Remark"] = item.Remark
                        model["MTList[" + index + "].MarketingCampaign"] = item.MarketingCampaign
                    })
                    mvvm.combatmmissionsList.$model.forEach(function (item, index) {
                        model["CMList[" + index + "].Id"] = item.Id
                        model["CMList[" + index + "].TaskMajorItem"] = item.TaskMajorItem
                        model["CMList[" + index + "].TaskSmallItem"] = item.TaskSmallItem
                        model["CMList[" + index + "].ConscientiousDepartment"] = item.ConscientiousDepartment
                        model["CMList[" + index + "].ConscientiousPerson"] = item.ConscientiousPerson
                        model["CMList[" + index + "].ConscientiousPersonDisplay"] = item.ConscientiousPersonDisplay
                        model["CMList[" + index + "].ExecutionStartTime"] = item.ExecutionStartTime
                        model["CMList[" + index + "].ExecutionEndTime"] = item.ExecutionEndTime
                        model["CMList[" + index + "].EstimatedCost"] = item.EstimatedCost
                        model["CMList[" + index + "].MainContent"] = item.MainContent
                        model["CMList[" + index + "].MarketingCampaign"] = item.MarketingCampaign
                    })
                    model.CampaignDescriptionAndSpecificPrograms = kind1.html();
                    var herf = mvvm.action == "add" ? "/Market/CampaignAdd/" : "/Market/CampaignUpdate/";
                    $.post(herf + model.Id, model, function (ret) {
                        CBCRM.showResult(ret, function () {
                            if (ret.result) {
                                var indialog = art.dialog.list['campaignForm']
                                if (indialog) indialog.close()
                                getCampaignList(queryData)
                                mvvm.action = "list"
                            }
                        })

                    });
                    return false;
                }
                //切换界面
                vm.onAction = function (actiontype) {
                    mvvm.action = actiontype;
                }

                vm.resandeqList = []  //人员配置
                vm.materialgearList = [] //物料装备
                vm.matingtrainList = [] //配套培训
                vm.combatmmissionsList = [] //具体战斗任务和相关采购计划
                vm.comMmisSum = 0 // 具体战斗任务和相关采购计划-预算合计
                //计算预算合计
                vm.onSumCost = function () {
                    var cost = 0
                    mvvm.combatmmissionsList.$model.forEach(function (item, index) {
                        var currCost = 0
                        if (item.EstimatedCost) currCost = parseFloat(item.EstimatedCost)
                        cost = cost + currCost;
                    })
                    mvvm.comMmisSum = cost
                }
                //编辑界面列表全选
                vm.onChkAll = function (obj) {
                    var chkVal = $(this).attr("checked");
                    $("input[name='" + obj + "']").each(function (index, item) {
                        item.checked = chkVal
                    })
                }
                //战役资源配备-表格新加一行
                vm.onRelevanceAdd = function (obj) {
                    switch (obj) {
                        case "resandeq":
                            mvvm.resandeqList.push(avalon.mix({}, resandeqData))
                            break
                        case "materialgear":
                            mvvm.materialgearList.push(avalon.mix({}, materialgearData))
                            break
                        case "matingtrain":
                            mvvm.matingtrainList.push(avalon.mix({}, matingtrainData))
                            break
                        case "combatmmissions":
                            mvvm.combatmmissionsList.push(avalon.mix({}, combatmmissionsData))
                            break
                    }
                }
                //战役资源配备-表格删除一行
                vm.onRelevanceDel = function (obj) {
                    var index = parseInt($(this).attr('index'))
                    switch (obj) {
                        case "resandeq":
                            mvvm.resandeqList.removeAt(index)
                            break
                        case "materialgear":
                            mvvm.materialgearList.removeAt(index);
                            break
                        case "matingtrain":
                            mvvm.matingtrainList.removeAt(index);
                            break
                        case "combatmmissions":
                            mvvm.combatmmissionsList.removeAt(index);
                            mvvm.onSumCost();
                            break
                    }
                }
                //战役资源配备-表格删除所有选中行
                vm.onRelevanceAllDel = function (obj) {
                    var list
                    switch (obj) {
                        case "resandeq":
                            list = mvvm.resandeqList
                            break
                        case "materialgear":
                            list = mvvm.materialgearList
                            break
                        case "matingtrain":
                            list = mvvm.matingtrainList;
                            break
                        case "combatmmissions":
                            list = mvvm.combatmmissionsList;
                            break
                    }
                    $("input[name='" + obj + "']:checked").each(function (index, item) {
                        list.removeAt(parseInt($(this).attr('index')))
                        if (obj == "combatmmissions") mvvm.onSumCost();
                    })
                }
                //上传文件
                vm.uploadFiles = function () {
                    var upwin = CBCRM.upload(true, function (node, data, file) {
                        mvvm.entity.Files = '/upload/' + file.Path;
                        upwin.close();
                    });
                    
                }
                vm.tabChange = function () {
                    mvvm.tab = $(this).attr("val")
                }

            })
            var action = that.params.action;
            mvvm.entity = modelFactory.create('Campaign');

            //创建查询对象并提交
            var createDate = {
                campaigntype: 0,
                startdatespan: 0,
                key: '',
                pageSize: 20,
                pageIndex: 1
            }
            //创建筛选对象
            var searchItem = {
                campaigntype: '',
                startdatespan: ''
            }

            //创建编辑界面关联表数据对象
            var resandeqData = { Id: 0, JobTitle: "", EmployeeId: 0, EmployeeName: "", MainTasks: "", AddBy: 0, MarketingCampaign: 0 }
            var materialgearData = { Id: 0, MaterialName: "", Num: "", Price: "", Remark: "", MarketingCampaign: 0 }
            var matingtrainData = { Id: 0, MatingTrainName: "", Remark: "", MarketingCampaign: 0 }
            var combatmmissionsData = {
                Id: 0, TaskMajorItem: "", TaskSmallItem: "", ConscientiousDepartment: "", ConscientiousPerson: 0, ConscientiousPersonDisplay: ""
                                 , ExecutionStartTime: "", ExecutionEndTime: "", EstimatedCost: "", MainContent: "", MarketingCampaign: 0
            }
            if (that.params.id && action == 'key') {
                key = decodeURI(that.params.id);
                createDate.key = key;
                mvvm.keyword = key;
            }
            var queryData = avalon.mix({}, createDate);
            mvvm.showItem = avalon.mix({}, searchItem);
            InitDataItem()

            function getCampaignList(data, callback, view) {
                $.get('/Market/Campaign/', data || {}, function (ret) {
                    mvvm.campaignList = ret.data.Source;
                    if (!view) avalon.vmodels.upaing.total = ret.data.RecordTotal;

                    mvvm.ADD = ret.data.ADD
                    mvvm.DELETE = ret.data.DELETE
                    if (callback) callback(ret);
                })
            }

            //从字典取数据
            function InitDataItem() {
                $.get('/Settings/Dictionary/', { "id": 100030 }, function (ret) {
                    mvvm.campaignTypeData = ret.data
                })
            }

            // 新增初始化数据
            function InitDataForAdd() {
                mvvm.resandeqList = [{ Id: 0, JobTitle: "战役指挥官", EmployeeId: 0, EmployeeName: "", MarketingCampaign: 0, MainTasks: "", AddBy: 0 },
                                    { Id: 0, JobTitle: "参谋统筹组成员", EmployeeId: 0, EmployeeName: "", MarketingCampaign: 0, MainTasks: "", AddBy: 0 },
                                    { Id: 0, JobTitle: "后勤保障组成员", EmployeeId: 0, EmployeeName: "", MarketingCampaign: 0, MainTasks: "", AddBy: 0 },
                                    { Id: 0, JobTitle: "媒体传播组成员", EmployeeId: 0, EmployeeName: "", MarketingCampaign: 0, MainTasks: "", AddBy: 0 },
                                    { Id: 0, JobTitle: "前方参战人员", EmployeeId: 0, EmployeeName: "", MarketingCampaign: 0, MainTasks: "", AddBy: 0 }]
                mvvm.materialgearList = [{ Id: 0, MaterialName: "X展架", Num: "", Price: "", Remark: "", MarketingCampaign: 0 }]
                mvvm.matingtrainList = [avalon.mix({}, matingtrainData)]
                mvvm.combatmmissionsList = [avalon.mix({}, combatmmissionsData)]
            }

            //获取人员配置、物料装备、配套培训、具体战斗任务和相关采购计划数据
            function GetRelevanceData(Id) {
                $.get('/Market/GetRelevance/', { "Id": Id }, function (ret) {
                    mvvm.resandeqList = ret.data.resEquList
                    mvvm.materialgearList = ret.data.matGearList
                    mvvm.matingtrainList = ret.data.matTraList
                    mvvm.combatmmissionsList = ret.data.comMmisList
                    mvvm.comMmisSum = ret.data.comMmisSum
                })
            }
            function InCometWindow(title) {
                mvvm.tab = "tab1";
                var dialog = messageBox.openHtml(title, '780px', '500px', '', [{
                    name: '确定',
                    focus: true,
                    callback: function () {

                        mvvm.onSubmit();

                        return false;
                    }
                }], function () {
                    if (avalon.vmodels.campaignSponsorTree)
                        avalon.vmodels.campaignSponsorTree.destroy()
                    //if (avalon.vmodels.belongToTree2)
                    //    avalon.vmodels.belongToTree2.destroy();
                    //if (avalon.vmodels.setParetCustomer)
                    //    avalon.vmodels.setParetCustomer.destroy();
                }, 'campaignForm'

              );

                var content = $(dialog.content())
                content.attr('ms-include', 'campaignForm')
                content.parent().css('vertical-align', 'top');

                avalon.scan(content[0], mvvm)

                avalon.nextTick(function () {
                    if (kind1) kind1.remove();
                    kind1 = setEditerSimple('SpecificPrograms', '89%', '180px');

                    kind1.html(mvvm.entity.$model.CampaignDescriptionAndSpecificPrograms);
                })
            }

            function viewWindow(title) {
                mvvm.tab = "tab1";
                var dialog = openTmpl({
                    vm: mvvm, title: title, w: 820, h: 400,
                    tmplId: "viewTemplate", tmpl: tmpl
                });
            }
            if (that.params.id && action == "view") {
                getCampaignList({ id: that.params.id }, function (ret) {
                    mvvm.doview(that.params.id);
                }, true);

            } else {
                getCampaignList(queryData);
                require('commonui', function () {
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                })
            }
        }

        ///销售管理-市场调查反馈
        , ProbeFeedback: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM;
            that = this
            var kind1;
            var mvvm = CBCRM.define('marketingfeedback', function (vm) {
                vm.lang = lang
                vm.entity = {}
                vm.feedbackList = []
                vm.feedbackpaing = {
                    paging: function () {
                        var thatpage = this
                        queryData.pageSize = thatpage.pagesize
                        queryData.pageIndex = thatpage.currentindex + 1
                        getFeedbackList(queryData);
                    }
                }

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

                vm.ADD = true
                vm.DELETE = true

                //左边导航子项显示隐藏
                vm.ShowSubNav = ''
                vm.onSubNav = function (subname) {
                    if (mvvm.ShowSubNav == subname)
                        mvvm.ShowSubNav = ''
                    else
                        mvvm.ShowSubNav = subname
                }
                //下拉调查反馈人配置
                vm.selectFeedbackPerson = function () {
                    plugins.selectUser({
                        dataAuth: 2020201,
                        callback: function (us) {
                            var u = us[0];
                            mvvm.entity.ProbeFeedbackPerson = u.Id;
                            mvvm.entity.ProbeFeedbackPersonDisplay = u.FullName;
                            mvvm.entity.ProbeFeedbackDepartment = u.GroupId;
                        }
                    });
                }
                //下拉共享给配置
                vm.selectShareTo = function () {
                    var ids = [];
                    if (mvvm.entity.ShareTo) ids = mvvm.entity.ShareTo.split(",");
                    plugins.selectUser({
                        dataAuth: 2020201,
                        listData:ids,
                        multiple: true,
                        required:false,
                        callback: function (us) {
                            var ids = [], names = [];
                            us.forEach(function (u) {
                                ids.push(u.Id);
                                names.push(u.FullName);
                            });
                            mvvm.entity.ShareTo = ids.join(",");
                            mvvm.entity.ShareToDisplay = names.join(",");
                        }
                    });
                }
                
                //关键字搜索
                vm.search = function () {
                    if (mvvm.keyword) {
                        queryData.key = mvvm.keyword;
                        getFeedbackList(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;
                    getFeedbackList(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] = ''
                    getFeedbackList(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);
                    getFeedbackList(queryData);
                }
                //快速筛选 
                vm.itemClick = function () {
                    $(this).attr('class', '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;
                            }
                        }
                    }
                    getFeedbackList(queryData);
                }

                //新增
                vm.doadd = function () {
                    mvvm.entity = modelFactory.create('ProbeFeedback')
                    mvvm.entity.ProbeType = mvvm.probeTypeData.length > 0 ? mvvm.probeTypeData[0].Id : ''
                    mvvm.entity.ProbeFeedbackPerson = CBCRM.memberShip.Id
                    mvvm.entity.ProbeFeedbackPersonDisplay = CBCRM.memberShip.FullName
                    mvvm.entity.AddBy.Id = CBCRM.memberShip.Id
                    mvvm.entity.AddBy.FullName = CBCRM.memberShip.FullName
                    FormSubmit("新增市场调查反馈")
                }
                //编辑
                vm.doedit = function () {
                    var id = $(this).val()
                    mvvm.feedbackList.$model.forEach(function (item) {
                        if (item.Id == id) {
                            mvvm.entity = item
                        }
                    })
                    FormSubmit("编辑市场调查反馈")
                }
                //查看
                vm.doview = function () {
                    var id = $(this).val()
                    mvvm.feedbackList.$model.forEach(function (item) {
                        if (item.Id == id) {
                            mvvm.entity = item
                        }
                    })

                    var dialog = messageBox.openHtml('市场调查反馈详细', '880px', '300px', '');
                    var content = $(dialog.content())
                    content.attr('ms-include', 'viewTemplate')
                    avalon.scan(content[0], mvvm)

                }
                //查看战役
                vm.campaigndoview = publicFn.campaigndoview;
                //查看市场活动
                vm.activitydoview = publicFn.activitydoview;

                //删除
                vm.dodel = function () {
                    var index = parseInt($(this).attr('index'));
                    var id = $(this).val();
                    messageBox.confirm('确定删除此数据吗？', function () {
                        $.post('/Market/ProbeFeedbackDel/' + id, {}, function (ret) {
                            if (ret.result)
                                mvvm.feedbackList.removeAt(index);
                            messageBox.succeed(ret.message);
                        })
                    });
                }
                //批量删除
                vm.doalldel = function () {
                    var deleteIds = checkAll();
                    messageBox.confirm('确定删除选中的数据吗？', function () {
                        $.post('/Market/ProbeFeedbackAllDel/', deleteIds, function (ret) {
                            if (ret.result) {
                                getFeedbackList(queryData);
                                messageBox.succeed(ret.message);
                            }
                        });
                    });
                }
                //选择所属战役
                vm.campaignList = []
                vm.campaignPanel = false
                vm.campaignKey = ''
                vm.selectCampaign = function () {
                    $('body').bind('mousedown', function () {
                        mvvm.campaignPanel = false
                        $('body').unbind('mousdown')
                    })
                    getCampaignList();
                    mvvm.campaignPanel = true;
                }
                vm.searchCampaign = function () {
                    getCampaignList();
                }
                vm.closeCampaignPanel = function () {
                    mvvm.campaignPanel = false;
                }
                vm.clickCampaign = function () {
                    var campaign = $(this);
                    mvvm.entity.MarketingCampaign = campaign.attr("key");
                    mvvm.entity.MarketingCampaignDisplay = campaign.attr("alt");
                    mvvm.campaignPanel = false;
                }
                vm.clearCampaignValue = function () {
                    mvvm.entity.MarketingCampaign = ''
                    mvvm.entity.MarketingCampaignDisplay = ''
                }
                //选择所属活动
                vm.activityList = []
                vm.activityPanel = false
                vm.activityKey = ''
                vm.selectActivity = function () {
                    $('body').bind('mousedown', function () {
                        vm.activityPanel = false
                        $('body').unbind('mousedown')
                    })
                    getActivityList();
                    mvvm.activityPanel = true;
                }
                vm.searchActivity = function () {
                    getActivityList();
                }
                vm.closeActivityPanel = function () {
                    mvvm.activityPanel = false;
                }
                vm.clickActivity = function () {
                    var activity = $(this);
                    mvvm.entity.MarketActivity = activity.attr("key");
                    mvvm.entity.MarketActivityDisplay = activity.attr("alt");
                    mvvm.activityPanel = false;
                }
                vm.clearActivityValue = function () {
                    mvvm.entity.MarketActivity = ''
                    mvvm.entity.MarketActivityDisplay = ''
                }
                vm.mousedownstop = function (e) {
                    e.stopPropagation()
                }

                //上传文件
                vm.uploadFiles = function () {
                    var upwin = CBCRM.upload(true, function (node, data, file) {
                        mvvm.entity.Files = '/upload/' + file.Path;
                        upwin.close();
                    });
                }
            })
            var action = that.params.action;
            mvvm.entity = modelFactory.create('ProbeFeedback');

            //保存
            function FormSubmit(title) {
                var dialog = messageBox.openHtml(title, '860px', '300px', '', [{
                    name: '提交',
                    focus: true,
                    callback: function () {
                        var model = mvvm.entity.$model;
                        model.ProbeDescribe = kind1.html();
                        var url = (model.Id == 0 ? "/Market/ProbeFeedbackAdd/" : "/Market/ProbeFeedbackUpdate/");
                        $.post(url + model.Id, model, function (ret) {
                            if (ret.result) {
                                messageBox.ok(ret.message, function () { getFeedbackList(queryData); messageBox.close(); });
                            }
                            else {
                                messageBox.fail(ret.message, function () { });
                            }
                        })

                        return false;
                    }
                }]);

                var content = $(dialog.content())
                content.attr('ms-include', 'formTemplate')
                avalon.scan(content[0], mvvm)
                avalon.nextTick(function () {
                    if (kind1) kind1.remove();
                    kind1 = setEditerSimple('ProbeDescribe', '99%', '250px');
                    kind1.html(mvvm.entity.$model.ProbeDescribe);
                })
            }

            //创建查询对象并提交
            var createDate = {
                probetype: 0,
                startdatespan: 0,
                key: '',
                pageSize: 20,
                pageIndex: 1
            }
            //创建筛选对象
            var searchItem = {
                probetype: '',
                startdatespan: ''
            }
            if (that.params.id && action == 'key') {
                key = decodeURI(that.params.id);
                createDate.key = key;
                mvvm.keyword = key;
            }
            var queryData = avalon.mix({}, createDate);
            mvvm.showItem = avalon.mix({}, searchItem);
            InitDataItem()

            function getFeedbackList(data) {
                $.get('/Market/ProbeFeedback/', data || {}, function (ret) {
                    mvvm.feedbackList = ret.data.Source
                    avalon.vmodels.upaing.total = ret.data.RecordTotal

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

            //从字典取数据
            function InitDataItem() {
                $.get('/Settings/Dictionary/', { "id": 100047 }, function (ret) {
                    mvvm.probeTypeData = ret.data
                })
            }

            //取所属战役
            function getCampaignList() {
                var key = mvvm.campaignKey;
                $.get('/Market/Campaign/', { "key": key }, function (ret) {
                    mvvm.campaignList = ret.data.Source;
                })
            }
            //取所属活动
            function getActivityList() {
                var key = mvvm.activityKey;
                var campaignId = mvvm.entity.MarketingCampaign;
                $.get('/Market/Activity/', { "key": key, "campaignid": campaignId }, function (ret) {
                    mvvm.activityList = ret.data.Source;
                })
            }

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

        }

        ///销售管理-市场活动
        , Activity: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM,
                that = this

            var mvvm = CBCRM.define('marketingactivity', function (vm) {
                vm.lang = lang
                vm.entity = {}
                vm.action = 'list'
                vm.title = ''
                vm.describe = ''
                vm.activityList = []
                vm.activitypaing = {
                    paging: function () {
                        var thatpage = this
                        queryData.pageSize = thatpage.pagesize
                        queryData.pageIndex = thatpage.currentindex + 1
                        GetActivityList(queryData);
                    }
                }

                vm.tabWidth = 700;
                vm.keyword = ''
                vm.history = []
                vm.showItem = {}
                vm.has = false
                vm.activityTypeData = []
                vm.salesList = [];
                vm.contractList = [];

                vm.ADD = true
                vm.DELETE = true

                //客户分类
                vm.cTypes = {
                    "10107": "终端客户",
                    "10131": "合作伙伴",
                    "10132": "渠道代理商",
                    "10133": "供应商",
                    "10134": "媒体资源",
                };

                //左边导航子项显示隐藏
                vm.ShowSubNav = ''
                vm.onSubNav = function (subname) {
                    if (mvvm.ShowSubNav == subname)
                        mvvm.ShowSubNav = ''
                    else
                        mvvm.ShowSubNav = subname
                }
                //标签切换
                vm.tab = "tab1";
                vm.tabChange = function () {
                    var val = $(this).attr('val');
                    mvvm.tab = val;
                }
                //关键字搜索
                vm.search = function () {
                    if (mvvm.keyword) {
                        queryData.key = mvvm.keyword;
                        GetActivityList(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;
                    GetActivityList(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] = ''
                    GetActivityList(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);
                    GetActivityList(queryData);
                }
                //快速筛选 
                vm.itemClick = function () {
                    $(this).attr('class', '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;
                            }
                        }
                    }
                    GetActivityList(queryData);
                }

                //新增
                vm.doadd = function () {
                    mvvm.createEntity();
                    mvvm.action = 'add'
                    mvvm.title = '新增市场活动'
                    mvvm.describe = '新增一条市场活动'
                    showForm(mvvm.title);
                }
                //编辑
                vm.doedit = function (item) {
                    mvvm.createEntity(item);
                    mvvm.action = 'edit'
                    mvvm.title = '编辑市场活动'
                    mvvm.describe = '编辑一条市场活动'
                    showForm(mvvm.title);
                    getSalesList();
                    getContractList();
                }
                //建立实体对象
                vm.createEntity = function (item) {
                    if (!item) {
                        mvvm.entity = modelFactory.create('MarketActivity');
                        mvvm.entity.DiscountType = '优惠金额';
                        mvvm.entity.ActivityType = mvvm.activityTypeData.length > 0 ? mvvm.activityTypeData[0].Id : ''
                        var curr = CBCRM.memberShip
                        mvvm.entity.ConscientiousPerson = curr.Id
                        mvvm.entity.ConscientiousPersonDisplay = curr.FullName
                        mvvm.entity.AddBy = { Id: '', FullName: curr.FullName };
                    } else {
                        mvvm.entity = item.$model || item;
                        mvvm.entity.CustomerTypeTarget = item.CustomerTypeTarget ? item.CustomerTypeTarget.split(",") : [];
                    }
                    mvvm.entity.IsSalesPromotion += '';
                    var s = [];
                    mvvm.entity.CustomerTypeTarget.forEach(function (item) {
                        if (mvvm.cTypes[item]) s.push(mvvm.cTypes[item]);
                    });
                    mvvm.entity.CustomerTypeTargetDisplay = s.join(",");
                }
                //查看
                vm.doview = function (id) {
                    $.each(mvvm.activityList.$model, function (i, item) {
                        if (item.Id == id) {
                            mvvm.action = 'view'
                            mvvm.createEntity(item);
                            mvvm.entity.IsSalesPromotion = mvvm.entity.IsSalesPromotion ? '是' : '否'
                            showForm("查看市场活动", false);
                            getSalesList();
                            getContractList();
                            return false;
                        }
                    });
                }
                //查看战役
                vm.campaigndoview = publicFn.campaigndoview;
                //查看机会
                vm.salesOpportunitiesdoview = publicFn.salesOpportunitiesdoview;
                //查看合同
                vm.contractdoview = publicFn.contractdoview;
                vm.customerdoview = publicFn.customerdoview;
                //删除
                vm.dodel = function () {
                    var index = parseInt($(this).attr('index'))
                    var id = $(this).attr("value")
                    messageBox.confirm('确定删除此数据吗？', function () {
                        $.post('/Market/ActivityDel/' + id, {}, function (ret) {
                            if (ret.result)
                                mvvm.activityList.removeAt(index)
                            messageBox.succeed(ret.message)
                        })
                    });
                }
                //批量删除
                vm.doalldel = function () {
                    var deleteIds = checkAll()
                    messageBox.confirm('确定删除选中的数据吗？', function () {
                        $.post('/Market/ActivityAllDel/', deleteIds, function (ret) {
                            if (ret.result) {
                                GetActivityList(queryData)
                                messageBox.succeed(ret.message)
                            }
                        });
                    });
                }
                //下拉负责人配置
                vm.selectConscientiousPerson = function () {
                    plugins.selectUser({
                        dataAuth: 2020301,
                        callback: function (us) {
                            var u = us[0];
                            mvvm.entity.ConscientiousPerson = u.Id;
                            mvvm.entity.ConscientiousPersonDisplay = u.FullName;
                            mvvm.entity.ConscientiousDepartment = u.GroupId;
                        }
                    });
                }
                
                //时间范围配置
                vm.startdateOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        mvvm.entity.StartDate = formatDate
                    }
                }
                vm.enddateOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        mvvm.entity.EndDate = formatDate
                    }
                }
                //选择所属战役
                vm.campaignList = []
                vm.campaignPanel = false
                vm.campaignKey = ''
                vm.selectCampaign = function () {
                    $('body').bind('mousedown', function () {
                        mvvm.campaignPanel = false
                        $('body').unbind('mousedown')
                    })
                    getCampaignList();
                    mvvm.campaignPanel = true;
                }
                vm.searchCampaign = function () {
                    getCampaignList();
                }
                vm.closeCampaignPanel = function () {
                    mvvm.campaignPanel = false;
                }
                vm.clickCampaign = function () {
                    var campaign = $(this);
                    mvvm.entity.MarketingCampaign = campaign.attr("key");
                    mvvm.entity.MarketingCampaignDisplay = campaign.attr("alt");
                    mvvm.campaignPanel = false;
                }
                vm.clearCampaignValue = function () {
                    mvvm.entity.MarketingCampaign = ''
                    mvvm.entity.MarketingCampaignDisplay = ''
                }
                //选择所属反馈
                vm.probeFeedbackList = []
                vm.probeFeedbackPanel = false
                vm.probeFeedbackKey = ''
                vm.selectProbeFeedback = function () {
                    $('body').bind('mousedown', function () {
                        mvvm.probeFeedbackPanel = false
                        $('body').unbind('mousedown')
                    })
                    getProbeFeedbackList();
                    mvvm.probeFeedbackPanel = true;
                }
                vm.searchProbeFeedback = function () {
                    getProbeFeedbackList();
                }
                vm.closeProbeFeedbackPanel = function () {
                    mvvm.probeFeedbackPanel = false;
                }
                vm.clickProbeFeedback = function () {
                    var probeFeedback = $(this);
                    mvvm.entity.ProbeFeedback = probeFeedback.attr("key");
                    mvvm.entity.ProbeFeedbackDisplay = probeFeedback.attr("alt");
                    mvvm.probeFeedbackPanel = false;
                }
                vm.clearProbeFeedbackValue = function () {
                    mvvm.entity.ProbeFeedback = ''
                    mvvm.entity.ProbeFeedbackDisplay = ''
                }

                vm.mousedownstop = function (e) {
                    e.stopPropagation()
                }
            })
            var action = that.params.action;
            //mvvm.entity = modelFactory.create('MarketActivity');
            //mvvm.createEntity();

            //创建查询对象并提交
            var createDate = {
                activitytype: 0,
                startdatespan: 0,
                key: '',
                pageSize: 20,
                pageIndex: 1
            }
            //创建筛选对象
            var searchItem = {
                activitytype: '',
                startdatespan: ''
            }
            if (that.params.id && action == 'key') {
                key = decodeURI(that.params.id);
                createDate.key = key;
                mvvm.keyword = key;
            }
            var queryData = avalon.mix({}, createDate);
            mvvm.showItem = avalon.mix({}, searchItem);
            InitDataItem()

            function GetActivityList(data, callback, view) {
                $.get('/Market/Activity/', data || {}, function (ret) {
                    mvvm.activityList = ret.data.Source;
                    if (!view) avalon.vmodels.upaing.total = ret.data.RecordTotal;

                    mvvm.ADD = ret.data.ADD
                    mvvm.DELETE = ret.data.DELETE
                    if (callback) callback(ret);
                })
            }

            //从字典取数据
            function InitDataItem() {
                $.get('/Settings/Dictionary/', { "id": 100050 }, function (ret) {
                    mvvm.activityTypeData = ret.data
                })
            }

            //取所属战役
            function getCampaignList() {
                var key = mvvm.campaignKey;
                $.get('/Market/Campaign/', { "key": key }, function (ret) {
                    mvvm.campaignList = ret.data.Source;
                })
            }
            //取所属反馈 
            function getProbeFeedbackList() {
                var key = mvvm.probeFeedbackKey;
                var campaignId = mvvm.entity.MarketingCampaign
                $.get('/Market/ProbeFeedback/', { "key": key, "campaignid": campaignId }, function (ret) {
                    mvvm.probeFeedbackList = ret.data.Source;
                })
            }
            //取销售机会列表
            function getSalesList() {
                mvvm.salasList = [];
                $.get('/Market/SalesOpportunities/', { "marketActivity": mvvm.entity.Id, pageSize: 1000 }, function (ret) {
                    if (ret.result && ret.data.Source) mvvm.salesList = ret.data.Source;
                })
            }
            //取合同订单列表
            function getContractList() {
                mvvm.contractList = [];
                $.get('/Market/Contract/', { "marketActivity": mvvm.entity.Id, pageSize: 1000 }, function (ret) {
                    if (ret.result && ret.data.Source) mvvm.contractList = ret.data.Source;
                })
            }
            //创建编辑框
            var editor1, editor2;
            function createEditor() {
                if (mvvm.action == "view") return;
                var h = "180px";
                if (editor1) editor1.remove();
                editor1 = setEditerSimple('ExpectedTarget', '97%', h);
                editor1.html(mvvm.entity.ExpectedTarget);
                if (mvvm.action == "edit") {
                    if (editor2) editor2.remove();
                    editor2 = setEditerSimple('ActivitySummary', '100%', '400px');
                    editor2.html(mvvm.entity.ActivitySummary);
                }
            }
            function showForm(title, b) {
                mvvm.tab = "tab1";
                var btns = b == false ? null : [{
                    name: '提交',
                    focus: true,
                    callback: function () {
                        if (editor1) mvvm.entity.ExpectedTarget = editor1.html();
                        if (editor2) mvvm.entity.ActivitySummary = editor2.html();
                        var m = $.extend(true, {}, mvvm.entity.$model);
                        if (m.ActivityTheme == "") {
                            messageBox.warning('请填写活动主题！');
                            return false;
                        }
                        if (!m.StartDate || !m.EndDate) {
                            messageBox.warning('请选择开始与结束时间！');
                            return false;
                        }
                        var url = (m.Id == 0 ? "/Market/ActivityAdd/" : "/Market/ActivityUpdate/" + m.Id);
                        m.CustomerTypeTarget = m.CustomerTypeTarget.join(",");
                        $.post(url, m, function (ret) {
                            CBCRM.showResult(ret, function () {
                                if (ret.data.Id) {
                                    mvvm.entity.Id = ret.data.Id;
                                }
                                if (dialog) dialog.close();
                                GetActivityList(queryData)
                            });
                        })
                        return false;
                    }
                }];
                var tmplid = 'MarketActivity' + mvvm.action + 'Template';
                var dialog= openTmpl({
                    vm: mvvm, title: title, w: mvvm.tabWidth,h:410,
                    tmplId: tmplid, tmpl: tmpl, button: btns,
                    onScan: function () {
                        createEditor();
                    }
                });
            }

            if (that.params.id && action == "view") {
                var id = that.params.id;
                GetActivityList({ id: id }, function (ret) {
                    mvvm.doview(id);
                }, true);
            } else {
                require('commonui', function () {
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                })
            }

            CBCRM.onLoadModuleBefore = function () {
                if (avalon.vmodels.conscientiousPersonTree)
                    avalon.vmodels.conscientiousPersonTree.destroy()
                if (avalon.vmodels.shareToTree)
                    avalon.vmodels.shareToTree.destroy()
                if (avalon.vmodels.customertargetid)
                    avalon.vmodels.customertargetid.destroy()
                avalon.vmodels.Activity = null
            }
        }

        ///销售管理-销售机会
        , SalesOpportunities: function (tmpl, lang, contentId, module,paramData) {
            var CBCRM = avalon.vmodels.CBCRM,
                that = this, detail, vmid = "marketingsalesopportunities"
            var action = that.params.action, paramid = that.params.id;
            var mvvm = CBCRM.define(vmid, function (vm) {
                vm.init = false;
                vm.lang = lang
                vm.entity = {}
                vm.action = 'list'
                vm.title = ''
                vm.describe = ''
                vm.destroy = function () {
                    mvvm.grid1.destroy();
                }
                vm.currNav = 1;
                vm.doChangeNav = function (nav) {
                    mvvm.currNav = nav;
                    var navs = { 2: "/Market/DocumentaryOffer", 3: "/Office/CbCalendar", 4: "/Market/Contract" };
                    var url = navs[nav]
                    if (nav == 1 && mvvm.needReload) mvvm.reloadEntity();
                    if (nav != 1 && url) {
                        url += "/" + mvvm.entity.Id + "/salesopp";
                        var data = {
                            entity: mvvm.entity.$model, hideSalesopp: true,
                            viewOther:mvvm.viewOther,
                            onReloadSalesopp: function () {
                                mvvm.needReload = true;
                            }
                        };
                        goto(url, true,data);
                    }
                }
                vm.needReload = false;
                vm.reloadEntity = function () {
                    mvvm.needReload = false;
                    var id = mvvm.entity.Id;
                    if (!id) return;
                    mvvm.grid1.getEntity(id, function (entity) {
                        mvvm.entity = entity;
                    }, true);
                }
                vm.$otherviewid = "#salesOtherview";
                vm.viewOther = function (tmpl, ovm, select) {
                    ovm.insalesopp = true;
                    var el = $(mvvm.$otherviewid).html("");
                    el.append(select == null ? tmpl : $(tmpl).find(select));
                    avalon.scan(el[0], ovm);
                }
                vm.addContact = function () {
                    var m = mvvm.entity, cid = m.Customer;
                    if (!cid) cid = 0;
                    var url = '/Customer/Contacts/' + cid + '/toadd';
                    var data = {
                        customerId: cid, customerName: m.CustomerDisplay,
                        onSave: function (ret,c) {
                            if (cid) mvvm.setCustomerContacts(cid);
                        }
                    }
                    goto(url, true, data);
                }
                //打印
                vm.doPrint = function () {
                    messageBox.confirm('您确定要打印当前销售机会信息吗？', function () {
                        $("#salesPanelPrint").printArea()
                    })
                }
                vm.viewCustomer = function (cid) {
                    goto('/Customer/DetailCustomer/' + cid, true);
                }
                vm.viewContact = function (id) {
                    goto('/Customer/Contacts/' + id + "/view", true);
                }
                vm.salesopportunitieslist = []
                initQuerys(vm, function (data, name, val, type) {
                    mvvm.grid1.loadData(data);
                });
                vm.queryMore = false;
                vm.createQueryData = function () {
                    return {
                        opportunitiestype: { label: "机会状态", val: "", valLabel: "", next: "followStage", items: [{ label: "不限", val: '', curr: true }] },
                        followStage: { label: "跟单阶段", val: "", valLabel: "", jump: true, items: [{ label: "不限", val: '', curr: true }] },
                        discoverdate: {
                            label: "发现日期", val: "", valLabel: "", next: "expectsigningdate",
                            items: [
                                { label: "不限", val: '', curr: true },
                                { label: "1个月以内", val: '1', curr: false },
                                { label: "3个月以内", val: '3', curr: false },
                                { label: "6个月以内", val: '6', curr: false },
                                { label: "9个月以内", val: '9', curr: false },
                                { label: "12个月以内", val: '12', curr: false }
                            ]
                        },
                        expectsigningdate: {
                            label: "预签日期", val: "", valLabel: "", jump: true,
                            items: [
                                { label: "不限", val: '', curr: true },
                                { label: "1个月以内", val: '1', curr: false },
                                { label: "3个月以内", val: '3', curr: false },
                                { label: "6个月以内", val: '6', curr: false },
                                { label: "9个月以内", val: '9', curr: false },
                                { label: "12个月以内", val: '12', curr: false }
                            ]
                        },
                        customersource: { label: "客户来源", val: "", valLabel: "", items: [{ label: "不限", val: '', curr: true }] },
                        followServerTag: { label: "跟单标签", val: "", valLabel: "", items: [{ label: "不限", val: '', curr: true }] },
                        listType: { label: "列表类型", val: 0, noRemove: true },
                        key: { label: "关键词", val: "", valLabel: "" }
                    }
                }
                vm.queryData = vm.createQueryData();
                vm.listtab = 0;
                vm.listTabs = [
                    { label: "全部机会", val: 0 }, { label: "我的机会", val: 1 }, { label: "下属机会", val: 2 }
                ]
                vm.listtabChange = function (tabid) {
                    if (tabid == mvvm.listtab) return;
                    mvvm.listtab = tabid;
                    mvvm.addQuery("listType", tabid);
                }
                vm.createGrid1 = function () {
                    return createGrid({
                        url: "/Market/SalesOpportunities/",
                        modelFactory: modelFactory,
                        $lang: lang,
                        entityId: "SalesOpportunities",
                        pageid: vmid + "_grid1_page",
                        extParam: {
                            showCustomer: true,
                            colCount: 10
                        },
                        createQuery: function () {
                            var data = mvvm.createQuery();
                            //只取某一客户销售机会
                            var param
                            if (action == 'customer')
                                data.customerid = paramid;
                            return data;
                        },
                        onLoadData: function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            mvvm.ADD = ret.data.ADD
                            mvvm.DELETE = ret.data.DELETE
                            mvvm.NOPAGE = ret.data.NOPAGE
                            if (mvvm.NOPAGE) {
                                mvvm.grid1.destroyPage();
                            }
                        },
                        onRemove: function (deleteIds) {
                            var gvm = this;
                            $.post('/Market/SalesOpportunitiesAllDel/', deleteIds, function (ret) {
                                CBCRM.showResult(ret);
                                if (ret.result) {
                                    gvm.reloadData();
                                    var salesdialog = art.dialog.list['salesdialog']
                                    if (salesdialog) {
                                        salesdialog.close()
                                    }
                                }
                            });
                        }
                    });
                }
                vm.grid1 = vm.createGrid1();
                vm.decumentaryofferforcustomerlist = []
                vm.decumentaryofferpaing = {
                    paging: function () {
                        var thatpage = this
                        queryData.pageSize = thatpage.pagesize
                        queryData.pageIndex = thatpage.currentindex + 1
                        GetDocumentaryOfferList(queryData);
                    }
                }
                //跟单阶段
                vm.stageOpts = {
                    onSetStage: function (item) {
                        mvvm.entity.FollowStage = item.Id
                        mvvm.entity.FollowStageDisplay = item.label
                    }
                }
                vm.stageOpts2 = {
                    readonly: true
                }
                //热度
                vm.hotOpts = {
                    val: 10,
                    valChanged: function (val) {
                        mvvm.entity.OpportunitiesPossibility = val
                    }
                }
                vm.hotOpts2 = {
                    val: 10,
                    readonly: true
                }

                vm.keyword = ''
                vm.history = []
                vm.showItem = {}
                vm.has = false
                vm.opportunitiesstatedata = []
                vm.customersourcedata = []
                vm.followservertagdata = []
                vm.followstagedata = []
                vm.CustomerContactData = []

                vm.ADD = true
                vm.DELETE = true
                vm.NOPAGE = false
                vm.showOnlyList = false

                //左边导航子项显示隐藏
                vm.ShowSubNav = ''
                vm.onSubNav = function (subname) {
                    if (mvvm.ShowSubNav == subname)
                        mvvm.ShowSubNav = ''
                    else
                        mvvm.ShowSubNav = subname
                }

                //机会跟单人
                vm.selectopportunitiesFollow = function () {
                    plugins.selectUser({
                        dataAuth: 2020401,
                        callback: function (us) {
                            var u = us[0];
                            mvvm.entity.OpportunitiesFollow = u.Id;
                            mvvm.entity.OpportunitiesFollowDisplay = u.FullName;
                        }
                    });
                }
                
                vm.selectCustomer = function () {
                    plugins.selectCustomer({
                        type: "contacts",
                        callback: function (cus,cons) {
                            var cu = cus[0];
                            mvvm.entity.CustomerName = cu.Name
                            mvvm.entity.CustomerDisplay=cu.Name
                            mvvm.entity.Customer= cu.Id

                            mvvm.CustomerContactData = [];
                            if (cu.Contacts) {
                                cu.Contacts.forEach(function (c) {
                                    mvvm.CustomerContactData.push(c);
                                });
                            }
                            if (cons.length > 0) {
                                var con = cons[0];
                                mvvm.entity.CustomerContact = con.Id
                                mvvm.entity.CustomerContactDisplay = con.Name
                            }
                        }
                    });
                }
                
                //发现日期
                vm.discoverdateOpts = {
                    onSelect: function (date, formatDate, format) {
                        mvvm.entity.DiscoverDate = formatDate
                    }
                }
                //预计签单日期
                vm.expectsigningdateOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        mvvm.entity.ExpectSigningDate = formatDate
                    }
                }
                //新增
                vm.doadd = function () {
                    mvvm.entity = modelFactory.create('SalesOpportunities')
                    mvvm.entity.State = mvvm.opportunitiesstatedata.length > 0 ? mvvm.opportunitiesstatedata[0].Id + '' : ''
                    mvvm.entity.CustomerSource = mvvm.customersourcedata.length > 0 ? mvvm.customersourcedata[0].Id : ''
                    if (mvvm.followstagedata.length > 0) mvvm.followstagedata[0].curr = true;
                    var currUser = CBCRM.memberShip
                    mvvm.entity.OpportunitiesFollow = currUser.Id;
                    mvvm.entity.OpportunitiesFollowDisplay = currUser.FullName;
                    mvvm.entity.DiscoverDate = GetDateTime();
                    mvvm.hotOpts.val = 10
                    mvvm.followstagedata.forEach(function (f) {
                        f.curr = f.Id == mvvm.followstagedata[0].Id
                    })
                    mvvm.formSubmit('新增销售机会')
                }
                //编辑
                vm.doedit = function (id) {
                    mvvm.grid1.getEntity(id, function (entity) {
                        mvvm.entity = entity;
                        mvvm.entity.State += ''
                        var tag = mvvm.entity.FollowServerTag;
                        mvvm.entity.FollowServerTag = tag ? tag.split(',') : []
                        mvvm.hotOpts.val = mvvm.entity.OpportunitiesPossibility
                        mvvm.entity.LastUpdateBy = CBCRM.memberShip.Id
                        var currDate = new Date()
                        mvvm.entity.LastUpdateDate = currDate.getFullYear() + '-' + (currDate.getMonth() + 1) + '-' + currDate.getDate()

                        mvvm.followstagedata.forEach(function (f) {
                            f.curr = f.Id == mvvm.entity.FollowStage
                        })
                        mvvm.formSubmit('编辑销售机会')
                    })
                }
                vm.hasPrevious = false;
                vm.hasNext = false;
                vm.previousLabel = false;
                vm.nextLabel = false;
                vm.previousId = '';
                vm.nextId = '';

                vm.stateChange = function (item) {
                    mvvm.entity.StateDisplay = item.Data;
                }

                //查看
                vm.doview = function (id) {
                    mvvm.grid1.getEntity(id, function (entity) {
                        mvvm.entity = entity;
                        mvvm.tab = 'tab1'
                        mvvm.currNav = 1;
                        mvvm.hotOpts2.val = mvvm.entity.OpportunitiesPossibility
                        mvvm.hasPrevious = entity.hasPrevious;
                        mvvm.hasNext = entity.hasNext;
                        mvvm.previousLabel = entity.previousLabel;
                        mvvm.nextLabel = entity.nextLabel;
                        mvvm.previousId = entity.previousId;
                        mvvm.nextId = entity.nextId;
                        CBCRM.loadView('/Market/salesViewTemplate.html', function (tmpl) {
                            var salesdialog = art.dialog.list['salesdialog']
                            if (salesdialog) {
                                salesdialog.close()
                            }
                            var dialog = openTmpl({
                                vm: mvvm,
                                title: "销售机会详情", w: 990, h:590,
                                tmplid: tmpl, iscontent: true,
                                extParam: {id:"salesdialog"}
                            });
                            $(dialog.content()).css({ padding: "0px" });
                            avalon.nextTick(function () {
                                //GetDocumentaryOfferList({ "salesid": mvvm.entity.Id, "customerid": mvvm.entity.Customer })
                                avalon.vmodels.followStage2.datasource = mvvm.followstagedata
                                mvvm.followstagedata.forEach(function (f) {
                                    f.curr = f.Id == mvvm.entity.FollowStage
                                })
                            }, 500)
                        })
                    }, true)
                }
                vm.$editor1 = "salesCustomerDemand";
                vm.formSubmit = function (title) {
                    var editor;
                    var btns = [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            mvvm.entity.CustomerDemand = editor.html();
                            var model = mvvm.entity.$model;
                            model.FollowServerTag = model.FollowServerTag.toString();
                            var url = (model.Id == 0 ? "/Market/SalesOpportunitiesAdd/" : "/Market/SalesOpportunitiesUpdate/");
                            $.post(url + model.Id, model, function (ret) {
                                CBCRM.showResult(ret, function () {
                                    if (ret.result) {
                                        //GetSalesOpportunitiesList(queryData)
                                        mvvm.grid1.reloadData();
                                        var salesdialog = art.dialog.list['salesdialog']
                                        if (salesdialog) mvvm.doview(model.Id);
                                        var pvm = avalon.vmodels["marketingdocumentaryoffer"];
                                        if (pvm && paramid && paramid != "0") pvm.setSalesOpportunities(paramid);
                                        if (dialog) dialog.close()
                                    }
                                })
                            })
                            return false;
                        }
                    }]
                    var dialog = mvvm.openTmpl({
                        title: title, w: 830, h: 500,padding:"def2",
                        tmpl: tmpl, tmplid: "saleformTemplate", btns: btns,
                        afterscan:function(){
                            editor = ketool.simple(mvvm.$editor1);
                            editor.html(mvvm.entity.CustomerDemand);
                            avalon.vmodels.followStage.datasource = mvvm.followstagedata
                            /*赋值对应客户*/
                            if (action == 'customer') {
                                if (paramData) {
                                    var c = paramData.entity;
                                    mvvm.entity.Customer = c.Id
                                    mvvm.entity.CustomerDisplay = c.Name;
                                    mvvm.setCustomerContacts(c.Id)
                                }
                            }else if(action == 'add'){
                                if (paramData) {
                                    mvvm.entity.Customer = paramData.customerId
                                    mvvm.entity.CustomerDisplay = paramData.customerName;
                                    if (paramData.contactId) {
                                        mvvm.entity.CustomerContact = paramData.contactId;
                                        mvvm.entity.CustomerContactDisplay = paramData.contactName;
                                    }
                                    if (paramData.customerId) mvvm.setCustomerContacts(paramData.customerId);
                                }
                            }else if (mvvm.entity.Customer) {
                                mvvm.setCustomerContacts(mvvm.entity.Customer)
                            }
                            $("#title",this.content()).focus().select();
                        },
                        onclose: function () {
                            destroyui(["marketingsalesopportunities_setParentCustomer", "opportunitiesFollowTree"])
                            editor.destroy();
                        }
                    });
                }

                vm.setCustomerContacts = function (customerid) {
                    $.get('/Customer/Contacts', { 'customerId': customerid }, function (ret) {
                        var temp = mvvm.entity.CustomerContact;
                        mvvm.CustomerContactData = ret.data.contacts.Source
                        mvvm.entity.CustomerContact = "";
                        mvvm.entity.CustomerContact = temp;
                    })
                }
                vm.onCancel = function () {
                    mvvm.action = 'list'
                }
                //删除
                vm.dodel = function (id) {
                    mvvm.grid1.removeById(id);
                }
                //批量删除
                vm.doalldel = function () {
                    mvvm.grid1.removeAll();
                }
                //选择所属战役
                vm.campaignList = []
                vm.campaignPanel = false
                vm.campaignKey = ''
                vm.selectCampaign = function () {
                    $('body').bind('mousedown', function () {
                        mvvm.campaignPanel = false
                        $('body').unbind('mousedown')
                    })
                    getCampaignList();
                    mvvm.campaignPanel = true;
                }


                vm.searchCampaign = function () {
                    getCampaignList();
                }
                vm.closeCampaignPanel = function () {
                    mvvm.campaignPanel = false;
                }
                vm.clickCampaign = function () {
                    var campaign = $(this);
                    mvvm.entity.MarketingCampaign = campaign.attr("key");
                    mvvm.entity.MarketingCampaignDisplay = campaign.attr("alt");
                    mvvm.campaignPanel = false;
                }
                vm.clearCampaignValue = function () {
                    mvvm.entity.MarketingCampaign = ''
                    mvvm.entity.MarketingCampaignDisplay = ''
                }
                //选择所属活动
                vm.activityList = []
                vm.activityPanel = false
                vm.activityKey = ''
                vm.selectActivity = function () {
                    $('body').bind('mousedown', function () {
                        mvvm.activityPanel = false
                        $('body').unbind('mousedown')
                    })
                    getActivityList();
                    mvvm.activityPanel = true;
                }
                vm.searchActivity = function () {
                    getActivityList();
                }
                vm.closeActivityPanel = function () {
                    mvvm.activityPanel = false;
                }
                vm.clickActivity = function () {
                    var activity = $(this);
                    mvvm.entity.MarketActivity = activity.attr("key");
                    mvvm.entity.MarketActivityDisplay = activity.attr("alt");
                    mvvm.activityPanel = false;
                }
                vm.clearActivityValue = function () {
                    mvvm.entity.MarketActivity = ''
                    mvvm.entity.MarketActivityDisplay = ''
                }

                vm.mousedownstop = function (e) {
                    e.stopPropagation()
                }

                //tab切换
                vm.tab = 'tab1'
                vm.tabChange = function () {
                    var tabid = $(this).attr("val")
                    mvvm.tab = tabid
                }

                vm.contactChange = function () {
                    var id = $(this).find('option:selected').val()
                    var name = $(this).find('option:selected').text()
                    if (id) {
                        mvvm.entity.CustomerContact = id
                        mvvm.entity.CustomerContactDisplay = name
                    } else {
                        mvvm.entity.CustomerContact = ''
                        mvvm.entity.CustomerContactDisplay = ''
                    }
                }

                vm.cnsigneChange = function () {
                    var id = $(this).find('option:selected').val()
                    var name = $(this).find('option:selected').text()
                    if (id) {
                        mvvm.entity.Consignee = id
                        mvvm.entity.ConsigneeDisplay = name
                    } else {
                        mvvm.entity.Consignee = ''
                        mvvm.entity.ConsigneeDisplay = ''
                    }
                }

                //列表显示更多
                vm.showindex = -1;
                vm.showmore = function (index, id) {
                    if (index != mvvm.showindex) mvvm.showindex = index;
                    else mvvm.showindex = -1
                    GetDocumentaryOfferListById(id);

                }
                vm.hidemore = function () {
                    mvvm.showindex = '-1'
                }

                vm.decumentaryofferlist = []
                vm.uploadAtta = function () {
                    var dialog=CBCRM.upload(true, function (node,data,file) {
                        console.log(file)
                        f = file.length ? file[0] : file;
                        mvvm.entity.AttachmentPath = "/Upload/" + f.Path;
                        mvvm.entity.AttachmentName = f.FileName;
                        dialog.close();
                    })
                }
                vm.delAtta = function () {
                    mvvm.entity.AttachmentPath ="";
                    mvvm.entity.AttachmentName = "";
                }
                //查看跟单
                vm.viewOffer = function (did,sid) {
                    mvvm.gotoview(did, "offer", {
                        reloadList: function () {
                            GetDocumentaryOfferListById(sid)
                        }
                    })
                }
            })
            mvvm.grid1.init();
            if (action == 'key') {
                key = decodeURI(paramid);
                mvvm.queryData.key.val = key;
            }
            InitDataItem()


            function GetDocumentaryOfferListById(id) {
                mvvm.decumentaryofferlist = []
                $.get('/Market/GetDocumentaryOfferById/', { Id: id }, function (ret) {
                    if (ret.data)
                        mvvm.decumentaryofferlist = ret.data;
                })
            }


            function GetSalesOpportunitiesList(data) {
                //只取某一客户销售机会
                var param
                if (action == 'customer')
                    data.customerid = paramid;

                $.get('/Market/SalesOpportunities/', data || {}, function (ret) {
                    if (!ret.result) return CBCRM.showResult(ret);
                    mvvm.ADD = ret.data.ADD
                    mvvm.DELETE = ret.data.DELETE
                    mvvm.NOPAGE = ret.data.NOPAGE
                    mvvm.salesopportunitieslist = ret.data.Source;
                    var page = avalon.vmodels.upaing;
                    if (mvvm.NOPAGE) {
                        destroyui(["upaing"]);
                    } else {
                        if (page) page.total = ret.data.RecordTotal;
                    }


                })
            }

            function GetDocumentaryOfferList(data) {
                $.get('/Market/DocumentaryOffer/', data || {}, function (ret) {
                    mvvm.decumentaryofferforcustomerlist = ret.data.Source;
                })
            }

            //从字典取数据
            function InitDataItem() {
                if (mvvm.init) {
                    if (action == "add" || action == "addfromcallcenter") gotoadd();
                    return;
                }
                $.get('/Market/GetSalesOpportunitiesDictionary/', {}, function (ret) {
                    mvvm.init = true;
                    ret.data.stateList.forEach(function (item) {
                        mvvm.queryData.opportunitiestype.items.push({ label: item.Data, val: item.Id, curr: false });
                    });
                    ret.data.cusList.forEach(function (item) {
                        mvvm.queryData.customersource.items.push({ label: item.Data, val: item.Id, curr: false });
                    });
                    ret.data.serverList.forEach(function (item) {
                        mvvm.queryData.followServerTag.items.push({ label: item.Data, val: item.Id, curr: false });
                    });
                    ret.data.stageList.forEach(function (item) {
                        mvvm.queryData.followStage.items.push({ label: item.Data, val: item.Id, curr: false });
                    });
                    mvvm.customersourcedata = ret.data.cusList
                    mvvm.followservertagdata = ret.data.serverList
                    ret.data.stageList.forEach(function (s) {
                        s.curr = false
                        s.label = s.Data
                    })
                    mvvm.followstagedata = ret.data.stageList
                    mvvm.opportunitiesstatedata = ret.data.stateList
                    if (action == "add" || action == "addfromcallcenter") gotoadd();
                })
            }
            //取所属战役
            function getCampaignList() {
                var key = mvvm.campaignKey;
                $.get('/Market/Campaign/', { "key": key }, function (ret) {
                    mvvm.campaignList = ret.data.Source;
                })
            }
            //取所属活动
            function getActivityList() {
                var key = mvvm.activityKey;
                var campaignId = mvvm.entity.MarketingCampaign;
                $.get('/Market/Activity/', { "key": key, "campaignid": campaignId }, function (ret) {
                    mvvm.activityList = ret.data.Source;
                })
            }
            mvvm.showOnlyList = false;
            //客户信息中调用
            if (action == 'customer') {
                detail = avalon.vmodels.ViewCustomer
                /*隐藏其它，只显示列表块*/
                mvvm.showOnlyList = true
                mvvm.grid1.showCustomer = false;
                mvvm.grid1.colCount = 9;
                paramData.viewOther(tmpl, mvvm, "#tableList");
            } else if (action == 'view') {
                //查看一条销售机会 
                mvvm.doview(paramid);
            } else if (action == "add" || action == "addfromcallcenter") {
                //放到InitDataItem()方法里面执行了
            } else {
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            }

            function gotoadd() {
                mvvm.doadd();
                if (action == "addfromcallcenter") {
                    mvvm.entity.FromId = paramid;
                    var callvm = avalon.vmodels.Calls;
                    if (callvm) {
                        mvvm.entity.Title = callvm.kuaijieVal
                        var customer = callvm.customerEntity, callEntity = callvm.callCenterEntity;
                        if (callEntity.Cid) {
                            mvvm.entity.Customer = callEntity.Cid;
                            mvvm.showOnlyList = true;
                            mvvm.entity.CustomerContact = callEntity.ContactsId;
                            mvvm.entity.CustomerContactDisplay = callEntity.CallsName;
                            mvvm.entity.CustomerSource = 10056;//电话来访
                            mvvm.entity.CustomerDemand = callEntity.CallsContent.replace(/\n/g,"<br>");
                        }
                    }
                } else if (paramid && paramid != "0") {
                    mvvm.entity.Customer = paramid;
                    mvvm.showOnlyList = true;
                }
                //var pvm = avalon.vmodels["marketingdocumentaryoffer"];
                //if (pvm && pvm.entity) {
                //    mvvm.entity.CustomerDisplay = pvm.entity.CustomerDisplay;
                //}
            }
        }

        ///销售管理-跟单报价
        , DocumentaryOffer: function (tmpl, lang, contentId, module,paramData) {
            var CBCRM = avalon.vmodels.CBCRM, that = this, detail, conditions, dialog, vmid = "marketingdocumentaryoffer";
            var action = that.params.action, paramid = that.params.id
            var mvvm = CBCRM.define(vmid, function (vm) {
                vm.lang = lang
                vm.entity = {}
                vm.urlAction = action;
                vm.action = 'list'
                vm.title = ''
                vm.describe = ''
                vm.decumentaryofferlist = []
                vm.insalesopp = false;
                vm.listtab = 0;
                vm.listTabs = [
                    { label: "全部跟单", val: 0 }, { label: "我的跟单", val: 1 }, { label: "下属跟单", val: 2 }
                ]
                vm.listtabChange = function (tabid) {
                    if (tabid == mvvm.listtab) return;
                    mvvm.listtab = tabid;
                    mvvm.addQuery("listType", tabid);
                }
                initQuerys(vm, function (data,name,val,type) {
                    mvvm.grid1.loadData(data);
                })
                //交货日期 不限     
                vm.queryData = {
                    offertype: { label: "报价类型", val: "", valLabel: "",next:"offerdate", items: [{ label: "不限", val: '', curr: true }] },
                    offerdate: {
                        label: "报价时间", val: "", valLabel: "",jump:true, items: [
                            { label: "不限", val: '', curr: true }, { label: "昨天", val: 'd_-1', curr: false },
                            { label: "今天", val: 'd_0', curr: false }, { label: "本周", val: 'w', curr: false },
                            { label: "上周", val: 'w_-1', curr: false }, { label: "本月", val: 'm', curr: false },
                            { label: "上月", val: 'm_-1', curr: false }
                        ]
                    },
                    paytype: { label: "付款方式", val: "", valLabel: "", next: "balancetype", items: [{ label: "不限", val: '', curr: true }] },
                    balancetype: { label: "结算方式", val: "", valLabel: "",jump:true, items: [{ label: "不限", val: '', curr: true }] },
                    deliverydate: {
                        label: "交货日期", val: "", valLabel: "",next:"issign", items: [
                            { label: "不限", val: '', curr: true }, { label: "1个月以内", val: '1', curr: false },
                            { label: "3个月以内", val: '3', curr: false }, { label: "6个月以内", val: '6', curr: false },
                            { label: "9个月以内", val: '9', curr: false }, { label: "12个月以内", val: '12', curr: false }
                        ]
                    },
                    issign: {
                        label: "签单状态", val: "", valLabel: "",jump:true, items: [
                            { label: "不限", val: '', curr: true }, { label: "已签单", val: '1', curr: false }, { label: "未签单", val: '2', curr: false }]
                    },
                    cmstate: {
                        label: "点评状态", val: "", valLabel: "", items: [
                            { label: "不限", val: '', curr: true }, { label: "已有点评", val: '1', curr: false },
                            { label: "未有点评", val: '0', curr: false }, { label: "别人点评我", val: '2', curr: false },
                            { label: "我点评别人", val: '3', curr: false },
                        ]
                    },
                    key: { label: "关键字", val: "", valLabel: "" },
                    listType: { label: "列表类型", val: 0, noRemove: true },
                    orderName: { label: "排序名称", val: "" },
                    orderValue: { label: "排序值", val: "" },
                    pageSize: { label: "页大小", val: "" },
                    pageIndex: { label: "页码", val: "" }
                };
                vm.grid1 = createGrid({
                    url: "/Market/DocumentaryOffer/",
                    modelFactory: modelFactory,
                    $lang: lang,
                    entityId: "DocumentaryOffer",
                    pageid: vmid + "_grid1_page",
                    extParam:{showCustomer: true, showSalesopp: true, colCount: 8},
                    createQuery: function () {
                        var data = mvvm.createQuery();
                        //只取某一客户销售机会
                        if (action == "customer") data.customerid = paramid;
                        else if (action == "salesopp") data.salesid = paramid;
                        data.orderName = mvvm.sort
                        data.orderValue = mvvm.sortValue
                        return data;
                    },
                    onLoadData: function (ret) {
                        if (!ret.result) return CBCRM.showResult(ret);
                        mvvm.ADD = ret.data.ADD
                        mvvm.DELETE = ret.data.DELETE
                        mvvm.NOPAGE = ret.data.NOPAGE
                        if (mvvm.NOPAGE) {
                            var page = mvvm.grid1.getPage();
                            if (page) page.destroy();
                        }
                        ret.data.Source.forEach(function (item) {
                            item.nocheck = item.IsSign;
                        });
                        return ret.data;
                    },
                    onRemove: function (deleteIds) {
                        var gvm = this;
                        $.post('/Market/DocumentaryOfferAllDel', deleteIds, function (ret) {
                            CBCRM.showResult(ret);
                            if (ret.result) {
                                gvm.reloadData();
                            }
                        });
                    }
                });
                vm.decumentaryofferpaing = {
                    paging: function (pageIndex,pageSize) {
                        mvvm.addQuerys({ pageIndex: pageIndex, pageSize: pageSize });
                    }
                }
                //新增联系人
                vm.addContact = function () {
                    var m = mvvm.entity, cid = m.Customer;
                    if (!cid) cid = 0;
                    var url = '/Customer/Contacts/' + cid + '/toadd';
                    var data = {
                        customerId: cid, customerName: m.CustomerDisplay,
                        onSave: function (ret, c) {
                            if (cid) mvvm.setCustomerContacts(cid);
                        }
                    }
                    goto(url, true, data);
                }
                //跟单报价产品
                vm.documentaryofferproductslist = []
                vm.CustomerContactData = []

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

                vm.commentItem = {}

                vm.has = false
                vm.offertypedata = []
                vm.paytypedata = []
                vm.balancetypedata = []
                vm.opportunitiestypedata = []
                vm.consignmenttypedata = []
                vm.billtypedata = []

                vm.ADD = true
                vm.DELETE = true
                vm.ADDCONTRACT = true //建立合同
                vm.NOPAGE = false

                vm.showOnlyList = false
                //左边导航子项显示隐藏
                vm.ShowSubNav = ''
                vm.onSubNav = function (subname) {
                    if (mvvm.ShowSubNav == subname)
                        mvvm.ShowSubNav = ''
                    else
                        mvvm.ShowSubNav = subname
                }

                //排序
                vm.sort=vm.queryData.orderName.val = "OfferDate"
                vm.sortValue =vm.queryData.orderValue.val=  1;
                vm.sortModel = {
                    OfferDate: 1
                }
                vm.dautosort = function (colname) {
                    var sortvalue = mvvm.sortModel[colname] == 0 ? 1 : 0;
                    mvvm.sort = colname;
                    mvvm.sortValue = sortvalue;
                    mvvm.sortModel[colname] = sortvalue;
                    mvvm.addQuerys({ orderName: colname, orderValue: sortvalue });
                }

                vm.clearTitle = function () {
                    mvvm.entity.Title = "";
                }
                vm.doaddSales = function () {
                    var m = mvvm.entity.$model;
                    var id = m.Customer || 0;
                    var url = "/Market/SalesOpportunities/" + id + "/add";
                    var data = {
                        customerName: m.CustomerDisplay, customerId: m.Customer,
                        contactName: m.CustomerContactDisplay, contactId: m.CustomerContact
                    };
                    goto(url, true,data);
                }
                //新增
                vm.doadd = function () {
                    mvvm.action = "add";
                    mvvm.entity = mvvm.grid1.getEntity();
                    mvvm.documentaryofferproductslist = []
                    mvvm.opportunitiestypedata = []
                    mvvm.entity.OfferType = mvvm.offertypedata.length > 0 ? mvvm.offertypedata[0].Id : ''

                    mvvm.entity.OfferDate = GetDateTime()
                    var currUser = CBCRM.memberShip
                    mvvm.entity.DocumentaryEmployee = currUser.Id
                    mvvm.entity.DocumentaryEmployeeDisplay = currUser.FullName
                    mvvm.entity.BelongTo = currUser.Id
                    mvvm.entity.BelongToDisplay = currUser.FullName;
                    mvvm.entity.Title = modelFactory.getDateTime(null, "yyyy-MM-dd") + "跟单记录-" + CBCRM.memberShip.FullName;
                    var dt = new Date();
                    dt.setMonth(dt.getMonth() + 1);
                    mvvm.entity.ValidityDate = GetDateTime(dt, "yyyy-MM-dd");
                    if (action == "customer") {
                        var centity = paramData.entity;
                        mvvm.entity.Customer = centity.Id;
                        mvvm.entity.CustomerDisplay = centity.Name;
                    }else if (action == "salesopp") {
                        var sentity = paramData.entity;
                        mvvm.entity.SalesOpportunities = sentity.Id;
                        mvvm.entity.SalesOpportunitiesDisplay = sentity.Title;
                        mvvm.entity.Customer = sentity.Customer;
                        mvvm.entity.CustomerDisplay = sentity.CustomerDisplay;
                    }

                    mvvm.formSubmit('新增跟单报价')
                }
                //编辑
                vm.doedit = function (id) {
                    mvvm.action = "edit";
                    mvvm.grid1.getEntity(id,function (entity) {
                        mvvm.entity = entity;
                        mvvm.formSubmit('编辑跟单报价')
                        GetDocumentaryOfferProductsList(id)
                    })
                }
                vm.formSubmit = function (title) {
                    var edid = "CustomerDemand_text", editor;
                    var btns = [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            if (mvvm.hasPriceError) {
                                messageBox.warning("包含小于最低限价的产品价格，请检查！");
                                return false;
                            }
                            if (editor) mvvm.entity.CustomerDemand = editor.html();
                            var model = mvvm.entity.$model
                            mvvm.documentaryofferproductslist.$model.forEach(function (item, index) {
                                model["DPList[" + index + "].Id"] = item.Id
                                model["DPList[" + index + "].Product"] = item.Product
                                model["DPList[" + index + "].Standard"] = item.Standard
                                model["DPList[" + index + "].Price"] = item.Price
                                model["DPList[" + index + "].Num"] = item.Num
                                model["DPList[" + index + "].Money"] = item.Money
                                model["DPList[" + index + "].Remark"] = item.Remark
                            })
                            var url = (mvvm.entity.Id == 0 ? "/Market/DocumentaryOfferAdd/" : "/Market/DocumentaryOfferUpdate/");
                            $.post(url + model.Id, model, function (ret) {
                                CBCRM.showResult(ret, function () {
                                    if (ret.result) {
                                        if (isFill) mvvm.grid1.reloadData();
                                        if (dialog) dialog.close()
                                    }
                                })
                            })
                            return false;
                        }
                    }]
                    var dialog = openTmpl({
                        vm: mvvm, title: title, w: 820, h: 300,
                        tmpl: tmpl, tmplid: "offerformTemplate", btns: btns,
                        onclose: function () {
                            destroyui(["belongToTree", "setParetCustomer", "consigneeid", "documentaryEmployeeTree", "daliyReportSendToTree"]);
                            if (editors[edid]) {
                                editors[edid].remove();
                                delete editors[edid];
                            }
                        }
                    });
                    avalon.nextTick(function () {
                        if (mvvm.entity.Customer) {
                            mvvm.setCustomerContacts(mvvm.entity.Customer)
                            mvvm.setSalesOpportunities(mvvm.entity.Customer)
                        }
                        mvvm.documentaryofferproductslist = []
                        mvvm.documentaryofferproductslist.push(avalon.mix({}, documentaryoffproductDate))
                        setEditor();
                        editor = editors[edid];
                        if (editor) editor.html(mvvm.entity.CustomerDemand);
                    })
                }
                //取当前客户的销售机会
                vm.setSalesOpportunities = function (customerid) {
                    if (action == "salesopp") return;//从销售机会详情面板添加、编辑，销售机会是固定的
                    var q = { 'customerid': customerid }; //customerid ?  : { opportunitiestype: 10301 };//机会：跟踪状态
                    $.get('/Market/SalesOpportunities/', q, function (ret) {
                        var list = ret.data.Source;
                        mvvm.opportunitiestypedata = list
                        var temp = mvvm.entity.SalesOpportunities;
                        mvvm.entity.SalesOpportunities = "";
                        mvvm.entity.SalesOpportunities = temp;
                    })
                }
                vm.setCustomerContacts = function (customerid) {
                    $.get('/Customer/Contacts', { 'customerId': customerid }, function (ret) {
                        mvvm.CustomerContactData = ret.data.contacts.Source
                    })
                }
                //查看
                vm.entityDetailList = []
                vm.viewWidth = 900;
                vm.doview = function (id) {
                    mvvm.tab = 'tab1'
                    mvvm.action = "view";
                    mvvm.entityDetailList = []
                    mvvm.grid1.getEntity(id, function (entity) {
                        mvvm.entity = entity
                        GetCommentItem(id)
                        GetDocumentaryOfferProductsList(id)
                    });
                    CBCRM.loadView('/Market/offerViewTemplate.html', function (tmpl) {
                        var offerdialog = art.dialog.list['offerdialog']
                        if (offerdialog) {
                            offerdialog.close()
                        }
                        mvvm.openTmpl({
                            title: "跟单报价详细", w: mvvm.viewWidth,h:580, tmplid: tmpl, iscontent: true,
                            extParam: { id: "offerdialog" }
                        });
                    })
                }

                //tab切换
                vm.tab = 'tab1'
                vm.tabChange = function () {
                    var tabid = $(this).attr("val")
                    mvvm.tab = tabid
                }
                vm.uid = 0
                vm.show = true

                //新增点评
                vm.commentAdd = function (entity,t) {
                    mvvm.commentItem = modelFactory.create('Comment')
                    var currUser = CBCRM.memberShip
                    mvvm.commentItem.DocumentaryOfferId = entity.Id
                    mvvm.commentItem.AddEmpId = currUser.Id
                    mvvm.commentItem.AddByName = currUser.FullName
                    FormSubmit("跟单点评",t)
                }
                //编辑点评
                vm.commentEdit = function (Item) {
                    mvvm.commentItem = modelFactory.create('Comment')
                    mvvm.commentItem.DocumentaryOfferId = Item.DocumentaryOfferId
                    mvvm.commentItem.AddEmpId = Item.AddEmpId
                    mvvm.commentItem.AddByName = Item.AddByName
                    mvvm.commentItem.Id = Item.Id
                    mvvm.commentItem.Comments = Item.Comments
                    mvvm.commentItem.CommentDate = GetDateTime();
                    FormSubmit("跟单点评")
                }


                vm.viewproductById = function (pid) {
                    var url = "/Product/Product/" + pid + "/view";
                    goto(url, true);
                }

                vm.doviewSales = function () {
                    var id = $(this).attr("val")
                    goto('/Market/SalesOpportunities/' + id + '/view',true)
                }
                vm.doviewContract = function () {
                    var contractid = $(this).attr('val')
                    var path = '/Market/Contract/' + contractid + '/view'
                    goto(path,true)
                }
                vm.viewCustomer = publicFn.customerdoview;
                vm.truncontract = function () {
                    var id = $(this).attr("value")
                    goto('/Market/Contract/' + id + '/trun',true)
                }
                
                //编辑界面列表全选
                vm.onChkAll = function () {
                    var chkVal = $(this).attr("checked");
                    $("input[name='productlist']").each(function (index, item) {
                        item.checked = chkVal
                    })
                }
                //产品-新加一行
                vm.onProductAdd = function () {
                    mvvm.documentaryofferproductslist.push(avalon.mix(true, {}, documentaryoffproductDate));
                }
                //产品-删除一行
                vm.onProductDel = function (obj) {
                    var index = parseInt($(this).attr('index'))
                    mvvm.documentaryofferproductslist.removeAt(index)
                    mvvm.onSumCost()
                }
                //产品-删除所有选中行
                vm.onProductAllDel = function (obj) {
                    $("input[name='productlist']:checked").each(function (index, item) {
                        mvvm.documentaryofferproductslist.removeAt(parseInt($(this).attr('index')))
                    })
                    mvvm.onSumCost()
                }
                vm.detailsTotalAmount = 0
                //报价金额合计
                vm.hasPriceError = false;
                vm.onSumCost = function (product) {
                    if ($(this).attr("data-id") == "Price" && product) {
                        var title = (product.LowestPrice && product.Price < product.LowestPrice) ? "该产品的最低价为：" + product.LowestPrice : "";
                        $(this).attr("title", title);
                    }
                    var cost = 0
                    mvvm.hasPriceError = false;
                    mvvm.documentaryofferproductslist.forEach(function (item, index) {
                        if (item.LowestPrice && item.Price < item.LowestPrice) {
                            mvvm.hasPriceError = true;
                            messageBox.warning("产品(" + item.ProductName + ")的单价(" + item.Price + ")小于该产品的最低限价(" + item.LowestPrice + ")！");
                            return;
                        }
                        var money = parseFloat(item.Num) * parseFloat(item.Price)
                        if (money) {
                            item.Money = money
                            cost = cost + money
                        }
                    })
                    mvvm.entity.OfferTotal = cost
                    mvvm.onMathTaxAmt()
                }
                //计算税额
                vm.onMathTaxAmt = function () {
                    if (mvvm.entity.TaxRate >= 0) {
                        var taxamt = parseFloat(mvvm.entity.OfferTotal) * parseFloat(mvvm.entity.TaxRate) / 100
                        if (taxamt) mvvm.entity.TaxAmt = taxamt
                    }
                    mvvm.entity.TotalAmt = parseFloat(mvvm.entity.OfferTotal) + parseFloat(mvvm.entity.TaxAmt)
                }
                //选择所属战役
                vm.campaignList = []
                vm.campaignPanel = false
                vm.campaignKey = ''
                vm.selectCampaign = function () {
                    $('body').bind('mousedown', function () {
                        mvvm.campaignPanel = false
                        $('body').unbind('mousedown')
                    })
                    getCampaignList();
                    mvvm.campaignPanel = true;
                }
                vm.searchCampaign = function () {
                    getCampaignList();
                }
                vm.closeCampaignPanel = function () {
                    mvvm.campaignPanel = false;
                }
                vm.clickCampaign = function () {
                    var campaign = $(this);
                    mvvm.entity.MarketingCampaign = campaign.attr("key");
                    mvvm.entity.MarketingCampaignDisplay = campaign.attr("alt");
                    mvvm.campaignPanel = false;
                }
                vm.clearCampaignValue = function () {
                    mvvm.entity.MarketingCampaign = ''
                    mvvm.entity.MarketingCampaignDisplay = ''
                }
                //选择所属活动
                vm.activityList = []
                vm.activityPanel = false
                vm.activityKey = ''
                vm.selectActivity = function () {
                    $('body').bind('mousedown', function () {
                        mvvm.activityPanel = false
                        $('body').unbind('mousedown')
                    })
                    getActivityList();
                    mvvm.activityPanel = true;
                }
                vm.searchActivity = function () {
                    getActivityList();
                }
                vm.closeActivityPanel = function () {
                    mvvm.activityPanel = false;
                }
                vm.clickActivity = function () {
                    var activity = $(this);
                    mvvm.entity.MarketActivity = activity.attr("key");
                    mvvm.entity.MarketActivityDisplay = activity.attr("alt");
                    mvvm.activityPanel = false;
                }
                vm.clearActivityValue = function () {
                    mvvm.entity.MarketActivity = ''
                    mvvm.entity.MarketActivityDisplay = ''
                }

                vm.mousedownstop = function (e) {
                    e.stopPropagation()
                }

                //下拉归属人配置
                vm.belongToOpts = {
                    treeopts: {
                        callback: {
                            onCheck: function (e, treeId, treeNode) {
                                mvvm.entity.BelongTo = treeNode.Id;
                                mvvm.entity.BelongToDisplay = treeNode.Name;
                            }
                        },
                        async: {
                            url: function (treeId, treeNode) {
                                var url = "/Settings/GetGroupPostUser/2020500"
                                vmtree = avalon.vmodels.belongToTree
                                if (vmtree && vmtree.q && vmtree.q !== vmtree.qcopy) {
                                    url += '?empName=' + vmtree.q
                                }
                                return url
                            },
                            dataFilter: notMemberFilter
                        },
                        check: {
                            enable: true,
                            chkStyle: 'radio',
                            radioType: "all"
                        }
                    }
                }
                //下拉跟单报价人
                vm.selectDocumentaryEmployeeTree = function () {
                    plugins.selectUser({
                        dataAuth: 2020501,
                        callback: function (us) {
                            var u = us[0];
                            mvvm.entity.DocumentaryEmployee = u.Id;
                            mvvm.entity.DocumentaryEmployeeDisplay = u.FullName;
                        }
                    });
                }
                
                //选客户/联系人
                vm.selectCustomer = function () {
                    plugins.selectCustomer({
                        type: "contacts",
                        callback: function (cus, cons) {
                            var cu = cus[0], entity = mvvm.entity;
                            entity.Customer = cu.Id
                            entity.CustomerDisplay = cu.Name
                            entity.CustomerMemberGradeDisplay=cu.MemberGradeDisplay
                            mvvm.CustomerMemberGradeDisplay = cu.MemberGradeDisplay
                            mvvm.CustomerContactData = [];
                            if (cu.Contacts) {
                                cu.Contacts.forEach(function (c) {
                                    mvvm.CustomerContactData.push(c);
                                });
                            }
                            var con = cons[0];
                            entity.CustomerContact = con.Id
                            entity.CustomerContactDisplay = con.Name

                            mvvm.setSalesOpportunities(cu.Id);
                        }
                    });
                }

                //选收货人
                vm.selectConsignee = function () {
                    plugins.selectCustomer({
                        type: "contacts",
                        required:{con:true},
                        callback: function (cus, cons) {
                            var entity = mvvm.entity,con = cons[0];
                            entity.Consignee = con.Id
                            entity.ConsigneeDisplay = con.Name;
                        }
                    });
                }
                //报价有效期
                vm.validitydateOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        mvvm.entity.ValidityDate = formatDate
                    }
                }
                //报价时间
                vm.offerdateOpts = {
                    onSelect: function (date, formatDate, format) {
                        mvvm.entity.OfferDate = formatDate
                    }
                }
                //交货日期
                vm.delivedateOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        mvvm.entity.DeliveryDate = formatDate
                    }
                }
                //上传文件
                vm.uploadFiles = function () {
                    var upwin = CBCRM.upload(true, function (node, data, file) {
                        mvvm.entity.Files = '/upload/' + file.Path;
                        upwin.close();
                    });
                }
                vm.delFiles = function () {
                    mvvm.entity.Files = "";
                }
                //设置报价产品当前行
                vm.pIndex = 0
                vm.onSetIndex = function () {
                    mvvm.pIndex = this.$vmodel.$index
                }
                //选择产品
                vm.productKey = ''
                vm.catecoryId = 0
                vm.productList = []
                vm.productpaing = {
                    pagesize: 10,
                    pagesizeopts: [10, 20, 50, 100, 200, 500, 1000],
                    paging: function (pageIndex, pageSize) {
                        mvvm.getProcutList(pageIndex, pageSize)
                    }
                }
                //取产品
                vm.getProcutList = function (pageIndex, pageSize) {
                    var data = {
                        "typeid": mvvm.catecoryId, "key": mvvm.productKey, "pageSize": pageSize, "pageIndex": pageIndex
                    };
                    if (mvvm.entity.Customer) data.customerId = mvvm.entity.Customer;
                    $.get('/Product/PriceList/', data, function (ret) {
                        if (!ret.result) {
                            CBCRM.showResult(ret);
                            return;
                        }
                        mvvm.productList = ret.data.productList.Source;
                        var page = avalon.vmodels.productupaing;
                        if (page) {
                            page.total = ret.data.productList.RecordTotal;
                            page.setIndex(ret.data.productList.PageIndex);
                        }
                    })
                }
                vm.onSelectProuct = function () {
                    mvvm.productKey = ''
                    mvvm.catecoryId = 0
                    dialog = messageBox.openHtml('选择产品', '980px', '300px', '', [{
                        name: '确定',
                        focus: true,
                        callback: function () {
                            var product = mvvm.productList.$model[mvvm.productListIndex]
                            mvvm.selectedProduct(product);
                        }
                    }]);
                    var content = $(dialog.content())
                    //content.attr('ms-include', 'ProductListTemp')
                    var inputTmpl = $(tmpl).find("#ProductListTemp").text()
                    content.html(inputTmpl)
                    avalon.scan(content[0], mvvm)
                }
                vm.onSearchProduct = function () {
                    mvvm.getProcutList(1, 10)
                }
                vm.productListIndex = 0
                vm.onSetProductIndex = function () {
                    mvvm.productListIndex = this.$vmodel.$index
                    $("input[name='rdoproduct']").eq(mvvm.productListIndex).attr("checked", "checked")
                }
                vm.selectedProduct = function (product) {
                    var documentaryofferproduct = mvvm.documentaryofferproductslist[mvvm.pIndex]
                    documentaryofferproduct.Product = product.Id
                    documentaryofferproduct.ProductName = product.Name
                    documentaryofferproduct.Standard = product.Standard
                    documentaryofferproduct.Price = product.SpecialPrice || product.GradePrice || product.GeneralCustomerPrice
                    documentaryofferproduct.LowestPrice = product.LowestPrice;
                    documentaryofferproduct.Num = 1
                    mvvm.onSumCost()
                    if (dialog) dialog.close()
                }
                vm.formatPriceList = formatPriceList;
                //产品分类树配置
                vm.pCategoryTreeOpts = {
                    treeopts: {
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                mvvm.catecoryId = treeNode.Id
                                var page = avalon.vmodels.productupaing, pageSize = page ? page.pagesize : 10;
                                mvvm.getProcutList(1, pageSize);
                            }
                        },
                        view: {
                            addHoverDom: '',
                            removeHoverDom: ''
                        }
                    }
                }

                vm.contactChange = function () {
                    var id = $(this).find('option:selected').val()
                    var name = $(this).find('option:selected').text()
                    if (id) {
                        mvvm.entity.CustomerContact = id
                        mvvm.entity.CustomerContactDisplay = name
                    } else {
                        mvvm.entity.CustomerContact = ''
                        mvvm.entity.CustomerContactDisplay = ''
                    }
                }

                vm.salestChange = function () {
                    var id = $(this).find('option:selected').val()
                    var name = $(this).find('option:selected').text()
                    if (id) {
                        mvvm.entity.SalesOpportunities = id
                        mvvm.entity.SalesOpportunitiesDisplay = name
                    } else {
                        mvvm.entity.SalesOpportunities = ''
                        mvvm.entity.SalesOpportunitiesDisplay = ''
                    }
                }
                vm.CustomerMemberGrade = "";
                vm.CustomerMemberGradeDisplay = "";
                vm.destroy = function () {
                    if (avalon.vmodels.belongToTree)
                        avalon.vmodels.belongToTree.destroy()
                    if (avalon.vmodels.setParetCustomer)
                        avalon.vmodels.setParetCustomer.destroy()
                    if (avalon.vmodels.consigneeid)
                        avalon.vmodels.consigneeid.destroy()
                    if (avalon.vmodels.documentaryEmployeeTree)
                        avalon.vmodels.documentaryEmployeeTree.destroy()
                    avalon.vmodels.DocumentaryOffer = null
                }


                //列表显示更多
                vm.showindex = -1;
                vm.showmore = function (index, id) {
                    if (index != mvvm.showindex) mvvm.showindex = index;
                    else mvvm.showindex = -1
                    //GetDocumentaryOfferProductsById(id)
                    getComments(id);
                }
                vm.hidemore = function () {
                    mvvm.showindex = '-1'
                }
                //vm.getdecumentaryofferlist = []
                vm.comments = [];
                vm.watchItem = function (item) {
                    item.$watch("ProductName", function (n) {
                        if (!n) return;
                    });
                }
            })
            mvvm.grid1.init();
            //保存
            function FormSubmit(title,t) {
                var dialog = mvvm.openTmpl({
                    title: title,
                    tmpl: tmpl,
                    tmplid: "commentView",
                    w: 520,
                    padding:"def2",
                    onclose: function () {
                    },
                    btns: [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            var model = mvvm.commentItem.$model
                            var url = (model.Id == 0 ? "/Market/CommentAdd/" : "/Market/CommentUpdate/")
                            $.post(url + model.Id, model, function (ret) {
                                CBCRM.showResult(ret, function () {
                                    var did = model.DocumentaryOfferId;
                                    if (t == 1) getComments(did)
                                    else GetCommentItem(did)
                                    if (dialog) dialog.close();
                                    if (paramData) {
                                        if (paramData.reloadList) paramData.reloadList();
                                    }
                                });
                            })
                            return false
                        }
                    }]
                });
            }

            var action = that.params.action, paramid = that.params.id, isFill = false;

            //创建报价产品对象
            var documentaryoffproductDate = {
                Id: '',
                Num: '',
                Price: '',
                LowestPrice: '',
                Money: '',
                Remark: '',
                DocumentaryOffer: '',
                Product: '',
                ProductName: '',
                Standard: ''
            }
            //创建筛选对象
            var searchItem = {
                offertype: '',
                offerdate: '',
                paytype: '',
                balancetype: '',
                deliverydate: '',
                issign: ''
            }
            
            if (action == "key") {
                mvvm.queryData.key.val=decodeURI(paramid)
            }
            InitDataItem();
            function getMemberGrade() {
                $.get('/Product/GetMemberGrade/' + paramid, {}, function (ret) {
                    if (ret.result) {
                        mvvm.CustomerMemberGrade = ret.data.CustomerMemberGrade;
                        mvvm.CustomerMemberGradeDisplay = ret.data.CustomerMemberGradeDisplay;
                    }
                });
            }
            

            function GetDocumentaryOfferProductsById(id) {
                mvvm.getdecumentaryofferlist = []
                $.get('/Market/GetDocumentaryOfferProductsById/', { "id": id }, function (ret) {
                    mvvm.getdecumentaryofferlist = ret.data
                })
            }
            function GetDocumentaryOfferProductsList(id) {
                mvvm.getdecumentaryofferlist = []
                $.get('/Market/GetDocumentaryOfferProducts/', { "id": id }, function (ret) {
                    mvvm.documentaryofferproductslist = ret.data.Source
                    mvvm.getdecumentaryofferlist = ret.data.Source
                    mvvm.detailsTotalAmount = ret.data.totalMeney
                })
            }
            //从字典取数据
            function InitDataItem() {
                var data = {};
                if (that.params.id && !that.params.key) data.id = that.params.id;
                $.get('/Market/GetDocumentaryOfferDictionary/', data, function (ret) {
                    mvvm.offertypedata = ret.data.offertypeList
                    mvvm.paytypedata = ret.data.paytypeList
                    mvvm.balancetypedata = ret.data.balancetypeList
                    mvvm.consignmenttypedata = ret.data.consignmenttypeList
                    mvvm.billtypedata = ret.data.billtypeList
                    var queryData = mvvm.queryData;
                    ret.data.offertypeList.forEach(function (item) {
                        queryData.offertype.items.push({ label: item.Data, val: item.Id, curr: false });
                    });
                    ret.data.paytypeList.forEach(function (item) {
                        queryData.paytype.items.push({ label: item.Data, val: item.Id, curr: false });
                    });
                    ret.data.balancetypeList.forEach(function (item) {
                        queryData.balancetype.items.push({ label: item.Data, val: item.Id, curr: false });
                    });
                })
            }
            function GetCommentItem(Id) {
                mvvm.entityDetailList = []
                getCommentList(Id, function (list) {
                    mvvm.entityDetailList = list;
                    var user = CBCRM.memberShip
                    mvvm.uid = user.Id
                    //var c = findArr(ret.data, function (item) { return item.AddEmpId == user.Id });
                    //mvvm.show = c == null;
                    mvvm.show = true;
                });
            }
            function getComments(id) {
                getCommentList(id, function (list) {
                    mvvm.comments = list;
                })
            }
            function getCommentList(id,callback) {
                $.get('/Market/DocumentaryOfferCommentById', { id: id }, function (ret) {
                    if (!ret.result) {
                        return CBCRM.showResult(ret);
                    }
                    ret.data.forEach(function (item) {
                        if (!item.Picture) {
                            item.Picture = "/Content/Themes/Base/Images/" + (item.EmpSex ? "lady" : "man") + "_default.png";
                        }
                    });
                    callback(ret.data);
                })
            }


            //取所属战役
            function getCampaignList() {
                var key = mvvm.campaignKey;
                $.get('/Market/Campaign/', { "key": key }, function (ret) {
                    mvvm.campaignList = ret.data.Source;
                })
            }
            //取所属活动
            function getActivityList() {
                var key = mvvm.activityKey;
                var campaignId = mvvm.entity.MarketingCampaign;
                $.get('/Market/Activity/', { "key": key, "campaignid": campaignId }, function (ret) {
                    mvvm.activityList = ret.data.Source;
                })
            }
            //取产品
            function getProcutList(pageIndex, pageSize) {
                $.get('/Product/Product/', {
                    "typeid": mvvm.catecoryId, "key": mvvm.productKey, "pageSize": pageSize, "pageIndex": pageIndex
                }, function (ret) {
                    mvvm.productList = ret.data.Source;
                    var page = avalon.vmodels.productupaing;
                    if (page) {
                        page.total = ret.data.productList.RecordTotal;
                        page.setIndex(ret.data.productList.PageIndex);
                    }
                })
            }
            var editors = {};
            function setEditor() {
                var id = "CustomerDemand_text";
                if (editors[id]) editors[id].remove();
                editors[id] = setEditerSimple("CustomerDemand_text");
            }
            //客户信息中调用
            switch (action) {
                case "customer":
                    isFill = true;
                    mvvm.grid1.showCustomer = false;
                    mvvm.grid1.colCount = 7;
                    /*隐藏其它，只显示列表块*/
                    paramData.viewOther(tmpl, mvvm, "#tableList");
                    
                    getMemberGrade();
                    break;
                case "get":
                case "view":
                    mvvm.doview(paramid);
                    break;
                case "add":
                    mvvm.doadd()
                    break;
                    break;
                case "salesopp":
                    isFill = true;
                    mvvm.grid1.showSalesopp = false;
                    mvvm.grid1.colCount = 7;
                    paramData.viewOther(tmpl, mvvm, "#tableList");
                    break;
                default:
                    fill();
                    break;
            }
            function fill() {
                isFill = true;
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            }
        }

        ///销售管理-合同订单
        , Contract: function (tmpl, lang, contentId, module,paramData) {
            var CBCRM = avalon.vmodels.CBCRM, dialog, that = this, detail, init = false, dialog;
            var vmid = "marketingcontract";
            //, oldvm = avalon.vmodels[vmid];
            //if (oldvm) oldvm.destroy();
            var action = that.params.action, paramid = that.params.id;
            var mvvm = CBCRM.define(vmid, function (vm) {
                vm.$skipArray = ['lang']
                vm.lang = lang
                vm.entity = {}
                vm.contractlist = []
                vm.otherContent = ''
                vm.isCustInfo = true
                vm.sumAmount = 0;
                vm.contractpaing = {
                    paging: function (pageIndex,pageSize) {
                        var queryData = mvvm.getQueryData();
                        queryData.pageSize = pageSize
                        queryData.pageIndex = pageIndex
                        //GetContractList(queryData);
                        mvvm.mgrid.loadData(queryData);
                    }
                }
                initQuerys(vm, function (data, name, val, type) {
                    var queryData = mvvm.getQueryData();
                    mvvm.mgrid.loadData(queryData);
                })
                //创建查询对象并提交
                vm.queryData = {
                    contracttype: { label: "合同类型", val: "", valLabel: "", next: "state", items: [{ label: "不限", val: '', curr: true }] },
                    state: {
                        label: "合同状态", val: "", valLabel: "", jump: true, items: [
                            { label: "不限", val: '', curr: true }]
                    },
                    signcontractdate: {
                        label: "签约时间", val: "", valLabel: "", next: "contractdate", items: [
                            { label: "不限", val: '', curr: true }, { label: "1个月以内", val: '1', curr: false },
                            { label: "3个月以内", val: '3', curr: false }, { label: "6个月以内", val: '6', curr: false },
                            { label: "9个月以内", val: '9', curr: false }, { label: "12个月以内", val: '12', curr: false }
                        ]
                    },
                    contractdate: {
                        label: "合同期限", val: "", valLabel: "",jump: true, items: [
                            { label: "不限", val: '', curr: true }, { label: "1个月以内", val: '1', curr: false },
                            { label: "3个月以内", val: '3', curr: false }, { label: "6个月以内", val: '6', curr: false },
                            { label: "9个月以内", val: '9', curr: false }, { label: "12个月以内", val: '12', curr: false }
                        ]
                    },
                    issample: {label:"合同格式",val:"", valLabel: "" },
                    key: { label: "关键字", val: "", valLabel: "",syncLabel:true },
                    listType: { label: "列表类型", val: 0, noRemove: true },
                    orderName: { label: "排序名称", val: "" },
                    orderValue: { label: "排序值", val: "" },
                    pageSize: { label: "页大小", val: "" },
                    pageIndex: { label: "页码", val: "" }
                };
                vm.getQueryData = function () {
                    var data = mvvm.createQuery();
                    //只取某一客户、某销售机会的合同订单
                    if (action == 'customer') data.customerId = paramid;
                    else if (action == "salesopp") data.salesid = paramid;
                    data.orderName = mvvm.sort
                    data.orderValue = mvvm.sortValue
                    return data;
                }
                vm.mgrid = createGrid({
                    url: "/Market/Contract",
                    modelFactory: modelFactory,
                    $lang: lang,
                    entityId: "Contract",
                    pageid: vmid + "_mgrid_page",
                    createQuery: vm.getQueryData,
                    onLoadData: function (ret) {
                        if (!ret.result) return CBCRM.showResult(ret);
                        mvvm.ADD = ret.data.ADD
                        //mvvm.ADDSimple = ret.data.ADDSimple
                        mvvm.DELETE = ret.data.DELETE
                        mvvm.NOPAGE = ret.data.NOPAGE
                        mvvm.PRODUCTSTOCKTPRICE = ret.data.PRODUCTSTOCKTPRICE;
                        mvvm.sumAmount = 0;
                        ret.data.Source.forEach(function (item) {
                            if (item.Amount) mvvm.sumAmount += item.Amount;
                        });
                        if (mvvm.NOPAGE) {
                            var page = mvvm.mgrid.getPage();
                            if (page) page.destroy();
                        }
                        return ret.data;
                    },
                    onRemove: function (deleteIds) {
                        var gvm = this;
                        $.post('/Market/ContractAllDel', deleteIds, function (ret) {
                            CBCRM.showResult(ret);
                            if (ret.result) {
                                gvm.reloadData();
                            }
                        });
                    }
                });
                vm.listtab = 0;
                vm.listTabs = [
                    { label: "全部合同订单", val: 0 }, { label: "我的合同", val: 1 }, { label: "下属的合同", val: 2 }
                ]
                vm.listtabChange = function (tabid) {
                    if (tabid == mvvm.listtab) return;
                    mvvm.listtab = tabid;
                    mvvm.addQuery("listType", tabid);
                }
                //排序,0倒序，1升序
                vm.sort = "SignAContractDate"
                vm.sortValue = 0;
                vm.sortModel = {
                    SignAContractDate: 0,
                    Amount: 0
                }
                vm.dautosort = function (colname) {
                    var sortvalue = mvvm.sortModel[colname] == 0 ? 1 : 0;
                    mvvm.sort = colname;
                    mvvm.sortValue = sortvalue;
                    mvvm.sortModel[colname] = sortvalue;
                    mvvm.addQuerys({ orderName: mvvm.sort, orderValue: mvvm.sortValue });
                }

                vm.viewCustomer = function () {
                    var vm = this.$vmodel,
                    item = vm[vm.$itemName]
                    goto('/Customer/DetailCustomer/' + item.Customer)
                }

                vm.viewProduct = function (id) {
                    goto('/Product/Product/' + id + "/view", true);
                }
                //合同产品明细
                vm.contractdetailslist = []
                //出库明细
                vm.outlist = [];
                //计划付款期次
                vm.planofpaylist = []
                vm.showindex = -1;
                vm.showmore = function (index) {
                    mvvm.showindex = mvvm.showindex == index ? -1 : index;
                }
                vm.action = 'list'
                vm.title = ''
                vm.describe = ''
                vm.keyword = ''
                vm.history = []
                vm.showItem = {}
                vm.has = false
                vm.contracttypedata = []
                vm.contractstatedata = []
                vm.contractstagedata = []
                vm.billtypedata = []
                vm.currencytypedata = []
                vm.paytpyedata = []
                vm.consignmenttype = [] 
                vm.returnedstatedata = []
                vm.bankdata = []
                vm.balancetypedata = []
                vm.CustomerContactData = []

                vm.contractdetailsdellist = []

                vm.ADD = true
                vm.ADDSimple = true;
                vm.DELETE = true
                vm.NOPAGE = false
                vm.PRODUCTSTOCKTPRICE = false;

                vm.showOnlyList = false

                //左边导航子项显示隐藏
                vm.ShowSubNav = ''
                vm.onSubNav = function (subname) {
                    if (mvvm.ShowSubNav == subname)
                        mvvm.ShowSubNav = ''
                    else
                        mvvm.ShowSubNav = subname
                }
                //合同正文附件显示隐藏
                vm.ShowAttachment = false
                vm.onShowAttachment = function () {
                    mvvm.ShowAttachment = !mvvm.ShowAttachment
                }
                vm.addSalesOut = function () {
                    var url = "/Product/ProductStorageSalesOut/" + mvvm.entity.Id + "," + mvvm.entity.ContractNum + "/add";
                    goto(url, true);
                }

                vm.timeSpans = [
                    { label: "3月", val: 3 }, { label: "6月", val: 6 },
                    { label: "1年", val: 12 },{ label: "2年", val: 24 }
                ];
                vm.computeEndDate = function (ts) {
                    var st = new Date(mvvm.entity.StartDate) || new Date();
                    var et = GetDateAdd(st, "M", ts.val);
                    mvvm.entity.StartDate = GetDateTimeYMD(st);
                    mvvm.entity.EndDate = GetDateTimeYMD(et);
                }
                //新增
                vm.doadd = function (ctype) {
                    mvvm.tab = 'tab1'
                    mvvm.entity = mvvm.mgrid.getEntity();
                    mvvm.entity.IsSample = ctype
                    var dindex = 0
                    mvvm.entity.ContractType = mvvm.contracttypedata.length > 0 ? mvvm.contracttypedata[dindex].Id : ''
                    mvvm.entity.State = mvvm.contractstatedata.length > 0 ? mvvm.contractstatedata[dindex].Id : ''
                    mvvm.entity.CurrentStage = mvvm.contractstagedata.length > 0 ? mvvm.contractstagedata[dindex].Id : ''
                    mvvm.entity.Currency = mvvm.currencytypedata.length > 0 ? mvvm.currencytypedata[dindex].Id : ''
                    mvvm.entity.FillUpTaxCurrency = mvvm.currencytypedata.length > 0 ? mvvm.currencytypedata[dindex].Id : ''

                    mvvm.entity.SignAContractDate = GetDateTimeYMD()
                    mvvm.entity.StartDate = GetDateTimeYMD()

                    mvvm.contractdetailslist = []
                    mvvm.onRelevanceAdd('contractdetails')
                    mvvm.contractdetailsdellist = []
                    if (!mvvm.entity.IsSample) {
                        //付款期次初始化2条数据  
                        mvvm.planofpaylist = []
                        planofpayData.Item = '首付定金'
                        planofpayData.Percents = 30;
                        mvvm.onRelevanceAdd('planofpay')
                        planofpayData.Item = '结单余额'
                        planofpayData.Percents = 70;
                        mvvm.onRelevanceAdd('planofpay')
                        planofpayData.Item = ''
                        planofpayData.Percents = ''
                    }
                    else {
                        mvvm.entity.EndDate = GetDateTimeYMD();
                    }
                    //销售机会跳转过来
                    if (action == "salesopp") {
                        var pvm = avalon.vmodels["marketingsalesopportunities"];
                        if (pvm != null) {
                            var sentity = pvm.entity;
                            mvvm.entity.SalesOpportunities = sentity.Id;
                            mvvm.entity.SalesOpportunitiesDisplay = sentity.Title;
                            mvvm.entity.Customer = sentity.Customer;
                            mvvm.entity.CustomerDisplay = sentity.CustomerDisplay;
                        }
                    }

                    var currUser = CBCRM.memberShip
                    /*赋值归属员工*/
                    mvvm.entity.BelongTo = currUser.Id
                    mvvm.entity.BelongToDisplay = currUser.FullName
                    /*赋值我方签约人*/
                    mvvm.entity.MySignPersion = currUser.Id
                    mvvm.entity.MySignPersionDisplay = currUser.FullName
                    mvvm.arapList = [];
                    mvvm.arapDelList = [];
                    mvvm.formSubmit('新增合同订单')
                    GetAutoCode()
                }

                //编辑
                vm.doedit = function (id) {
                    mvvm.tab = 'tab1'
                    mvvm.arapList = [];
                    mvvm.arapDelList = [];
                    mvvm.mgrid.getEntity(id, function (entity) {
                        mvvm.entity = entity
                        mvvm.contractdetailsdellist = []
                        mvvm.formSubmit('编辑合同订单')
                        GetContractRelevanceList(entity.Id)
                    },true);
                }
                //上下条
                vm.hasPrevious = true;
                vm.hasNext = true;
                vm.previousId = '';
                vm.nextId = '';
                vm.previousLabel = '';
                vm.nextLabel = '';

                vm.showdate = true;
                vm.dtime = 0;

                vm.viewproductById = function (pid) {
                    var url = "/Product/Product/" + pid + "/view";
                    goto(url, true);
                }

                //查看 
                vm.loadEntity = function (id,callback) {
                    mvvm.mgrid.getEntity(id, function (entity, ret) {
                        mvvm.needReLoad = false;
                        mvvm.entity = entity
                        mvvm.entity.AddByName = entity.AddBy.FullName;
                        var val = exDateRange(mvvm.entity.EndDate, GetDateTime(new Date(), "yyyy-MM-dd"))
                        if (val > 0) {
                            mvvm.showdate = true
                            mvvm.dtime = exDateRange(mvvm.entity.EndDate, GetDateTime(new Date(), "yyyy-MM-dd"));
                        } else {
                            mvvm.showdate = false
                            mvvm.dtime = exDateRange(GetDateTime(new Date(), "yyyy-MM-dd"), mvvm.entity.EndDate);
                        }
                        mvvm.hasPrevious = ret.data.hasPrevious;
                        mvvm.previousId = ret.data.previousId;
                        mvvm.previousLabel = ret.data.previousLabel;
                        mvvm.hasNext = ret.data.hasNext;
                        mvvm.nextId = ret.data.nextId;
                        mvvm.nextLabel = ret.data.nextLabel;
                        GetContractRelevanceList(id);
                        if (callback) callback();
                    }, true);
                }
                vm.doview = function (id) {
                    mvvm.contractId = id
                    var has = false;
                    mvvm.tab = 'tab1'
                    mvvm.currNav = 1;
                    mvvm.arapList = [];
                    mvvm.arapDelList = [];
                    mvvm.loadEntity(id, function () {
                        if (dialog) dialog.close();
                        dialog = mvvm.openTmpl({
                            title: "合同订单详细", w: 1000, h: 510,
                            url: "/Market/ContractView", padding: "0px",
                            onClose: function () {
                                dialog = null;
                            }
                        });
                    });
                }

                //关闭查看对话框
                vm.close = function () {
                    if (dialog) dialog.close();
                }

                //删除
                vm.dodel = function (id) {
                    messageBox.confirm('确定删除此数据吗？', function () {
                        $.post('/Market/ContractDel/' + id, {}, function (ret) {
                            CBCRM.showResult(ret);
                            if (ret.result) {
                                if (dialog) dialog.close();
                                var item = findArr(mvvm.mgrid.list, id);
                                if (item != null) mvvm.mgrid.reloadData();
                                if (paramData && paramData.reloadCustomer) paramData.reloadCustomer();
                            }
                        })
                    });
                }

                vm.contractId = 0;
                vm.$otherviewid = "#ContractOtherview";
                vm.viewOther = function (tmpl, ovm, select) {
                    ovm.inContract = true;
                    var el = $(mvvm.$otherviewid).html("");
                    el.append(select == null ? tmpl : $(tmpl).find(select));
                    avalon.scan(el[0], ovm);
                }

                vm.contractId = 0;
                //相关合同
                var gridops1 = {
                    url: "/FinancialAffairs/AccountListByContract",
                    pageid: vmid + "grid1Page",
                    method: "post",
                    createQuery: function () {
                        return { contractid: mvvm.contractId, orderName: mvvm.csort, orderValue: mvvm.csortValue }
                    }
                }
                vm.grid1 = createGrid(gridops1);
                //排序
                vm.csort = "ReceiptDate"
                vm.csortValue = 1;
                vm.csortModel = {
                    Money: 1,
                    AddTime: 0,
                }
                vm.cautosort = function (colname) {
                    var sortvalue = mvvm.csortModel[colname] == 0 ? 1 : 0;
                    mvvm.csort = colname;
                    mvvm.csortValue = sortvalue;
                    mvvm.csortModel[colname] = sortvalue;
                    mvvm.grid1.doSearch();
                }
                //打印
                vm.doPrint = function () {
                    messageBox.confirm('您确定要打印当前产品信息吗？', function () {
                        $("#ContractPanelPrint").printArea()
                    })
                }

                vm.GetContractRelevanceList = GetContractRelevanceList;
                //保存
                vm.formSubmit = function (title) {
                    var btns = [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            if (mvvm.hasPriceError) {
                                messageBox.warning("存在低于最低限价的产品价格，请检查！");
                                return false;
                            }
                            var planSum = arrSum(mvvm.planofpaylist.$model, "Money")
                            if (planSum > mvvm.entity.Amount) {
                                messageBox.warning("计划付款的金额总和大于合同总金额，请检查！");
                                return false;
                            }
                            if (txtRemark) mvvm.entity.Remark = txtRemark.html();
                            var ids = [];
                            mvvm.entity.FileList.forEach(function (file) {
                                if (file.Id) {
                                    //兼容旧版本数据，有可能存的是路径
                                    ids.push(file.Id > 0 ? file.Id : file.Path);
                                }
                            })
                            mvvm.entity.Files = ids.join(",");
                            var model = $.extend(true, {}, mvvm.entity.$model);
                            delete model.FileList;
                            mvvm.contractdetailslist.forEach(function (item) {
                                item.Customer = model.Customer;
                                item.BelongTo = model.BelongTo;
                            });
                            $.extend(model,jsonToSubmit("CList",mvvm.contractdetailslist.$model))
                            mvvm.contractdetailsdellist.$model.forEach(function (item, index) {
                                model["CDelList[" + index + "].Id"] = item.Id
                            })
                            mvvm.planofpaylist.$model.forEach(function (item, index) {
                                model["PList[" + index + "].Id"] = item.Id
                                model["PList[" + index + "].Num"] = item.Num
                                model["PList[" + index + "].Item"] = item.Item
                                model["PList[" + index + "].Money"] = item.Money
                                model["PList[" + index + "].Percents"] = item.Percents
                                model["PList[" + index + "].ReturnedDate"] = item.ReturnedDate
                                model["PList[" + index + "].ReturnedState"] = item.ReturnedState
                                model["PList[" + index + "].Remark"] = item.Remark
                            })
                            if (action == "addfromcallcenter") {
                                model.callid = paramid;
                            }
                            var arapList = mvvm.arapList.$model.concat([]);
                            arapList.forEach(function (item) {
                                item.SalesmanId = mvvm.entity.BelongTo;
                                item.SalesmanName = mvvm.entity.BelongToDisplay;
                                delete item.Contract;
                                delete item.AddBy;
                            });
                            $.extend(model, jsonToSubmit("aList", mvvm.arapList));
                            $.extend(model, jsonToSubmit("aDelList", mvvm.arapDelList));
                            var url = (mvvm.entity.Id > 0 ? "/Market/ContractUpdate/" : "/Market/ContractAdd/");
                            $.post(url + model.Id, model, function (ret) {
                                CBCRM.showResult(ret, function () {
                                    if (ret.result) {
                                        mvvm.mgrid.reloadData();
                                        if (dialog) dialog.close()
                                        if (paramData && paramData.reloadCustomer) paramData.reloadCustomer();
                                    }
                                })
                            })
                            return false
                        }
                    }]
                    var tmplUrl = "/Market/ContractForm";
                    //action == "addfromcallcenter"
                    if (mvvm.entity.IsSample) {
                        title = "快速新增订单(简易)";
                        tmplUrl = "/Market/ContractFormFast";
                    }
                    var dialog = mvvm.openTmpl({
                        title: title, w: 1000, h: 520,
                        btns: btns, url: tmplUrl,
                        onClose: function () {
                            destroyui(["selectProjectTree"]);
                        },
                        onScan: function () {
                            txtRemark = ketool.simple('txtRemark', '98%', '50px')
                            txtRemark.html(mvvm.entity.Remark);
                            /*赋值对应客户*/
                            if (action == 'customer') {
                                mvvm.entity.Customer = paramid
                                if(paramData)mvvm.entity.CustomerDisplay = paramData.entity.Name
                            }
                            if (mvvm.entity.Customer) {
                                mvvm.setCustomerContacts(mvvm.entity.Customer)
                            }
                        }
                    });
                    mvvm.entity.$watch('ContainsTax', function (o, n) {
                        if (o != n) {
                            mvvm.onSumTax()
                        }
                    })
                }
                vm.setCustomerContacts = function (customerid) {
                    $.get('/Customer/Contacts', { 'customerId': customerid }, function (ret) {
                        mvvm.CustomerContactData = ret.data.contacts.Source
                    })
                }
                //取消
                vm.onCancel = function () {
                    mvvm.action = 'list'
                }
                //选择所属战役
                vm.campaignList = []
                vm.campaignPanel = false
                vm.campaignKey = ''
                vm.selectCampaign = function () {
                    $('body').bind('mousedown', function () {
                        mvvm.campaignPanel = false
                        $('body').unbind('mousedown')
                    })
                    getCampaignList();
                    mvvm.campaignPanel = true;
                }
                vm.searchCampaign = function () {
                    getCampaignList();
                }
                vm.closeCampaignPanel = function () {
                    mvvm.campaignPanel = false;
                }
                vm.clickCampaign = function () {
                    var campaign = $(this);
                    mvvm.entity.MarketingCampaign = campaign.attr("key");
                    mvvm.entity.MarketingCampaignDisplay = campaign.attr("alt");
                    mvvm.campaignPanel = false;
                }
                vm.clearCampaignValue = function () {
                    mvvm.entity.MarketingCampaign = ''
                    mvvm.entity.MarketingCampaignDisplay = ''
                }
                //选择所属活动
                vm.activityList = []
                vm.activityPanel = false
                vm.activityKey = ''
                vm.selectActivity = function () {
                    $('body').bind('mousedown', function () {
                        mvvm.activityPanel = false
                        $('body').unbind('mousedown')
                    })
                    getActivityList();
                    mvvm.activityPanel = true;
                }

                vm.searchActivity = function () {
                    getActivityList();
                }
                vm.closeActivityPanel = function () {
                    mvvm.activityPanel = false;
                }
                vm.clickActivity = function () {
                    var activity = $(this);
                    mvvm.entity.MarketActivity = activity.attr("key");
                    mvvm.entity.MarketActivityDisplay = activity.attr("alt");
                    mvvm.activityPanel = false;
                }
                vm.clearActivityValue = function () {
                    mvvm.entity.MarketActivity = ''
                    mvvm.entity.MarketActivityDisplay = ''
                }
                //选择所属销售机会
                vm.salesOpportunitiesList = []
                vm.salesOpportunitiesPanel = false
                vm.salesOpportunitiesKey = ''
                vm.selectSalesOpportunities = function () {
                    $('body').bind('mousedown', function () {
                        mvvm.salesOpportunitiesPanel = false
                        $('body').unbind('mousedown')
                    })
                    getSalesOpportunitiesList();
                    mvvm.salesOpportunitiesPanel = true;
                }
                vm.searchSalesOpportunities = function () {
                    getSalesOpportunitiesList();
                }
                vm.closeSalesOpportunitiesPanel = function () {
                    mvvm.salesOpportunitiesPanel = false;
                }
                vm.clickSalesOpportunities = function () {
                    var vm = this.$vmodel
                        , itemVM = vm[vm.$itemName]
                        , customerVM = avalon.vmodels.setParetCustomer
                    mvvm.entity.SalesOpportunities = itemVM.Id
                    mvvm.entity.SalesOpportunitiesDisplay = itemVM.Title
                    mvvm.entity.Customer = itemVM.Customer
                    mvvm.entity.CustomerDisplay = itemVM.CustomerDisplay
                    mvvm.salesOpportunitiesPanel = false;
                    if (customerVM) {
                        customerVM.q = itemVM.CustomerDisplay
                        customerVM.loadData.call(customerVM)
                    }
                }
                vm.clearSalesOpportunitiesValue = function () {
                    var customerVM = avalon.vmodels.setParetCustomer
                    mvvm.entity.SalesOpportunities = ''
                    mvvm.entity.SalesOpportunitiesDisplay = ''
                    if (customerVM) {
                        customerVM.q = ''
                        customerVM.loadData.call(customerVM)
                        avalon.log('remove customer name')
                    }
                }
                //选择所属跟单报价
                vm.documentaryOfferList = []
                vm.documentaryOfferPanel = false
                vm.documentaryOfferKey = ''
                vm.selectDocumentaryOffer = function () {
                    $('body').bind('mousedown', function () {
                        mvvm.documentaryOfferPanel = false
                        $('body').unbind('mousedown')
                    })
                    getDocumentaryOfferList();
                    mvvm.documentaryOfferPanel = true;
                }
                vm.searchDocumentaryOffer = function () {
                    getDocumentaryOfferList();
                }
                vm.closeDocumentaryOfferPanel = function () {
                    mvvm.documentaryOfferPanel = false;
                }
                vm.clickDocumentaryOffer = function () {
                    var documentaryOffer = $(this);
                    mvvm.entity.DocumentaryOffer = documentaryOffer.attr("key");
                    mvvm.entity.DocumentaryOfferDisplay = documentaryOffer.attr("alt");
                    mvvm.documentaryOfferPanel = false;
                    $.get('/Market/DocumentaryOffer', { 'id': mvvm.entity.DocumentaryOffer }, function (ret) {
                        var source = ret.data.Source
                        if (source.length > 0) {
                            var offer = source[0]
                            //销售机会转合同订单 
                            mvvm.entity.Customer = offer.Customer
                            mvvm.entity.CustomerDisplay = offer.CustomerDisplay
                            mvvm.entity.CustomerSign = offer.CustomerContact
                            mvvm.entity.CustomerSignDisplay = offer.CustomerContactDisplay
                            mvvm.entity.CountAmount = offer.OfferTotal
                            mvvm.entity.TaxRate = offer.TaxRate
                            mvvm.entity.FillUpTax = offer.TaxAmt
                            mvvm.entity.ContainsTax = offer.TaxAmt > 0 ? true : false
                            mvvm.entity.Amount = offer.TotalAmt
                            mvvm.entity.PayType = offer.PayType
                            mvvm.entity.BalanceType = offer.BalanceType
                            mvvm.entity.PayRemark = offer.PayToRemark
                            mvvm.entity.NoteType = offer.NoteType
                            mvvm.entity.ConsignmentType = offer.ConsignmentType
                            mvvm.entity.DeliveryDate = offer.DeliveryDate
                            mvvm.entity.Consignee = offer.Consignee
                            mvvm.entity.ConsigneeDisplay = offer.ConsigneeDisplay
                            mvvm.entity.FreightBearRemark = offer.FreightBear
                            mvvm.entity.ConsigneePhone = offer.ConsigneePhone
                            mvvm.entity.ConsigneeAddress = offer.ConsigneeAddress
                            mvvm.entity.BelongTo = offer.DocumentaryEmployee
                            mvvm.entity.BelongToDisplay = offer.DocumentaryEmployeeDisplay
                            $.get('/Market/GetDocumentaryOfferProducts/', { "id": offer.Id }, function (ret) {
                                var detailsource = ret.data.Source
                                var detaildata = []
                                if (detailsource.length > 0) {
                                    detailsource.forEach(function (item, i) {
                                        var detailsData = avalon.mix({}, contractdetailsData)
                                        detailsData.Num = item.Num
                                        detailsData.Price = item.Price
                                        detailsData.Money = item.Money
                                        detailsData.Product = item.Product
                                        detailsData.ProductName = item.ProductName
                                        detailsData.Standard = item.Standard
                                        detaildata.push(detailsData)
                                    })
                                    mvvm.contractdetailslist = detaildata
                                }
                            })
                        }
                    })
                }
                vm.clearDocumentaryOfferValue = function () {
                    mvvm.entity.DocumentaryOffer = ''
                    mvvm.entity.DocumentaryOfferDisplay = ''
                }

                vm.mousedownstop = function (e) {
                    e.stopPropagation()
                }
                //归属员工
                vm.selectBelongTo = function () {
                    plugins.selectUser({
                        dataAuth: 2020601,
                        callback: function (us) {
                            var u = us[0];
                            mvvm.entity.BelongTo = u.Id;
                            mvvm.entity.BelongToDisplay = u.FullName;
                        }
                    });
                }
                //我方签约
                vm.selectSignpersion = function () {
                    plugins.selectUser({
                        dataAuth: 2020601,
                        callback: function (us) {
                            var u = us[0];
                            mvvm.entity.MySignPersion = u.Id;
                            mvvm.entity.MySignPersionDisplay = u.FullName;
                        }
                    });
                }
                //选客户/联系人
                vm.selectCustomer = function () {
                    plugins.selectCustomer({
                        type: "contacts",
                        required:{con:false},
                        callback: function (cus, cons) {
                            var cu = cus[0], entity = mvvm.entity;
                            entity.Customer = cu.Id
                            entity.CustomerDisplay = cu.Name
                            entity.CustomerMemberGrade = cu.MemberGrade
                            entity.CustomerMemberGradeDisplay = cu.MemberGradeDisplay
                            mvvm.CustomerMemberGrade = cu.MemberGrade
                            mvvm.CustomerMemberGradeDisplay = cu.MemberGradeDisplay
                            entity.ConsigneeAddress = cu.CompanyAddress || "";

                            //mvvm.setCustomerContacts(cu.Id)
                            mvvm.CustomerContactData = [];
                            if (cu.Contacts) {
                                cu.Contacts.forEach(function (c) {
                                    mvvm.CustomerContactData.push(c);
                                });
                            }
                            if (cons.length > 0) {
                                var con = cons[0];
                                entity.CustomerSign = con.Id
                                entity.CustomerSignDisplay = con.Name
                                entity.CustomerMobile = con.MobileNumber1
                            } else {
                                entity.CustomerSign = ""
                                entity.CustomerSignDisplay = ""
                            }
                        }
                    });
                }
                //签约日期
                vm.signacontractdateOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        mvvm.entity.SignAContractDate = formatDate
                    }
                }
                //合同期限
                vm.contractstardateOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        mvvm.entity.StartDate = formatDate
                    }
                }
                vm.contractenddateOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        mvvm.entity.EndDate = formatDate
                    }
                }
                //交货时间
                vm.deliverydateOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        mvvm.entity.DeliveryDate = formatDate
                    }
                }
                //取当前行序号
                vm.pIndex = 0
                vm.onSetIndex = function () {
                    mvvm.pIndex = this.$vmodel.$index
                }
                //计划交付日期 
                vm.planofpaydateOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        mvvm.contractdetailslist[mvvm.pIndex].PlanOfPayDate = formatDate
                    }
                }
                //计划回款日期
                vm.retrunmoneydateOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        mvvm.planofpaylist[mvvm.pIndex].PlanOfPayDate = formatDate
                    }
                }
                //服务期限
                vm.serverstardateOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        mvvm.contractdetailslist[mvvm.pIndex].StartDate = formatDate
                    }
                }
                vm.serverenddateOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        mvvm.contractdetailslist[mvvm.pIndex].EndDate = formatDate
                    }
                }
                //上传附件
                vm.uploadFiles = function () {
                    var upwin = CBCRM.upload(true, function (node, data, files) {
                        mvvm.entity.FileList = mvvm.entity.FileList.$model.concat(files);
                        upwin.close();
                    }, { settings: {multi:true}});
                }
                vm.delFile = function (index) {
                    mvvm.entity.FileList.splice(index, 1);
                }
                //切换界面
                vm.onAction = function (actiontype) {
                    mvvm.action = actiontype;
                }
                //编辑界面列表全选
                vm.onChkAll = function (obj) {
                    var chkVal = $(this).attr("checked");
                    $("input[name='" + obj + "']").each(function (index, item) {
                        if (obj == 'planofpay' && index == 0)
                            item.checked = false
                        else
                            item.checked = chkVal
                    })
                }
                //产品明细、付款计划-新加一行
                vm.onRelevanceAdd = function (obj) {
                    switch (obj) {
                        case "contractdetails":
                            mvvm.contractdetailslist.push(avalon.mix(true, {}, contractdetailsData));
                            break
                        case "planofpay":
                            var num = mvvm.planofpaylist.length + 1
                            planofpayData.Num = num
                            mvvm.entity.PlanOfPayNum = num
                            if (mvvm.returnedstatedata.length > 0) planofpayData.ReturnedState = mvvm.returnedstatedata[0].Id;
                            mvvm.planofpaylist.push(avalon.mix({}, planofpayData))
                            if (planofpayData.Percents) mvvm.doMathResult(mvvm.planofpaylist[num - 1]);
                            break
                    }
                }
                //产品明细、付款计划-删除一行
                vm.onRelevanceDel = function (obj) {
                    var index = parseInt($(this).attr('index'))
                    switch (obj) {
                        case "contractdetails":
                            mvvm.contractdetailsdellist.push(mvvm.contractdetailslist[index])
                            mvvm.contractdetailslist.removeAt(index)
                            mvvm.onSumCost()
                            break
                        case "planofpay":
                            mvvm.planofpaylist.removeAt(index)
                            mvvm.entity.PlanOfPayNum = mvvm.planofpaylist.$model.length
                            break
                    }
                }
                //产品明细、付款计划-删除所有选中行
                vm.onRelevanceAllDel = function (obj) {
                    var list
                    switch (obj) {
                        case "contractdetails":
                            list = mvvm.contractdetailslist
                            mvvm.contractdetailsdellist = list
                            break
                        case "planofpay":
                            list = mvvm.planofpaylist
                            break
                    }
                    $("input[name='" + obj + "']:checked").each(function (index, item) {
                        list.removeAt(parseInt($(this).attr('index')))
                    })
                    if (obj == "planofpay") mvvm.entity.PlanOfPayNum = mvvm.planofpaylist.$model.length
                    if (obj == "contractdetails") mvvm.onSumCost()
                }
                vm.detailsTotalAmount = 0
                //合同金额合计
                vm.hasPriceError = false;
                vm.onSumCost = function () {
                    var cost = 0, profit = 0;
                    vm.hasPriceError = false;
                    mvvm.contractdetailslist.forEach(function (item, index) {
                        var num = parseFloat(item.Num), price = parseFloat(item.Price), sPrice = parseFloat(item.StockPrice);
                        if (!item.Money) {
                            var rowmoney = num * price
                            if (rowmoney) {
                                item.Money = rowmoney
                            }
                        }
                        var money = parseFloat(item.Money)
                        if (money) {
                            cost +=  money
                            profit += (money - (sPrice * num));
                        }
                    })
                    mvvm.entity.CountAmount = cost
                    mvvm.entity.GrossProfit = profit;
                    mvvm.onSumTax()
                    mvvm.computeRoyalty();
                }
                vm.onSumRowMoney = function (product) {
                    if ($(this).attr("data-id") == "Price" && product) {
                        var title = (product.LowestPrice && product.Price < product.LowestPrice) ? "该产品的最低价为：" + product.LowestPrice : "";
                        $(this).attr("title", title);
                    }
                    var index = $(this).attr('index')
                    mvvm.contractdetailslist.forEach(function (item, i) {
                        if (item.LowestPrice && item.Price < item.LowestPrice) {
                            mvvm.hasPriceError = true;
                            //messageBox.warning("产品(" + item.ProductName + ")的单价(" + item.Price + ")小于该产品的最低限价(" + item.LowestPrice + ")！");
                            return;
                        }
                        if (index == i) {
                            var money = parseFloat(item.Num) * parseFloat(item.Price)
                            if (money && money >= 0) {
                                item.Money = money
                            } else {
                                item.Money = 0
                            }
                        }
                    })
                    mvvm.onSumCost()
                }
                vm.onSumTax = function () {
                    var taxrate = parseFloat(mvvm.entity.TaxRate)
                    if (taxrate) mvvm.entity.FillUpTax = parseFloat(mvvm.entity.CountAmount) * taxrate / 100
                    var favourable = parseFloat(mvvm.entity.FavourableAmount)
                    if (!favourable) mvvm.entity.FavourableAmount = 0
                    if (mvvm.entity.ContainsTax) {
                        mvvm.entity.Amount = parseFloat(mvvm.entity.CountAmount) + parseFloat(mvvm.entity.FillUpTax) - parseFloat(mvvm.entity.FavourableAmount)
                    } else {
                        mvvm.entity.Amount = parseFloat(mvvm.entity.CountAmount) - parseFloat(mvvm.entity.FavourableAmount)
                    }
                }
                //回款计算占百分比
                vm.doMathRate = function (item) {
                    var amount = mvvm.entity.Amount;
                    if (!amount || isNaN(amount)) {
                        item.Percents = 0;
                        return;
                    }
                    var money = item.Money;
                    if (!money || isNaN(money)) item.Percents = 0;
                    else item.Percents = (money / amount * 100).toFixed(1).replace(".0", "");
                }
                //占百分比计算回款
                vm.doMathResult = function (item) {
                    var amount = mvvm.entity.Amount;
                    if (!amount || isNaN(amount)) {
                        item.Money=0
                        return;
                    }
                    var rate = item.Percents;
                    if (!rate || isNaN(rate)) item.Money = 0;
                    else item.Money = (amount * rate / 100).toFixed(1).replace(".0", "");
                }
                //按百分比计算所有回款
                vm.mathAllResult = function () {
                    mvvm.planofpaylist.forEach(mvvm.doMathResult);
                }
                //计算提成
                vm.computeRoyalty = function () {
                    mvvm.contractdetailslist.forEach(function (item) {
                        var num = item.Num || 0, price = item.Price || 0, rPrice = item.RoyaltyPrice || 0, rValue = item.RoyaltyValue || 0;
                        num = parseFloat(num, 10);
                        price = parseFloat(price, 10);
                        rPrice = parseFloat(rPrice, 10);
                        rValue = parseFloat(rValue, 10);      
                        if (item.RoyaltyType == 1) {
                            //按数量
                            item.RoyaltyMoney = (num * rValue).toFixed(2).replace(".00", "");
                        } else {
                            //按百分比
                            if (item.RoyaltyCompute == 1) {
                                //按销售金额百分比
                                item.RoyaltyMoney = (num * rPrice * rValue / 100).toFixed(2).replace(".00", "");
                            } else {
                                //按毛利百分比
                                item.RoyaltyMoney = (num * (price - rPrice) * rValue / 100).toFixed(2).replace(".00", "");
                            }
                        }
                    });
                }
                //提成说明
                vm.royaltyDsc = function (item) {
                    return avalon.filters.royaltyDsc(item);
                }
                //选择产品
                vm.productKey = ''
                vm.catecoryId = 0
                vm.productList = []
                vm.productpaing = {
                    pagesize: 10,
                    pagesizeopts: [10, 20, 50, 100, 200, 500, 1000],
                    paging: function (pageIndex, pageSize) {
                        mvvm.getProcutList(pageIndex, pageSize)
                    }
                }
                //取产品
                vm.getProcutList = function (pageIndex, pageSize) {
                    var data = {
                        "typeid": mvvm.catecoryId, "key": mvvm.productKey, "pageSize": pageSize, "pageIndex": pageIndex
                    };
                    if (mvvm.entity.Customer) data.customerId = mvvm.entity.Customer;
                    $.get('/Product/PriceList/', data, function (ret) {
                        mvvm.productList = ret.data.productList.Source;
                        var page = avalon.vmodels.productupaing;
                        if (page) {
                            page.total = ret.data.productList.RecordTotal;
                            page.setIndex(ret.data.productList.PageIndex);
                        }
                    })
                }
                vm.onSelectProuct = function () {
                    mvvm.productKey = ''
                    mvvm.catecoryId = 0
                    dialog = openTmpl({
                        vm: mvvm, title: "选择产品", w: 1000, h: 300, tmpl: tmpl, tmplid: "ProductListTemp",
                        btns: [{
                            name: '确定',
                            focus: true,
                            callback: function () {
                                var product = mvvm.productList.$model[mvvm.productListIndex]
                                mvvm.selectedProduct(product);
                            }
                        }]
                    });
                }
                vm.onSearchProduct = function () {
                    var page = avalon.vmodels.productupaing, pageSize = page ? page.pagesize : 10;
                    mvvm.getProcutList(1, pageSize);
                }
                vm.productListIndex = 0
                vm.onSetProductIndex = function () {
                    var index = this.$vmodel.$index;
                    var item = this.$vmodel.item.$model;
                    if (item.State == 2) return;
                    mvvm.productListIndex = index;
                    $("input[name='rdoproduct']").eq(index).attr("checked", "checked")
                }

                vm.selectedProduct = function (product) {
                    if (product.State == 2) {
                        messageBox.warning("抱歉，该产品已经下架！");
                        return false;
                    }
                    var contractdetails = mvvm.contractdetailslist[mvvm.pIndex]
                    contractdetails.Product = product.Id
                    contractdetails.ProductName = product.Name
                    contractdetails.BrandDisplay = product.Brand.Name
                    contractdetails.Standard = product.Standard
                    //单价:特工价-〉级别价-〉标准价
                    var price = product.SpecialPrice || product.GradePrice || product.GeneralCustomerPrice, num = 1;
                    //成交单价
                    contractdetails.Price = price;
                    contractdetails.StockPrice = product.StockPrice;
                    contractdetails.StandardPrice = product.GeneralCustomerPrice;
                    contractdetails.LowestPrice = product.LowestPrice
                    contractdetails.RoyaltyPrice = product.RoyaltyPrice
                    contractdetails.RoyaltyType = product.RoyaltyType
                    contractdetails.RoyaltyCompute = product.RoyaltyCompute
                    contractdetails.RoyaltyValue = product.RoyaltyValue
                    //contractdetails.RoyaltyMoney = product.RoyaltyMoney
                    contractdetails.Num = num
                    contractdetails.Money = price * num;
                    contractdetails.Unit = product.Units
                    contractdetails.UnitsDisplay = product.UnitsDisplay
                    contractdetails.No = product.No
                    contractdetails.BrandId = product.Brand ? product.Brand.Id : "";
                    contractdetails.BrandName = product.Brand ? product.Brand.Name : "";
                    mvvm.onSumCost()
                    mvvm.mathAllResult();
                    if (dialog) dialog.close()
                }
                vm.formatPriceList = formatPriceList;
                //产品分类树配置
                vm.pCategoryTreeOpts = {
                    treeopts: {
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                mvvm.catecoryId = treeNode.Id
                                var page = avalon.vmodels.productupaing, pageSize = page ? page.pagesize : 10;
                                mvvm.getProcutList(1, pageSize);
                            }
                        },
                        view: {
                            addHoverDom: '',
                            removeHoverDom: ''
                        }
                    }
                }
                //tab切换
                vm.tab = 'tab1'
                vm.tabChange = function () {
                    var tabid = $(this).attr("val")
                    mvvm.tab = tabid
                }

                vm.contactChange = function () {
                    var id = $(this).find('option:selected').val()
                    var name = $(this).find('option:selected').text()
                    if (id) {
                        mvvm.entity.CustomerContact = id
                        mvvm.entity.CustomerSignDisplay = name
                    } else {
                        mvvm.entity.CustomerContact = ''
                        mvvm.entity.CustomerSignDisplay = ''
                    }
                    for(var i = 0; i < mvvm.CustomerContactData.length; i++)
                    {
                        if (mvvm.CustomerContactData[i].Id == id)
                            mvvm.entity.CustomerMobile = mvvm.CustomerContactData[i].MobileNumber1;
                    }
                }
                vm.cnsigneChange = function () {
                    var id = $(this).find('option:selected').val()
                    var name = $(this).find('option:selected').text()
                    if (id) {
                        mvvm.entity.Consignee = id
                        mvvm.entity.ConsigneeDisplay = name
                    } else {
                        mvvm.entity.Consignee = ''
                        mvvm.entity.ConsigneeDisplay = ''
                    }
                }
                vm.CustomerMemberGrade = "";
                vm.CustomerMemberGradeDisplay = "";

                vm.canout = true;
                vm.destroy = function () {
                    // avalon.vmodels[vmid] = null;
                }

                //导航切换
                vm.currNav = 1;
                vm.needReLoad = false;
                vm.doChangeNav = function (n, no, cId, mId) {
                    var id=mvvm.entity.Id;
                    mvvm.currNav = n;
                    if (n == 1) {
                        mvvm.isCustInfo = true
                        if (mvvm.needReLoad) mvvm.loadEntity(id);
                    }
                    else if (n == 2) {
                        mvvm.isCustInfo = false
                    }
                    var paths = {
                        2: '/FinancialAffairs/Accounting/' + no + '/Contract/' + cId + '/' + mId,
                        //4:"/FinancialAffairs/ARAP/"+id+"/Contract",
                        4:"/FinancialAffairs/ARAPCollect/"+id+"/Contract",
                        5: "/FinancialAffairs/ARAPPay/" + id + "/Contract"
                    }
                    if (paths[n])
                        goto(paths[n], true, {
                            entity: mvvm.entity.$model,
                            reloadEntity: function () {
                                //标记下次点击合同面板左边导航的合同详情时候,需要重新读取合同信息
                                mvvm.needReLoad = true;
                            },
                            viewOther: mvvm.viewOther
                        });
                }
                vm.tabWidth = 780;

                vm.tabs = 1;
                vm.tabChanges = function () {
                    var val = $(this).attr("val");
                    mvvm.tabs = val;
                }

                vm.getcontractlist = []
                //列表显示更多
                vm.showindex = -1;
                vm.showmore = function (index, id) {
                    if (index != mvvm.showindex) mvvm.showindex = index;
                    else mvvm.showindex = -1
                    GetContractRelevanceList(id);
                }
                vm.hidemore = function () {
                    mvvm.showindex = '-1'
                }

                //应收应付
                vm.arapList = [];
                vm.arapDelList = [];
                vm.arapSum = { m1: 0, m2: 0, m3: 0 };
                vm.doArapSum = function () {
                    var arapSum = { m1: 0, m2: 0, m3: 0 };
                    mvvm.arapList.forEach(function (item) {
                        if (item.Type == 0) {
                            arapSum.m1 += parseFloat(item.Money);
                        }
                        else {
                            arapSum.m2 += parseFloat(item.Money);
                        }
                    });
                    arapSum.m3 = arapSum.m1 - arapSum.m2;
                    mvvm.arapSum = arapSum;
                }
                vm.watchArapItem = function (item) {
                    item.$watch("Money", mvvm.doArapSum);
                    item.$watch("Type", mvvm.doArapSum);
                }
                vm.addArap = function () {
                    var m = modelFactory.create("ARAP");
                    var c=mvvm.entity.$model;
                    if (!c.Id && mvvm.arapList.length == 0) {
                        m.CustomerId = c.Customer;
                        m.CustomerName = c.CustomerDisplay;
                        m.SettleCustomerId = c.Customer;
                        m.SettleCustomerName = c.CustomerDisplay;
                        m.Type = 0;
                        m.Money = c.Amount;
                        m.NotSettleMoney = c.Amount;
                    }
                    m.DutyPersonId = CBCRM.memberShip.Id;
                    m.DutyPersonName = CBCRM.memberShip.FullName;
                    mvvm.arapList.push(m);
                    var item=mvvm.arapList[mvvm.arapList.length - 1]
                    mvvm.watchArapItem(item);
                    mvvm.doArapSum();
                }
                vm.delArap = function (index,id) {
                    if (id) mvvm.arapDelList.push(id);
                    mvvm.arapList.removeAt(index);
                    mvvm.doArapSum();
                }
                //结算客户
                vm.selectSettleCustomer = function (item) {
                    plugins.selectCustomer({
                        callback: function (cus) {
                            var cu = cus[0];
                            item.SettleCustomerId = cu.Id;
                            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.selectProject= function (item) {
                    var treeid = "selectProjectTree", panelid = "selectProjectTreepanel";
                    var panel = avalon.vmodels[panelid],tree = avalon.vmodels[treeid]
                    if (!panel) {
                        //dropDownGroupPostUserTree
                        avalon.ui.dropDownTree(this, {
                            dropDownTreeId: treeid,
                            dropDownTreeOptions: {
                                q: '请输入收支项目名称',
                                treeopts: {
                                    callback: {
                                        onClick: function (e, treeId, treeNode) {
                                            item.Project = treeNode.Name;
                                            panel.toggle(false)
                                        }
                                    },
                                    async: {
                                        enable:true,
                                        url: function (treeId, treeNode) {
                                            var url = "/FinancialAffairs/PorjectDrodonwn";
                                            return url;
                                        },
                                        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;
                                        }
                                    },
                                    data: {
                                        simpleData: {
                                            enable: true,
                                            idKey: 'Id',
                                            pIdKey: 'ParentId'
                                        },
                                        key: {
                                            name: 'Name'
                                        }
                                    }
                                }
                            },
                            initevent: false
                        }, this.$vmodels)
                        panel = avalon.vmodels[panelid]
                        tree = avalon.vmodels[treeid]
                    } else {
                        panel.target = this
                    }
                    panel.toggle(true)
                }

                vm.getAutoCode = function () {
                    GetAutoCode();
                }
                //字典
                vm.settleWays = [];//结算方式
                vm.getDicts = function () {
                    getDicts({ settleWays: 100056 }, mvvm);
                }
            })
            mvvm.mgrid.init();
            mvvm.grid1.init();
            mvvm.getDicts();
            //mvvm.entity = modelFactory.create('Contract');

            avalon.filters.StorageOutState = function (val) {
                var states = { 0: "未出库", 1: "部分出库", 2: "已出库", 3: "入库转运中", 4: "已销售待出库" }
                return states[val];
            }
            
            //合同产品明细对象
            var contractdetailsData = modelFactory.create("ContractDetails");
            contractdetailsData.PlanOfPayNum = 1;
            contractdetailsData.No = 0;
            //计划付款期次
            var planofpayData = {
                Id: '',
                Num: 1,
                Item: '',
                Money: '',
                Percents: '',
                ReturnedDate: '',
                ReturnedState: '',
                ReturnedStateDisplay: '',
                Contract: '',
                Remark: ''
            }
            InitDataItem()
            if (action != "key" && paramid) getMemberGrade();
            function getMemberGrade() {
                $.get('/Product/GetMemberGrade/' + paramid, {}, function (ret) {
                    if (ret.result) {
                        mvvm.CustomerMemberGrade = ret.data.CustomerMemberGrade;
                        mvvm.CustomerMemberGradeDisplay = ret.data.CustomerMemberGradeDisplay;
                    }
                });
            }
            function GetContractList(data, callback, view) {
                mvvm.mgrid.gridmsg = lang.LoadingMsg;
                data = data || {};
                //只取某一客户合同订单
                if (action == 'customer')
                    data.customerId = paramid;
                else if (action == "salesopp") {
                    data.salesid = paramid;
                }
                $.get('/Market/Contract', data, function (ret) {
                    mvvm.mgrid.gridmsg = "";
                    if (ret.result) {
                        mvvm.ADD = ret.data.ADD
                        mvvm.ADDSimple = ret.data.ADDSimple
                        mvvm.DELETE = ret.data.DELETE
                        mvvm.NOPAGE = ret.data.NOPAGE
                        mvvm.mgrid.gridmsg = ret.data.Source.length > 0 ? "" : lang.NoListData;
                        mvvm.contractlist = ret.data.Source;
                        mvvm.sumAmount = 0;
                        mvvm.contractlist.forEach(function (item) {
                            if (item.Amount) mvvm.sumAmount += item.Amount;
                        });
                        if (!view) {
                            if (mvvm.NOPAGE) {
                                destroyui(["upaing"]);
                            } else {
                                var page = avalon.vmodels.upaing;
                                if (page) page.total = ret.data.RecordTotal;
                            }
                        }


                        if (callback) callback(ret);
                    } else
                        messageBox.error(ret.message);

                })
            }

            //取业务明细、付款期次，应收应付数据
            function GetContractRelevanceList(contractId) {
                mvvm.getcontractlist = []
                mvvm.arapList = [];
                $.get('/Market/GetContractRelevance/', { "Id": contractId }, function (ret) {
                    mvvm.arapList = ret.data.arapList;
                    mvvm.contractdetailslist = ret.data.contractDetailsList
                    mvvm.getcontractlist = ret.data.contractDetailsList
                    mvvm.planofpaylist = ret.data.planOfPayList
                    mvvm.detailsTotalAmount = ret.data.detailsSum
                    mvvm.outlist = ret.data.outlist
                    mvvm.canout = mvvm.contractdetailslist.length > 0 && mvvm.outlist.length == 0 ? true : false;
                    $.each(mvvm.contractdetailslist, function (item) {
                        if (item.OutNum < item.Num) {
                            mvvm.canout = true;
                            return false;
                        }
                    });
                    mvvm.arapList.forEach(function (item) {
                        mvvm.watchArapItem(item);
                    })
                    mvvm.doArapSum();
                })
            }
            //从字典取数据
            function InitDataItem() {
                $.get('/Market/GetContractDictionary/', {}, function (ret) {
                    mvvm.contracttypedata = ret.data.contracttypeList
                    mvvm.contractstatedata = ret.data.contractstateList
                    mvvm.contractstagedata = ret.data.contractstageList
                    mvvm.billtypedata = ret.data.billtypeList
                    mvvm.currencytypedata = ret.data.currencytypeList
                    mvvm.paytpyedata = ret.data.paytpyeList
                    mvvm.consignmenttype = ret.data.consignmentTypeList
                    mvvm.returnedstatedata = ret.data.returnedstateList
                    mvvm.bankdata = ret.data.bankList
                    mvvm.balancetypedata = ret.data.balancetypeList
                    if (mvvm.contracttypedata.length > 0 && mvvm.entity) {
                        var dct = findArr(mvvm.contracttypedata.$model, function (item) { return item.IsDefault });
                        if (dct == null) dct = mvvm.contracttypedata.$model[0];
                        mvvm.entity.ContractType = dct.Id;
                    }
                    if (mvvm.contractstatedata.length > 0 && mvvm.entity) {
                        var dct = findArr(mvvm.contractstatedata.$model, function (item) { return item.IsDefault });
                        if (dct == null) dct = mvvm.contractstatedata.$model[0];
                        mvvm.entity.State = dct.Id;
                    }
                    if (mvvm.contractstagedata.length > 0 && mvvm.entity) {
                        var dct = findArr(mvvm.contractstagedata.$model, function (item) { return item.IsDefault });
                        if (dct == null) dct = mvvm.contractstagedata.$model[0];
                        mvvm.entity.CurrentStage = dct.Id;
                    }
                    ret.data.contracttypeList.forEach(function (item) {
                        mvvm.queryData.contracttype.items.push({val:item.Id,label:item.Data,curr:false});
                    });
                    ret.data.contractstateList.forEach(function (item) {
                        mvvm.queryData.state.items.push({val:item.Id,label:item.Data,curr:false});
                    });
                })
            }
            //取所属战役
            function getCampaignList() {
                var key = mvvm.campaignKey;
                $.get('/Market/Campaign/', { "key": key }, function (ret) {
                    mvvm.campaignList = ret.data.Source;
                })
            }
            //取所属活动
            function getActivityList() {
                var key = mvvm.activityKey;
                var campaignId = mvvm.entity.MarketingCampaign;
                $.get('/Market/Activity/', { "key": key, "campaignid": campaignId }, function (ret) {
                    mvvm.activityList = ret.data.Source;
                })
            }
            //取所属销售机会
            function getSalesOpportunitiesList() {
                var key = mvvm.salesOpportunitiesKey;
                //只取当前客户
                var customerId = ''
                if (that.params.id && that.params.action == 'customer') {
                    customerId = that.params.id
                }

                $.get('/Market/SalesOpportunities/', { "key": key, "customerid": customerId }, function (ret) {
                    mvvm.salesOpportunitiesList = ret.data.Source;
                })
            }
            //取所属跟单报价
            function getDocumentaryOfferList() {
                var key = mvvm.documentaryOfferKey
                    , customerId = ''
                    , saleId = 0
                if (that.params.id && that.params.action == 'customer') {
                    customerId = that.params.id
                }

                if (mvvm.entity && mvvm.entity.SalesOpportunities) {
                    saleId = mvvm.entity.SalesOpportunities
                }

                $.get('/Market/DocumentaryOffer/', {
                    "key": key
                    , "customerid": customerId
                    , 'salesid': saleId
                }, function (ret) {
                    mvvm.documentaryOfferList = ret.data.Source;
                })
            }

            //取合同自动编号
            function GetAutoCode(prdfix) {
                $.get('/Market/GetContractAutoCode', { "prdfix": prdfix }, function (ret) {
                    mvvm.entity.ContractNum = ret.data.autoCode
                    mvvm.entity.ContractName = "合同订单（" + ret.data.autoCode + "）";
                })
            }

            function addFromCallCenter() {
                mvvm.doadd(true);
                var st = new Date(), et = new Date();
                et.setYear(et.getFullYear() + 1);
                var format = "yyyy-MM-dd";
                mvvm.entity.StartDate = GetDateTime(st, format);
                mvvm.entity.EndDate = GetDateTime(et, format);
                var callvm = avalon.vmodels.Calls;
                var customer = callvm.customerEntity, callEntity = callvm.callCenterEntity;
                if (callEntity.Cid) {
                    mvvm.entity.Customer = callEntity.Cid;
                    mvvm.entity.CustomerDisplay = callEntity.CustomerName
                    mvvm.entity.CustomerSign = callEntity.ContactId;
                    mvvm.entity.CustomerSignDisplay = callEntity.CallsName;
                    mvvm.entity.CustomerMobile = callEntity.CallsMobile;
                    mvvm.entity.ConsigneeAddress = callEntity.Address;
                    mvvm.setCustomerContacts(callEntity.Cid)
                    /*归属员工*/
                    mvvm.entity.BelongTo = customer.Owner;
                    mvvm.entity.BelongToDisplay = customer.OwnerBy;

                    if (customer) {
                        mvvm.entity.CustomerMemberGrade = customer.MemberGrade
                        mvvm.entity.CustomerMemberGradeDisplay = customer.MemberGradeDisplay
                        mvvm.CustomerMemberGrade = customer.MemberGrade
                        mvvm.CustomerMemberGradeDisplay = customer.MemberGradeDisplay
                    }
                }
            }
            if (action == 'key') {
                key = decodeURI(that.params.id);
                mvvm.queryData.key.val = key;
            }
            switch (action) {
                case "customer":
                    /*隐藏其它，只显示列表块*/
                    mvvm.showOnlyList = true
                    paramData.viewOther(tmpl, mvvm);
                    break;
                case "get":
                case "view":
                    mvvm.doview(paramid);
                    break;
                case "addfromcallcenter":
                    addFromCallCenter();
                    break;
                case "edit":
                    mvvm.doedit(paramid)
                    break;
                case "trun":
                    $.get('/Market/DocumentaryOffer', { 'id': that.params.id }, function (ret) {
                        var source = ret.data.Source
                        if (source.length > 0) {
                            var offer = source[0]
                            //销售机会转合同订单
                            mvvm.doadd()
                            mvvm.entity.DocumentaryOffer = offer.Id
                            mvvm.entity.DocumentaryOfferDisplay = offer.Title
                            mvvm.entity.SalesOpportunities = offer.SalesOpportunities
                            mvvm.entity.SalesOpportunitiesDisplay = offer.SalesOpportunitiesDisplay
                            mvvm.entity.Customer = offer.Customer
                            mvvm.entity.CustomerDisplay = offer.CustomerDisplay
                            mvvm.entity.CustomerMemberGrade = offer.CustomerMemberGrade || "";
                            mvvm.entity.CustomerMemberGradeDisplay = offer.CustomerMemberGradeDisplay || "";
                            mvvm.entity.CustomerSign = offer.CustomerContact
                            mvvm.entity.CustomerSignDisplay = offer.CustomerContactDisplay
                            mvvm.entity.CountAmount = offer.OfferTotal
                            mvvm.entity.TaxRate = offer.TaxRate
                            mvvm.entity.FillUpTax = offer.TaxAmt
                            mvvm.entity.ContainsTax = offer.TaxAmt > 0 ? true : false
                            mvvm.entity.Amount = offer.TotalAmt
                            mvvm.entity.PayType = offer.PayType
                            mvvm.entity.BalanceType = offer.BalanceType
                            mvvm.entity.PayRemark = offer.PayToRemark
                            mvvm.entity.NoteType = offer.NoteType
                            mvvm.entity.ConsignmentType = offer.ConsignmentType
                            mvvm.entity.DeliveryDate = offer.DeliveryDate
                            mvvm.entity.Consignee = offer.Consignee
                            mvvm.entity.ConsigneeDisplay = offer.ConsigneeDisplay
                            mvvm.entity.FreightBearRemark = offer.FreightBear
                            mvvm.entity.ConsigneePhone = offer.ConsigneePhone
                            mvvm.entity.ConsigneeAddress = offer.ConsigneeAddress
                            mvvm.entity.BelongTo = offer.DocumentaryEmployee
                            mvvm.entity.BelongToDisplay = offer.DocumentaryEmployeeDisplay
                            $.get('/Market/GetDocumentaryOfferProducts/', { "id": offer.Id }, function (ret) {
                                var detailsource = ret.data.Source
                                var detaildata = []
                                if (detailsource.length > 0) {
                                    detailsource.forEach(function (item, i) {
                                        var detailsData = avalon.mix({}, contractdetailsData)
                                        detailsData.Num = item.Num
                                        detailsData.Price = item.Price
                                        detailsData.Money = item.Money
                                        detailsData.Product = item.Product
                                        detailsData.ProductName = item.ProductName
                                        detailsData.Standard = item.Standard
                                        detaildata.push(detailsData)
                                    })
                                    mvvm.contractdetailslist = detaildata
                                }
                            })
                        }
                    })
                    break;
                case "salesopp":
                    if (paramData) paramData.viewOther(tmpl, mvvm, "#tableList");
                    break;
                default:
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                    break;
            }
            var txtRemark = null;
        }

        ///销售管理-业务明细
        , ProductList: function (tmpl, lang, contentId, module,paramData) {
            var CBCRM = avalon.vmodels.CBCRM,vmid="productlist", that = this, dialog;
            var mvvm = CBCRM.define(vmid, function (vm) {
                vm.lang = lang
                vm.entity = {}
                vm.entityList = []
                vm.showItem = {}
                vm.keyword = ''
                vm.customerId = '';
                vm.history = []
                vm.showOnlyList = false
                vm.contractSelect = []
                vm.ADD = false
                vm.DELETE = false
                vm.NOPAGE = false
                vm.ACCOUNTING = false
                vm.PRODUCTSTOCKTPRICE = false;
                vm.totalMoney = 0
                vm.totalReturnedMoney = 0
                //左边导航子项显示隐藏
                vm.ShowSubNav = ''
                vm.onSubNav = function (subname) {
                    if (mvvm.ShowSubNav == subname)
                        mvvm.ShowSubNav = ''
                    else
                        mvvm.ShowSubNav = subname
                }
                //关键字搜索
                vm.search = function () {
                    var data = mvvm.createQuery();
                    data.key = mvvm.keyword;
                    initWhthPageList(data);
                }
                //分页
                vm.grid1 = { gridmsg: "" };
                vm.userpaing = {
                    paging: function (pageIndex,pageSize) {
                        var data = mvvm.createQuery();
                        data.pageSize = pageSize;
                        data.pageIndex = pageIndex;
                        initWhthPageList(data);
                    }
                }
                //查询条件
                initQuerys(vm);
                vm.queryData = {
                    overtime: {
                        label: "到期提醒", val: "", valLabel: "",
                        items: [
                            { label: "不限", val: "", curr: true },
                            { label: "30天内", val: "30", curr: false },
                            { label: "7天内", val: "7", curr: false },
                            { label: "今天", val: "1", curr: false },
                            { label: "已过期1-7天", val: "-7", curr: false },
                            { label: "已过期8-30天", val: "-8", curr: false },
                            { label: "过期大于30天", val: "-30", curr: false }
                        ]
                    }
                }
                vm.onQueryChange = function (data, name, val, type) {
                    data.key = mvvm.keyword;
                    initWhthPageList(data);
                }
                vm.viewProduct = function (id) {
                    goto('/Product/Product/' + id + "/view", true);
                }
                //新增
                vm.doadd = function () {
                    mvvm.entity = modelFactory.create('ContractDetails');
                    mvvm.entity.AddBy = CBCRM.memberShip.Id
                    mvvm.entity.AddByName = CBCRM.memberShip.FullName
                    var dindex = 0
                    mvvm.unitsData.forEach(function (item, i) { if (item.IsDefault) dindex = i })
                    mvvm.entity.Unit = mvvm.unitsData.length > 0 ? mvvm.unitsData[dindex].Id : ''

                    if (action == "customer" && paramData) {
                        var cu = paramData.entity || {};
                        mvvm.entity.Customer = cu.Id;
                        mvvm.entity.CustomerName = cu.Name;
                    }
                    formTemplate('新增业务明细')
                    watchs()
                }
                vm.getEntity = function (id, callback) {
                    $.get("/Market/ProductList/", { id: id }, function (ret) {
                        if (ret.result) {
                            if (ret.data.Source.length == 0) {
                                messageBox.warning("该业务明细不存在或已经被删除！");
                                return;
                            }
                            callback(ret.data.Source[0]);
                        } else {
                            CBCRM.showResult(ret);
                        }
                    });
                }
                //编辑
                vm.doedit = function (id) {
                    mvvm.getEntity(id, function (entity) {
                        mvvm.entity = entity;
                        mvvm.entity.AddByName = entity.AddBy.FullName;
                        formTemplate('编辑业务明细')
                        watchs()
                    })
                }
                //查看
                vm.doview = function (id) {
                    mvvm.getEntity(id, function (entity) {
                        mvvm.entity = entity;
                        mvvm.entity.AddByName = entity.AddBy.FullName;
                        viewTemplate('查看业务明细')
                    });
                }
                vm.contractdoview = function (contractid) {
                    var path = '/Market/Contract/' + contractid + '/view';
                    goto(path,true)
                }
                //删除
                vm.dodel = function () {
                    var index = parseInt($(this).attr('index'))
                    var conModel = mvvm.entityList[index]
                    if (conModel.Contract) {
                        messageBox.warning('此业务明细是合同订单[' + conModel.ContractNum + ']中的一条业务明细,请到合同订单中删除。')
                    } else {
                        var id = $(this).attr("value")
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/Market/ContractDetailsDel/' + id, {}, function (ret) {
                                if (ret.result)
                                    mvvm.entityList.removeAt(index)
                                messageBox.succeed(ret.message)
                            })
                        })
                    }
                }
                //选择产品
                vm.productKey = ''
                vm.catecoryId = 0
                vm.productList = []
                vm.productpaing = {
                    pagesize: 10,
                    pagesizeopts: [10, 20, 50, 100, 200, 500, 1000],
                    paging: function (pageIndex, pageSize) {
                        mvvm.getProcutList(pageIndex, pageSize)
                    }
                }
                //取产品 
                vm.getProcutList = function (pageIndex, pageSize) {
                    var data = {
                        "typeid": mvvm.catecoryId, "key": mvvm.productKey, "pageSize": pageSize, "pageIndex": pageIndex
                    };
                    if (mvvm.entity.Customer) data.customerId = mvvm.entity.Customer;
                    $.get('/Product/PriceList/', data, function (ret) {
                        if (!ret || !ret.result) return CBCRM.showResult(ret);
                        var cu = ret.data.cu;
                        mvvm.entity.CustomerMemberGrade = cu.MemberGrade;
                        mvvm.entity.CustomerMemberGradeDisplay = cu.MemberGradeDisplay;
                        mvvm.productList = ret.data.productList.Source;
                        var page = avalon.vmodels.productupaing;
                        if (page) {
                            page.total = ret.data.productList.RecordTotal;
                            page.setIndex(ret.data.productList.PageIndex);
                        }
                    })
                }
                vm.onSelectProuct = function () {
                    mvvm.productKey = ''
                    mvvm.catecoryId = 0
                    dialog = messageBox.openHtml('选择产品', '1000px', '300px', '', [{
                        name: '确定',
                        focus: true,
                        callback: function () {
                            var product = mvvm.productList.$model[mvvm.productListIndex]
                            mvvm.selectedProduct(product);
                        }
                    }]);
                    var content = $(dialog.content())
                    content.attr('ms-include', 'ProductListTemp')
                    avalon.scan(content[0], mvvm)
                }
                vm.onSearchProduct = function () {
                    mvvm.getProcutList(1, 10)
                }
                vm.productListIndex = 0
                vm.onSetProductIndex = function () {
                    var item = this.$vmodel.item;
                    if (item.State == 2) return;
                    mvvm.productListIndex = this.$vmodel.$index
                    $("input[name='rdoproduct']").eq(mvvm.productListIndex).attr("checked", "checked")
                }
                vm.selectedProduct = function (product) {
                    if (product.State == 2) {
                        messageBox.warning("抱歉，该产品已经下架！");
                        return false;
                    }
                    mvvm.entity.Product = product.Id
                    mvvm.entity.ProductName = product.Name
                    mvvm.entity.Price = product.SpecialPrice || product.GradePrice || product.GeneralCustomerPrice
                    mvvm.entity.StockPrice = product.StockPrice;
                    mvvm.entity.StandardPrice = product.GeneralCustomerPrice;
                    mvvm.entity.LowestPrice = product.LowestPrice
                    mvvm.entity.RoyaltyPrice = product.RoyaltyPrice
                    mvvm.entity.RoyaltyType = product.RoyaltyType
                    mvvm.entity.RoyaltyCompute = product.RoyaltyCompute
                    mvvm.entity.RoyaltyValue = product.RoyaltyValue

                    mvvm.entity.PriceTitle = "最低限价：" + product.LowestPrice;
                    mvvm.entity.Money = product.GeneralCustomerPrice * 1
                    mvvm.entity.Standard = product.Standard
                    mvvm.entity.BrandId= product.Brand ? product.Brand.Id : ''
                    mvvm.entity.BrandName = product.Brand ? product.Brand.Name : ''
                    mvvm.entity.Unit = product.Units
                    mvvm.entity.UnitsDisplay = product.UnitsDisplay

                    computeRoyalty();
                    if (dialog) dialog.close()
                }
                //产品分类树配置
                vm.pCategoryTreeOpts = {
                    treeopts: {
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                mvvm.catecoryId = treeNode.Id
                                var page = avalon.vmodels.productupaing, pageSize = page ? page.pagesize : 10;
                                mvvm.getProcutList(1, pageSize);
                            }
                        },
                        view: {
                            addHoverDom: '',
                            removeHoverDom: ''
                        }
                    }
                }
                //选择客户
                vm.selectCustomer = function () {
                    plugins.selectCustomer({
                        callback: function (cus) {
                            var cu = cus[0];
                            mvvm.entity.Customer = cu.Id;
                            mvvm.entity.CustomerName = cu.Name;
                        }
                    });
                }

                //归属员工
                vm.selectBelongTo = function () {
                    plugins.selectUser({
                        dataAuth: 2020701,
                        callback: function (us) {
                            var u = us[0];
                            mvvm.entity.BelongTo = u.Id;
                            mvvm.entity.BelongToDisplay = u.FullName;
                        }
                    });
                }

                //服务开始时间
                vm.startDateOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        mvvm.entity.StartDate = formatDate
                    }
                }
                //服务结束时间
                vm.endDateOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        mvvm.entity.EndDate = formatDate
                    }
                }
                //录入时间
                vm.addTimeOpts = {
                    onSelect: function (date, formatDate, format) {
                        mvvm.entity.AddTime = formatDate
                    }
                }

                //选择合同
                vm.selContactList = []
                vm.contractKey = ''
                vm.selectContract = function () {
                    mvvm.contractKey = ''
                    var dialog = mvvm.openTmpl({
                        title: "选择合同业务", w: 800, h: 300,
                        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.entity.Contract = con.Id
                                    mvvm.entity.ContractName = con.ContractName;
                                    mvvm.entity.ContractNum = con.ContractNum;
                                    mvvm.entity.Customer = con.Customer;
                                    if (dialog) dialog.close()
                                }
                                return false;
                            }
                        }]
                    })
                    mvvm.getContractList()
                }
                vm.getContractList = function () {
                    $.get('/Market/Contract/', {
                        'key': mvvm.contractKey,
                        'paystate': 1,
                        'customerid': mvvm.entity.Customer
                    }, function (ret) {
                        mvvm.selContactList = ret.data.Source
                    })
                }
                vm.selectedContract = function (index) {
                    $("input[name='selectContract']").eq(index).attr("checked", true);
                }

                //收款
                vm.doReceipts = function (item) {
                    var id = item.Id, url = "/FinancialAffairs/Accounting/" + id + "/doadd";
                    var data = {
                        from: "ProductList", type: "addDetailReceipts", entity: {
                            CustomId: item.Customer, CustomName: item.CustomerName,
                            Contract: item.Contract, ContractNum: item.ContractNum,
                            Product: item.Id, ProductDisplay: item.ProductName,
                            ProductAlias: item.ProductAlias, ProductBrand: item.BrandDisplay,
                            ProductStandard: item.Standard, ProductPrice: item.Price,DealPrice: item.StandardPrice,
                            ProductNum: item.Num, Unit: item.Unit,
                            Amount: item.ReturnAmount ? item.Money - item.ReturnAmount : item.Money
                        },
                        reloadList: function () {
                            mvvm.search();
                        }
                    };
                    mvvm.gotourl(url, true, data);
                }

                //字典
                vm.billtypes = [];//票据类型
                vm.unitsData = [];//单位
            });
            var action = that.params.action, id = that.params.id, paramid = id;
            mvvm.entity = modelFactory.create('ContractDetails');

            function initWhthPageList(data) {
                mvvm.grid1.gridmsg = lang.LoadingMsg;
                data = data || {};
                if (mvvm.customerId) data.customerId = mvvm.customerId;
                $.get("/Market/ProductList", data, function (ret) {
                    if (!ret.result) return CBCRM.showResult(ret)
                    mvvm.ADD = ret.data.ADD
                    mvvm.DELETE = ret.data.DELETE
                    mvvm.NOPAGE = ret.data.NOPAGE;
                    mvvm.ACCOUNTING = ret.data.ACCOUNTING;
                    mvvm.PRODUCTSTOCKTPRICE = ret.data.PRODUCTSTOCKTPRICE;
                    mvvm.grid1.gridmsg = ret.data.RecordTotal > 0 ? "" : lang.NoListData;
                    mvvm.entityList = ret.data.Source;
                    if (mvvm.NOPAGE) {
                        destroyui(["upaing"])
                    } else {
                        var page = avalon.vmodels.upaing
                        if (page) page.total = ret.data.RecordTotal //分页总数
                    }

                    mvvm.totalMoney = mvvm.totalReturnedMoney = 0
                    mvvm.entityList.forEach(function (item, i) {
                        var money = parseFloat(item.Money)
                        var returnmoney = parseFloat(item.ReturnAmount)
                        if (money)
                            mvvm.totalMoney += money
                        if (returnmoney)
                            mvvm.totalReturnedMoney += returnmoney
                    })

                });
            }
            function formTemplate(title) {
                var dialog = mvvm.openTmpl({
                    title: title, w: 780, h: 480,
                    tmplId: "formTemplate", tmpl: tmpl,
                    button: [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            //if (mvvm.entity.ContractNum == "") {
                            //    messageBox.warning("请选择归属合同订单！");
                            //    return false;
                            //}
                            if (mvvm.entity.ProductName == "") {
                                messageBox.warning("请选择商品！");
                                return false;
                            }
                            if (mvvm.entity.Price < mvvm.entity.LowestPrice) {
                                messageBox.warning("成交单价小于产品的最低限价，请检查！");
                                return false;
                            }

                            var model = mvvm.entity.$model;
                            var url = model.Id == 0 ? "/Market/ContractDetailsAdd/" : "/Market/ContractDetailsEdit/" + model.Id;
                            $.post(url, model, function (ret) {
                                CBCRM.showResult(ret, function () {
                                    if (dialog) dialog.close();
                                    mvvm.search();
                                });
                            });
                            return false;
                        }
                    }]
                });
            }
            //查看
            function viewTemplate(title) {
                var dialog = mvvm.openTmpl({
                    title: title, w: 800, h: 350,padding:"0px",
                    tmplId: "viewTemplate", tmpl: tmpl
                });
            }
            //各种监控
            function watchs() {
                //获取合同订单
                //$.get('/Market/ContractSelect/', { customerId: that.params.id }, function (ret) {
                //    var list = [];
                //    if (ret.result) {
                //        list = ret.data || [];
                //    }
                //    list.unshift({ Id: '', ContractName: '请选择合同订单' });
                //    mvvm.contractSelect = list;
                //})
                mvvm.entity.$watch('Price', function (n, o) {
                    mvvm.entity.Money = n * mvvm.entity.Num
                    if (mvvm.entity.LowestPrice && n < mvvm.LowestPrice) {

                    }
                    computeRoyalty();
                })
                mvvm.entity.$watch('Num', function (n, o) {
                    mvvm.entity.Money = n * mvvm.entity.Price
                    computeRoyalty();
                })
                mvvm.entity.$watch('HasServiceTimeLimit', function (n, o) {
                    if (!n) {
                        mvvm.entity.StartDate = ''
                        mvvm.entity.EndDate = ''
                    }
                })
                mvvm.entity.$watch('HasSerialNumber', function (n, o) {
                    if (!n)
                        mvvm.entity.SerialNumber = ''
                })
                mvvm.entity.$watch('HasAccountPwd', function (n, o) {
                    if (!n) {
                        mvvm.entity.UserName = ''
                        mvvm.entity.PassWord = ''
                    }
                })
                mvvm.entity.$watch('IsUseLimit', function (n, o) {
                    if (!n)
                        mvvm.entity.UseLimitOfNum = 0
                })
                mvvm.entity.$watch('Contract', function (n) {
                    mvvm.entity.Customer = "";
                    mvvm.contractSelect.forEach(function (item) {
                        if (item.Id == n) {
                            mvvm.entity.Customer = item.Customer;
                        }
                    });
                });
            }
            //计算提成
            function computeRoyalty() {
                var item = mvvm.entity;
                var num = item.Num || 0, price = item.Price || 0, rPrice = item.RoyaltyPrice || 0, rValue = item.RoyaltyValue || 0;
                num = parseFloat(num, 10);
                price = parseFloat(price, 10);
                rPrice = parseFloat(rPrice, 10);
                rValue = parseFloat(rValue, 10);
                if (item.RoyaltyType == 1) {
                    //按数量
                    item.RoyaltyMoney = (num * rValue).toFixed(2).replace(".00", "");
                } else {
                    //按百分比
                    if (item.RoyaltyCompute == 1) {
                        //按销售金额百分比
                        item.RoyaltyMoney = (num * rPrice * rValue / 100).toFixed(2).replace(".00", "");
                    } else {
                        //按毛利百分比
                        item.RoyaltyMoney = (num * (price - rPrice) * rValue / 100).toFixed(2).replace(".00", "");
                    }
                }
            }
            //从字典取数据
            function InitDictData() {
                getDicts({ billtypes: 100057, unitsData: 100110 }, mvvm);
            }

            InitDictData()
            switch (action) {
                case "view":
                    mvvm.doview(id);
                    break;
                case "overtime":
                    if (id) mvvm.addQuery("overtime", id, null, true);
                    fill();
                    break;
                case "customer":
                    //客户信息中，合同订单调用
                    mvvm.customerId = id;
                    /*隐藏其它，只显示列表块*/
                    mvvm.showOnlyList = true
                    if (paramData) paramData.viewOther(tmpl, mvvm);
                    break;
                case "key":
                    mvvm.keyword = decodeURI(paramid);
                    fill();
                    break;
                default:
                    fill();
                    break;
            }
            function fill() {
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
            }
        }

        ///销售管理-销售漏斗
        , SalesFunnel: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM;
            var mvvm = CBCRM.define('SalesFunnel', function (vm) {
                vm.destroy = function () {
                    mvvm.destroyui(["inputGroupTree"])
                }
                vm.lang = lang
                vm.$skipArray = ['lang']
                vm.salasList = []
                vm.salasGroup = []
                vm.stage = []
                vm.follow = []
                vm.showItem = {}
                vm.checkAll = false;
                vm.checkAllCall = function () {
                    mvvm.checkAll = !mvvm.checkAll;
                }
                vm.checkCall = function () {
                    var $pvm = this.$vmodels[2];
                    var current = this.$vmodel.item;
                    current["check"] = !current["check"];
                    $pvm.check.call($pvm, false);
                }
                vm.check = function (checkState, change) {
                    var $v = this;
                    var data = $v.salasGroup;
                    var len = data.length;
                    var cur;
                    var followStageRange = [];
                    var followStagedata = []
                    while (len) {
                        len--;
                        cur = data[len];
                        if (change) {
                            cur.check = checkState;
                        }
                        if (cur.check) {
                            followStagedata.push(cur.FollowStage);
                            followStageRange.push(cur.FollowStageDisplay);
                        }
                    }
                    // mvvm.showItem.followStage = followStageRange.join(",");
                    queryData.followStage = followStagedata.join(",");
                    initWithPageList(queryData);
                };
                //分页
                vm.userpaing = {
                    paging: function () {
                        var that = this
                        queryData.pageSize = that.pagesize
                        queryData.pageIndex = that.currentindex + 1
                        initWithPageList(queryData);
                    }
                }
                vm.createChart = function (opt) {
                    var charts = {
                        chart: {
                            manageresize: "1",
                            caption: "2013-4-1 至 2013-4-30 各阶段机会数量",
                            decimals: "1",
                            basefontsize: "12",
                            issliced: "0",
                            usesameslantangle: "1",
                            ishollow: "0",
                            labeldistance: "5"
                        },
                        data: [],
                        styles: {
                            definition: [{
                                type: "font",
                                name: "captionFont",
                                size: "15"
                            }],
                            application: [{
                                toobject: "CAPTION",
                                styles: "captionFont"
                            }]
                        }
                    },
                        myChart = new FusionCharts("/Scripts/Charts/Charts/Funnel.swf", "sellFunnelChart", "400", "300");;
                    $.extend(true, charts, opt);
                    myChart.setJSONData(charts);
                    myChart.render("chartdiv");
                }
                vm.loadSellTotal = function (data) {
                    $.get("/Market/GetChart/",
                        data,
                        function (ret) {
                            var result = ret.data;
                            if (!result || !result.length) return;
                            var total = 0,
                            percent = 0,
                            chartData = [],
                            title = [],
                            chart = {};
                            avalon.each(result, function (i, item) {
                                total = total.add(item.NumOfSells);
                            });
                            var c = 0,de=false;
                            avalon.each(result, function (i, item) {
                                if (i > 0) {
                                    if (c != item.NumOfSells) de = true;
                                }
                                c = item.NumOfSells;
                                //item.SellsPercents = item.NumOfSells.div(total).mul(100).toFixed(2);
                                if (total > 0) item.SellsPercents = (item.NumOfSells / total).mul(100).toFixed(2);
                                else item.SellsPercents = 0
                                percent = percent.add(item.SellsPercents);
                                chartData.push({
                                    "label": item.FollowStageDisplay,
                                    "value": item.NumOfSells,
                                    "tooltext": item.FollowStageDisplay + ' ' + item.SellsPercents + '%'
                                });
                            });
                            if (chartData.length) {
                                if (!de) {
                                    avalon.log(percent);
                                    chart.chart = {
                                        "caption": "各阶段销售机会数据无法构成销售漏斗"
                                    };
                                } else {
                                    if (data.StartDate) {
                                        title.push(data.StartDate);
                                    }
                                    if (data.EndDate) {
                                        if (title.length) title.push(" 至 ");
                                        title.push(data.EndDate);
                                    }
                                    chart.chart = {
                                        "caption": title.join("") + " 各阶段机会数量"
                                    };
                                }
                                chart.data = chartData;
                                mvvm.createChart(chart);
                            }
                            var len = result.length;
                            while (len) {
                                len--;
                                result[len]["check"] = true;
                            }
                            mvvm.salasGroup = result;
                        });
                }

                //左边导航子项显示隐藏
                vm.ShowSubNav = ''
                vm.onSubNav = function (subname) {
                    if (mvvm.ShowSubNav == subname)
                        mvvm.ShowSubNav = ''
                    else
                        mvvm.ShowSubNav = subname
                }


                //机会跟单人
                vm.OfferSponsor = 0
                vm.OfferSponsorDisplay = ''
                vm.selectOfferSponsor = function () {
                    plugins.selectUser({
                        dataAuth: 2020800,
                        callback: function (us) {
                            var u = us[0];
                            mvvm.OfferSponsor = u.Id;
                            mvvm.OfferSponsorDisplay = u.FullName;
                        }
                    });
                }

                //部门
                vm.GroupId = 0
                vm.GroupName = ''
                vm.inputGroupTreeOpts = {
                    dataAuth: 2020800,
                    treeopts: {
                        callback: {
                            onClick: function (event, treeId, treeNode) {
                                mvvm.GroupName = treeNode.Name
                                mvvm.GroupId = treeNode.Id
                            }
                        }
                    }
                }

                //查看OK
                vm.doviews = function () {
                    var path = $(this).attr('path')
                    goto(path, true)
                }

                //选择所属战役
                vm.campaignList = []
                vm.campaignPanel = false
                vm.campaignKey = ''
                vm.MarketingCampaign = 0
                vm.MarketingCampaignDisplay = ''
                vm.selectCampaign = function () {
                    $('body').bind('mousedown', function () {
                        mvvm.campaignPanel = false
                        $('body').unbind('mousedown')
                    })
                    getCampaignList();
                    mvvm.campaignPanel = true;
                }
                vm.searchCampaign = function () {
                    getCampaignList();
                }
                vm.closeCampaignPanel = function () {
                    mvvm.campaignPanel = false;
                }
                vm.clickCampaign = function () {
                    var campaign = $(this);
                    mvvm.MarketingCampaign = campaign.attr("key");
                    mvvm.MarketingCampaignDisplay = campaign.attr("alt");
                    mvvm.campaignPanel = false;
                }
                vm.clearCampaignValue = function () {
                    mvvm.MarketingCampaign = 0
                    mvvm.MarketingCampaignDisplay = ''
                }
                //选择所属活动
                vm.activityList = []
                vm.activityPanel = false
                vm.activityKey = ''
                vm.MarketActivity = 0
                vm.MarketActivityDisplay = ''
                vm.selectActivity = function () {
                    $('body').bind('mousedown', function () {
                        mvvm.activityPanel = false
                        $('body').unbind('mousedown')
                    })
                    getActivityList();
                    mvvm.activityPanel = true;
                }
                vm.searchActivity = function () {
                    getActivityList();
                }
                vm.closeActivityPanel = function () {
                    mvvm.activityPanel = false;
                }
                vm.clickActivity = function () {
                    var activity = $(this);
                    mvvm.MarketActivity = activity.attr("key");
                    mvvm.MarketActivityDisplay = activity.attr("alt");
                    mvvm.activityPanel = false;
                }
                vm.clearActivityValue = function () {
                    mvvm.MarketActivity = 0
                    mvvm.MarketActivityDisplay = ''
                }

                vm.mousedownstop = function (e) {
                    e.stopPropagation()
                }
                //发现机会开始时间
                vm.StartDate = ''
                vm.startdataOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        mvvm.StartDate = formatDate
                    }
                }
                //发现机会结束时间
                vm.EndDate = ''
                vm.enddateOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        mvvm.EndDate = formatDate
                    }
                }

                //搜索
                vm.doSearch = function () {
                    queryData.startDate = mvvm.StartDate
                    itemDate.startDate = mvvm.StartDate
                    queryData.endDate = mvvm.EndDate
                    itemDate.endDate = mvvm.EndDate
                    queryData.offerSponsor = mvvm.OfferSponsor
                    itemDate.offerSponsor = mvvm.OfferSponsorDisplay
                    queryData.campaign = mvvm.MarketingCampaign
                    itemDate.campaign = mvvm.MarketingCampaignDisplay
                    queryData.activity = mvvm.MarketActivity
                    itemDate.activity = mvvm.MarketActivityDisplay
                    queryData.group = mvvm.GroupId
                    itemDate.group = mvvm.GroupName

                    mvvm.showItem = itemDate
                    initWithPageList(queryData)
                    mvvm.loadSellTotal(queryData)
                    isHasItem()
                }
                //显示全部
                vm.doShowAll = function () {
                    queryData.startDate = ''
                    itemDate.startDate = ''
                    queryData.endDate = ''
                    itemDate.endDate = ''
                    queryData.offerSponsor = ''
                    itemDate.offerSponsor = ''
                    queryData.campaign = ''
                    itemDate.campaign = ''
                    queryData.activity = ''
                    itemDate.activity = ''
                    queryData.group = ''
                    itemDate.group = ''

                    mvvm.showItem = itemDate
                    initWithPageList(queryData)
                    mvvm.loadSellTotal(queryData)
                    mvvm.has = false
                }
                vm.has = false
                //移除单个
                vm.removeItem = function () {
                    var searchKey = this.$vmodel.$key;
                    mvvm.showItem[searchKey] = ''
                    queryData[searchKey] = ''
                    initWithPageList(queryData)
                    mvvm.loadSellTotal(queryData)
                    isHasItem()
                }
            });

            mvvm.$watch("checkAll", function (current, old) {
                this.check.apply(this, [current, true]);
            });

            var queryData = {
                pageIndex: 1,
                pageSize: 20,
                startDate: '',
                endDate: '',
                followStage: '',
                offerSponsor: 0,
                campaign: 0,
                activity: 0,
                group: 0,
            }

            var itemDate = {
                campaign: '',
                activity: '',
                offerSponsor: '',
                group: '',
                startDate: '',
                endDate: '',
                followStage: ''
            }

            mvvm.showItem = avalon.mix({}, itemDate);

            function initWithDictionary() {
                $.get('/Market/GetDictionary/', {}, function (ret) {
                    mvvm.stage = ret.data.stage;
                    mvvm.follow = ret.data.follow;
                });
            }
            initWithDictionary();

            function initWithPageList(data) {
                $.get('/Market/SalesFunnel/', data || {}, function (ret) {
                    mvvm.salasList = ret.data.Source
                    avalon.vmodels.upaing.total = ret.data.RecordTotal //分页总数
                })
            }

            function isHasItem() {
                mvvm.has = false
                for (var item in mvvm.showItem.$model) {
                    if (mvvm.showItem.$model[item]) {
                        mvvm.has = true
                        break
                    }
                }
            }

            mvvm.loadSellTotal({});

            //取所属战役
            function getCampaignList() {
                var key = mvvm.campaignKey;
                $.get('/Market/Campaign/', { "key": key }, function (ret) {
                    mvvm.campaignList = ret.data.Source;
                })
            }
            //取所属活动
            function getActivityList() {
                var key = mvvm.activityKey;
                var campaignId = mvvm.MarketingCampaign;
                $.get('/Market/Activity/', { "key": key, "campaignid": campaignId }, function (ret) {
                    mvvm.activityList = ret.data.Source;
                })
            }

            avalon.filters.stageDisplay = function (val) {
                var result = '';
                mvvm.stage.forEach(function (item) {
                    if (item.Id == val) result = item.Data
                })
                return result;
            }
            avalon.filters.followDisplay = function (val) {
                var result = '';
                mvvm.follow.forEach(function (item) {
                    if (item.Id == val) result = item.Data
                })
                return result;
            }
            require('commonui', function () {
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            })
        }

        ///销售目标-客户数目标
        , CustomerSaleTarget: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM
            var navopt = avalon.define("navopt", function (vm) {
                //左边导航子项显示隐藏
                vm.ShowSubNav = 'salestarget'
                vm.onSubNav = function (subname) {
                    if (navopt.ShowSubNav == subname)
                        navopt.ShowSubNav = ''
                    else
                        navopt.ShowSubNav = subname
                }
            })

            SalesTarget()

            var vmodels = [avalon.vmodels['market.targets'], avalon.vmodels['market.totalChart']
                , avalon.vmodels['search'], navopt]
            CBCRM.fillContent(tmpl, lang, contentId, module, vmodels)

            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.CustomerSaleTarget = null
                avalon.vmodels['market.targets'] = null
                avalon.vmodels['market.totalChart'] = null
            }
        }

        ///销售目标-签约额目标
        , SignAContractMoney: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM
            var navopt = avalon.define("navopt", function (vm) {
                //左边导航子项显示隐藏
                vm.ShowSubNav = 'salestarget'
                vm.onSubNav = function (subname) {
                    if (navopt.ShowSubNav == subname)
                        navopt.ShowSubNav = 'salestarget'
                    else
                        navopt.ShowSubNav = subname
                }
            })

            SalesTarget()

            var vmodels = [avalon.vmodels['market.targets'], avalon.vmodels['market.totalChart']
                , avalon.vmodels['search'], navopt]
            CBCRM.fillContent(tmpl, lang, contentId, module, vmodels)

            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.SignAContractMoney = null
                avalon.vmodels['market.targets'] = null
                avalon.vmodels['market.totalChart'] = null
            }
        }

        ///销售目标-回款额目标
        , ReturnedMoney: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM
            var navopt = avalon.define("navopt", function (vm) {
                //左边导航子项显示隐藏
                vm.ShowSubNav = 'salestarget'
                vm.onSubNav = function (subname) {
                    if (navopt.ShowSubNav == subname)
                        navopt.ShowSubNav = ''
                    else
                        navopt.ShowSubNav = subname
                }
            })
            SalesTarget()
            var vmodels = [avalon.vmodels['market.targets'], avalon.vmodels['market.totalChart']
                , avalon.vmodels['search'], navopt]
            CBCRM.fillContent(tmpl, lang, contentId, module, vmodels)

            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.ReturnedMoney = null
                avalon.vmodels['market.targets'] = null
                avalon.vmodels['market.totalChart'] = null
            }
        }

        ///销售目标-签单数目标
        , SignAContractSaleTarget: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM
            var navopt = avalon.define("navopt", function (vm) {
                //左边导航子项显示隐藏
                vm.ShowSubNav = 'salestarget'
                vm.onSubNav = function (subname) {
                    if (navopt.ShowSubNav == subname)
                        navopt.ShowSubNav = ''
                    else
                        navopt.ShowSubNav = subname
                }
            })

            SalesTarget()

            var vmodels = [avalon.vmodels['market.targets'], avalon.vmodels['market.totalChart']
                , avalon.vmodels['search'], navopt]
            CBCRM.fillContent(tmpl, lang, contentId, module, vmodels)

            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.SignAContractSaleTarget = null
                avalon.vmodels['market.targets'] = null
                avalon.vmodels['market.totalChart'] = null
            }
        }

        ///销售目标-销售目标设置
        , SaleTargetSet: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM
            var navopt = avalon.define("navopt", function (vm) {
                //左边导航子项显示隐藏
                vm.ShowSubNav = 'salestarget'
                vm.onSubNav = function (subname) {
                    if (navopt.ShowSubNav == subname)
                        navopt.ShowSubNav = ''
                    else
                        navopt.ShowSubNav = subname
                }
                vm.destroy = function () {
                    avalon.vmodels['market.targets'] = null
                    avalon.vmodels['market.totalChart'] = null
                    destroyui(["settagertdepartid"]);
                }
            })

            SalesTarget()

            var vmodels = [avalon.vmodels['market.targets'], avalon.vmodels['market.totalChart']
                , avalon.vmodels['search'], navopt]
            CBCRM.fillContent(tmpl, lang, contentId, module, vmodels)
        }

        ///物料管理-礼品/赠品列表
        , MaterialsGift: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM, that = this
            var Mvvm = avalon.define('marketingmaterialsgift', function (vm) {
                vm.lang = lang
                vm.entity = {}
                vm.materialsgiftList = []
                vm.materialsgiftpaing = {
                    paging: function () {
                        var thatpage = this
                        queryData.pageSize = thatpage.pagesize
                        queryData.pageIndex = thatpage.currentindex + 1
                        GetMaterialsGiftList(queryData)
                    }
                }

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

                vm.ADD = true
                vm.DELETE = true

                vm.giftTypeData = []

                //左边导航子项显示隐藏
                vm.ShowSubNav = 'materialsgift'
                vm.onSubNav = function (subname) {
                    Mvvm.ShowSubNav = subname
                }

                //关键字搜索
                vm.search = function () {
                    if (Mvvm.keyword) {
                        queryData.key = Mvvm.keyword;
                        GetMaterialsGiftList(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;
                    GetMaterialsGiftList(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] = ''
                    GetMaterialsGiftList(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);
                    GetMaterialsGiftList(queryData);
                }
                //快速筛选 
                vm.itemClick = function () {
                    $(this).attr('class', '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;
                            }
                        }
                    }
                    GetMaterialsGiftList(queryData);
                }

                //新增
                vm.doadd = function () {
                    Mvvm.entity = modelFactory.create('MaterialsGift')
                    Mvvm.entity.GiftType = Mvvm.giftTypeData.length ? Mvvm.giftTypeData[0].Id : ''
                    var curr = CBCRM.memberShip.$model
                    Mvvm.entity.BuyerId = curr.Id
                    Mvvm.entity.BuyerDisplay = curr.FullName
                    Mvvm.entity.BuyTime = GetDateTime()
                    FormSubmit("新增礼品/赠品")
                }
                //编辑
                vm.doedit = function () {
                    var id = $(this).val()
                    Mvvm.materialsgiftList.$model.forEach(function (item) {
                        if (item.Id == id) {
                            Mvvm.entity = item
                        }
                    })
                    FormSubmit("编辑礼品/赠品")
                }
                //查看 
                vm.doview = function () {
                    var id = 0
                    if (that.params.id) {
                        id = that.params.id
                        that.params.id = null
                    }
                    else {
                        id = $(this).val()
                    }
                    Mvvm.materialsgiftList.$model.forEach(function (item) {
                        if (item.Id == id) {
                            Mvvm.entity = item
                        }
                    })

                    var dialog = messageBox.openHtml('礼品/赠品详细', '975px', '300px', '');
                    var content = $(dialog.content())
                    content.attr('ms-include', 'viewTemplateGift')
                    avalon.scan(content[0], Mvvm)

                }
                //删除
                vm.dodel = function () {
                    var index = parseInt($(this).attr('index'));
                    var id = $(this).val();
                    messageBox.confirm('确定删除此数据吗？', function () {
                        $.post('/Market/MaterialsGiftDel/' + id, {}, function (ret) {
                            if (ret.result)
                                Mvvm.materialsgiftList.removeAt(index);
                            messageBox.succeed(ret.message);
                        })
                    });
                }
                //批量删除
                vm.doalldel = function () {
                    var deleteIds = checkAll();
                    messageBox.confirm('确定删除选中的数据吗？', function () {
                        $.post('/Market/MaterialsGiftAllDel/', deleteIds, function (ret) {
                            if (ret.result) {
                                GetMaterialsGiftList(queryData);
                                messageBox.succeed(ret.message);
                            }
                        });
                    });
                }

                //供应商
                vm.supliersTreeOpts = {
                    treeopts: {
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                if (treeNode.level > 0) {
                                    var zTree = $.fn.zTree.getZTreeObj(treeId)
                                    var parentTreeNode = zTree.getNodeByTId(treeNode.parentTId)
                                    Mvvm.entity.SupliersId = parentTreeNode.Id
                                    Mvvm.entity.SupliersDisplay = parentTreeNode.Name
                                    Mvvm.entity.ContactId = treeNode.Id
                                    Mvvm.entity.ContactDisplay = treeNode.Name;
                                }
                            }
                        },
                        async: {
                            url: function () {
                                var url = '/Customer/GetCustomerContacts?superiorCategoryId=10133'
                                var vmtree = avalon.vmodels.supliersTreeId
                                if (vmtree && vmtree.q && vmtree.q !== vmtree.qcopy) {
                                    url += '&customerName=' + vmtree.q
                                }
                                return url
                            },
                            dataFilter: function (treeId, parentNode, responseData) {
                                var ret = [], len, curr
                                var list = responseData.data;
                                if (list && list.customers.length) {
                                    list.customers.forEach(function (item) {
                                        item.icon = '/Content/themes/base/images/ico/tree_customercategory0.png'
                                        ret.push(item);
                                        if (item.Contacts && item.Contacts.length) {
                                            item.Contacts.forEach(function (itemChild) {
                                                itemChild.icon = '/Content/themes/base/images/ico/tree_customercategory0.png'
                                                itemChild.ParentId = item.Id
                                                ret.push(itemChild)
                                            })
                                        }
                                    })
                                }
                                return ret
                            }
                        }
                    }
                }

                //计算总价
                vm.sumAount = function () {
                    if (Mvvm.entity.Amount && Mvvm.entity.Price)
                        Mvvm.entity.TotalPrice = parseFloat(Mvvm.entity.Amount) * parseFloat(Mvvm.entity.Price)
                    if (Mvvm.entity.Amount)
                        Mvvm.entity.Stock = Mvvm.entity.Amount
                }

            })

            Mvvm.entity = modelFactory.create('MaterialsGift');

            //保存
            function FormSubmit(title) {
                var dialog = messageBox.openHtml(title, '840px', '400px', '', [{
                    name: '提交',
                    focus: true,
                    callback: function () {
                        var model = Mvvm.entity.$model;
                        var url = (model.Id == 0 ? "/Market/MaterialsGiftAdd/" : "/Market/MaterialsGiftUpdate/");
                        $.post(url + model.Id, model, function (ret) {
                            if (ret.result) {
                                messageBox.ok(ret.message, function () { GetMaterialsGiftList(queryData); messageBox.close(); });
                            }
                            else {
                                messageBox.fail(ret.message, function () { });
                            }
                        })

                        return false;
                    }
                }], function () {
                    avalon.vmodels.supliersTreeId.destroy();
                });

                var content = $(dialog.content())
                content.attr('ms-include', 'formTemplateGift')
                avalon.scan(content[0], Mvvm)
            }

            //创建查询对象并提交
            var createDate = {
                gifttype: 0,
                stocknum: 0,
                key: '',
                pageSize: 20,
                pageIndex: 1
            }
            //创建筛选对象
            var searchItem = {
                gifttype: '',
                stocknum: ''
            }

            var queryData = avalon.mix({}, createDate);
            Mvvm.showItem = avalon.mix({}, searchItem);
            InitDictItem()

            function GetMaterialsGiftList(data) {
                $.get('/Market/MaterialsGift/', data || {}, function (ret) {
                    Mvvm.materialsgiftList = ret.data.Source
                    avalon.vmodels.upaing.total = ret.data.RecordTotal

                    Mvvm.ADD = ret.data.ADD
                    Mvvm.DELETE = ret.data.DELETE

                    //传有参数Id,跳到查看
                    if (that.params.id) {
                        Mvvm.doview()
                    }
                })
            }

            //从字典取数据
            function InitDictItem() {
                //礼品类型
                $.get('/Settings/Dictionary/', { "id": 100033 }, function (ret) {
                    Mvvm.giftTypeData = ret.data
                })
            }

            require('commonui', function () {
                CBCRM.fillContent(tmpl, lang, contentId, module, Mvvm)
            })
            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.MaterialsGift = null
            }
        }

        ///物料管理-礼品/赠品领用
        , MaterialsGiftUse: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM, that = this
            var mvvm = CBCRM.define('marketmaterialsgiftuse', function (vm) {
                vm.lang = lang
                vm.entity = {}
                vm.materialsgiftuseList = []
                vm.materialsgiftusepaing = {
                    paging: function () {
                        var thatpage = this
                        queryData.pageSize = thatpage.pagesize
                        queryData.pageIndex = thatpage.currentindex + 1
                        GetMaterialsGiftUseList(queryData);
                    }
                }

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

                vm.ADD = true
                vm.DELETE = true

                //左边导航子项显示隐藏
                vm.ShowSubNav = 'materialsgift'
                vm.onSubNav = function (subname) {
                    mvvm.ShowSubNav = subname
                }

                //关键字搜索
                vm.search = function () {
                    if (mvvm.keyword) {
                        queryData.key = mvvm.keyword;
                        GetMaterialsGiftUseList(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;
                    GetMaterialsGiftUseList(queryData);
                }
                //清空
                vm.clear = function () {
                    mvvm.keyword = '';
                    queryData = avalon.mix({}, createDate);
                    GetMaterialsGiftUseList(queryData);
                }
                //新增
                vm.doadd = function () {
                    mvvm.entity = modelFactory.create('MaterialsGiftUse')
                    var curr = CBCRM.memberShip.$model
                    mvvm.entity.User_Id = curr.Id
                    mvvm.entity.UserDisplay = curr.FullName
                    mvvm.entity.PostBy = curr.Id
                    mvvm.entity.PostByDisplay = curr.FullName
                    mvvm.entity.UseTime = GetDateTime()

                    if (that.params.id && that.params.name) {
                        mvvm.entity.GiftId = that.params.id
                        mvvm.entity.GiftDisplay = decodeURI(that.params.name)
                        that.params.name = null
                        that.params.id = null
                    }

                    FormSubmit("新增礼品/赠品领用")
                }
                //编辑
                vm.doedit = function () {
                    var id = $(this).val()
                    mvvm.materialsgiftuseList.$model.forEach(function (item) {
                        if (item.Id == id) {
                            mvvm.entity = item
                        }
                    })
                    FormSubmit("编辑礼品/赠品领用")
                }
                //查看
                vm.doview = function () {
                    var id = $(this).val()
                    mvvm.materialsgiftuseList.$model.forEach(function (item) {
                        if (item.Id == id) {
                            mvvm.entity = item
                        }
                    })

                    var dialog = messageBox.openHtml('礼品/赠品领用详细', '900px', '200px', '');
                    var content = $(dialog.content())
                    content.attr('ms-include', 'viewTemplateGiftUse')
                    avalon.scan(content[0], mvvm)
                }
                //删除
                vm.dodel = function () {
                    var index = parseInt($(this).attr('index'));
                    var id = $(this).val();
                    messageBox.confirm('确定删除此数据吗？', function () {
                        $.post('/Market/MaterialsGiftUseDel/' + id, {}, function (ret) {
                            if (ret.result)
                                mvvm.materialsgiftuseList.removeAt(index);
                            messageBox.succeed(ret.message);
                        })
                    });
                }
                //批量删除
                vm.doalldel = function () {
                    var deleteIds = checkAll();
                    messageBox.confirm('确定删除选中的数据吗？', function () {
                        $.post('/Market/MaterialsGiftUseAllDel/', deleteIds, function (ret) {
                            if (ret.result) {
                                GetMaterialsGiftUseList(queryData);
                                messageBox.succeed(ret.message);
                            }
                        });
                    });
                }

                //领用人
                vm.selectUser = function () {
                    plugins.selectUser({
                        dataAuth: 2050201,
                        callback: function (us) {
                            var u = us[0];
                            mvvm.entity.User_Id = u.Id;
                            mvvm.entity.UserDisplay = u.FullName;
                        }
                    })
                }
                //客户联系人
                vm.selectCustomer = function () {
                    plugins.selectCustomer({
                        type: "contacts",
                        callback: function (cus,cons) {
                            var cu = cus[0], con = cons[0];
                            mvvm.entity.CustomerId = cu.Id
                            mvvm.entity.CustomerDisplay = cu.Name
                            mvvm.entity.ContactId = con.Id
                            mvvm.entity.ContactDisplay = con.Name;
                        }
                    });
                }
                vm.customerTreeOpts = {
                    treeopts: {
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                if (treeNode.level > 0) {
                                    var zTree = $.fn.zTree.getZTreeObj(treeId)
                                    var parentTreeNode = zTree.getNodeByTId(treeNode.parentTId)
                                    mvvm.entity.CustomerId = parentTreeNode.Id
                                    mvvm.entity.CustomerDisplay = parentTreeNode.Name
                                    mvvm.entity.ContactId = treeNode.Id
                                    mvvm.entity.ContactDisplay = treeNode.Name;
                                }
                            }
                        },
                        async: {
                            url: function () {
                                var url = '/Customer/GetCustomerContacts/2050200'
                                var vmtree = avalon.vmodels.customerTreeId
                                if (vmtree && vmtree.q && vmtree.q !== vmtree.qcopy) {
                                    url += '?customerName=' + vmtree.q
                                }
                                return url
                            },
                            dataFilter: function (treeId, parentNode, responseData) {
                                var ret = [], len, curr
                                var list = responseData.data;
                                if (list && list.customers.length) {
                                    list.customers.forEach(function (item) {
                                        item.icon = '/Content/themes/base/images/ico/tree_customercategory0.png'
                                        ret.push(item);
                                        if (item.Contacts && item.Contacts.length) {
                                            item.Contacts.forEach(function (itemChild) {
                                                itemChild.icon = '/Content/themes/base/images/ico/tree_customercategory0.png'
                                                itemChild.ParentId = item.Id
                                                ret.push(itemChild)
                                            })
                                        }
                                    })
                                }
                                return ret
                            }
                        }
                    }
                }

                //领用时间
                vm.useTimeOpts = {
                    onSelect: function (date, formatDate, format) {
                        mvvm.UseTime = formatDate
                    }
                }

                //选择礼品赠品
                vm.giftList = []
                vm.giftPanel = false
                vm.giftKey = ''
                vm.selectGifts = function () {
                    $('body').bind('mousedown', function () {
                        mvvm.giftPanel = false
                        $('body').unbind('mousedown')
                    })
                    GetGiftList();
                    mvvm.giftPanel = true;
                }
                vm.searchGift = function () {
                    GetGiftList();
                }
                vm.closeGiftPanel = function () {
                    mvvm.giftPanel = false;
                }
                vm.clickGift = function () {
                    var gift = $(this);
                    mvvm.entity.GiftId = gift.attr("key");
                    mvvm.entity.GiftDisplay = gift.attr("alt");
                    mvvm.giftPanel = false;
                }
                vm.mousedownstop = function (e) {
                    e.stopPropagation()
                }
            })

            mvvm.entity = modelFactory.create('MaterialsGiftUse');

            //保存
            function FormSubmit(title) {
                var dialog = mvvm.openTmpl({
                    title: title, w: 720, h: 300,
                    tmplId: "formTemplateGiftUse", tmpl: tmpl,
                    button: [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            var model = mvvm.entity.$model;
                            var url = (model.Id == 0 ? "/Market/MaterialsGiftUseAdd/" : "/Market/MaterialsGiftUseUpdate/");
                            $.post(url + model.Id, model, function (ret) {
                                CBCRM.showResult(ret, function () {
                                    GetMaterialsGiftUseList(queryData);
                                    if (dialog) dialog.close();
                                })
                            })
                            return false;
                        }
                    }]
                });
            }

            //创建查询对象并提交
            var createDate = {
                key: '',
                pageSize: 20,
                pageIndex: 1
            }

            var queryData = avalon.mix({}, createDate)

            function GetMaterialsGiftUseList(data) {
                $.get('/Market/MaterialsGiftUse/', data || {}, function (ret) {
                    mvvm.materialsgiftuseList = ret.data.Source
                    avalon.vmodels.upaing.total = ret.data.RecordTotal

                    mvvm.ADD = ret.data.ADD
                    mvvm.DELETE = ret.data.DELETE

                })
            }

            function GetGiftList() {
                var key = mvvm.giftKey
                $.get('/Market/MaterialsGift/', { "key": key }, function (ret) {
                    mvvm.giftList = ret.data.Source;
                })
            }

            require('commonui', function () {
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)

            })

            //传有参数Id,礼品赠品列表中领用跳到领用新增页,参数Id为礼品赠品Id
            if (that.params.id && that.params.name) {
                mvvm.doadd()
            }

            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.MaterialsGiftUse = null
            }
        }

        ///物料管理-物料/印刷品列表
        , MaterialsOrPrint: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM, that = this
            var mvvm = CBCRM.define('marketingmaterialsorprint', function (vm) {
                vm.lang = lang
                vm.entity = {}
                vm.materialsorprintList = []
                vm.materialsorprintpaing = {
                    paging: function () {
                        var thatpage = this
                        queryData.pageSize = thatpage.pagesize
                        queryData.pageIndex = thatpage.currentindex + 1
                        GetMaterialsOrPrintList(queryData)
                    }
                }

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

                vm.ADD = true
                vm.DELETE = true

                vm.materialTypeData = []
                vm.countUnitData = []

                //左边导航子项显示隐藏
                vm.ShowSubNav = 'materialsorprint'
                vm.onSubNav = function (subname) {
                    mvvm.ShowSubNav = subname
                }

                //关键字搜索
                vm.search = function () {
                    if (mvvm.keyword) {
                        queryData.key = mvvm.keyword;
                        GetMaterialsOrPrintList(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;
                    GetMaterialsOrPrintList(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] = ''
                    GetMaterialsOrPrintList(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);
                    GetMaterialsOrPrintList(queryData);
                }
                //快速筛选 
                vm.itemClick = function () {
                    $(this).attr('class', '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;
                            }
                        }
                    }
                    GetMaterialsOrPrintList(queryData);
                }

                //新增
                vm.doadd = function () {
                    mvvm.entity = modelFactory.create('MaterialsOrPrint')
                    mvvm.entity.MaterialType = mvvm.materialTypeData.length ? mvvm.materialTypeData[0].Id : ''
                    mvvm.entity.CountUnit = mvvm.countUnitData.length ? mvvm.countUnitData[0].Id : ''
                    var curr = CBCRM.memberShip.$model
                    mvvm.entity.BuyerId = curr.Id
                    mvvm.entity.BuyerDisplay = curr.FullName
                    mvvm.entity.BuyTime = GetDateTime()
                    FormSubmit("新增物料/印刷品")
                }
                //编辑
                vm.doedit = function () {
                    var id = $(this).val()
                    mvvm.materialsorprintList.$model.forEach(function (item) {
                        if (item.Id == id) {
                            mvvm.entity = item
                        }
                    })
                    FormSubmit("编辑物料/印刷品")
                }
                //查看 
                vm.doview = function () {
                    var id = 0
                    if (that.params.id) {
                        id = that.params.id
                        that.params.id = null
                    }
                    else {
                        id = $(this).val()
                    }
                    mvvm.materialsorprintList.$model.forEach(function (item) {
                        if (item.Id == id) {
                            mvvm.entity = item
                        }
                    })

                    var dialog = messageBox.openHtml('物料/印刷品详细', '700px', '200px', '');
                    var content = $(dialog.content())
                    content.attr('ms-include', 'viewTemplatePrint')
                    avalon.scan(content[0], mvvm)

                }
                //删除
                vm.dodel = function () {
                    var index = parseInt($(this).attr('index'));
                    var id = $(this).val();
                    messageBox.confirm('确定删除此数据吗？', function () {
                        $.post('/Market/MaterialsOrPrintDel/' + id, {}, function (ret) {
                            if (ret.result)
                                mvvm.materialsorprintList.removeAt(index);
                            messageBox.succeed(ret.message);
                        })
                    });
                }
                //批量删除
                vm.doalldel = function () {
                    var deleteIds = checkAll();
                    messageBox.confirm('确定删除选中的数据吗？', function () {
                        $.post('/Market/MaterialsorprintAllDel/', deleteIds, function (ret) {
                            if (ret.result) {
                                GetMaterialsOrPrintList(queryData);
                                messageBox.succeed(ret.message);
                            }
                        });
                    });
                }

                //供应商
                vm.selectSupliers = function () {
                    plugins.selectCustomer({
                        type: "contacts",
                        superiorCategoryId: 10133,
                        callback: function (cus,cons) {
                            var cu = cus[0], con = cons[0];
                            mvvm.entity.SupliersId = cu.Id
                            mvvm.entity.SupliersDisplay = cu.Name
                            mvvm.entity.ContactId = con.Id
                            mvvm.entity.ContactDisplay = con.Name;
                        }
                    })
                }
                vm.supliersTreeOpts = {
                    treeopts: {
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                if (treeNode.level > 0) {
                                    var zTree = $.fn.zTree.getZTreeObj(treeId)
                                    var parentTreeNode = zTree.getNodeByTId(treeNode.parentTId)
                                    mvvm.entity.SupliersId = parentTreeNode.Id
                                    mvvm.entity.SupliersDisplay = parentTreeNode.Name
                                    mvvm.entity.ContactId = treeNode.Id
                                    mvvm.entity.ContactDisplay = treeNode.Name;
                                }
                            }
                        },
                        async: {
                            url: function () {
                                var url = '/Customer/GetCustomerContacts?superiorCategoryId=10133'
                                var vmtree = avalon.vmodels.supliersTreeId
                                if (vmtree && vmtree.q && vmtree.q !== vmtree.qcopy) {
                                    url += '&customerName=' + vmtree.q
                                }
                                return url
                            },
                            dataFilter: function (treeId, parentNode, responseData) {
                                var ret = [], len, curr
                                var list = responseData.data;
                                if (list && list.customers.length) {
                                    list.customers.forEach(function (item) {
                                        item.icon = '/Content/themes/base/images/ico/tree_customercategory0.png'
                                        ret.push(item);
                                        if (item.Contacts && item.Contacts.length) {
                                            item.Contacts.forEach(function (itemChild) {
                                                itemChild.icon = '/Content/themes/base/images/ico/tree_customercategory0.png'
                                                itemChild.ParentId = item.Id
                                                ret.push(itemChild)
                                            })
                                        }
                                    })
                                }
                                return ret
                            }
                        }
                    }
                }

                //计算总价
                vm.sumAount = function () {
                    if (mvvm.entity.Amount && mvvm.entity.Price)
                        mvvm.entity.TotalPrice = parseFloat(mvvm.entity.Amount) * parseFloat(mvvm.entity.Price)
                    if (mvvm.entity.Amount)
                        mvvm.entity.Stock = mvvm.entity.Amount
                }

            })

            mvvm.entity = modelFactory.create('MaterialsOrPrint');

            //保存
            function FormSubmit(title) {
                var dialog = messageBox.openHtml(title, '720px', '300px', '', [{
                    name: '提交',
                    focus: true,
                    callback: function () {
                        var model = mvvm.entity.$model;
                        var url = (model.Id == 0 ? "/Market/MaterialsOrPrintAdd/" : "/Market/MaterialsOrPrintUpdate/");
                        $.post(url + model.Id, model, function (ret) {
                            if (ret.result) {
                                messageBox.ok(ret.message, function () { GetMaterialsOrPrintList(queryData); messageBox.close(); });
                            }
                            else {
                                messageBox.fail(ret.message, function () { });
                            }
                        })

                        return false;
                    }
                }], function () {
                    if (avalon.vmodels.supliersTreeId)
                        avalon.vmodels.supliersTreeId.destroy();
                });

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

            //创建查询对象并提交
            var createDate = {
                materialtype: 0,
                countunit: 0,
                stocknum: 0,
                key: '',
                pageSize: 20,
                pageIndex: 1
            }
            //创建筛选对象
            var searchItem = {
                materialtype: '',
                countunit: '',
                stocknum: ''
            }

            var queryData = avalon.mix({}, createDate);
            mvvm.showItem = avalon.mix({}, searchItem);

            function GetMaterialsOrPrintList(data) {
                $.get('/Market/MaterialsOrPrint/', data || {}, function (ret) {
                    mvvm.materialsorprintList = ret.data.Source
                    avalon.vmodels.upaing.total = ret.data.RecordTotal

                    mvvm.ADD = ret.data.ADD
                    mvvm.DELETE = ret.data.DELETE

                    //传有参数Id,跳到查看
                    if (that.params.id) {
                        mvvm.doview()
                    }
                })
            }
            InitDictItem()

            //从字典取数据
            function InitDictItem() {
                $.get('/Market/GetMaterialsDictionary/', {}, function (ret) {
                    mvvm.materialTypeData = ret.data.MaterialTypeData
                    mvvm.countUnitData = ret.data.CountUnitData
                })
            }

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

        ///物料管理-物料/印刷品领用
        , MaterialsUse: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM, that = this
            var mvvm = CBCRM.define('marketingmaterialsorprintuse', function (vm) {
                vm.lang = lang
                vm.entity = {}
                vm.materialsorprintuseList = []
                vm.materialsorprintusepaing = {
                    paging: function () {
                        var thatpage = this
                        queryData.pageSize = thatpage.pagesize
                        queryData.pageIndex = thatpage.currentindex + 1
                        GetMaterialsOrPrintUseList(queryData);
                    }
                }

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

                vm.ADD = true
                vm.DELETE = true

                //左边导航子项显示隐藏
                vm.ShowSubNav = 'materialsorprint'
                vm.onSubNav = function (subname) {
                    mvvm.ShowSubNav = subname
                }

                //关键字搜索
                vm.search = function () {
                    if (mvvm.keyword) {
                        queryData.key = mvvm.keyword;
                        GetMaterialsOrPrintUseList(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;
                    GetMaterialsOrPrintUseList(queryData);
                }
                //清空
                vm.clear = function () {
                    mvvm.keyword = '';
                    mvvm.showItem = avalon.mix({}, searchItem);
                    queryData = avalon.mix({}, createDate);
                    GetMaterialsOrPrintUseList(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] = ''
                    GetMaterialsOrPrintUseList(queryData);
                }
                //快速筛选 
                vm.itemClick = function () {
                    $(this).attr('class', '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;
                            }
                        }
                    }
                    GetMaterialsOrPrintUseList(queryData);
                }
                //新增
                vm.doadd = function () {
                    mvvm.entity = modelFactory.create('MaterialsOrPrintUse')
                    var curr = CBCRM.memberShip.$model
                    mvvm.entity.User_Id = curr.Id
                    mvvm.entity.UserDisplay = curr.FullName
                    mvvm.entity.PostBy = curr.Id
                    mvvm.entity.PostByDisplay = curr.FullName
                    mvvm.entity.UseTime = GetDateTime()
                    mvvm.entity.OperationVal = '1'

                    if (that.params.id && that.params.name) {
                        mvvm.entity.MaterialsId = that.params.id
                        mvvm.entity.MaterialsDisplay = decodeURI(that.params.name)
                        that.params.name = null
                        that.params.id = null
                    }

                    FormSubmit("新增印刷品/物料领用")
                }
                //编辑
                vm.doedit = function () {
                    var id = $(this).val()
                    mvvm.materialsorprintuseList.$model.forEach(function (item) {
                        if (item.Id == id) {
                            mvvm.entity = item
                        }
                    })
                    FormSubmit("编辑印刷品/物料领用")
                }
                //查看
                vm.doview = function () {
                    var id = $(this).val()
                    mvvm.materialsorprintuseList.$model.forEach(function (item) {
                        if (item.Id == id) {
                            mvvm.entity = item
                        }
                    })

                    var dialog = messageBox.openHtml('印刷品/物料领用详细', '705px', '200px', '');
                    var content = $(dialog.content())
                    content.attr('ms-include', 'viewTemplatePrintUse')
                    avalon.scan(content[0], mvvm)
                }
                //删除
                vm.dodel = function () {
                    var index = parseInt($(this).attr('index'));
                    var id = $(this).val();
                    messageBox.confirm('确定删除此数据吗？', function () {
                        $.post('/Market/MaterialsOrPrintUseDel/' + id, {}, function (ret) {
                            if (ret.result)
                                mvvm.materialsorprintuseList.removeAt(index);
                            messageBox.succeed(ret.message);
                        })
                    });
                }
                //批量删除
                vm.doalldel = function () {
                    var deleteIds = checkAll();
                    messageBox.confirm('确定删除选中的数据吗？', function () {
                        $.post('/Market/MaterialsOrPrintUseAllDel/', deleteIds, function (ret) {
                            if (ret.result) {
                                GetMaterialsOrPrintUseList(queryData);
                                messageBox.succeed(ret.message);
                            }
                        });
                    });
                }

                //领用人
                vm.selectUser = function () {
                    plugins.selectUser({
                        dataAuth: 2050401,
                        callback: function (us) {
                            var u = us[0];
                            mvvm.entity.User_Id = u.Id;
                            mvvm.entity.UserDisplay = u.FullName;
                        }
                    });
                }
                

                //客户联系人
                vm.selectCustomer = function () {
                    plugins.selectCustomer({
                        type: "contacts",
                        callback: function (cus,cons) {
                            var cu = cus[0], con = cons[0];
                            mvvm.entity.CustomerId = cu.Id
                            mvvm.entity.CustomerDisplay = cu.Name
                            mvvm.entity.ContactId = con.Id
                            mvvm.entity.ContactDisplay = con.Name;
                        }
                    });
                }

                //领用时间
                vm.useTimeOpts = {
                    onSelect: function (date, formatDate, format) {
                        mvvm.UseTime = formatDate
                    }
                }

                //选择印刷品/物料
                vm.printList = []
                vm.printPanel = false
                vm.printKey = ''
                vm.selectPrint = function () {
                    $('body').bind('mousedown', function () {
                        mvvm.printPanel = false
                        $('body').unbind('mousedown')
                    })
                    GetPrintList()
                    mvvm.printPanel = true;
                }
                vm.searchPrint = function () {
                    GetPrintList();
                }
                vm.closePrintPanel = function () {
                    mvvm.printPanel = false;
                }
                vm.clickPrint = function () {
                    var gift = $(this);
                    mvvm.entity.MaterialsId = gift.attr("key");
                    mvvm.entity.MaterialsDisplay = gift.attr("alt");
                    mvvm.printPanel = false;
                }
                vm.mousedownstop = function (e) {
                    e.stopPropagation()
                }
            })

            mvvm.entity = modelFactory.create('MaterialsOrPrintUse')

            //保存
            function FormSubmit(title) {
                var dialog = mvvm.openTmpl({
                    title: title, w: 740, h: 280,
                    tmplId: "formTemplatePrintUse", tmpl: tmpl,
                    button:[{
                    name: '提交',
                    focus: true,
                    callback: function () {
                        var model = mvvm.entity.$model;
                        var url = (model.Id == 0 ? "/Market/MaterialsOrPrintUseAdd/" : "/Market/MaterialsOrPrintUseUpdate/");
                        $.post(url + model.Id, model, function (ret) {
                            CBCRM.showResult(ret, function () {
                                GetMaterialsOrPrintUseList(queryData);
                                if (dialog) dialog.close();
                            })
                        })
                        return false;
                    }
                }]
                })
            }

            //创建查询对象并提交
            var createDate = {
                operationval: '',
                key: '',
                pageSize: 20,
                pageIndex: 1
            }

            //创建筛选对象
            var searchItem = {
                operationval: ''
            }

            var queryData = avalon.mix({}, createDate)
            mvvm.showItem = avalon.mix({}, searchItem)

            function GetMaterialsOrPrintUseList(data) {
                $.get('/Market/MaterialsUse/', data || {}, function (ret) {
                    mvvm.materialsorprintuseList = ret.data.Source
                    avalon.vmodels.upaing.total = ret.data.RecordTotal

                    mvvm.ADD = ret.data.ADD
                    mvvm.DELETE = ret.data.DELETE

                })
            }

            function GetPrintList() {
                var key = mvvm.printKey
                $.get('/Market/MaterialsOrPrint/', { "key": key }, function (ret) {
                    mvvm.printList = ret.data.Source;
                })
            }

            require('commonui', function () {
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)

            })

            //传有参数Id,列表中领用跳到领用新增页,参数Id为物料Id
            if (that.params.id && that.params.name) {
                mvvm.doadd()
            }
        }

        ///物料管理-优惠劵列表
        , MaterialsCoupon: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM, that = this
            var Mvvm = avalon.define('marketingmaterialscoupon', function (vm) {
                vm.lang = lang
                vm.entity = {}
                vm.materialscouponList = []
                vm.materialscouponpaing = {
                    paging: function () {
                        var thatpage = this
                        queryData.pageSize = thatpage.pagesize
                        queryData.pageIndex = thatpage.currentindex + 1
                        GetMaterialsCouponList(queryData)
                    }
                }

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

                vm.ADD = true
                vm.DELETE = true

                //左边导航子项显示隐藏
                vm.ShowSubNav = 'materialscoupon'
                vm.onSubNav = function (subname) {
                    Mvvm.ShowSubNav = subname
                }

                //关键字搜索
                vm.search = function () {
                    if (Mvvm.keyword) {
                        queryData.key = Mvvm.keyword;
                        GetMaterialsCouponList(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;
                    GetMaterialsCouponList(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] = ''
                    GetMaterialsCouponList(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);
                    GetMaterialsCouponList(queryData);
                }
                //快速筛选 
                vm.itemClick = function () {
                    $(this).attr('class', '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;
                            }
                        }
                    }
                    GetMaterialsCouponList(queryData);
                }

                //新增
                vm.doadd = function () {
                    Mvvm.entity = modelFactory.create('MaterialsCoupon')
                    var curr = CBCRM.memberShip.$model
                    Mvvm.entity.Publisher = curr.Id
                    Mvvm.entity.PublisherDisplay = curr.FullName
                    Mvvm.entity.PublishDate = GetDateTime()
                    FormSubmit("新增优惠劵")
                }
                //编辑
                vm.doedit = function () {
                    var id = $(this).val()
                    Mvvm.materialscouponList.$model.forEach(function (item) {
                        if (item.Id == id) {
                            Mvvm.entity = item
                        }
                    })
                    FormSubmit("编辑优惠劵")
                }
                //查看 
                vm.doview = function () {
                    var id = 0
                    if (that.params.id) {
                        id = that.params.id
                        that.params.id = null
                    }
                    else {
                        id = $(this).val()
                    }
                    Mvvm.materialscouponList.$model.forEach(function (item) {
                        if (item.Id == id) {
                            Mvvm.entity = item
                        }
                    })
                    var dialog = openTmpl({
                        vm: Mvvm, title: "优惠劵详细", w: 800, h: 300,
                        tmplId:"viewTemplateCoupon",tmpl:tmpl
                    });

                }
                //删除
                vm.dodel = function () {
                    var index = parseInt($(this).attr('index'));
                    var id = $(this).val();
                    messageBox.confirm('确定删除此数据吗？', function () {
                        $.post('/Market/MaterialsCouponDel/' + id, {}, function (ret) {
                            if (ret.result)
                                Mvvm.materialscouponList.removeAt(index);
                            messageBox.succeed(ret.message);
                        })
                    });
                }
                //批量删除
                vm.doalldel = function () {
                    var deleteIds = checkAll();
                    messageBox.confirm('确定删除选中的数据吗？', function () {
                        $.post('/Market/MaterialsCouponAllDel/', deleteIds, function (ret) {
                            if (ret.result) {
                                GetMaterialsCouponList(queryData);
                                messageBox.succeed(ret.message);
                            }
                        });
                    });
                }
                //开始日期
                vm.startdateOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        Mvvm.entity.StartDate = formatDate
                    }

                }
                //结束日期
                vm.enddateOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        Mvvm.entity.EndDate = formatDate
                    }

                }
                //可用量
                vm.setResidualVal = function () {
                    Mvvm.entity.ResidualVal = Mvvm.entity.Stock
                }
                //选择所属战役
                vm.campaignList = []
                vm.campaignPanel = false
                vm.campaignKey = ''
                vm.selectCampaign = function () {
                    $('body').bind('mousedown', function () {
                        Mvvm.campaignPanel = false
                        $('body').unbind('mousedown')
                    })
                    getCampaignList();
                    Mvvm.campaignPanel = true;
                }
                vm.searchCampaign = function () {
                    getCampaignList();
                }
                vm.closeCampaignPanel = function () {
                    Mvvm.campaignPanel = false;
                }
                vm.clickCampaign = function () {
                    var campaign = $(this);
                    Mvvm.entity.CampaignId = campaign.attr("key");
                    Mvvm.entity.CampaignDisplay = campaign.attr("alt");
                    Mvvm.campaignPanel = false;
                }
                vm.clearCampaignValue = function () {
                    Mvvm.entity.CampaignId = ''
                    Mvvm.entity.CampaignDisplay = ''
                }
                //选择所属活动
                vm.activityList = []
                vm.activityPanel = false
                vm.activityKey = ''
                vm.selectActivity = function () {
                    $('body').bind('mousedown', function () {
                        Mvvm.activityPanel = false
                        $('body').unbind('mousedown')
                    })
                    getActivityList();
                    Mvvm.activityPanel = true;
                }
                vm.searchActivity = function () {
                    getActivityList();
                }
                vm.closeActivityPanel = function () {
                    Mvvm.activityPanel = false;
                }
                vm.clickActivity = function () {
                    var activity = $(this);
                    Mvvm.entity.ActivityId = activity.attr("key");
                    Mvvm.entity.ActivityDisplay = activity.attr("alt");
                    Mvvm.activityPanel = false;
                }
                vm.clearActivityValue = function () {
                    Mvvm.entity.ActivityId = ''
                    Mvvm.entity.ActivityDisplay = ''
                }

                vm.mousedownstop = function (e) {
                    e.stopPropagation()
                }
            })

            Mvvm.entity = modelFactory.create('MaterialsCoupon');

            //保存
            function FormSubmit(title) {
                var dialog = openTmpl({
                    vm: Mvvm, title: title, w: 800, h: 400,
                    tmplId: "formTemplateCoupon", tmpl: tmpl,
                    button: [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            var model = Mvvm.entity.$model;
                            var url = (model.Id == 0 ? "/Market/MaterialsCouponAdd/" : "/Market/MaterialsCouponUpdate/");
                            $.post(url + model.Id, model, function (ret) {
                                if (ret.result) {
                                    messageBox.ok(ret.message, function () { GetMaterialsCouponList(queryData); messageBox.close(); });
                                }
                                else {
                                    messageBox.fail(ret.message, function () { });
                                }
                            })

                            return false;
                        }
                    }]
                });
            }

            //创建查询对象并提交
            var createDate = {
                coupontype: 0,
                stocknum: 0,
                key: '',
                pageSize: 20,
                pageIndex: 1
            }
            //创建筛选对象
            var searchItem = {
                coupontype: '',
                stocknum: ''
            }

            var queryData = avalon.mix({}, createDate);
            Mvvm.showItem = avalon.mix({}, searchItem);

            function GetMaterialsCouponList(data) {
                $.get('/Market/MaterialsCoupon/', data || {}, function (ret) {
                    Mvvm.materialscouponList = ret.data.Source
                    avalon.vmodels.upaing.total = ret.data.RecordTotal

                    Mvvm.ADD = ret.data.ADD
                    Mvvm.DELETE = ret.data.DELETE

                    //传有参数Id,跳到查看
                    if (that.params.id) {
                        Mvvm.doview()
                    }
                })
            }

            //取所属战役
            function getCampaignList() {
                var key = Mvvm.campaignKey;
                $.get('/Market/Campaign/', { "key": key }, function (ret) {
                    Mvvm.campaignList = ret.data.Source;
                })
            }
            //取所属活动
            function getActivityList() {
                var key = Mvvm.activityKey;
                var campaignId = Mvvm.entity.CampaignId;
                $.get('/Market/Activity/', { "key": key, "campaignid": campaignId }, function (ret) {
                    Mvvm.activityList = ret.data.Source;
                })
            }

            require('commonui', function () {
                CBCRM.fillContent(tmpl, lang, contentId, module, Mvvm)
            })
            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.MaterialsCoupon = null
            }
        }

        ///物料管理-优惠劵领用
        , MaterialsCouponUse: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM, that = this
            var mvvm = CBCRM.define('marketingmaterialscouponuse', function (vm) {
                vm.lang = lang
                vm.entity = {}
                vm.materialscouponuseList = []
                vm.materialscouponusepaing = {
                    paging: function () {
                        var thatpage = this
                        queryData.pageSize = thatpage.pagesize
                        queryData.pageIndex = thatpage.currentindex + 1
                        GetMaterialsCouponUseList(queryData);
                    }
                }

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

                vm.ADD = true
                vm.DELETE = true

                //左边导航子项显示隐藏
                vm.ShowSubNav = 'materialscoupon'
                vm.onSubNav = function (subname) {
                    mvvm.ShowSubNav = subname
                }

                //关键字搜索
                vm.search = function () {
                    if (mvvm.keyword) {
                        queryData.key = mvvm.keyword;
                        GetMaterialsCouponUseList(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;
                    GetMaterialsCouponUseList(queryData);
                }
                //清空
                vm.clear = function () {
                    mvvm.keyword = '';
                    queryData = avalon.mix({}, createDate);
                    GetMaterialsCouponUseList(queryData);
                }
                //新增
                vm.doadd = function () {
                    mvvm.entity = modelFactory.create('MaterialsCouponUse')
                    var curr = CBCRM.memberShip.$model
                    mvvm.entity.User_Id = curr.Id
                    mvvm.entity.UserDisplay = curr.FullName
                    mvvm.entity.UseTime = GetDateTimeYMD()

                    if (that.params.id && that.params.name) {
                        mvvm.entity.CouponId = that.params.id
                        mvvm.entity.CouponDisplay = decodeURI(that.params.name)
                        that.params.name = null
                        that.params.id = null
                    }

                    FormSubmit("新增优惠券领用")
                }
                //编辑
                vm.doedit = function () {
                    var id = $(this).val()
                    mvvm.materialscouponuseList.$model.forEach(function (item) {
                        if (item.Id == id) {
                            mvvm.entity = item
                        }
                    })
                    FormSubmit("编辑优惠券领用")
                }
                //查看
                vm.doview = function () {
                    var id = $(this).val()
                    mvvm.materialscouponuseList.$model.forEach(function (item) {
                        if (item.Id == id) {
                            mvvm.entity = item
                        }
                    })
                    var dialog = openTmpl({
                        vm: mvvm, title: "优惠券领用详细", w: 700, h: 300,
                        tmplId:"viewTemplateCouponUse",tmpl:tmpl
                    });
                }
                //删除
                vm.dodel = function () {
                    var index = parseInt($(this).attr('index'));
                    var id = $(this).val();
                    messageBox.confirm('确定删除此数据吗？', function () {
                        $.post('/Market/MaterialsCouponUseDel/' + id, {}, function (ret) {
                            if (ret.result)
                                mvvm.materialscouponuseList.removeAt(index);
                            messageBox.succeed(ret.message);
                        })
                    });
                }
                //批量删除
                vm.doalldel = function () {
                    var deleteIds = checkAll();
                    messageBox.confirm('确定删除选中的数据吗？', function () {
                        $.post('/Market/MaterialsCouponUseAllDel/', deleteIds, function (ret) {
                            if (ret.result) {
                                GetMaterialsCouponUseList(queryData);
                                messageBox.succeed(ret.message);
                            }
                        });
                    });
                }

                //领用人
                vm.selectUser = function () {
                    plugins.selectUser({
                        dataAuth: 2050600,
                        callback: function (us) {
                            var u = us[0];
                            mvvm.entity.User_Id = u.Id;
                            mvvm.entity.UserDisplay = u.FullName;
                        }
                    })
                }
                vm.userTreeOpts = {
                    treeopts: {
                        callback: {
                            onCheck: function (e, treeId, treeNode) {
                                mvvm.entity.User_Id = treeNode.Id;
                                mvvm.entity.UserDisplay = treeNode.Name;
                            }
                        },
                        async: {
                            url: function (treeId, treeNode) {
                                var url = "/Settings/GetGroupPostUser/2050600"
                                vmtree = avalon.vmodels.userTreeId
                                if (vmtree && vmtree.q && vmtree.q !== vmtree.qcopy) {
                                    url += '?empName=' + vmtree.q
                                }
                                return url
                            },
                            dataFilter: notMemberFilter
                        },
                        check: {
                            enable: true,
                            chkStyle: 'radio',
                            radioType: "all"
                        }
                    }
                }

                //客户联系人
                vm.selectCustomer = function () {
                    plugins.selectCustomer({
                        type: "contacts",
                        callback: function (cus,cons) {
                            var cu = cus[0], con = cons[0];
                            mvvm.entity.CustomerId = cu.Id
                            mvvm.entity.CustomerDisplay = cu.Name
                            mvvm.entity.ContactId = con.Id
                            mvvm.entity.ContactDisplay = con.Name;
                        }
                    })
                }
                vm.customerTreeOpts = {
                    treeopts: {
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                if (treeNode.level > 0) {
                                    var zTree = $.fn.zTree.getZTreeObj(treeId)
                                    var parentTreeNode = zTree.getNodeByTId(treeNode.parentTId)
                                    mvvm.entity.CustomerId = parentTreeNode.Id
                                    mvvm.entity.CustomerDisplay = parentTreeNode.Name
                                    mvvm.entity.ContactId = treeNode.Id
                                    mvvm.entity.ContactDisplay = treeNode.Name;
                                }
                            }
                        },
                        async: {
                            url: function () {
                                var url = '/Customer/GetCustomerContacts/2050600'
                                var vmtree = avalon.vmodels.customerTreeId
                                if (vmtree && vmtree.q && vmtree.q !== vmtree.qcopy) {
                                    url += '?customerName=' + vmtree.q
                                }
                                return url
                            },
                            dataFilter: function (treeId, parentNode, responseData) {
                                var ret = [], len, curr
                                var list = responseData.data;
                                if (list && list.customers.length) {
                                    list.customers.forEach(function (item) {
                                        item.icon = '/Content/themes/base/images/ico/tree_customercategory0.png'
                                        ret.push(item);
                                        if (item.Contacts && item.Contacts.length) {
                                            item.Contacts.forEach(function (itemChild) {
                                                itemChild.icon = '/Content/themes/base/images/ico/tree_customercategory0.png'
                                                itemChild.ParentId = item.Id
                                                ret.push(itemChild)
                                            })
                                        }
                                    })
                                }
                                return ret
                            }
                        }
                    }
                }

                //领用时间
                vm.useTimeOpts = {
                    format: '%Y-%m-%d',
                    onSelect: function (date, formatDate, format) {
                        mvvm.UseTime = formatDate
                    }
                }

                //选择礼品赠品
                vm.couponList = []
                vm.couponPanel = false
                vm.couponKey = ''
                vm.selectCoupon = function () {
                    $('body').bind('mousedown', function () {
                        mvvm.giftPanel = false
                        $('body').unbind('mousedown')
                    })
                    GetCouponList();
                    mvvm.couponPanel = true;
                }
                vm.searchCoupon = function () {
                    GetCouponList();
                }
                vm.closeCouponPanel = function () {
                    mvvm.couponPanel = false;
                }
                vm.clickCoupon = function () {
                    var coupon = $(this);
                    mvvm.entity.CouponId = coupon.attr("key");
                    mvvm.entity.CouponDisplay = coupon.attr("alt");
                    mvvm.couponPanel = false;
                }
                vm.mousedownstop = function (e) {
                    e.stopPropagation()
                }
            })

            mvvm.entity = modelFactory.create('MaterialsCouponUse');

            //保存
            function FormSubmit(title) {
                var dialog = mvvm.openTmpl({
                    title: title, w: 720, h: 300,
                    tmplId:"formTemplateCouponUse",tmpl:tmpl,
                    button:[{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            var model = mvvm.entity.$model;
                            var url = (model.Id == 0 ? "/Market/MaterialsCouponUseAdd/" : "/Market/MaterialsCouponUseUpdate/");
                            $.post(url + model.Id, model, function (ret) {
                                if (ret.result) {
                                    messageBox.ok(ret.message, function () { GetMaterialsCouponUseList(queryData); messageBox.close(); });
                                }
                                else {
                                    messageBox.fail(ret.message, function () { });
                                }
                            })

                            return false;
                        }
                    }],
                    onClose:function () {
                        destroyui(["customerTreeId", "userTreeId"]);
                    }
                });
            }

            //创建查询对象并提交
            var createDate = {
                key: '',
                pageSize: 20,
                pageIndex: 1
            }

            var queryData = avalon.mix({}, createDate)

            function GetMaterialsCouponUseList(data) {
                $.get('/Market/MaterialsCouponUse/', data || {}, function (ret) {
                    mvvm.materialscouponuseList = ret.data.Source
                    avalon.vmodels.upaing.total = ret.data.RecordTotal

                    mvvm.ADD = ret.data.ADD
                    mvvm.DELETE = ret.data.DELETE

                })
            }

            function GetCouponList() {
                var key = mvvm.couponKey
                $.get('/Market/MaterialsCoupon/', { "key": key }, function (ret) {
                    mvvm.couponList = ret.data.Source;
                })
            }

            require('commonui', function () {
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)

            })

            //传有参数Id,列表中领用跳到领用新增页
            if (that.params.id && that.params.name) {
                mvvm.doadd()
            }

            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.MaterialsCouponUse = null
            }
        }

        ///广告宣传-广告素材
        , AdvertisingMaterials: function (tmpl, lang, contentId, module, conditionKey) {
            var router = this
            require('ConditionFactory,leftMenu', function (conditionFactory) {
                var conditions = conditionFactory.create(conditionKey || 'AdvertisingMaterials')
                , model, init = false, menus

                CBCRM = avalon.vmodels.CBCRM
                conditions.conditionChanged = function (item, conditions) {

                    model.loadData(conditions)
                }
                conditions.keyCol = 'Name';
                conditions.keyDynamic = false;
                model = CBCRM.define('AdvertisingMaterials', function (scope) {
                    avalon.mix(true, scope, conditions)
                    scope.$skipArray = ['lang']
                    scope.lang = lang
                    /*公用按钮权限设置参数 start*/
                    scope.ADD = true
                    scope.DELETE = true
                    /*公用按钮权限设置参数 end*/
                    /*客户 start*/
                    scope.listOpts = { //列表分页组件
                        paging: function () {
                            var m = model,
                            data = m.createDyQuery()
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    scope.imgtyps = ["jpg", "png", "gif", "jpeg"];
                    scope.previewPath = "";
                    scope.entity = modelFactory.create('AdvertisingMaterials');
                    scope.addAction = 'AdvertisingMaterialsAdd'
                    scope.editAction = 'AdvertisingMaterialsUpdate'
                    scope.list = []
                    scope.tab = "tab1";
                    scope.tabWidth = 650;
                    scope.tabHeight = 300;
                    scope.checkAll = false
                    scope.showAdd = function () {
                        model.entity = modelFactory.create('AdvertisingMaterials');
                        model.previewPath = "";
                        model.entity.UploadType = 1;
                        model.entity.AddBy.FullName = CBCRM.memberShip.FullName;
                        if (!model.entity.AddBy.FullName) model.entity.AddBy.FullName = "";
                        model.entity.ContentFormat = model.contentFormat1[0].val;
                        model.entity.MaterialType = model.materialType1[0].val;
                        model.entity.Holidays = model.holidays1[0].val;
                        showForm("新增广告素材");
                    }
                    scope.showEdit = function () {
                        var itemVm = this.$vmodel,
                        curitem = itemVm[itemVm.$itemName];
                        avalon.mix(model.entity, curitem.$model);
                        model.entity = curitem.$model;
                        model.entity.StartDate = model.entity.StartDate.replace("00:00", "");
                        model.entity.EndDate = model.entity.EndDate.replace("00:00", "");
                        if (typeof (model.entity.MediaType) == "string") model.entity.MediaType = model.entity.MediaType.split(",");
                        if (model.imgtyps.indexOf(model.entity.FileFormat.toLowerCase()) != -1) model.previewPath = model.entity.Path;
                        else model.previewPath = "";
                        showForm("编辑广告素材");
                    }
                    scope.showView = function () {
                        var itemVm = this.$vmodel,
                        curitem = itemVm[itemVm.$itemName];
                        model.entity = curitem.$model;
                        model.entity.StartDate = model.entity.StartDate.replace("00:00", "");
                        model.entity.EndDate = model.entity.EndDate.replace("00:00", "");
                        if (typeof (model.entity.MediaType) == "string") model.entity.MediaType = model.entity.MediaType.split(",");
                        showForm("查看广告素材", false);
                    }
                    scope.uploadFiles = function () {
                        var upwin = CBCRM.upload(true, function (node, data, file) {
                            model.entity.Path = '/upload/' + file.Path;
                            model.entity.Size = file.Size;
                            model.entity.FileFormat = file.FileType;
                            if (model.imgtyps.indexOf(file.FileType.toLowerCase()) != -1) model.previewPath = model.entity.Path;
                            else model.previewPath = "";
                            upwin.close();
                        });
                    }
                    scope.doRemoveAll = function () {
                        var ids = checkAll();
                        if (!ids["deleteIds[0]"]) {
                            messageBox.error(lang.RemoveAllAdvertisingMaterialsError);
                            return;
                        }
                        messageBox.confirm(lang.RemoveConfirm, function () {
                            $.post('/Market/AdvertisingMaterialsAllDel/', ids).done(function (ret) {
                                avalon.vmodels.CBCRM.showResult(ret, function () {
                                    var m = model
                                    m.conditionChanged(null, m.createDyQuery())
                                    messageBox.close()
                                })
                            });
                        });

                    }
                    scope.doRemove = function () {
                        var that = this
                        messageBox.confirm(lang.RemoveConfirm, function () {
                            var curVm = that.$vmodel,
                            curItem = curVm[curVm.$itemName]
                            $.post('/Market/AdvertisingMaterialsDel/' + curItem.Id)
                            .done(function (ret) {
                                avalon.vmodels.CBCRM.showResult(ret, function () {
                                    var m = model
                                    m.conditionChanged(null, m.createDyQuery())
                                    messageBox.close()
                                })
                            })
                        })
                    }

                    scope.initList = function (ret) {
                        avalon.log('ret is server response data')
                    }
                    scope.loadData = function (param) {
                        $.post(router.path || '/Market/AdvertisingMaterials/', param)
                        .done(function (ret) {
                            if (ret.result) {
                                var lst, stages
                                if (ret.data.Source) {
                                    model.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                                model.ADD = ret.data.ADD;
                                model.DELETE = ret.data.DELETE;
                            }
                        })
                    }
                    scope.contentFormat1 = [];
                    scope.materialType1 = [];
                    scope.mediaType1 = [];
                    scope.holidays1 = [];
                    scope.loadDict = function () {
                        $.get('/Market/AdvertisingMaterialsGetDict/').done(function (ret) {
                            for (var i = 0, l = ret.data.contentFormat.length; i < l; i++) {
                                var item = ret.data.contentFormat[i];
                                model.contentFormat.items.push({ label: item.Data, val: item.Id, curr: false });
                                if (i > 0) {
                                    model.contentFormat1.push({ label: item.Data, val: item.Id, curr: false });
                                }
                            }
                            for (var i = 0, l = ret.data.materialType.length; i < l; i++) {
                                var item = ret.data.materialType[i];
                                model.materialType.items.push({ label: item.Data, val: item.Id, curr: false });
                                if (i > 0) {
                                    model.materialType1.push({ label: item.Data, val: item.Id, curr: false });
                                }
                            }
                            for (var i = 0, l = ret.data.mediaType.length; i < l; i++) {
                                var item = ret.data.mediaType[i];
                                model.mediaType.items.push({ label: item.Data, val: item.Id, curr: false });
                                if (i > 0) {
                                    model.mediaType1.push({ label: item.Data, val: item.Id, curr: false });
                                }
                            }
                            for (var i = 0, l = ret.data.holidays.length; i < l; i++) {
                                var item = ret.data.holidays[i];
                                model.holidays.items.push({ label: item.Data, val: item.Id, curr: false });
                                if (i > 0) {
                                    model.holidays1.push({ label: item.Data, val: item.Id, curr: false });
                                }
                            }
                        });
                    }
                    //标签切换
                    scope.tabChange = function () {
                        var val = $(this).attr('val');
                        model.tab = val;
                    }
                    //日期参数
                    scope.birthdayOpts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            if (model.entity.EndDate != "" && formatDate > model.entity.EndDate) {
                                messageBox.fail("截止日期必须大于等于起始日期", function () {
                                    model.entity.StartDate = "";
                                });
                            }
                            else model.entity.StartDate = model.entity.StartDate;
                        }
                    }
                    scope.birthdayOpts2 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            if (model.entity.StartDate != "" && formatDate < model.entity.StartDate) {
                                messageBox.fail("截止日期必须大于等于起始日期", function () {
                                    model.entity.EndDate = "";
                                });
                            }
                            else model.entity.EndDate = formatDate;
                        }
                    }
                })

                function showForm(title, b) {
                    model.tab = "tab1";
                    var btn = b == false ? null : [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            var m = model.entity.$model;
                            m.MediaType = m.MediaType.join(",");

                            if (m.Name != "") {
                                var url = (m.Id == 0 ? "/Market/AdvertisingMaterialsAdd/" : "/Market/AdvertisingMaterialsUpdate/");
                                $.post(url + m.Id, m, function (ret) {
                                    if (ret.result) {
                                        messageBox.ok(ret.message, function () {
                                            if (ret.data.Id) {
                                                model.entity.Id = ret.data.Id;
                                            }
                                            messageBox.close();
                                            model.conditionChanged(null, model.createDyQuery());
                                        });
                                    }
                                    else {
                                        messageBox.fail(ret.message, function () { messageBox.close(); });
                                    }
                                })
                            }
                            else messageBox.warning('请填写名称！');
                            model.tab = 'tab1';
                            return false;
                        }
                    }];
                    var tmplId = b == false ? 'AdvertisingMaterialsviewTemplate' : 'AdvertisingMaterialsformTemplate';
                    var dialog = openTmpl({
                        vm: model, title: title, w: model.tabWidth, h: model.tabHeight,
                        tmplId:tmplId,tmpl:tmpl,button:btn
                    });
                }
                function getDictData(arr, id) {
                    arr.forEach(function (item) {
                        if (item.Id == id) return item.Data;
                    });
                    return "";
                }
                if (router.params.key) {
                    model.key = router.params.key
                    model.execSearch(model)
                }
                model.loadDict();

                avalon.vmodels.CBCRM.fillContent(tmpl, lang, contentId, module, model)
            })
        }

        ///广告宣传-广告投放
        , AdvertisingList: function (tmpl, lang, contentId, module, conditionKey) {
            var router = this
            require('ConditionFactory,leftMenu', function (conditionFactory) {
                var conditions = conditionFactory.create(conditionKey || 'AdvertisingList')
                , model, init = false, menus

                CBCRM = avalon.vmodels.CBCRM
                conditions.conditionChanged = function (item, conditions) {

                    model.loadData(conditions)
                }
                conditions.keyCol = 'Theme';
                conditions.keyDynamic = false;
                model = CBCRM.define('AdvertisingList', function (scope) {
                    avalon.mix(true, scope, conditions)
                    scope.$skipArray = ['lang']
                    scope.lang = lang
                    /*公用按钮权限设置参数 start*/
                    scope.ADD = true
                    scope.DELETE = true
                    /*公用按钮权限设置参数 end*/
                    /*客户 start*/
                    scope.listOpts = { //列表分页组件
                        paging: function () {
                            var m = model,
                            data = m.createDyQuery()
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    scope.entity = modelFactory.create('Advertising');
                    scope.imgtyps = ["jpg", "png", "gif", "jpeg"];
                    scope.previewPath = "";
                    scope.list = []
                    scope.medias = [];
                    scope.mediaKeyword = "";
                    scope.tab = "tab1";
                    scope.tabWidth = 640;
                    scope.tabHeight = 350;
                    scope.checkAll = false
                    scope.showAdd = function () {
                        model.entity = modelFactory.create('Advertising');
                        model.previewPath = "";
                        model.entity.UploadType = 1;
                        model.entity.AddBy.FullName = CBCRM.memberShip.FullName;
                        if (!model.entity.AddBy.FullName) model.entity.AddBy.FullName = "";
                        model.entity.CountUnit = model.countUnit[0].Id;
                        showForm("新增广告投放");
                    }
                    scope.showEdit = function () {
                        var itemVm = this.$vmodel,
                        curitem = itemVm[itemVm.$itemName];
                        model.entity = curitem.$model;
                        model.entity.StartDate = model.entity.StartDate.replace("00:00", "");
                        model.entity.EndDate = model.entity.EndDate.replace("00:00", "");
                        model.previewPath = "";
                        if (model.entity.AdAnnex) {
                            var a = model.entity.AdAnnex.split(".");
                            a = a[a.length - 1].toLowerCase();
                            if (model.imgtyps.indexOf(a) != -1) model.previewPath = model.entity.AdAnnex;
                        }
                        showForm("编辑广告投放");
                    }
                    scope.showView = function () {
                        var itemVm = this.$vmodel,
                        curitem = itemVm[itemVm.$itemName];
                        model.entity = curitem.$model;
                        model.entity.StartDate = model.entity.StartDate.replace("00:00", "");
                        model.entity.EndDate = model.entity.EndDate.replace("00:00", "");
                        showForm("查看广告投放", false);
                    }
                    scope.uploadFiles = function () {
                        var upwin = CBCRM.upload(true, function (node, data, file) {
                            model.entity.AdAnnex = '/upload/' + file.Path;
                            if (model.imgtyps.indexOf(file.FileType.toLowerCase()) != -1) model.previewPath = model.entity.AdAnnex;
                            else model.previewPath = "";
                            upwin.close();
                        });
                    }
                    scope.doRemoveAll = function () {
                        var ids = checkAll();
                        if (!ids["deleteIds[0]"]) {
                            messageBox.error(lang.RemoveAllAdvertisingError);
                            return;
                        }
                        messageBox.confirm(lang.RemoveConfirm, function () {
                            $.post('/Market/AdvertisingAllDel/', ids).done(function (ret) {
                                CBCRM.showResult(ret, function () {
                                    var m = model
                                    m.conditionChanged(null, m.createDyQuery())
                                    messageBox.close()
                                })
                            });
                        });
                    }
                    scope.doRemove = function () {
                        var that = this
                        messageBox.confirm(lang.RemoveConfirm, function () {
                            var curVm = that.$vmodel,
                            curItem = curVm[curVm.$itemName]
                            $.post('/Market/AdvertisingDel/' + curItem.Id)
                            .done(function (ret) {
                                CBCRM.showResult(ret, function () {
                                    var m = model
                                    m.conditionChanged(null, m.createDyQuery())
                                    messageBox.close()
                                })
                            })
                        })
                    }
                    scope.initList = function (ret) {
                        avalon.log(ret);
                    }
                    scope.loadData = function (param) {
                        $.post(router.path || '/Market/AdvertisingList/', param)
                        .done(function (ret) {
                            if (ret.result) {
                                var lst, stages
                                if (ret.data.Source) {
                                    model.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                                model.ADD = ret.data.ADD;
                                model.DELETE = ret.data.DELETE;
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    scope.countUnit = [];
                    scope.loadDict = function () {
                        $.get('/Market/AdvertisingGetDict/').done(function (ret) {
                            if (ret.result) {
                                scope.countUnit = ret.data.countUnit;
                            }
                            for (var i = 0, l = ret.data.mediaType.length; i < l; i++) {
                                var item = ret.data.mediaType[i];
                                model.mediaType.items.push({ label: item.Data, val: item.Id, curr: false });
                            }
                        });
                    }
                    //标签切换
                    scope.tabChange = function () {
                        var val = $(this).attr('val');
                        model.tab = val;
                    }
                    //日期参数
                    scope.birthdayOpts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            if (model.entity.EndDate != "" && formatDate > model.entity.EndDate) {
                                messageBox.fail("截止日期必须大于等于起始日期", function () {
                                    model.entity.StartDate = "";
                                });
                            }
                            else model.entity.StartDate = model.entity.StartDate;
                        }
                    }
                    scope.birthdayOpts2 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            if (model.entity.StartDate != "" && formatDate < model.entity.StartDate) {
                                messageBox.error("截止日期必须大于等于起始日期");
                                model.entity.EndDate = "";
                            }
                            else model.entity.EndDate = formatDate;
                        }
                    }
                    //联系人
                    scope.selectMedias = function () {
                        plugins.selectCustomer({
                            type: "contacts",
                            superiorCategoryId: 10134,
                            callback: function (cus,cons) {
                                var cu = cus[0], con = cons[0];
                                model.entity.MediaId = cu.Id;
                                model.entity.MediaIdData = cu.Name;
                                model.entity.ContactId = con.Id;
                                model.entity.ContactIdData = con.Name;
                                model.entity.MediaType = cu.CategoryId;
                                model.entity.MediaTypeData = where(model.mediaType.items, function (m) {
                                    return m.val == cu.CategoryId;
                                }, "label") || "";
                            }
                        })
                    }
                })

                function showForm(title, b) {
                    model.tab = "tab1";
                    var btn = b == false ? null : [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            var m = model.entity.$model;

                            if (m.Theme != "") {
                                var url = (m.Id == 0 ? "/Market/AdvertisingAdd/" : "/Market/AdvertisingUpdate/");
                                $.post(url + m.Id, m, function (ret) {
                                    if (ret.result) {
                                        messageBox.ok(ret.message, function () {
                                            if (ret.data.Id) {
                                                model.entity.Id = ret.data.Id;
                                            }
                                            if (dialog) dialog.close();
                                            model.conditionChanged(null, model.createDyQuery());
                                        });
                                    }
                                    else {
                                        console.log(ret);
                                        var fwin = messageBox.fail(ret.message, function () { if (fwin) fwin.close(); });
                                    }
                                })
                            }
                            else messageBox.warning('请填写主题名称！');
                            model.tab = 'tab1';
                            return false;
                        }
                    }];
                    var tmplId = b == false ? 'AdvertisingviewTemplate' : 'AdvertisingformTemplate';
                    var dialog = openTmpl({
                        vm: model, title: title, w: model.tabWidth, h: model.tabHeight,
                        tmplId: tmplId, tmpl: tmpl, button: btn,
                        onClose: function () {
                            if (avalon.vmodels.advertisingSelectMedia) avalon.vmodels.advertisingSelectMedia.destroy();
                        }
                    });
                }
                if (router.params.key) {
                    model.key = router.params.key
                    model.execSearch(model)
                }
                model.loadDict();

                avalon.vmodels.CBCRM.fillContent(tmpl, lang, contentId, module, model)
            })
        }

        ///渠道管理-工作台
        , Channel: function (tmpl, lang, contentId, module, conditionKey) {
            var CBCRM = avalon.vmodels.CBCRM
            var Mvvm = avalon.define('marketingchannel', function (vm) {
                vm.lang = lang;
                vm.policyList = [];
                vm.channelList = [];
                vm.contractList = [];
                vm.customerList = [];
                vm.keyword = "";
                vm.totalCustomer = 0;
                vm.count = { count1: 0, count2: 0, scale: 0 };
                vm.listPageOps = {
                    showtotal: false,
                    enablesetsize: false,
                    paging: function () {
                        getCustomerList({
                            pageSize: this.pagesize,
                            pageIndex: (this.currentindex + 1) || 1
                        });
                    }
                }
                vm.onkeyup = function (e) {
                    if (e.keyCode == 13) {
                        Mvvm.searchCustomer();
                    }
                }
                vm.searchCustomer = function () {
                    getCustomerList();
                }
                vm.getChannel = function (id) {
                    $.post("/Market/Channel/", { channelAgentId: id }).done(function (ret) {
                        if (ret.result) {
                            Mvvm.channelList = ret.data.channelList;
                            Mvvm.contractList = ret.data.contractList;
                        }
                    });
                }
                vm.channelLoadData = function () {
                    $.get("/Market/ChannelLoadData/", {}).done(function (ret) {
                        if (ret.result) {
                            Mvvm.count = ret.data.count;
                            Mvvm.policyList = ret.data.policyList
                        }
                    });
                }
            });
            function getCustomerList(data) {
                var params = avalon.mix({ name: Mvvm.keyword }, data || {});
                $.post("/Market/ChannelSearchCustomer/", params).done(function (ret) {
                    if (ret.result) {
                        Mvvm.customerList = ret.data.Source;
                        avalon.vmodels.listPage.total = ret.data.RecordTotal;
                        Mvvm.totalCustomer = ret.data.RecordTotal;
                    }
                });
            }
            CBCRM.fillContent(tmpl, lang, contentId, module, Mvvm)
            Mvvm.getChannel(0);
            Mvvm.channelLoadData();

            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.Channel = null
            }
        }

        ///渠道管理-渠道政策
        , ChannelPolicy: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM, that = this, txtContent
            var mvvm = CBCRM.define('marketingchannelpolicy', function (vm) {
                vm.lang = lang
                vm.entity = {}
                vm.channelpolicyList = []
                vm.channelpolicypaing = {
                    paging: function () {
                        var thatpage = this
                        queryData.pageSize = thatpage.pagesize
                        queryData.pageIndex = thatpage.currentindex + 1
                        GetChannelPolicyList(queryData);
                    }
                }

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

                vm.ADD = true
                vm.DELETE = true

                //关键字搜索
                vm.doSearch = function () {
                    queryData.key = mvvm.keyword;
                    GetChannelPolicyList(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;
                    GetChannelPolicyList(queryData);
                }
                //清空
                vm.clear = function () {
                    mvvm.keyword = '';
                    queryData = avalon.mix({}, createDate);
                    GetChannelPolicyList(queryData);
                }
                //新增
                vm.doadd = function () {
                    mvvm.entity = modelFactory.create('ChannelPolicy')
                    var curr = CBCRM.memberShip.$model
                    mvvm.entity.AddBy.Id = curr.Id
                    mvvm.entity.AddBy.FullName = curr.FullName
                    mvvm.entity.AddTime = GetDateTime()
                    FormSubmit("新增渠道政策")
                }
                //编辑
                vm.doedit = function () {
                    var id = $(this).val()
                    mvvm.channelpolicyList.$model.forEach(function (item) {
                        if (item.Id == id) {
                            mvvm.entity = item
                        }
                    })
                    FormSubmit("编辑渠道政策")
                }
                //查看
                vm.doview = function () {
                    var id = 0
                    if (that.params.id) {
                        id = that.params.id
                        that.params.id = null
                    }
                    else {
                        id = $(this).val()
                    }
                    mvvm.channelpolicyList.$model.forEach(function (item) {
                        if (item.Id == id) {
                            mvvm.entity = item
                        }
                    })

                    var dialog = messageBox.openHtml('渠道政策详细', '743px', '300px', '');
                    var content = $(dialog.content())
                    content.attr('ms-include', 'viewTemplatePolicy')
                    avalon.scan(content[0], mvvm)
                }
                //删除
                vm.dodel = function () {
                    var index = parseInt($(this).attr('index'));
                    var id = $(this).val();
                    messageBox.confirm('确定删除此数据吗？', function () {
                        $.post('/Market/ChannelPolicyDel/' + id, {}, function (ret) {
                            if (ret.result)
                                mvvm.channelpolicyList.removeAt(index);
                            messageBox.succeed(ret.message);
                        })
                    });
                }
                //批量删除
                vm.doalldel = function () {
                    var deleteIds = checkAll();
                    messageBox.confirm('确定删除选中的数据吗？', function () {
                        $.post('/Market/ChannelPolicyAllDel/', deleteIds, function (ret) {
                            if (ret.result) {
                                GetChannelPolicyList(queryData);
                                messageBox.succeed(ret.message);
                            }
                        });
                    });
                }
                //指定区域 
                vm.setPolicyObjectTreeOpts = {
                    treeopts: {
                        async: {
                            url: function () {
                                return '/Market/ChannelArea'
                            }
                        },
                        callback: {
                            onCheck: function (e, treeId, treeNode) {
                                var treeObj = $.fn.zTree.getZTreeObj(treeId)
                                var nodes = treeObj.getCheckedNodes(true)

                                var data = [], names = []
                                nodes.forEach(function (n, i) {
                                    data.push(n.Id)
                                    names.push(n.Name)
                                })
                                mvvm.entity.PolicyObject = data.join(',')
                                mvvm.entity.PolicyObjectDisplay = names.join(',')
                            }
                        },
                        view: {
                            addHoverDom: '',
                            removeHoverDom: ''
                        },
                        check: {
                            enable: true,
                            chkStyle: "checkbox",
                            chkboxType: { "Y": "p", "N": "s" }
                        }
                    }
                }
                //制定部门
                vm.setDepartTreeOpts = {
                    dataAuth:2030100,
                    treeopts: {
                        callback: {
                            onClick: function (event, treeId, treeNode) {
                                mvvm.entity.PublishSector = treeNode.Id
                                mvvm.entity.PublishSectorDisplay = treeNode.Name
                            }
                        }
                    }
                }
                //上传文件
                vm.uploadFiles = function () {
                    var upwin = CBCRM.upload(true, function (node, data, file) {
                        mvvm.entity.Affix = '/upload/' + file.Path;
                        upwin.close();
                    });
                }

            })

            mvvm.entity = modelFactory.create('ChannelPolicy');

            //保存
            function FormSubmit(title) {
                var dialog = mvvm.openTmpl({
                    title: title, w: 760, h: 400,
                    tmplid: "formTemplatePolicy", tmpl: tmpl,
                    button: [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            var model = mvvm.entity.$model
                            model.Content = txtContent.html()
                            if (model.PolicyType + '' == '1')
                                model.PolicyObject = 0 //为全部区域
                            var url = (model.Id == 0 ? "/Market/ChannelPolicyAdd/" : "/Market/ChannelPolicyUpdate/");
                            $.post(url + model.Id, model, function (ret) {
                                if (ret.result) {
                                    messageBox.ok(ret.message, function () { GetChannelPolicyList(queryData); messageBox.close(); });
                                }
                                else {
                                    messageBox.fail(ret.message, function () { });
                                }
                            })

                            return false;
                        }
                    }],
                    onClose: function () {
                        mvvm.destroyui(["setPolicyObjectTreeId", "setDepartTreeId"])
                    },
                    onScan: function () {
                        txtContent = ketool.simple('txtContent', '99%', '150px');
                        txtContent.html(mvvm.entity.Content);
                    }
                });
            }

            //创建查询对象并提交
            var createDate = {
                key: '',
                pageSize: 20,
                pageIndex: 1
            }

            var queryData = avalon.mix({}, createDate)

            function GetChannelPolicyList(data) {
                $.get('/Market/ChannelPolicy/', data || {}, function (ret) {
                    mvvm.channelpolicyList = ret.data.Source
                    avalon.vmodels.upaing.total = ret.data.RecordTotal

                    mvvm.ADD = ret.data.ADD
                    mvvm.DELETE = ret.data.DELETE

                    //传有参数Id,跳到查看
                    if (that.params.id) {
                        mvvm.doview()
                    }
                })
            }
            require('commonui', function () {
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            })
        }

        ///渠道管理-渠道开发维护
        , ChannelDevelop: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM, that = this, txtContent
            var mvvm = CBCRM.define('marketingchanneldevelop', function (vm) {
                vm.lang = lang
                vm.entity = {}
                vm.channeldevelopList = []
                vm.channeldeveloppaing = {
                    paging: function () {
                        var thatpage = this
                        queryData.pageSize = thatpage.pagesize
                        queryData.pageIndex = thatpage.currentindex + 1
                        GetChannelDevelopList(queryData)
                    }
                }

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

                vm.ADD = true
                vm.DELETE = true

                vm.behaviorData = []


                //关键字搜索
                vm.doSearch = function () {
                    queryData.key = mvvm.keyword;
                    GetChannelDevelopList(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;
                    GetChannelDevelopList(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] = ''
                    GetChannelDevelopList(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);
                    GetChannelDevelopList(queryData);
                }
                //快速筛选 
                vm.itemClick = function () {
                    $(this).attr('class', '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;
                            }
                        }
                    }
                    GetChannelDevelopList(queryData);
                }

                //新增
                vm.doadd = function () {
                    mvvm.entity = modelFactory.create('ChannelDevelop')
                    mvvm.entity.Behavior = mvvm.behaviorData.length ? mvvm.behaviorData[0].Id : ''
                    var curr = CBCRM.memberShip.$model
                    mvvm.entity.AddBy.Id = curr.Id
                    mvvm.entity.AddBy.FullName = curr.FullName
                    mvvm.entity.AddTime = GetDateTime()
                    mvvm.entity.Executor = curr.Id
                    mvvm.entity.ExecutorDisplay = curr.FullName
                    mvvm.entity.ExecutorTime = GetDateTime()
                    FormSubmit("新增渠道开发维护")
                }
                //编辑
                vm.doedit = function () {
                    var id = $(this).val()
                    mvvm.channeldevelopList.$model.forEach(function (item) {
                        if (item.Id == id) {
                            mvvm.entity = item
                        }
                    })
                    FormSubmit("编辑渠道开发维护")
                }
                //查看 
                vm.doview = function () {
                    var id = 0
                    if (that.params.id) {
                        id = that.params.id
                        that.params.id = null
                    }
                    else {
                        id = $(this).val()
                    }
                    mvvm.channeldevelopList.$model.forEach(function (item) {
                        if (item.Id == id) {
                            mvvm.entity = item
                        }
                    })

                    var dialog = messageBox.openHtml('渠道开发维护详细', '765px', '300px', '');
                    var content = $(dialog.content())
                    content.attr('ms-include', 'viewTemplateDevelop')
                    avalon.scan(content[0], mvvm)

                }
                //删除
                vm.dodel = function () {
                    var index = parseInt($(this).attr('index'));
                    var id = $(this).val();
                    messageBox.confirm('确定删除此数据吗？', function () {
                        $.post('/Market/ChannelDevelopDel/' + id, {}, function (ret) {
                            if (ret.result)
                                mvvm.channeldevelopList.removeAt(index);
                            messageBox.succeed(ret.message);
                        })
                    });
                }
                //批量删除
                vm.doalldel = function () {
                    var deleteIds = checkAll();
                    messageBox.confirm('确定删除选中的数据吗？', function () {
                        $.post('/Market/ChannelDevelopAllDel/', deleteIds, function (ret) {
                            if (ret.result) {
                                GetChannelDevelopList(queryData);
                                messageBox.succeed(ret.message);
                            }
                        });
                    });
                }

                //代理商
                vm.selectSupliers = function () {
                    plugins.selectCustomer({
                        type: "contacts",
                        required:{con:false},
                        superiorCategoryId:10132,
                        callback: function (cus,cons) {
                            var cu = cus[0];
                            mvvm.entity.ChannelAgentId = cu.Id
                            mvvm.entity.ChannelAgentDisplay = cu.Name
                            var con = cons.length > 0 ? cons[0] : { Id: "", Name: "" };
                            mvvm.entity.ContactId = con.Id
                            mvvm.entity.ContactDisplay = con.Name;
                        }
                    });
                }
                //执行人
                vm.selectExecutor = function () {
                    plugins.selectUser({
                        dataAuth: 2030201,
                        callback: function (us) {
                            var u = us[0];
                            mvvm.entity.Executor = u.Id;
                            mvvm.entity.ExecutorDisplay = u.FullName;
                        }
                    })
                }
            })

            mvvm.entity = modelFactory.create('ChannelDevelop');

            //保存
            function FormSubmit(title) {
                var dialog = mvvm.openTmpl({
                    title: title, w: 780, h: 300,
                    tmplId: "formTemplateDevelop", tmpl: tmpl,
                    button: [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            var model = mvvm.entity.$model;
                            model.Content = txtContent.html()
                            var url = (model.Id == 0 ? "/Market/ChannelDevelopAdd/" : "/Market/ChannelDevelopUpdate/");
                            $.post(url + model.Id, model, function (ret) {
                                CBCRM.showResult(ret, function () {
                                    GetChannelDevelopList(queryData);
                                    if (dialog) dialog.close();
                                })
                            })
                            return false;
                        }
                    }],
                    onClose: function () {
                        mvvm.destroyui(["supliersTreeId", "executorTreeId"])
                    },
                    onScan: function () {
                        txtContent = ketool.simple('txtContent', '99%', '150px');
                        txtContent.html(mvvm.entity.Content) 
                    }
                });
            }

            //创建查询对象并提交
            var createDate = {
                behavior: 0,
                key: '',
                pageSize: 20,
                pageIndex: 1
            }
            //创建筛选对象
            var searchItem = {
                behavior: ''
            }

            var queryData = avalon.mix({}, createDate);
            mvvm.showItem = avalon.mix({}, searchItem);
            InitDictItem()

            function GetChannelDevelopList(data) {
                $.get('/Market/ChannelDevelop/', data || {}, function (ret) {
                    mvvm.channeldevelopList = ret.data.Source
                    avalon.vmodels.upaing.total = ret.data.RecordTotal

                    mvvm.ADD = ret.data.ADD
                    mvvm.DELETE = ret.data.DELETE

                    //传有参数Id,跳到查看
                    if (that.params.id) {
                        mvvm.doview()
                    }
                })
            }

            //从字典取数据
            function InitDictItem() {
                //行为分类
                $.get('/Settings/Dictionary/', { "id": 100028 }, function (ret) {
                    mvvm.behaviorData = ret.data
                })
            }
            CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
        }

        ///渠道管理-渠道订单
        , ChannelOrder: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM, that = this, detail

            var mvvm = CBCRM.define('marketingchannelorder', function (vm) {
                vm.lang = lang
                vm.contractlist = []
                vm.contractpaing = {
                    paging: function () {
                        var thatpage = this
                        queryData.pageSize = thatpage.pagesize
                        queryData.pageIndex = thatpage.currentindex + 1
                        GetContractList(queryData);
                    }
                }
                vm.keyword = ''
                vm.history = []
                vm.showItem = {}
                vm.has = false

                vm.DELETE = true
                vm.NOPAGE = false

                //关键字搜索
                vm.doSearch = function () {
                    queryData.key = mvvm.keyword;
                    GetContractList(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;
                    GetContractList(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] = ''
                    GetContractList(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);
                    GetContractList(queryData);
                }
                //快速筛选 
                vm.itemClick = function () {
                    $(this).attr('class', '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;
                            }
                        }
                    }
                    GetContractList(queryData);
                }
                //删除
                vm.dodel = function () {
                    var index = parseInt($(this).attr('index'))
                    var id = $(this).attr("value")
                    messageBox.confirm('确定删除此数据吗？', function () {
                        $.post('/Market/ContractDel/' + id, {}, function (ret) {
                            if (ret.result)
                                mvvm.contractlist.removeAt(index)
                            messageBox.succeed(ret.message)
                        })
                    });
                }
                //批量删除
                vm.doalldel = function () {
                    var deleteIds = checkAll()
                    messageBox.confirm('确定删除选中的数据吗？', function () {
                        $.post('/Market/ContractAllDel/', deleteIds, function (ret) {
                            if (ret.result) {
                                GetContractList(queryData)
                                messageBox.succeed(ret.message)
                            }
                        });
                    });
                }
            })


            //创建查询对象并提交
            var createDate = {
                issample: 0,
                customercategory: 10132,//代理商分类ID
                signcontractdate: 0,
                contractdate: 0,
                key: '',
                pageSize: 20,
                pageIndex: 1
            }
            //创建筛选对象
            var searchItem = {
                issample: '',
                signcontractdate: '',
                contractdate: ''
            }

            var queryData = avalon.mix({}, createDate);
            mvvm.showItem = avalon.mix({}, searchItem);

            function GetContractList(data) {
                $.get('/Market/Contract', data || {}, function (ret) {
                    if (!ret.result) return CBCRM.showResult(ret);
                    mvvm.DELETE = ret.data.DELETE
                    mvvm.NOPAGE = ret.data.NOPAGE
                    mvvm.contractlist = ret.data.Source;
                    var page = avalon.vmodels.upaing;
                    if (mvvm.NOPAGE) {
                        destroyui(["upaing"]);
                    } else {
                        if (page) page.total = ret.data.RecordTotal;
                    }
                })
            }

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

        ///渠道管理-代理商区域
        , ChannelArea: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM, that = this, txtContent
            var mvvm = CBCRM.define('channelarea', function (vm) {
                vm.destroy = function () {
                    mvvm.destroyui(["channelareaparentTree"]);
                }
                vm.lang = lang
                vm.entity = {}
                vm.list = []
                vm.ADD = true
                vm.DELETE = true
                vm.title = "新增代理商区域";
                vm.action = "add";
                vm.pChannelAreaTreeOpts = {
                    events: {
                        add: function ($cur, data) {
                            if (data.tadd) {
                                var pid = data.id, pname = data.name
                                mvvm.action = "add"
                                mvvm.title = "新增代理商区域"
                                mvvm.entity = modelFactory.create('ChannelArea')
                                mvvm.entity.Parent.Id = pid
                                mvvm.entity.Parent.Name = pname
                            } else {
                                messageBox.warning("您没有新增代理商区域权限")
                            }
                        },
                        edit: function ($cur, data) {
                            if (data.tedit) {
                                var id = data.id, name = data.name
                                mvvm.action = "edit"
                                mvvm.title = "编辑代理商区域"
                                $.get('/Market/ChannelArea/', { "id": id }, function (ret) {
                                    mvvm.entity = ret.data[0]
                                })
                            } else {
                                messageBox.warning("您没有编辑代理商区域权限")
                            }
                        },
                        remove: function ($cur, data) {
                            if (data.tdelete) {
                                var id = data.id, name = data.name
                                messageBox.confirm('确定删除此数据吗？', function () {
                                    $.post('/Market/ChannelAreaDelete/' + id, {}, function (ret) {
                                        if (ret.result) GetChannelAreaList();
                                        else messageBox.error(ret.message);
                                    })
                                })
                            } else {
                                messageBox.warning("您没有删除代理商区域权限")
                            }
                        }
                    },
                    treeopts: {
                        async: {
                            url: function () {
                                return '/Market/ChannelArea/'
                            }
                        },
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                mvvm.entity.Parent.Id = treeNode.Id
                                mvvm.entity.Parent.Name = treeNode.Name
                            }
                        }
                    }
                }
                //上级区域下拉树
                vm.parentTreeOpts = {
                    treeopts: {
                        async: {
                            url: function () {
                                return '/Market/ChannelArea/'
                            }
                        },
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                mvvm.entity.Parent.Id = treeNode.Id
                                mvvm.entity.Parent.Name = treeNode.Name
                            }
                        }
                    }
                }

                //新增
                vm.doadd = function () {
                    mvvm.action = "add"
                    mvvm.title = "新增代理商区域"
                    mvvm.entity = modelFactory.create('ChannelArea');
                    mvvm.entity.Parent.Id = "";
                    mvvm.entity.Parent.Name = "";
                }
                //保存
                vm.doSubmit = function () {
                    var model = avalon.mix({}, mvvm.entity.$model);
                    model["ParentId"] = model.Parent.Id;
                    delete model.AddBy;
                    delete model.Parent;
                    var herf = mvvm.action == "add" ? "/Market/ChannelAreaAdd/" : "/Market/ChannelAreaUpdate/" + model.Id;
                    if (model.Name == '') {
                        messageBox.error('区域名称不能为空！')
                        return
                    }
                    $.post(herf, model, function (ret) {
                        if (ret.result) {
                            messageBox.ok(ret.message)
                            GetChannelAreaList();
                            if (mvvm.action == "add") mvvm.entity = modelFactory.create('ChannelArea');
                        } else {
                            messageBox.error(ret.message);
                        }
                    })
                    return false;
                }

            })

            mvvm.entity = modelFactory.create('ChannelArea');

            function GetChannelAreaList(data) {
                $.get('/Market/ChannelArea/', data || {}, function (ret) {
                    mvvm.list = ret.data
                    avalon.vmodels.channelareatreeid.datasource = ret.data;
                    avalon.vmodels.channelareaparentTree.datasourceCopy = ret.data;
                })
            }
            CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
        }
    }
    return Market;
});