define('Product', ['modelFactory', 'plugins', 'json', 'dialog', 'common', 'leftMenu', 'jscal2', 'kindedit', 'Jpin', 'upload', 'fusionCharts', 'cjlmin', 'jqPrint'],
    function (modelFactory, plugins) {
        //下拉配置过滤数据 只可选员工
        var notMemberFilter = function (treeId, parentNode, responseData) {
            var CBCRM = avalon.vmodels.CBCRM
            var ret = [], len = 0, curr, hasEmp = false
            if (responseData.data && responseData.data.groups.length)
                len = responseData.data.groups.length
            while (len) {
                curr = responseData.data.groups[--len]
                curr.nocheck = true
                hasEmp = false
                curr.Posts.forEach(function (p, i) {
                    curr.Posts[i].ParentId = p.Boss ? p.Boss.Id : p.Group
                    curr.Posts[i].nocheck = true
                    p.Users.forEach(function (u, i) {
                        var u = p.Users[i]
                        if (u.Id === CBCRM.memberShip.Id) return true
                        u.ParentId = u.PositionId
                        u.Name = u.FullName
                        ret.push(u)
                    })
                    if (!hasEmp) {
                        hasEmp = p.Users.length > 0
                    }
                    if (hasEmp) {
                        ret.push(p)
                    }
                })
                if (hasEmp) ret.push(curr)
            }
            return ret
        },
        //只要部门和用户
            notPostFilter = function (treeId, parentNode, responseData) {
                var CBCRM = avalon.vmodels.CBCRM
                var ret = [], len = 0, curr, hasEmp = false
                if (responseData.data && responseData.data.groups.length)
                    len = responseData.data.groups.length
                while (len) {
                    curr = responseData.data.groups[--len]
                    curr.nocheck = true
                    hasEmp = false
                    curr.Posts.forEach(function (p, i) {
                        p.Users.forEach(function (u, i) {
                            //if (u.Id === CBCRM.memberShip.Id) return true
                            u.ParentId = p.Boss ? p.Boss.Id : p.Group
                            u.Post = p.Name;
                            u.Name = u.FullName + "(" + u.Post + ")";
                            u.GroupName = curr.Name;
                            ret.push(u)
                        })
                        if (!hasEmp) {
                            hasEmp = p.Users.length > 0
                        }
                    })
                    ret.push(curr);
                }
                return ret
            }

        var ProductMode = {
            Total: '',//总金额
            Numder: '',//总数量
            Product: '',//产品
            Sort: ''//排名
        };

        //JQuery 线性图
        function createJQLinear(chartId, title, chartData) {
            var linearData = [], series=[];
            var labels = [];
            var name = '';
            $(chartId).empty();
            try {
                chartData.forEach(function (item) {
                    series.push({
                        label: item.seriesname,
                        color: item.color ? "#" + item.color : null,
                    })
                    var a = [];
                    item.data.forEach(function (node, i) {
                        a.push([node.label, node.value]);
                    })
                    linearData.push(a);
                });
                $(chartId).jqplot(linearData, {
                    title: title,
                    series: series,
                    seriesDefaults: {
                        rendererOptions: { fillToZero: true },
                        // Rotate the bar shadow as if bar is lit from top right.
                        shadowAngle: 135
                    },
                    axes: {
                        xaxis: {
                            renderer: $.jqplot.CategoryAxisRenderer
                        }
                        //,
                        //yaxis: {
                        //    label: '',
                        //    tickOptions: {
                        //        formatString: '%.1f'
                        //    },
                        //    rendererOptions: {
                        //        forceTickAt0: true
                        //    },
                        //    lableRenderer: $.jqplot.CanvasAxisLabelRenderer,
                        //}
                    },
                    legend: {
                        renderer: $.jqplot.enhancedlegendrenderer,
                        show: true,
                        location: 'ne',
                         placement:'outsidegrid'
                    }
                });
            }
            catch (ex) {
                $(chartId).html("<p class='nodata'>" + ex.message + "</p>");
            }
        }

        //产品模块
        var Product = {
            ///产品管理
            Product: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, viewdialog, init = false, initBrand = false, priceError = [],
                    that = this, vmid = "Products"
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.lang = lang
                    vm.entity = {}
                    vm.productList = []
                    vm.priceList = []
                    vm.gradePricelist = [];
                    vm.gradelist = [];
                    vm.keyword = ''
                    vm.history = []
                    vm.showItem = {}
                    vm.action = "list"
                    vm.title = ""
                    vm.has = false
                    vm.ADD = true
                    vm.DELETE = true
                    vm.UP = true
                    vm.DOWN = true
                    vm.EDITPRICE = false;
                    vm.SPECIALPRICE = false;
                    //产品分类树配置
                    vm.pCategoryTreeOpts = {
                        treeopts: {
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    mvvm.brandDatas = [];
                                    mvvm.supplierDatas = [];
                                    mvvm.getBrandAndSuplier(treeNode.Id);
                                    queryData.typeid = treeNode.Id
                                    queryData.brandid = '';
                                    queryData.cusid = '';
                                    mvvm.showItem.typeid = '';
                                    mvvm.showItem.typeid = treeNode.Name;
                                    mvvm.showItem.brandid = '';
                                    mvvm.showItem.cusid = '';
                                    getProcutList(queryData)
                                    mvvm.action = 'list'
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            }
                        }
                    }
                    vm.getBrandAndSuplier = function (cid) {
                        if (!initBrand) {
                            initBrand = true;
                            //window.setTimeout(function () {
                            //    mvvm.getBrandAndSuplier(cid);
                            //}, 800);
                            //return;
                        }
                        $.get('/Product/BrandAndSuplier/', { cid: cid }, function (ret) {
                            mvvm.brandDatas = ret.data.brandData;
                            mvvm.brandDatasOriginal = ret.data.brandData;
                            mvvm.supplierDatas = ret.data.custromerData;
                            mvvm.supplierDatasOriginal = ret.data.custromerData;
                            if (ret.data.brandData.length < 5) mvvm.expanbran = false;
                            if (ret.data.custromerData < 5) mvvm.expansupplier = false;
                        })
                    }
                    //设置产品分类树配置
                    vm.setCategoryTreeOpts = {
                        treeopts: {
                            callback: {
                                onCheck: function (e, treeId, treeNode) {
                                    mvvm.entity.CategoryId = treeNode.Id;
                                    mvvm.entity.CategoryName = treeNode.Name;
                                    //供应商
                                    mvvm.entity.SuplierIds = ''
                                    mvvm.entity.SuplierNames = '';
                                    mvvm.entity.Brand.Id = '';
                                    mvvm.entity.Brand.Name = '';
                                    if ($.fn.zTree.getZTreeObj("suplierTreezTree"))
                                        $.fn.zTree.getZTreeObj("suplierTreezTree").reAsyncChildNodes(null, "refresh");
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            },
                            check: {
                                enable: true,
                                chkStyle: 'radio',
                                radioType: "all"
                            }
                        }
                    }
                    // 选择供应商
                    vm.selectSuplier = function () {
                        var ids = mvvm.entity.SuplierIds || [];
                        if (typeof (ids) == "string") ids = ids.split(",");
                        plugins.selectCustomer({
                            multiple: true,
                            required: { cu: false },
                            listData: ids,
                            superiorCategoryId: 10133,
                            //brandId:mvvm.entity.Brand.Id,
                            callback: function (cus) {
                                var ids = where(cus, true, "Id"), names = where(cus, true, "Name");
                                mvvm.entity.SuplierIds = ids.join(',');
                                mvvm.entity.SuplierNames = names.join(',');
                            }
                        })
                    }

                    vm.productpaing = {
                        paging: function () {
                            var thatpage = this
                            var data = $.extend({}, queryData, {
                                key: queryData.key,
                                pageSize: thatpage.pagesize,
                                pageIndex: thatpage.currentindex + 1
                            });
                            if (!init)init = true;
                            getProcutList(data);
                        }
                    }
                    //时间范围配置
                    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.units = []
                    //重量下拉
                    vm.weights = []
                    //产品图片
                    vm.OriginImgs = []
                    //品牌快速筛选数据选项
                    vm.brandDatas = []
                    vm.brandDatasOriginal = []
                    //供应商快速筛选数据选项
                    vm.supplierDatasOriginal = []
                    vm.supplierDatas = []
                    //关键字搜索
                    vm.doSearch = function () {
                        if (mvvm.keyword) {
                            queryData.key = mvvm.keyword;
                            getProcutList(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;
                        getProcutList(queryData);
                    }
                    //移除单个快速筛选
                    vm.remove = function () {
                        var searchKey = this.$vmodel.$key;
                        mvvm.showItem[searchKey] = '';
                        if (searchKey == "brandid" || searchKey == "cusid") {
                            $("#" + searchKey).next().addClass('selected');
                            $(".quickword1 input[key='" + searchKey + "']:checked").next().removeClass('selected');
                            $(".quickword1 input[key='" + searchKey + "']:checked").each(function () {
                                this.checked = false;
                            })
                        }
                        else {
                            $(".quickword1 a[key='" + searchKey + "']").eq(0).addClass('selected').siblings().removeClass('selected');
                        }
                        setShowRemoveAll();
                        queryData[searchKey] = '';
                        getProcutList(queryData);
                    }
                    //清空
                    vm.doClear = function () {
                        mvvm.keyword = '';
                        mvvm.showItem = avalon.mix({}, searchItem);
                        mvvm.has = false;
                        $(".quickword1 a").removeClass('selected');
                        $(".quickword1 input[type='checkbox']:checked").next().removeClass('selected');
                        $(".quickword1 a[value='0']").addClass('selected');
                        $(".quickword1 input[type='checkbox']:checked").each(function () {
                            this.checked = false;
                        })
                        queryData = avalon.mix({}, createDate);
                        getProcutList(queryData);
                    }
                    //快速筛选 
                    vm.itemClick = function () {
                        $(this).attr('class', 'selected').parent().siblings().find("a").removeClass('selected');
                        var key = $(this).attr("key");
                        var value = $(this).attr("value");
                        var name = $(this).parent().parent().parent().parent().find("span").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] = ''
                            setShowRemoveAll();
                        }
                        getProcutList(queryData);
                    }
                    vm.itemMutiClick = function () {
                        var chk = $(this);
                        var key = chk.attr("key");
                        var value = chk.attr("value");
                        var name = $("#" + key).text();
                        var display = chk.attr("title");
                        var itemVal = queryData[key];    //筛选条件值
                        var itemDiplay = mvvm.showItem[key]; //筛选条件显示
                        if (value == "0") {
                            itemVal = "";
                            itemDiplay = "";
                            chk.addClass("selected");
                        }
                        else if (chk.attr("checked")) {
                            itemVal = itemVal + value + ",";
                            if (!itemDiplay) itemDiplay = name + ":";
                            itemDiplay = itemDiplay + display + ",";
                            chk.next().addClass("selected");
                            $("#" + key).next().removeClass("selected");
                            mvvm.has = true;
                        }
                        else {
                            itemVal = itemVal.replace(value + ",", "");
                            itemDiplay = itemDiplay.replace(display + ",", "");
                            chk.next().removeClass("selected");
                            if (!itemVal) {
                                $("#" + key).next().addClass("selected");
                                itemDiplay = "";
                                setShowRemoveAll();
                            }
                        }
                        queryData[key] = "";
                        queryData[key] = itemVal;
                        mvvm.showItem[key] = "";
                        mvvm.showItem[key] = itemDiplay;

                        getProcutList(queryData);
                    }
                    //品牌收起/展开
                    vm.brankey = "";
                    vm.expanbran = false;
                    vm.onExpanbran = function () {
                        mvvm.expanbran = !mvvm.expanbran;
                        //$(this).text(mvvm.expanbran?"收起":"更多");
                    }
                    vm.findBrand = function () {
                        if (!mvvm.brankey) {
                            mvvm.brandDatas = mvvm.brandDatasOriginal.$model;
                            return;
                        }
                        mvvm.brandDatas.removeAll();
                        mvvm.brandDatasOriginal.forEach(function (item) {
                            if (item.Name.indexOf(mvvm.brankey) > -1) mvvm.brandDatas.push(item);
                        });
                    }
                    //供应商收起展开
                    vm.supplierkey = "";
                    vm.expansupplier = false;
                    vm.onExpansupplier = function () {
                        mvvm.expansupplier = !mvvm.expansupplier;
                        $(this).text(mvvm.expansupplier ? "收起" : "更多");
                    }
                    vm.findSupplier = function () {
                        if (!mvvm.supplierkey) {
                            mvvm.supplierDatas = mvvm.supplierDatasOriginal.$model;
                            return;
                        }
                        mvvm.supplierDatas.removeAll();
                        mvvm.supplierDatasOriginal.forEach(function (item) {
                            if (item.Name.indexOf(mvvm.brankey) > -1) mvvm.supplierDatas.push(item);
                        });
                    }
                    //分类树展开、收起
                    vm.$expancategory = true;
                    vm.expanCategory = function () {
                        mvvm.$expancategory = !mvvm.$expancategory;
                        $(this).text(mvvm.$expancategory ? "- 收起" : "+ 展开");
                        var tree = $.fn.zTree.getZTreeObj("productCategoryTree");
                        if (tree) {
                            var nodes = tree.getNodes();
                            if (nodes.length > 0) tree.expandNode(nodes[0], mvvm.$expancategory, true);
                            //收起的时候让根节点处于展开状态
                            if (!mvvm.$expancategory) tree.expandNode(nodes[0], !mvvm.$expancategory, false);
                        }
                    }

                    //导航切换
                    vm.currNav = 1;
                    vm.doChangeNav = function (n) {
                        mvvm.currNav = n;
                        if (n == 4) {
                            mvvm.getStorehouseList(mvvm.productId);
                        } else if (n == 5) {
                            getProductDynamicList(mvvm.productId, GetDateTime(new Date(), "yyyy-MM-dd"), "down");
                        }
                        else if (n == 6) {
                            avalon.nextTick(function () {
                                mvvm.show = false;
                                if (mvvm.show == true)
                                    mvvm.showTable = true
                                else
                                    mvvm.showTable = false
                                mvvm.TimeTypeOne = 0
                                mvvm.TimeTypeTwo = 0
                                mvvm.dateVal = 0
                                mvvm.bTime = GetDateTime(new Date(new Date().getFullYear(), new Date().getMonth(), 1), "yyyy-MM-dd");
                                mvvm.eTime = GetDateTime(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0), "yyyy-MM-dd");
                                mvvm.starTime = GetDateTime(new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1), "yyyy-MM-dd");
                                mvvm.endTime = GetDateTime(new Date(new Date().getFullYear(), new Date().getMonth(), 0), "yyyy-MM-dd");
                                getDataList(mvvm.productId, mvvm.dateVal, mvvm.bTime, mvvm.eTime, mvvm.starTime, mvvm.endTime, mvvm.show);
                            });
                        }
                        var paths = {
                            4: "",
                            5: ""
                        }
                        if (paths[n]) goto(paths[n]);
                    }
                    vm.tabWidth = 800;
                    vm.tab = 1;
                    vm.tabChange = function () {
                        var val = $(this).attr("val");
                        mvvm.tab = val;
                    }
                    vm.tabs = 1;
                    vm.tabChanges = function () {
                        var val = $(this).attr("val");
                        mvvm.tabs = val;
                    }
                    //新增
                    vm.doadd = function () {
                        mvvm.action = "add"
                        mvvm.title = "新增产品"
                        mvvm.entity = $.extend(true, {}, modelFactory.create('Product'));
                        if (mvvm.units.length > 0) mvvm.entity.Units = mvvm.units[0].Id;
                        if (mvvm.weights.length > 0) mvvm.entity.UnitOfWeight = mvvm.weights[0].Id;
                        mvvm.entity.IsSpecial += ''
                        mvvm.pro = [];
                        mvvm.OriginImgs = []
                        mvvm.initGradePrice([]);
                        mvvm.entity.$watch("GeneralCustomerPrice", mvvm.watchPrice);
                        mvvm.showForm(mvvm.title);
                    }
                    vm.watchPrice = function (n) {
                        mvvm.gradePricelist.forEach(function (item) {
                            item.Prints = (isNaN(n) || !n) ? "" : n * item.Discount / 100;
                        });
                    }
                    vm.syncPrice = function () {
                        mvvm.entity.RoyaltyPrice = mvvm.entity.GeneralCustomerPrice;
                    }
                    vm.initGradePrice = function (arr) {
                        var price = {};
                        arr.forEach(function (item) {
                            price[item.MemberGrade] = item;
                        });
                        var a = [];
                        mvvm.gradelist.forEach(function (item) {
                            var p = price[item.Id];
                            a.push({
                                Type: 1,
                                Id: p == null ? "" : p.Id,
                                MemberGradeDisplay: item.Name,
                                MemberGrade: item.Id,
                                Prints: p == null ? "" : p.Prints,
                                Discount: item.Discount
                            })
                        });
                        mvvm.gradePricelist = a;
                    }

                    vm.getEntity = function (id, callback, remote) {
                        var has = false;
                        if (!remote) {
                            $.each(mvvm.productList.$model, function (i, item) {
                                if (item.Id == id) {
                                    has = true;
                                    if (callback) callback(item);
                                    return false;
                                }
                            });
                        }
                        if (!has) {
                            _getProcutList({ id: id }, function (list, ret) {
                                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;
                                if (list.length > 0) {
                                    if (callback) callback(list[0]);
                                } else {
                                    messageBox.warning("记录不存在或已经被删除！");
                                }
                            });
                        }
                    }
                    //编辑
                    vm.doedit = function (id) {
                        //InitDictionary()
                        vm.action = "edit"
                        vm.title = "编辑产品"
                        mvvm.$delids = [];
                        mvvm.getEntity(id, function (item) {
                            item.IsSpecial += ''
                            mvvm.entity = item;
                            mvvm.entity.State += ""
                            //txtInfo.html(item.Info)
                            //txtAfterService.html(item.AfterService)
                            mvvm.OriginImgs = mvvm.entity.OriginImg ? mvvm.entity.OriginImg.split(',') : []
                            if (viewdialog) viewdialog.close();
                            getGradePricelist();
                            mvvm.entity.$watch("GeneralCustomerPrice", mvvm.watchPrice);
                            mvvm.showForm(mvvm.title);
                        });
                    }
                    //复制
                    vm.docopy = function () {
                        var deleteIds = checkAll();
                        if (deleteIds.length == 0) {
                            messageBox.error("操作失败<br />请选择一条数据！");
                            return;
                        }
                        if (deleteIds.length > 1) {
                            messageBox.error("操作失败<br />请只选择一条数据！");
                            return;
                        }
                        var id = deleteIds["deleteIds[0]"];
                        vm.action = "add"
                        vm.title = "复制产品"
                        mvvm.getEntity(id, function (item) {
                            item.IsSpecial += ''
                            mvvm.entity = item;
                            mvvm.entity.State += ""
                            //txtInfo.html(item.Info)
                            //txtAfterService.html(item.AfterService)
                            mvvm.OriginImgs = mvvm.entity.OriginImg ? mvvm.entity.OriginImg.split(',') : []
                            if (viewdialog) viewdialog.close();
                            getGradePricelist();
                            mvvm.entity.$watch("GeneralCustomerPrice", mvvm.watchPrice);
                            mvvm.entity.Id = "";
                            mvvm.showForm(mvvm.title);
                        });
                    }

                    //显示新增、编辑界面
                    vm.showForm = function (title) {
                        mvvm.tab = "tab1";
                        var btns = [{
                            name: "提交保存",
                            focus: true,
                            callback: function () {
                                mvvm.entity.Info = txtInfo.html();
                                mvvm.entity.AfterService = txtAfterService.html()
                                var model = $.extend(true, {}, mvvm.entity.$model);
                                model["BrandId"] = mvvm.entity.$model.Brand.Id;
                                if (!model.Name) {
                                    messageBox.error("操作错误 </br>产品名称不能为空！");
                                    return false;
                                }
                                //
                                if (!model.CategoryId) {
                                    messageBox.error("操作错误 </br>请选择产品分类！");
                                    return false;
                                }
                                priceError = [];
                                mvvm.lowestPrice(mvvm.entity.GeneralCustomerPrice, "销售价格");
                                $.each(mvvm.gradePricelist.$model, function (i, item) {
                                    mvvm.lowestPrice(item.Prints, item.MemberGradeDisplay + "价格");
                                });
                                if (priceError.length > 0) {
                                    messageBox.error("价格填写有误 </br>" + priceError.join(",") + "低于最低价格" + mvvm.entity.LowestPrice + "元");
                                    return false;
                                }
                                $.extend(model, jsonToSubmit("priceList1", mvvm.gradePricelist.$model));
                                $.extend(model, jsonToSubmit("specialList", mvvm.pro.$model));
                                $.extend(model, jsonToSubmit("delids", mvvm.$delids));
                                var herf = vm.action == "add" ? "/Product/ProductAdd/" : "/Product/ProductUpdate/" + model.Id
                                $.post(herf, model, function (ret) {
                                    CBCRM.showResult(ret, function () {
                                        if (ret.result) {
                                            if (dialog) dialog.close();
                                            //getProcutList(queryData)
                                            mvvm.productpaing.paging();
                                        }
                                    })
                                });
                                return false;
                            }
                        }]
                        var dialog = mvvm.openTmpl({
                            title: title, w: 800, btns: btns,
                            url:"/Product/ProductForm.html",
                            extParam: { top: 10 },
                            onClose: function () {
                                destroyui(["setCategory"]);
                            },
                            onScan: function () {
                                setEditor();
                            }
                        });
                        
                        if (mvvm.action == "edit") {
                            //loadZoomImg()
                            //getSpecialPrice()
                        }
                        if (mvvm.action == "add") {
                            var tree = $.fn.zTree.getZTreeObj("productCategoryTree");
                            if (tree) {
                                var treeNodes = tree.getSelectedNodes();
                                if (treeNodes.length > 0) {
                                    var treeNode = treeNodes[0];
                                    mvvm.entity.CategoryId = treeNode.Id;
                                    mvvm.entity.CategoryName = treeNode.Name;
                                    //供应商
                                    mvvm.entity.SuplierIds = ''
                                    mvvm.entity.SuplierNames = '';
                                    mvvm.entity.Brand.Id = '';
                                    mvvm.entity.Brand.Name = '';
                                }
                            }
                        }
                    }
                    //最低价格限制
                    vm.lowestPrice = function (price, name) {
                        var lprice = mvvm.entity.LowestPrice;
                        if (!lprice || isNaN(lprice)) return false;
                        lprice = parseFloat(lprice, 10);
                        price = parseFloat(price, 10);
                        var b = price < lprice;
                        if (b) priceError.push(name);
                        return b;
                    }
                    //上下条
                    vm.hasPrevious = true;
                    vm.hasNext = true;
                    vm.previousId = '';
                    vm.nextId = '';
                    vm.previousLabel = '';
                    vm.nextLabel = '';
                    //查看
                    vm.productId = 0
                    vm.doview = function (id) {
                        mvvm.tab = 1;
                        mvvm.currNav = 1;
                        mvvm.productId = id
                        mvvm.action = "view"
                        mvvm.title = "产品详细"
                        mvvm.$delids = [];
                        mvvm.getEntity(id, function (item) {
                            mvvm.entity = item
                            if (item.IsSpecial)
                                mvvm.entity.IsSpecial = "是";
                            else
                                mvvm.entity.IsSpecial = "否";
                            mvvm.OriginImgs = mvvm.entity.OriginImg ? mvvm.entity.OriginImg.split(',') : []
                            getGradePricelist();
                            viewdialog = mvvm.openTmpl({
                                title: "查看产品详情", w: 990, padding: "0px",
                                url: "/Product/ProductView.html",
                                extParam: { top: 10 },
                                onScan: function () {
                                    loadZoomImg();
                                }
                            })
                        }, true);
                    }

                    vm.doPrint = function () {
                        messageBox.confirm('您确定要打印当前产品信息吗？', function () {
                            $("#productPanelPrint").printArea()
                        })
                    }
                    //删除
                    vm.dodel = function (id) {
                        var msg = '确定要删除该产品吗？<br />删除产品后，将对相关订单、财务、统计报表造成影响。<br>建议确认该产品无相关数据后，再慎重删除！';
                        messageBox.confirm2(msg, "删除", "取消", function () {
                            $.post('/Product/ProductDel/' + id, {}, function (ret) {
                                if (ret.result) {
                                    if (viewdialog) viewdialog.close();
                                    $.each(mvvm.productList.$model, function (i) {
                                        if (this.Id == id) {
                                            mvvm.productList.removeAt(i);
                                            return false;
                                        }
                                    });
                                }
                                CBCRM.showResult(ret);
                            })
                        });
                    }
                    //批量删除
                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        var msg = '确定要删除该产品吗？<br />删除产品后，将对相关订单、财务、统计报表造成影响。<br>建议确认该产品无相关数据后，再慎重删除！';
                        messageBox.confirm2(msg, "删除", "取消", function () {
                            $.post('/Product/ProductAllDel/', deleteIds, function (ret) {
                                if (ret.result) {
                                    getProcutList(queryData);
                                    messageBox.succeed(ret.message);
                                }
                            });
                        });
                    }
                    //取消
                    vm.onCancel = function () {
                        vm.action = "list"
                    }
                    //切换产品列表，价格列表
                    vm.doturnlist = function (listType) {
                        mvvm.action = listType;
                    }
                    //产品名字转拼音
                    vm.onNameChange = function () {
                        mvvm.entity.Abbreviation = $('#txtName').toPinyin()
                    }
                    //上架 下架 转移分类
                    vm.TrunCategoryId = '' //转移分类ID
                    vm.TrunCategoryName = '' //转移分类名称
                    vm.doupdatefield = function (field, id) {
                        var deleteIds = checkAll();
                        var isHasItem = false;
                        var pid = $(this).val();
                        if (mvvm.action == "view" && pid) {
                            deleteIds['deleteIds[0]'] = pid;
                        }
                        if (id) deleteIds['deleteIds[0]'] = id;
                        for (var item in deleteIds) {
                            isHasItem = true;
                        }
                        if (!isHasItem) {
                            messageBox.warning('您没有选择任何数据');
                            return;
                        }

                        switch (field) {
                            case "up":
                                messageBox.confirm('确定上架产品吗？', function () {
                                    $.post('/Product/ProductUpdateByUp/', deleteIds, function (ret) {
                                        if (ret.result) {
                                            getProcutList(queryData);
                                            messageBox.succeed(ret.message);
                                            if (mvvm.action == "view" && pid) mvvm.entity.State = "上架";
                                        }
                                    });
                                });
                                break;
                            case "down":
                                messageBox.confirm('确定下架产品吗？', function () {
                                    $.post('/Product/ProductUpdateByDown/', deleteIds, function (ret) {
                                        if (ret.result) {
                                            getProcutList(queryData);
                                            messageBox.succeed(ret.message);
                                            if (mvvm.action == "view" && pid) mvvm.entity.State = "下架";
                                        }
                                    });
                                });
                                break;
                            case "trun":
                                mvvm.TrunCategoryId = ''
                                mvvm.TrunCategoryName = '';
                                var btns = [{
                                    name: '提交',
                                    focus: true,
                                    callback: function () {
                                        if (mvvm.TrunCategoryId == '') {
                                            messageBox.warning("请选择分类")
                                            return false;
                                        }
                                        $.post('/Product/ProductUpdateByTrun/', avalon.mix(deleteIds, { "categoryId": mvvm.TrunCategoryId }), function (ret) {
                                            CBCRM.showResult(ret);
                                            if (ret.result) {
                                                if (dialog) dialog.close();
                                                getProcutList(queryData);
                                            }
                                        });
                                        return false;
                                    }
                                }];
                                var dialog = mvvm.openTmpl({
                                    title: "",
                                    w: 400, h: 100,padding:"def2",
                                    tmplid: "trunCategoryTemplate",
                                    tmpl: tmpl,
                                    btns: btns,
                                    onClose: function () {
                                        mvvm.destroyui(["setTrunCategory"]);
                                        if (action != "view") getProcutList(queryData);
                                    }
                                })
                                break;
                        }
                    }
                    //选择转移分类
                    vm.setTrunCategoryTreeOpts = {
                        treeopts: {
                            callback: {
                                onCheck: function (e, treeId, treeNode) {
                                    mvvm.TrunCategoryId = treeNode.Id;
                                    mvvm.TrunCategoryName = treeNode.Name;
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            },
                            check: {
                                enable: true,
                                chkStyle: 'radio',
                                radioType: "all"
                            }
                        }
                    }
                    //选择品牌
                    vm.brandList = []
                    vm.brandPanel = false
                    vm.brandKey = ''
                    vm.selectBrand = function () {
                        getBrandList();
                        mvvm.brandPanel = true;
                        $("body").bind('mousedown', function (e) {
                            mvvm.brandPanel = false
                            $("body").unbind('mousedown')
                        })
                    }
                    vm.searchBrand = function () {
                        getBrandList();
                    }
                    vm.closeBrandPanel = function () {
                        mvvm.brandPanel = false;
                    }
                    vm.clearBrandValue = function () {
                        mvvm.entity.Brand.Id = ''
                        mvvm.entity.Brand.Name = ''
                    }
                    vm.clickBrand = function (e) {
                        var brand = $(this)
                        mvvm.entity.Brand.Id = brand.attr("key")
                        mvvm.entity.Brand.Name = brand.attr("alt")
                        mvvm.brandPanel = false;
                    }
                    vm.mouseDownBrand = function (e) {
                        e.stopPropagation()
                    }
                    //上传图片
                    vm.uploadpicture = function () {
                        var upwin = CBCRM.upload(true, function (node, data, files) {
                            if (!files.length) files = [files];
                            files.forEach(function (file) { mvvm.OriginImgs.push('/upload/' + file.Path); })
                            mvvm.entity.OriginImg = mvvm.OriginImgs.join(',')
                            upwin.close()
                        }, { settings: {multi:true}});
                    }
                    vm.delboximg = function () {
                        var index = parseInt($(this).attr('index'))
                        mvvm.OriginImgs.removeAt(index)
                        mvvm.entity.OriginImg = mvvm.OriginImgs.join(',')
                    }

                    //特供价格表 
                    vm.pro = []
                    vm.$prolist = [];
                    vm.$delids = [];
                    vm.checkallpro = false;
                    vm.proentity = {}
                    vm.proptions = {
                        paging: function () {
                            var pagesize = this.pagesize
                            var index = this.currentindex + 1
                            getSpecialPrice(pagesize, index)
                        },
                        enablesetsize: false
                    }
                    vm.specialAdd = function () {
                        mvvm.proentity = avalon.mix({}, specialdate)
                        mvvm.$proids = [];
                        mvvm.FormSubmit('新增特供价格')
                    }
                    vm.specialDel = function () {
                        messageBox.confirm("确定要删除吗？", function () {
                            var ids = [];
                            for (var i = 0; i < mvvm.pro.length; i++) {
                                var item = mvvm.pro[i];
                                if (item.checked) {
                                    if (mvvm.action == "edit" && item.Id) {
                                        mvvm.$delids.push(item.Id);
                                    }
                                    mvvm.pro.removeAt(i);
                                    i--;
                                }
                            }
                            mvvm.checkallpro = true;
                        });
                    }
                    vm.FormSubmit = function (title) {
                        var dialog = openTmpl({
                            vm: mvvm, title: title, w: 450, h: 120, tmpl: tmpl, tmplid: "specialTemplate",
                            btns: [{
                                name: '确定',
                                focus: true,
                                callback: function () {
                                    mvvm.$prolist.forEach(function (item) {
                                        mvvm.pro.push({ Id: 0, Type: 0, CustomerId: item.Id, CustomerDisplay: item.Name, Prints: mvvm.proentity.Prints, checked: false });
                                    });
                                }
                            }],
                            onclose: function () {
                                destroyui(["spCustomerId"])
                            }
                        });
                    }

                    //选特供客户
                    vm.selectSpecialCus = function () {
                        var ids = mvvm.proentity.CustomerId || [];
                        if (typeof (ids) == "string") ids = ids.split(",");
                        var ignore = where(mvvm.pro, true, "CustomerId");
                        plugins.selectCustomer({
                            listData: ids,
                            ignore: ignore,
                            multiple: true,
                            callback: function (cus) {
                                var ids = where(cus, true, "Id"), names = where(cus, true, "Name");
                                mvvm.$prolist = where(cus, true, { Id: "", Name: "" });
                                mvvm.proentity.CustomerId = ids.join(",");
                                mvvm.proentity.CustomerDisplay = names.join(",");
                            }
                        })
                    }
                    //相关合同
                    var gridops1 = {
                        url: "/Product/ProductContractSelect",
                        pageid: "contractPage",
                        method: "post",
                        createQuery: function () {
                            return { productId: mvvm.productId, orderName: mvvm.csort, orderValue: mvvm.csortValue }
                        }
                    }

                    vm.grid1 = createGrid(gridops1);

                    //相关订单
                    var gridops2 = {
                        url: "/Product/ProductDocumentaryOfferSelect",
                        pageid: "decumentaryofferPage",
                        method: "post",
                        createQuery: function () {
                            return { productId: mvvm.productId, orderName: mvvm.dsort, orderValue: mvvm.dsortValue }
                        }
                    }
                    vm.grid2 = createGrid(gridops2);
                    //查看OK
                    vm.doviews = function () {
                        var path = $(this).attr('path')
                        goto(path, true)
                    }
                    //列表显示更多
                    vm.sort = 1;
                    vm.showOnemore = function (index) {
                        if (index == 0)
                            mvvm.sort = 1
                        else
                            mvvm.sort = 0
                    }
                    //获取仓库列表
                    vm.StorehouseList = []
                    vm.getStorehouseList = function (productId) {
                        $.post('/Product/GetProductStorageView', { productId: productId }, function (result) {
                            if (result.data) {
                                mvvm.StorehouseList = result.data
                            }
                        })
                    }

                    vm.destroy = function () {
                        mvvm.destroyui([vmid+'_CategoryTree'])
                    }
                    vm.show = false;
                    vm.showTable = false;
                    vm.MonthOpts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                        }
                    }

                    vm.bTime = GetDateTime(new Date(new Date().getFullYear(), new Date().getMonth(), 1), "yyyy-MM-dd");
                    vm.eTime = GetDateTime(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0), "yyyy-MM-dd");
                    vm.starTime = GetDateTime(new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1), "yyyy-MM-dd");
                    vm.endTime = GetDateTime(new Date(new Date().getFullYear(), new Date().getMonth(), 0), "yyyy-MM-dd");
                    vm.dateVal = 0
                    vm.TimeTypeOne = 0
                    vm.TimeTypeTwo = 0
                    vm.search = function () {
                        if (mvvm.show == true)
                            mvvm.showTable = true
                        else
                            mvvm.showTable = false
                        getDataList(mvvm.productId, mvvm.dateVal, mvvm.bTime, mvvm.eTime, mvvm.starTime, mvvm.endTime, mvvm.show);
                    }
                    vm.Pmodel = {};
                    vm.PmodelOne = {};
                    vm.PmodelTwo = {};
                    vm.ProductDynamicList = []


                    vm.up = GetDateTime(new Date(), "yyyy-MM-dd");
                    vm.down = GetDateTime(new Date(), "yyyy-MM-dd");
                    vm.PageUp = function () {
                        getProductDynamicList(mvvm.productId, mvvm.up, "up")
                    }
                    vm.PageDown = function () {
                        getProductDynamicList(mvvm.productId, mvvm.down, "down")
                    }

                    //排序
                    vm.csort = "AddTime"
                    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.dsort = "OrderTime"
                    vm.dsortValue = 1;
                    vm.dsortModel = {
                        Money: 1,
                        OrderTime: 0,
                    }
                    vm.dautosort = function (colname) {
                        var sortvalue = mvvm.dsortModel[colname] == 0 ? 1 : 0;
                        mvvm.dsort = colname;
                        mvvm.dsortValue = sortvalue;
                        mvvm.dsortModel[colname] = sortvalue;
                        mvvm.grid2.doSearch();
                    }

                    vm.sQueryData = {
                        customerName: ""
                    }
                    vm.getSpecialPrice = function () {
                        getSpecialPrice(null, 1);
                    }
                })

                mvvm.Pmodel = ProductMode
                mvvm.PmodelOne = ProductMode
                mvvm.PmodelTwo = ProductMode
                mvvm.grid1.init();
                mvvm.grid2.init();
                mvvm.$watch("checkallpro", function (n) {
                    mvvm.pro.forEach(function (item) {
                        item.checked = n;
                    });
                });
                mvvm.$watch("TimeTypeOne", function (n) {
                    mvvm.dateVal = n;
                    mvvm.TimeTypeTwo = n;
                    var now = new Date();
                    var nows = new Date();
                    var y = now.getFullYear(), m = now.getMonth(), d = now.getDay();
                    var begin;
                    var end
                    switch (n) {
                        case "0":
                            begin = new Date(y, m, 1);
                            end = new Date(y, m + 1, 0);
                            break;
                        case "1":
                            begin = now;
                            end = nows;
                            break;
                        case "2":
                            begin = Getweekstart(now);
                            end = Getweekend(nows);
                            break;
                        case "3":
                            begin = GetQuarterStartDate(now);
                            end = GetQuarterEndDate(nows);
                            break;
                        case "4":

                            begin = new Date(y, 0, 1);
                            end = new Date(y, 12, 0);
                            break;
                    }

                    mvvm.bTime = GetDateTime(begin, "yyyy-MM-dd")
                    mvvm.eTime = GetDateTime(end, "yyyy-MM-dd")
                });
                mvvm.$watch("TimeTypeTwo", function (n) {
                    var now = new Date();
                    var nows = new Date();
                    var y = now.getFullYear(), m = now.getMonth(), d = now.getDay();
                    var begin;
                    var end
                    switch (n) {
                        case "0":
                            begin = new Date(y, m - 1, 1);
                            end = new Date(y, m, 0);
                            break;
                        case "1":
                            begin = DateAdd(now, 'd', -1);
                            end = now;
                            break;
                        case "2":
                            begin = Getweekstart(DateAdd(now, 'd', -7));
                            end = Getweekend(DateAdd(nows, 'd', -7));
                            break;
                        case "3":
                            begin = GetQuarterStartDate(DateAdd(now, 'M', -3));
                            end = GetQuarterEndDate(DateAdd(nows, 'M', -3));
                            break;
                        case "4":
                            begin = new Date(y - 1, 0, 1);
                            end = new Date(y - 1, 12, 0);
                            break;
                    }
                    mvvm.starTime = GetDateTime(begin, "yyyy-MM-dd")
                    mvvm.endTime = GetDateTime(end, "yyyy-MM-dd")
                });
                var action = that.params.action;
                mvvm.entity = modelFactory.create('Product');

                function getProductDynamicList(productId, gettime, type) {
                    mvvm.ProductDynamicList = []
                    $.post('/Product/ProductDynamic', { productId: productId, gettime: gettime, type: type }, function (result) {
                        if (result.data) {
                            mvvm.ProductDynamicList = result.data.pdist;
                            mvvm.up = result.data.up;
                            mvvm.down = result.data.down
                        }
                    })
                }

                function getDataList(productId, dateval, btime, etime, starTime, endTime, show) {
                    $.post('/Product/ProductStat', { productId: productId, state: dateval, btime: btime, etime: etime, starTime: starTime, endTime: endTime, show: show }, function (result) {
                        if (result.data) {

                            mvvm.Pmodel = result.data.chart_product
                            mvvm.PmodelOne = result.data.chart_productOne
                            mvvm.PmodelTwo = result.data.chart_productTwo
                            if (mvvm.show) {
                                createJQLinear("#chart_sign", "销售量走势图", result.data.chart_sign);
                                createJQLinear("#chart_Customer", "销售金额走势图", result.data.chart_Customer);
                            } else {
                                createJQLinear("#chart_sign", "销售量走势图", result.data.chart_signs);
                                createJQLinear("#chart_Customer", "销售金额走势图", result.data.chart_Customers);
                            }
                        }
                    })
                }

                //创建查询对象并提交
                var createDate = {
                    istatic: 0,
                    isspecial: 0,
                    kucunliang: 0,
                    goumaicishu: 0,
                    tousucishu: 0,
                    brandid: '',
                    cusid: '',
                    typeid: 0,
                    key: '',
                    pageSize: 20,
                    pageIndex: 1
                }
                //创建筛选对象
                var searchItem = {
                    istatic: '',
                    isspecial: '',
                    kucunliang: '',
                    goumaicishu: '',
                    tousucishu: '',
                    brandid: '',
                    cusid: '',
                    typeid: ''
                }
                var specialdate = {
                    Id: 0,
                    CustomerId: '',
                    CustomerDisplay: '',
                    ProductId: '',
                    Prints: ''
                }
                var queryData = avalon.mix({}, createDate);
                mvvm.showItem = avalon.mix({}, searchItem);
                function getProcutList(data) {
                    _getProcutList(data, function (list, ret) {
                        mvvm.productList = list;
                        avalon.vmodels.upaing.total = ret.data.RecordTotal;
                    })
                }
                function _getProcutList(data, callback) {
                    $.get('/Product/Product/', data || {}, function (ret) {
                        if (ret && ret.result) {
                            mvvm.ADD = ret.data.ADD;
                            mvvm.DELETE = ret.data.DELETE;
                            mvvm.UP = ret.data.UP;
                            mvvm.DOWN = ret.data.DOWN;
                            mvvm.EDITPRICE = ret.data.EDITPRICE;
                            mvvm.SPECIALPRICE = ret.data.SPECIALPRICE
                            callback(ret.data.Source, ret);
                        } else {
                            CBCRM.showResult(ret);
                        }
                    })
                }
                //筛选条件清除所有是否显示
                function setShowRemoveAll() {
                    mvvm.has = false;
                    for (var item in mvvm.showItem.$model) {
                        if (mvvm.showItem.$model[item]) {
                            mvvm.has = true;
                            break;
                        }
                    }
                }
                //从字典取数据邦定下拉
                function InitDictionary() {
                    $.get('/Product/GetProductDictionary/', {}, function (ret) {
                        mvvm.units = ret.data.unitsList;
                        mvvm.weights = ret.data.weightsList;
                        mvvm.gradelist = ret.data.gradelist;
                    })
                }
                //取品牌数据
                function getBrandList() {
                    $.get('/Product/Brand/', { "categoryid": mvvm.entity.CategoryId, "key": mvvm.brandKey, "pageSize": 1000 }, function (ret) {
                        if (ret.result && ret.data) mvvm.brandList = ret.data.Source;
                    })
                }
                //取特供价格
                function getSpecialPrice(pagesize, pageindex) {
                    if (mvvm.entity.Id > 0) {
                        var data = { "productId": mvvm.entity.Id, "pageSize": pagesize || 20, "pageIndex": pageindex || 1 };
                        $.extend(data, mvvm.sQueryData.$model);
                        $.get('/Product/GetSpecialPrice', data, function (ret) {
                            if (!ret.result || !ret.data) return;
                            if (avalon.vmodels.upaing2) avalon.vmodels.upaing2.total = ret.data.RecordTotal
                            mvvm.pro = ret.data.Source
                        })
                    }
                }
                //取会员价格
                function getGradePricelist() {
                    mvvm.gradePricelist = [];
                    if (mvvm.entity.Id > 0) {
                        $.get('/Product/GetGradePricelist', { "productId": mvvm.entity.Id }, function (ret) {
                            mvvm.initGradePrice(ret.data)
                        })
                    }
                }
                var txtInfo;
                var txtAfterService;
                function setEditor() {
                    if (txtInfo) txtInfo.remove();
                    if (txtAfterService) txtAfterService.remove();
                    txtInfo = setEditerSimple('txtInfo', '99%', '300px');
                    if (txtInfo) txtInfo.html(mvvm.entity.Info);
                    txtAfterService = setEditerSimple('txtAfterService', '99%', '80px');
                    if (txtAfterService) txtAfterService.html(mvvm.entity.AfterService);
                }
                InitDictionary()
                if (that.params.key) {
                    queryData.key = mvvm.keyword = decodeURI(that.params.key)
                }
                switch (action) {
                    case "view":
                        mvvm.doview(that.params.id);
                        break;
                    case "key":
                        queryData.key = mvvm.keyword = decodeURI(that.params.id);
                        break;
                }
                require("jqPlotPie,jqBar,jqCanvasAxisTick,jqPointLabels,jqCategory,jqCanvasText,jqCanvasAxisLabel,jqEnhancedLegend,jqPointLabel,jqCursor,jqHighlighter,jqMeterGauge",
                function () {
                   if (action != "view") {
                       mvvm.getBrandAndSuplier(1);
                       CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
                   }
               });

                /****商品图片****/
                function loadZoomImg() {
                    var idlist=$('#idList').html('')
                    var image=$('#idImage2').attr('src', '').click(function () {
                        mvvm.viewImg(this.src);
                    });
                    var arrPic = [], imgs = mvvm.OriginImgs || [];
                    imgs.forEach(function (item) {
                        arrPic.push({ smallPic: item, originPic: item, zoomPic: item });
                    });
                    if (arrPic.length == 0) {
                        var nopic = "/Content/Themes/Base/Images/credentials_default.png"
                        arrPic.push({ smallPic: nopic, originPic: nopic, zoomPic: nopic });
                    }
                    $$A.forEach(arrPic, function (o, i) {
                        var img = $("<img />").appendTo(idlist);
                        img.attr("src", o.smallPic).mouseover(function () {
                            image.attr("src", img.attr("src"));
                            idlist.find("img").removeClass("on");
                            $(this).addClass("on");
                        })
                        if (!i) img.trigger("mouseover");
                    })
                    var imgnum = mvvm.OriginImgs.length;
                    $("#btnleft").addClass("wuleft");
                    $("#btnright").addClass("wuright");

                    if (imgnum > 4) {
                        bindbtnright();
                        bindbtnleft();
                        $("#btnleft").addClass("haveleft").bind("click", leftclick);
                        $("#btnright").addClass("haveright").bind("click", rightclick);
                    }
                }
                var bindbtnleft = function () {
                    $("#btnleft").hover(
                      function () {
                          $(this).addClass("hoverleft");
                      },
                      function () {
                          $(this).removeClass("hoverleft");
                      }
                    );
                };
                var bindbtnright = function () {
                    $("#btnright").hover(
                      function () {
                          $(this).removeClass("haveright");
                          $(this).addClass("hoverright");
                      },
                      function () {
                          $(this).removeClass("hoverright");
                          $(this).addClass("haveright");
                      }
                );
                };
                var leftclick = function () {

                    animate("left", 57);
                }
                var rightclick = function () {
                    animate("right", 57);
                }

                var num = 0;
                function animate(dir, step) {
                    var imgnum = mvvm.OriginImgs.length;
                    var position;
                    position = parseInt($("#idList").css("margin-left"));
                    var contentwidth;
                    var sliderwidth;
                    contentwidth = parseInt($("#idList").css("width"));
                    sliderwidth = parseInt($("#slider").css("width"));
                    if ((num + 4) >= imgnum) {
                        if (dir == "right") {
                            dir = "left";
                        }
                    } else {
                        if (num <= 0 && dir == "left") {
                            dir = "right";
                        }
                    }
                    switch (dir) {
                        case "right":
                            num += 1;
                            position = ((position - step) < (sliderwidth - contentwidth)) ? (sliderwidth - contentwidth) : (position - step);
                            break;
                        case "left":
                            num -= 1;
                            position = ((position + step) > 0) ? 0 : (position + step);
                            break;
                        default:
                            break;
                    };
                    $("#idList").animate({ marginLeft: position + "px" }, 100);
                };
                /****end 商品图片****/
            },
            //产品价格表
            PriceList: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, viewdialog,vmid="PriceList",
                    that = this
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.lang = lang
                    vm.EXPORT = false;
                    vm.productList = []
                    vm.gradelist = [];
                    vm.destroy = function () {
                        destroyui([vmid+'CategoryTre']);
                    }
                    vm.pricepaing = {
                        paging: function (pageIndex, pageSize) {
                            var data = mvvm.createQuery()
                            data.pageSize = pageSize;
                            data.pageIndex = pageIndex;
                            mvvm.loadData(data);
                        }
                    }
                    vm.getPage = function () {
                        return avalon.vmodels.upaing1;
                    }
                    //产品分类树配置
                    vm.pCategoryTreeOpts = {
                        treeopts: {
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    queryData.typeid = treeNode.Id;
                                    mvvm.loadData(mvvm.createQuery());
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            }
                        }
                    }
                    vm.key = "";
                    vm.doSearch = function () {
                        queryData.key = mvvm.key;
                        mvvm.loadData(mvvm.createQuery());
                    }
                    vm.createQuery = function () {
                        var data = {};
                        for (var key in queryData) {
                            var val = queryData[key]
                            if (val != null && val != "") data[key] = val;
                        }
                        return data;
                    }
                    vm.msdropdown = msdropdown;
                    vm.loadData = function (data) {
                        vm.productList = []
                        $.post("/Product/PriceList/", data, function (ret) {
                            if (ret && ret.result) {
                                mvvm.EXPORT = ret.data.EXPORT;
                                mvvm.gradelist = ret.data.gradelist;
                                var prices = {};
                                //$.each(ret.data.gradePriceList, function (i, item) {
                                //    if (prices[item.ProductId]) prices[item.ProductId].push(item);
                                //    else prices[item.ProductId] = [item];
                                //});
                                //$.each(ret.data.productList.Source, function (i,item) {
                                //    item.PriceList=mvvm.initGradePrice(prices[item.Id])
                                //});
                                mvvm.productList = ret.data.productList.Source;
                                avalon.vmodels.upaing1.total = ret.data.productList.RecordTotal;
                            } else {
                                CBCRM.showResult(ret);
                            }
                        });
                    }
                    vm.exportExcel = function (act) {
                        var url = "/Product/PriceList/";
                        var data = mvvm.createQuery();
                        data.exportExcel = true;
                        if (act == 1) {
                            var page = mvvm.getPage();
                            if (page != null) {
                                data.pageSize = page.pagesize;
                                data.pageIndex = page.currentindex + 1;
                            }
                        }
                        frameSubmit(url, "get", data);
                    }
                    vm.initGradePrice = function (arr) {
                        arr = arr || [];
                        var price = {};
                        arr.forEach(function (item) {
                            price[item.MemberGrade] = item;
                        });
                        var a = [];
                        mvvm.gradelist.forEach(function (item) {
                            var p = price[item.Id];
                            a.push({
                                Type: 1,
                                Id: p == null ? "" : p.Id,
                                MemberGradeDisplay: item.Data,
                                MemberGrade: item.Id,
                                Prints: p == null ? "" : p.Prints
                            })
                        });
                        return a;
                    }
                    //分类树展开/收起
                    vm.$expancategory = true;
                    vm.expanCategory = function () {
                        mvvm.$expancategory = !mvvm.$expancategory;
                        $(this).text(mvvm.$expancategory ? "- 收起" : "+ 展开");
                        var tree = $.fn.zTree.getZTreeObj("productCategoryTree");
                        if (tree) {
                            var nodes = tree.getNodes();
                            if (nodes.length > 0) tree.expandNode(nodes[0], mvvm.$expancategory, true);
                            //收起的时候让根节点处于展开状态
                            if (!mvvm.$expancategory) tree.expandNode(nodes[0], !mvvm.$expancategory, false);
                        }
                    }

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

                    vm.doPrint = function () {
                        messageBox.confirm('您确定要打印价格表吗？', function () {
                            $("#pricePanelPrint").printArea()
                        })
                    }
                })
                var queryData = {};
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
            },
            ProductSettings: function (tmpl, lang, contentId, module) {
                CBCRM = avalon.vmodels.CBCRM;
                var mvvm = avalon.define('ProductSettings', function (vm) {

                });
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.ProductSettings = null
                }
            },
            ///分类管理
            Category: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, init = false,vmid="category";
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.destroy = function () {
                        mvvm.destroyui([vmid + 'CategoryTree']);
                    }
                    vm.lang = lang;
                    vm.auth = { EDIT: true, ADD: true, DELETE: true };
                    vm.entity = {}
                    vm.action = "add"
                    vm.title = "新增分类"
                    vm.sublist = [];
                    vm.originalCategorys = [];
                    vm.targetCategory = { Id: '', Name: '' };
                    vm.curParent = { Id: '', Name: '' };
                    //转移分类
                    vm.changeChild = true;
                    vm.moveCategorys = function () {
                        var ids = [];
                        mvvm.originalCategorys = [];
                        var arr = checkAll();
                        for (var key in arr) {
                            ids.push(arr[key]);
                        }
                        mvvm.sublist.forEach(function (item) {
                            if (ids.indexOf(item.Id.toString()) != -1) {
                                mvvm.originalCategorys.push(item.$model);
                            }
                        });
                        if (mvvm.originalCategorys.length == 0) {
                            messageBox.warning("请选择要转移的分类")
                            return false;
                        }
                        mvvm.targetCategory = { Id: '', Name: '' };
                        var dialog = mvvm.openTmpl({
                            title: "选择分类", w: 500,padding:"def2",
                            tmplId:"trunCategoryTemplate",tmpl:tmpl,
                            button: [{
                                name: '提交',
                                focus: true,
                                callback: function () {
                                    if (!mvvm.targetCategory.Id) {
                                        messageBox.warning("请选择目标分类")
                                        return false;
                                    }
                                    var data = { targetId: mvvm.targetCategory.Id, changeChild: mvvm.changeChild };
                                    data = $.extend(data, jsonToSubmit("originalIds", ids));
                                    $.post('/Product/CategorysMoveProduct/', data, function (ret) {
                                        CBCRM.showResult(ret, function () {
                                            if (ret.result) {
                                                messageBox.close();
                                                getCategoryList();
                                                return true;
                                            }
                                        });
                                    });
                                    return false;
                                }
                            }],
                            onClose: function () {
                                mvvm.destroyui(["setTrunCategory"])
                            }
                        })
                    }
                    //选择转移分类
                    vm.setTrunCategoryTreeOpts = {
                        treeopts: {
                            callback: {
                                onCheck: function (e, treeId, treeNode) {
                                    mvvm.targetCategory.Id = treeNode.Id;
                                    mvvm.targetCategory.Name = treeNode.Name;
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            },
                            check: {
                                enable: true,
                                chkStyle: 'radio',
                                radioType: "all"
                            }
                        }
                    }
                    vm.pCategoryTreeOpts = {
                        treeopts: {
                            async: {
                                url: ""
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    //mvvm.getSublist(treeNode.Id);
                                    mvvm.getSublist(treeNode);
                                }
                            },
                            view: {
                                addHoverDom: null,
                                removeHoverDom: null,
                                selectedMulti: false
                            }
                        }
                    }
                    vm.getSublist = function (node) {
                        var treeobj = $.fn.zTree.getZTreeObj("productCategoryTree");
                        treeobj.selectNode(node);
                        mvvm.curParent = node;
                        mvvm.sublist = [];
                        var a = [];
                        a.push(node);
                        if (node.children) {
                            node.children.forEach(function (item) {
                                a.push(item)
                            });
                        }
                        mvvm.sublist = a;
                    }
                    //分类树展开、收起
                    vm.$expancategory = true;
                    vm.expanCategory = function () {
                        mvvm.$expancategory = !mvvm.$expancategory;
                        $(this).text(mvvm.$expancategory ? "- 收起" : "+ 展开");
                        var tree = $.fn.zTree.getZTreeObj("productCategoryTree");
                        if (tree) {
                            var nodes = tree.getNodes();
                            if (nodes.length > 0) tree.expandNode(nodes[0], mvvm.$expancategory, true);
                            //收起的时候让根节点处于展开状态
                            if (!mvvm.$expancategory) tree.expandNode(nodes[0], !mvvm.$expancategory, false);
                        }
                    }
                    //分类下拉树
                    vm.parentTreeOpts = {
                        treeopts: {
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    if (mvvm.entity.Id) {
                                        $.get('/Product/GetSubIds', { 'categoryId': mvvm.entity.Id }, function (ret) {
                                            var subIds = ret.data;
                                            var strSubIds = subIds.join(',')
                                            //strSubIds && strSubIds.indexOf(treeNode.Id)
                                            if (subIds.indexOf(treeNode.Id) > -1) {
                                                messageBox.warning('上级分类不能选择自己或者子类')
                                            } else {
                                                mvvm.entity.Parent.Id = treeNode.Id
                                                mvvm.entity.Parent.Name = treeNode.Name
                                            }
                                        })
                                    } else {
                                        mvvm.entity.Parent.Id = treeNode.Id
                                        mvvm.entity.Parent.Name = treeNode.Name
                                    }
                                }
                            }
                        }
                    }
                    vm.createEntity = function (item) {
                        if (!item) {
                            item = $.extend(true, {}, modelFactory.create('Category'));
                        }
                        mvvm.entity = item;
                    }
                    //新增
                    vm.doadd = function (item) {
                        if (item == 0) {
                            item = mvvm.curParent.$model;
                        }
                        mvvm.action = "add"
                        mvvm.title = "新增分类"
                        mvvm.createEntity();
                        mvvm.entity.Parent.Id = item.Id;
                        mvvm.entity.Parent.Name = item.Name;
                        if (item.children && item.children.length > 0) {
                            var m = item.children[item.children.length - 1];
                            mvvm.entity.Sort = m.Sort ? parseInt(m.Sort) + 1 : 0;
                        } else {
                            mvvm.entity.Sort = 1;
                        }
                        mvvm.showForm(mvvm.title);
                    }
                    vm.doedit = function (id) {
                        mvvm.sublist.$model.forEach(function (item) {
                            if (item.Id == id) {
                                mvvm.createEntity(item);
                                mvvm.action = "edit";
                                mvvm.title = "编辑分类";
                                mvvm.showForm(mvvm.title);
                            }
                        });
                    }
                    vm.dodel = function (id) {
                        messageBox.confirm('确定要删除该分类吗？<br />如果该分类下包含有产品，将无法删除，您可以先转移产品到其它分类。', function () {
                            $.post('/Product/CategoryDel/' + id, {}, function (ret) {
                                CBCRM.showResult(ret);
                                if (ret.result) {
                                    getCategoryList();
                                }
                            })
                        });
                    }
                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        if (!deleteIds["deleteIds[0]"]) {
                            messageBox.warning("未选择任务数据！");
                            return;
                        }
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/Product/CategoryAllDel/', deleteIds, function (ret) {
                                CBCRM.showResult(ret);
                                if (ret.result) getCategoryList();
                            })
                        });
                    }
                    vm.showForm = function (title) {
                        var btns = [{
                            name: "提交",
                            callback: function () {
                                var model = avalon.mix({}, mvvm.entity.$model);
                                model["ParentId"] = model.Parent.Id;
                                delete model.AddBy;
                                delete model.Parent;
                                var name = model.Name;
                                if (name == '') {
                                    messageBox.error('分类名称不能为空')
                                    return false;
                                }
                                var herf = mvvm.action == "add" ? "/Product/CategoryAdd/" : "/Product/CategoryUpdate/" + model.Id;
                                $.post(herf, model, function (ret) {
                                    if (ret.result) {
                                        if (dialog) dialog.close();
                                        getCategoryList();
                                    }
                                    CBCRM.showResult(ret);
                                })
                                return false;
                            }
                        }]
                        var dialog = mvvm.openTmpl({
                            title: title, w: 350, btns: btns, padding: "20px",
                            tmpl: tmpl, tmplid: "ProductCategory",
                            onclose: function () {
                                destroyui(["parentTree"]);
                            }
                        })

                    }
                    vm.categoryMoreSave = function () {
                        var list = [];
                        mvvm.sublist.$model.forEach(function (item) {
                            if (item.Id == 1) return;
                            list.push({ Id: item.Id, Sort: item.Sort });
                        });
                        var data = jsonToSubmit("list", list);
                        $.post('/Product/CategoryMoreSave/', data, function (ret) {
                            CBCRM.showResult(ret);
                            if (ret.result) {
                                getCategoryList();
                            }
                        })
                    }
                    //选择品牌
                    vm.brandList = []
                    vm.brandPanel = false
                    vm.brandKey = ''
                    vm.selectBrand = function () {
                        getBrandList();
                        mvvm.brandPanel = true;
                        $("body").bind('mousedown', function (e) {
                            mvvm.brandPanel = false
                            $("body").unbind('mousedown')
                        })
                    }
                    vm.searchBrand = function () {
                        getBrandList();
                    }
                    vm.closeBrandPanel = function () {
                        mvvm.brandPanel = false;
                    }
                    vm.clickBrand = function () {
                        var ids = ''
                        var names = ''
                        $("input[name='Brands']:checked").each(function (item) {
                            var brand = $(this);
                            ids += brand.attr("key") + ",";
                            names += brand.attr("alt") + ",";
                        })
                        if (ids) ids = ids.substr(0, ids.length - 1);
                        if (names) names = names.substr(0, names.length - 1);
                        mvvm.entity.BrandIds = ids;
                        mvvm.entity.BrandNames = names;
                    }
                    vm.clearBrandValue = function () {
                        mvvm.entity.BrandIds = ''
                        mvvm.entity.BrandNames = ''
                    }
                    vm.mouseDownBrand = function (e) {
                        e.stopPropagation()
                    }

                })
                function getCategoryList() {
                    $.get('/Product/Category/', {}, function (ret) {
                        if (!ret.result) return;
                        ret.data.forEach(function (item) {
                            item._checked = false;
                        });
                        var $tree=avalon.vmodels[vmid+'CategoryTree']
                        if($tree)$tree.datasource = ret.data;
                        var treeobj = $.fn.zTree.getZTreeObj("productCategoryTree");
                        var a = treeobj.getNodes(), node;
                        if (!init) {
                            if (a.length > 0) {
                                node = a[0];
                            }
                            init = true;
                        } else {
                            var node = treeobj.getNodeByTId(mvvm.curParent.tId);
                            if (!node) {
                                if (mvvm.curParent) {
                                    node = mvvm.curParent.$model.getParentNode();
                                } else {
                                    node = a[0];
                                }
                            }
                        }
                        if (node) {
                            mvvm.getSublist(node);
                        }
                    })
                }
                //取品牌数据
                function getBrandList() {
                    $.get('/Product/Brand/', { "typeid": 0, "key": mvvm.brandKey, "pageSize": 1000 }, function (ret) {
                        mvvm.brandList = ret.data.Source;
                    })
                }
                //mvvm.getSublist(0);
                getCategoryList();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
            }
            ///品牌管理
            , Brand: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this, vmid = "brand";
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.destroy = function () {
                        mvvm.destroyui([vmid + 'CategoryTree']);
                    }
                    vm.lang = lang
                    vm.brandList = []
                    vm.brandpaing = {
                        paging: function () {
                            var that = this
                            queryData.pageSize = that.pagesize
                            queryData.pageIndex = that.currentindex + 1
                            getBrandList(queryData);
                        }
                    }
                    //产品分类树配置
                    vm.pCategoryTreeOpts = {
                        treeopts: {
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    queryData.categoryid = treeNode.Id;
                                    getBrandList(queryData);
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            }
                        }
                    }
                    //分类树展开、收起
                    vm.$expancategory = true;
                    vm.expanCategory = function () {
                        mvvm.$expancategory = !mvvm.$expancategory;
                        $(this).text(mvvm.$expancategory ? "- 收起" : "+ 展开");
                        var tree = $.fn.zTree.getZTreeObj("productCategoryTree");
                        if (tree) {
                            var nodes = tree.getNodes();
                            if (nodes.length > 0) tree.expandNode(nodes[0], mvvm.$expancategory, true);
                            //收起的时候让根节点处于展开状态
                            if (!mvvm.$expancategory) tree.expandNode(nodes[0], !mvvm.$expancategory, false);
                        }
                    }
                    vm.entity = {}
                    vm.keyword = ''
                    vm.history = []
                    vm.ADD = true
                    vm.DELETE = true
                    //关键字搜索
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        queryData.key = mvvm.keyword;
                        getBrandList(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;
                        getBrandList(queryData);
                    }
                    //显示全部
                    vm.clear = function () {
                        mvvm.keyword = '';
                        getBrandList(avalon.mix({}, createDate));
                    }

                    //新增
                    vm.doadd = function () {
                        mvvm.entity = modelFactory.create('Brand');
                        FormSubmit("新增品牌");
                    }
                    //编辑
                    vm.doedit = function () {
                        var id = $(this).val()
                        mvvm.brandList.$model.forEach(function (item) {
                            if (item.Id == id) {
                                mvvm.entity = item;
                            }
                        });
                        FormSubmit("编辑品牌");
                    }
                    //查看
                    vm.doview = function () {
                        var id = $(this).val()
                        mvvm.brandList.$model.forEach(function (item) {
                            if (item.Id == id) {
                                mvvm.entity = item;
                            }
                        });
                        var htmltmpl = $(tmpl).find("#viewTemplate").text();
                        var dialog = messageBox.openHtml('品牌详细', '700px', '220px', '');
                        var content = $(dialog.content());
                        content.html(htmltmpl);
                        //content.attr('ms-include', 'viewTemplate')
                        avalon.scan(content[0], mvvm)
                    }
                    //删除
                    vm.dodel = function () {
                        var index = $(this).attr('index');
                        var id = $(this).val();
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/Product/BrandDel/' + id, {}, function (ret) {
                                if (ret.result)
                                    mvvm.brandList.removeAt(index);
                            })
                        });
                    }
                    //批量删除
                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.post('/Product/BrandAllDel/', deleteIds, function (ret) {
                                if (ret.result) {
                                    getBrandList(queryData);
                                    messageBox.succeed(ret.message);
                                }
                            });
                        });
                    }

                    // 分类树配置
                    vm.categoryTreeOpts = {
                        treeopts: {
                            callback: {
                                onCheck: function (event, treeId, treeNode) {
                                    var treeObj = $.fn.zTree.getZTreeObj(treeId);
                                    var nodes = treeObj.getCheckedNodes(true);
                                    var ids = [];
                                    var names = [];
                                    for (var i = 0; i < nodes.length; i++) {
                                        ids.push(nodes[i].Id);
                                        names.push(nodes[i].Name);
                                    }
                                    mvvm.entity.CategoryIds = ids.join(',');
                                    mvvm.entity.CategoryNames = names.join(',');
                                }
                            },
                            check: {
                                enable: true,
                                chkStyle: "checkbox",
                                chkboxType: { "Y": "ps", "N": "ps" }

                            }
                        },
                        checkedIds: function (treeId, parentNode, ret) {
                            var ids = (mvvm.entity.CategoryIds || "").split(",");
                            return ids;
                        }
                    }
                    // 选择供应商
                    vm.selectSuplier = function () {
                        var ids = mvvm.entity.ProviderIds || [];
                        if (typeof (ids) == "string") ids = ids.split(",");
                        plugins.selectCustomer({
                            multiple: true,
                            required: { cu: false },
                            listData: ids,
                            superiorCategoryId: 10133,
                            //brandId:mvvm.entity.Brand.Id,
                            callback: function (cus) {
                                var ids = where(cus, true, "Id"), names = where(cus, true, "Name");
                                mvvm.entity.ProviderIds = ids.join(',');
                                mvvm.entity.ProviderNames = names.join(',');
                            }
                        })
                    }
                    //上传图片
                    vm.uploadpicture = function () {
                        var dialog=CBCRM.upload(true, function (node, data, file) {
                            var f = file.length ? file[0] : file;
                            mvvm.entity.Img = '/upload/' + f.Path;
                            dialog.close();
                        })
                    }
                    vm.deletePicture = function () {
                        mvvm.entity.Img = "";
                    }
                })

                //保存
                function FormSubmit(title) {
                    var dialog = mvvm.openTmpl({
                        title: title, w: 700, h: 300,padding:"20px",
                        tmplId: "formTemplate", tmpl: tmpl,
                        button: [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var model = mvvm.entity.$model;
                                var url = (model.Id == 0 ? "/Product/BrandAdd/" : "/Product/BrandUpdate/");
                                $.post(url + model.Id, model, function (ret) {
                                    CBCRM.showResult(ret, function () {
                                        getBrandList(queryData);
                                        if (dialog) dialog.close();
                                    })
                                })
                                return false;
                            }
                        }],
                        onClose: function () {
                            mvvm.destroyui(["categoryTree"])
                        }
                    });
                }

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

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

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

                function getBrandList(data) {
                    //Url传参
                    if (that.params.key) {
                        data.key = queryData.key = mvvm.keyword = decodeURI(that.params.key)
                    }
                    $.get('/Product/Brand/', data || {}, function (ret) {
                        mvvm.brandList = ret.data.Source;
                        avalon.vmodels.upaing.total = ret.data.RecordTotal;
                    })
                }

                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            }
            ///产品工作台
            , Index: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM
                var Mvvm = avalon.define('productdesktop', function (vm) {
                    vm.lang = lang
                    vm.searchFieldList = {}
                    vm.key = ""
                    vm.searchtype = "key"
                    vm.gotoPath = function () {
                        switch (Mvvm.searchtype) {
                            case 'key':
                                goto('/Product/Product/' + encodeURI(Mvvm.key))
                                break;
                            case 'brandid':
                                goto('/Product/Brand/' + encodeURI(Mvvm.key))
                                break;
                            case 'typeid':
                                goto('/Product/Category/')
                                break;
                        }
                    }
                })

                Mvvm.searchFieldList = {
                    key: "按名称",
                    brandid: "按品牌",
                    typeid: "按分类"
                }

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

                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.Index = null
                }
            }
            ///仓库管理
            , ProductStorage: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this, vmid = this.vmid = "ProductStorage";
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.lang = lang
                    vm.list = [];
                    vm.storageinfo = [];
                    vm.entity = {}
                    vm.ADD = true
                    vm.DELETE = true;
                    vm.tab = "tab1";
                    vm.tabWidth = 650;
                    vm.tabChange = function (tab) {
                        mvvm.tab = tab;
                    }
                    vm.grid1 = createGrid({
                        url: that.path,
                        pageid:vmid+"_grid1_page",
                        entityId:"Storage",
                        modelFactory: modelFactory,
                        createQuery: function () {
                            return mvvm.createQuery();
                        }
                    })
                    initQuerys(vm, function (data, name, val, type) {
                        if (name == "typeId" && type == "remove") {
                            mvvm.selectFirstTreeNode();
                        }
                        mvvm.loadData(data);
                    });
                    vm.queryData = {
                        keyword: {
                            label: "关键词：", val: ""
                        },
                        typeId: {
                            label: "分类", val: ""
                        }
                    }
                    //分类树
                    vm.storageTypeTreeOpts = {
                        treeopts: {
                            async: {
                                url: ""
                            },
                            data: {
                                simpleData: {
                                    enable: true,
                                    idKey: 'Id'
                                },
                                key: {
                                    name: 'Data'
                                }
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    var typeId = treeNode.Id;
                                    if (typeId == 1) typeId = "";
                                    mvvm.addQuery("typeId", typeId, mvvm.queryData.label + ":" + treeNode.Data);
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            },
                            url: false
                        }
                    }
                    vm.setTreeData = function () {
                        var atree = avalon.vmodels.storageTypeTree;
                        if (atree) {
                            var rows = [{ Id: 1, Data: "全部分类", open: true, checked: true }];
                            rows = rows.concat(mvvm.types.$model);
                            $.each(rows, function (i) {
                                if (i == 0) return;
                                this.pId = 1;
                            });
                            atree.datasource = rows;
                            mvvm.selectFirstTreeNode();
                        }
                    }
                    vm.selectFirstTreeNode = function () {
                        var tree = $.fn.zTree.getZTreeObj("storageTypeTree");
                        var nodes = tree.getNodes();
                        if (nodes.length > 0) {
                            tree.selectNode(nodes[0]);
                        }
                    };
                    //分类管理
                    vm.typeDeleteids = [];
                    vm.typeList = [];
                    vm.typeManage = function () {
                        mvvm.typeList = [];
                        mvvm.typeDeleteids = [];
                        mvvm.types.$model.forEach(function (item, i) {
                            mvvm.typeList.push(item);
                        });
                        var btns = [{
                            name: "提交保存",
                            focus: true,
                            callback: function () {
                                var data = jsonToSubmit("dicts", mvvm.typeList);
                                if (mvvm.typeDeleteids.length > 0) $.extend(data, jsonToSubmit("deleteIds", mvvm.typeDeleteids));
                                $.post("/Settings/DictionaryListSave/", data, function (ret) {
                                    CBCRM.showResult(ret);
                                    if (ret.result) {
                                        if (dialog) dialog.close();
                                        mvvm.getDicts();
                                    }
                                });
                                return false;
                            }
                        }];
                        var dialog = openTmpl({
                            title: "仓库类别管理",
                            vm: mvvm,
                            tmplid: "typeTmpl",
                            tmpl: tmpl,
                            btns: btns
                        });
                    }
                    vm.addType = function () {
                        var entity = $.extend(true, {}, modelFactory.create("Dictionary"));
                        entity.DictionaryId = mvvm.$dicts.types;
                        var arr = mvvm.types
                        entity.Sort = arr.length == 0 ? 1 : parseInt(arr[arr.length - 1].Sort, 10) + 1;
                        mvvm.typeList.push(entity);
                    }
                    //移除分类
                    vm.removeType = function (index) {
                        var item = mvvm.typeList[index];
                        if (!item.Id) mvvm.typeList.removeAt(index);
                        else {
                            $.post("/Product/ProductStorageCheckType/", { typeId: item.Id }, function (ret) {
                                if (!ret.result) return CBCRM.showResult(ret);
                                mvvm.typeList.removeAt(index);
                                mvvm.typeDeleteids.push(item.Id);
                            });
                        }
                    }
                    vm.loadData = function (data) {
                        mvvm.grid1.loadData(data);
                    }
                    //关键字搜索
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.addQuery("keyword", mvvm.queryData.keyword.val);
                    }

                    //新增
                    vm.doadd = function () {
                        mvvm.grid1.getEntity("", function (entity) {
                            var typeId = mvvm.queryData.typeId.val;
                            if (typeId && typeId != 1) entity.TypeId = typeId;
                            mvvm.entity = entity;
                            mvvm.spaceList = [];
                            mvvm.addSpace();
                            var m = mvvm.spaceList[0];
                            m.No = "1";
                            m.Name = "主仓位";
                            mvvm.showForm("新增仓库");
                        });
                    }
                    //编辑
                    vm.doedit = function (id) {
                        mvvm.grid1.getEntity(id, function (entity) {
                            mvvm.entity = entity;
                            mvvm.getSpace(entity.Id);
                            mvvm.showForm("编辑仓库");
                        });
                    }
                    vm.showForm = function (title) {
                        var btns = [{
                            name: "提交",
                            focus: true,
                            callback: function () {
                                var m = $.extend(true, {}, mvvm.entity.$model);
                                if (m.Name == "") {
                                    messageBox.error("请填写名称！");
                                    return false;
                                }
                                if (m.No == "") {
                                    messageBox.error("请填写编码！");
                                    return false;
                                }
                                $.extend(m, jsonToSubmit("spaceList", mvvm.spaceList));
                                var url = m.Id ? "/Product/ProductStorageUpdate/" + m.Id : "/Product/ProductStorageAdd/";
                                $.post(url, m, function (ret) {
                                    CBCRM.showResult(ret, function () {
                                        if (dialog) dialog.close();
                                        mvvm.grid1.reloadData();
                                    });
                                });
                                return false;
                            }
                        }
                        ];
                        var dialog = mvvm.openTmpl({
                            title: title,  w: mvvm.tabWidth,
                            tmplid: "formTemplate", tmpl: tmpl,
                            btns: btns
                        });
                    }
                    //查看
                    vm.doview = function (id) {
                        mvvm.grid1.getEntity(id, function (entity) {
                            mvvm.entity = entity;
                            mvvm.getSpace(entity.Id);
                            mvvm.openTmpl({ title: "查看仓库详情", w: mvvm.tabWidth, tmplid: "viewTemplate", tmpl: tmpl });
                        });

                    }
                    //删除
                    vm.remove = function (item) {
                        $.post('/Product/ProductStorageDel/' + item.Id, {}, function (ret) {
                            CBCRM.showResult(ret, function () {
                                mvvm.grid1.reloadData();
                            });
                        })
                    }
                    //批量删除
                    vm.removeAll = function (ids) {
                        $.post('/Product/ProductStorageAllDel/', ids, function (ret) {
                            CBCRM.showResult(ret);
                            if (ret.result) mvvm.grid1.reloadData();
                        })
                    }
                    vm.updateState = function (item, state) {
                        var msg = state == "1" ? "您确定要启用该仓库吗？" : "您确定要禁用该仓库吗？";
                        var data = { id: item.Id, state: state };
                        messageBox.confirm2(msg, function () {
                            $.post('/Product/ProductStorageUpdateState/' + data.id, data, function (ret) {
                                CBCRM.showResult(ret);
                                if (ret.result) {
                                    item.State = state;
                                    var gitem = mvvm.grid1.getRow(item.Id);
                                    if (gitem != null) gitem.State = state;
                                }
                            })
                        });
                    }
                    //仓位
                    vm.spaceList = [];
                    vm.getSpace = function (id) {
                        mvvm.spaceList = [];
                        var data = { storageId: id };
                        $.get('/Product/GetStorageSpaceList/', data, function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            mvvm.spaceList = ret.data.list;
                        })
                    }
                    vm.addSpace = function () {
                        var entity = $.extend(true, {}, modelFactory.create("StorageSpace"));
                        mvvm.spaceList.push(entity);
                    }
                    vm.removeSpace = function (index) {
                        mvvm.spaceList.removeAt(index);
                    }

                    vm.onNameChange = function () {
                        mvvm.entity.NameLetter = $('#storageName').toPinyin()
                    }

                    /*地图标注*/
                    vm.companyEntity = {};
                    vm.$mapLoaded = false;
                    vm.$map = null;
                    vm.markInMap = function () {
                        var _t = null;
                        if (!mvvm.$mapLoaded) {
                            var win = art.dialog({
                                width: 300,
                                height: 100,
                                title: "地图加载中……",
                                content: "<img src='/Content/Themes/Base/images/loading2.gif' />"
                            });
                            _t = window.setTimeout(function () {
                                if (win) win.close();
                                messageBox.warning("加载地图超时！<br />请确认您是否已经联网。");
                            }, 10 * 1000);
                        }
                        require(["bdmapTool", "ready!"], function (bdmapTool) {
                            mvvm.$mapLoaded = true;
                            if (win) win.close();
                            if (_t) window.clearTimeout(_t);
                            function _callBack(p, box) {
                                mvvm.entity.Address = p.address;
                                mvvm.entity.Lng = p.point.lng;
                                mvvm.entity.Lat = p.point.lat;
                                box.close();
                            }
                            var point, city = mvvm.companyEntity.CityDisplay;
                            if (",市辖区,县,".indexOf(city) > -1 || city == "") city = mvvm.companyEntity.ProvinceDisplay;
                            if (mvvm.companyEntity.Lng) {
                                point = new BMap.Point(mvvm.companyEntity.Lng, mvvm.companyEntity.Lat);
                            } else {
                                point = null;
                            }
                            var map = mvvm.$map = new bdmapTool({
                                mapContent: "#dmap",
                                tmpl: "search",
                                searchpanel: "seekpanel",
                                left: 285,
                                pointCallBack: _callBack,
                                searchCallBack: _callBack,
                                city: mvvm.companyEntity.CityDisplay,
                                point: point
                            });
                            map.openMap(function () {
                                var name = mvvm.companyEntity.CompanyName;
                                var address = mvvm.companyEntity.Address;
                                if (point) {
                                    map.addMarker(point, name, { html: name, ops: { width: 250 } });
                                } else {
                                    if (address != "") {
                                        map.searchMap(address);
                                    }
                                }
                            });
                        });
                    }
                    vm.getCompany = function () {
                        mvvm.companyEntity = CBCRM.cmyInfo.$model;
                    }

                    //字典
                    vm.types = [];
                    vm.$dicts = { types: 100112 };
                    vm.getDicts = function () {
                        getDicts(mvvm.$dicts, mvvm, function (ret) {
                            vm.setTreeData();
                        });
                    }
                })
                mvvm.grid1.init();
                mvvm.getDicts();
                mvvm.getCompany();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            }
            ///期初库存
            , ProductStorageInitAdd: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this, vmid = this.vmid = "ProductStorageInitAdd";
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.lang = lang
                    vm.list = [];
                    vm.entity = {}
                    vm.ADD = true
                    vm.DELETE = true;
                    vm.createEntity = function () {
                        var entity = $.extend(true, {}, modelFactory.create("StorageOutAndInBill"));
                        var user = $.extend(true, {}, CBCRM.memberShip.$model)
                        entity.ActionBy = user;
                        entity.ActionByGroup = user.Group
                        entity.ActionTime = entity.AddTime.substring(0, 10);
                        mvvm.entity = entity;
                    }
                    vm.showindex = -1;
                    vm.showmore = function (index) {
                        mvvm.showindex = index == mvvm.showindex ? -1 : index;
                    }
                    //仓库
                    vm.storageList = [];
                    vm.spaceList = [];
                    vm.getSpace = function (id) {
                        mvvm.spaceList = [];
                        var data = { storageId: id };
                        $.get('/Product/GetStorageSpaceList/', data, function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            mvvm.spaceList = ret.data.list;
                            mvvm.list.forEach(function (item) {
                                item.SpaceId = mvvm.spaceList.length == 1 ? mvvm.spaceList[0].Id : ""
                            })
                        })
                    }
                    vm.getStorage = function (id) {
                        mvvm.storageList = [];
                        $.get('/Product/GetStorageList/', {}, function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            mvvm.storageList = ret.data.list;
                        })
                    }
                    vm.rWidth = $(window).width() - 205;
                    vm.selectProduct = function () {
                        var pvmid = "ProductSelect", pvm,
                            url = "/Product/ProductSelect",
                            dialog = openWin("选择产品", pvmid, url, 900, 400, [{
                                name: "确定选择",
                                focus: true,
                                callback: function () {
                                    if (!pvm) {
                                        messageBox.warning("系统正在载入中，请稍候……");
                                        return false;
                                    }
                                    var list = pvm.grid1.getChecked();
                                    if (list.length == 0) {
                                        messageBox.warning("请选择数据！");
                                        return false;
                                    }
                                    var moneytotal = 0;
                                    list.forEach(function (item) {
                                        //for (var i = 0, l = mvvm.list.length; i < l; i++) {
                                        //    if (mvvm.list[i].ProductId == item.Id) return;
                                        //}
                                        //var model = avalon.mix(true,modelFactory.create("StorageOutAndIn"), item.$model);
                                        var model = $.extend(true, {}, modelFactory.create("StorageOutAndIn"))
                                        var map = {
                                            ProductId: "Id", ProductNo: "No", ProductName: "Name", Price: "StockPrice",
                                            ProductCategory: "CategoryName", Units: "UnitsDisplay"
                                        }
                                        extendValue(model, item.$model, map);
                                        model.Id = 0;
                                        model.StorageId = mvvm.entity.StorageId;
                                        if (mvvm.spaceList.length > 0) model.SpaceId = mvvm.spaceList[0].Id
                                        model.Number = 1;
                                        model.AddBy = {}
                                        model.AddTime = "";
                                        model.ValidDay = 365;
                                        model.Money = item.StockPrice;
                                        model.TotalMony = item.StockPrice;
                                        mvvm.list.push(model);
                                        var vitem = mvvm.list[mvvm.list.length - 1];
                                        moneytotal += item.StockPrice * model.Number;
                                        mvvm.watchItem(vitem);
                                    });
                                    if (mvvm.entity.TotalMoney > 0) {
                                        mvvm.getNewTotal();;
                                    } else {
                                        mvvm.entity.TotalMoney = moneytotal;
                                    }
                                }
                            }], function (tmpl, vmodel) {
                                pvm = vmodel, pageOps = pvm.listOpts;
                                pageOps.pagesize = 20;
                            });
                    }
                    vm.addInit = function (cb) {
                        var m = $.extend(true, {}, mvvm.entity.$model)
                        if (!m.StorageId) {
                            messageBox.error("请选择仓库");
                            return false;
                        }
                        if (!m.ActionBy.Id) {
                            messageBox.error("请选择经办人");
                            return false;
                        }
                        var list = mvvm.list
                        if (!mvvm.list.length) {
                            messageBox.error("未选择任何产品");
                            return false;
                        }
                        for (var i = 0, l = list.length; i < l; i++) {
                            var item = list[i]
                            if (!item.SpaceId) {
                                messageBox.error("请选择仓位！");
                                return false;
                            }
                            if (!item.Number || isNaN(item.Number) || item.Number < 0) {
                                messageBox.error("产品数量不能小于等于0或者非数字！");
                                return false;
                            }
                        }
                        $.extend(m, jsonToSubmit("ActionBy", m.ActionBy));
                        delete m.ActionBy
                        delete m.AddBy
                        var data = $.extend(m, jsonToSubmit("list", list));
                        $.post("/Product/ProductStorageInitAdd", data, function (ret) {
                            CBCRM.showResult(ret);
                            if (!ret.result) return;
                            //mvvm.createEntity();
                            //mvvm.list = [];
                            if (typeof (cb) == "function") {
                                cb();
                            }
                        });
                        return false;
                    }
                    vm.getNewTotal = function () {
                        mvvm.entity.TotalMoney = 0;
                        mvvm.list.forEach(function (li) {
                            mvvm.entity.TotalMoney += parseFloat(li.TotalMony);
                        });
                    }
                    vm.watchItem = function (item) {
                        function _watchPrice() {
                            item.Money = item.Price && item.Number ? parseFloat(item.Price, 10) * parseFloat(item.Number, 10) : 0;
                            if (item.DiscountRate) {
                                item.DiscountMoney = parseFloat(item.DiscountRate, 10) / 100 * item.Money;
                                item.Money -= item.DiscountMoney;
                            } else {
                                item.DiscountMoney = 0;
                            }
                            if (item.TaxRate) {
                                item.TaxMoney = parseFloat(item.TaxRate, 10) / 100 * item.Money;
                            } else {
                                item.TaxMoney = 0;
                            }
                            item.TotalMony = item.Money + item.TaxMoney;
                            item.DiscountMoney = item.DiscountMoney.toFixed(2)
                            item.Money = item.Money.toFixed(2)
                            item.TaxMoney = item.TaxMoney.toFixed(2)
                            item.TotalMoney = item.TotalMony.toFixed(2)
                            mvvm.getNewTotal();
                        }
                        ["Price", "Number", "DiscountRate", "TaxRate"].forEach(function (p) {
                            item.$watch(p, _watchPrice);
                        })
                        item.$watch("ProductionTime", function (n) {
                            if (n && item.ValidDay) {
                                try {
                                    var d = new Date(n), d2 = new Date(d.valueOf() + item.ValidDay * 24 * 60 * 60 * 1000)
                                    var a = [d2.getFullYear(), d2.getMonth() + 1, d2.getDate()]
                                    a[1] = a[1] < 9 ? "0" + a[1] : a[1];
                                    a[2] = a[2] < 9 ? "0" + a[2] : a[2];
                                    item.ValidDate = a.join("-")
                                } catch (ex) {
                                    item.ValidDate = ""
                                }
                            } else {
                                item.ValidDate = ""
                            }
                        })
                    }
                    vm.remove = function (index) {
                        mvvm.list.removeAt(index);
                        mvvm.getNewTotal();
                    }
                    vm.selectActionBy = function () {
                        plugins.selectUser({
                            dataAuth: 5062000,
                            callback: function (us) {
                                var u = us[0];
                                var actionBy = mvvm.entity.ActionBy
                                actionBy.Id = u.Id
                                actionBy.FullName = u.FullName
                                mvvm.entity.ActionByGroup = u.GroupName
                            }
                        })
                    }
                    vm.bindWatch = function () {
                        mvvm.entity.$watch("StorageId", function (n) {
                            mvvm.spaceList = [];
                            if (!n) {
                                mvvm.list.forEach(function (item) {
                                    item.SpaceId = ""
                                })
                                return;
                            }
                            mvvm.getSpace(n);
                        });
                    }
                },2)
                mvvm.createEntity();
                mvvm.bindWatch();
                mvvm.getStorage();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            },
            //库存状况
            ProductStorageList: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this, mvvm, init = false, vmid = "ProductStorageList";
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define(vmid, function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.loading = true;
                    vm.STORAGEINIT = true;
                    vm.key = "";
                    vm.toEnter = function (e) {
                        if (e.keyCode == 13) mvvm.toSearch();
                    }
                    vm.toSearch = function () {
                        mvvm.addQuery("key", mvvm.key, mvvm.key);
                    }
                    vm.listOpts = { //列表分页组件
                        pagesizeopts: [20, 30, 40, 50],
                        pagesize: 20,
                        paging: function () {
                            var m = mvvm, data = m.createQuery();
                            data.pageIndex = (this.currentindex + 1) || 1
                            data.pageSize = this.pagesize
                            m.loadData(data)
                        }
                    }
                    vm.grid1 = createGrid({});
                    initQuerys(vm, function (data, name, val, type) {
                        mvvm.loadData(data);
                        if (type == "remove" || type == "clear") {
                            switch (name) {
                                case "typeid":
                                    mvvm.unSelectType();
                                    break;
                                case "key":
                                    mvvm.key = "";
                                    break;
                            }
                        }
                    })
                    vm.queryData = {
                        key: { label: "关键词", val: "", valLabel: "" },
                        typeid: { label: "产品分类", val: "", valLabel: "" },
                        kucunliang: {
                            label: "库存状况", val: "", valLabel: "",
                            items: [
                                { label: "不限", val: "", curr: true },
                                { label: "无库存", val: "1", curr: false },
                                { label: "有库存", val: "5", curr: false },
                                { label: "<30", val: "2", curr: false },
                                { label: "30-100", val: "3", curr: false },
                                { label: ">100", val: "4", curr: false }
                            ]
                        }
                    }
                    //产品分类树配置
                    vm.pCategoryTreeOpts = {
                        treeopts: {
                            async: {
                                url: ""
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    mvvm.addQuery("typeid", treeNode.Id, treeNode.Name);
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            }
                        }
                    }
                    vm.unSelectType = function () {
                        var tree = avalon.vmodels["pStorageListCategoryTree"];
                        if (tree && tree.$treeObj) {
                            tree.$treeObj.cancelSelectedNode()
                        }
                    }
                    vm.getCategoryList = function () {
                        $.get('/Product/Category/', {}, function (ret) {
                            if (!ret.result) return;
                            ret.data.forEach(function (item) {
                                if (item.Id != 1) item.open = false;
                            });
                            avalon.vmodels.pStorageListCategoryTree.datasource = ret.data;
                        })
                    }
                    //分类树展开、收起
                    vm.$expancategory = false;
                    vm.expanCategory = function () {
                        mvvm.$expancategory = !mvvm.$expancategory;
                        $(this).text(mvvm.$expancategory ? "- 收起" : "+ 展开");
                        var tree = $.fn.zTree.getZTreeObj("storageListCategoryTree");
                        if (tree) {
                            var nodes = tree.getNodes();
                            if (nodes.length > 0) tree.expandNode(nodes[0], mvvm.$expancategory, true);
                            //收起的时候让根节点处于展开状态
                            if (!mvvm.$expancategory) tree.expandNode(nodes[0], !mvvm.$expancategory, false);
                        }
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Product/Product', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                if (ret.data.Source) {
                                    mvvm.grid1.initList(ret.data.Source, ret.data.RecordTotal);
                                }
                                avalon.vmodels[vmid + "ListPage"].total = mvvm.grid1.total;
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.reloadData = function () {
                        var m = mvvm, data = m.createQuery(), page = avalon.vmodels[vmid + "Page"];
                        if (page) {
                            data.pageIndex = page.currentindex
                            data.pageSize = page.pagesize
                        }
                        m.loadData(data)
                    }
                    vm.$initDialog = null;
                    vm.storageInit = function () {
                        var pvmid = "ProductStorageInitAdd", pvm,
                            url = "/Product/ProductStorageInitAdd";
                        openWin("期初库存", pvmid, url, $(window).width() - 200, 400, [{
                            name: "提交保存",
                            focus: true,
                            callback: function () {
                                if (!pvm) {
                                    messageBox.warning("系统正在载入中，请稍候……");
                                    return false;
                                }
                                pvm.addInit(function () {
                                    mvvm.closeInitDialog();
                                    mvvm.reloadData();
                                });
                                return false;
                            }
                        }], function (tmpl, vmodel) {
                            pvm = vmodel;
                            mvvm.$initDialog = this;
                        });
                    }
                    vm.closeInitDialog = function () {
                        if (mvvm.$initDialog) {
                            mvvm.$initDialog.close();
                            mvvm.$initDialog = null;
                        }
                    }
                })
                mvvm.grid1.bindWatch()
                mvvm.getCategoryList()
                function destroy() {
                    //destroyui(["pStorageListCategoryTree"])
                    avalon.vmodels[vmid] = null;
                }
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                CBCRM.onLoadModuleBefore = function (data) {
                    destroy();
                }
            },
            //产品选择
            ProductSelect: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this, mvvm, init = false, vmid = "ProductSelect";
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define(vmid, function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.loading = true;
                    vm.key = "";
                    vm.toEnter = function (e) {
                        if (e.keyCode == 13) mvvm.toSearch();
                    }
                    vm.toSearch = function () {
                        mvvm.addQuery("key", mvvm.key);
                    }
                    vm.listOpts = { //列表分页组件
                        pagesizeopts: [20, 30, 40, 50],
                        pagesize: 20,
                        paging: function () {
                            var m = mvvm, data = m.createQuery();
                            data.pageIndex = (this.currentindex + 1) || 1
                            data.pageSize = this.pagesize
                            m.loadData(data)
                        }
                    }
                    //vm.list = []
                    //router, router.path, "Product", modelFactory
                    vm.grid1 = createGrid({});
                    initQuerys(vm, function (data) {
                        mvvm.loadData(data);
                    })
                    vm.queryData = {
                        key: { label: "关键词", val: "" },
                        typeid: { label: "产品分类", val: "" }
                    }
                    //产品分类树配置加
                    vm.pCategoryTreeOpts = {
                        treeopts: {
                            async: {
                                url: ""
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    mvvm.addQuery("typeid", treeNode.Id);
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            }
                        }
                    }
                    vm.getCategoryList = function () {
                        $.get('/Product/Category/', {}, function (ret) {
                            if (!ret.result) return;
                            ret.data.forEach(function (item) {
                                if (item.Id != 1) item.open = false;
                            });
                            avalon.vmodels.pSelectCategoryTree.datasource = ret.data;
                        })
                    }
                    //分类树展开、收起
                    vm.$expancategory = false;
                    vm.expanCategory = function () {
                        mvvm.$expancategory = !mvvm.$expancategory;
                        $(this).text(mvvm.$expancategory ? "- 收起" : "+ 展开");
                        var tree = $.fn.zTree.getZTreeObj("productSelectCategoryTree");
                        if (tree) {
                            var nodes = tree.getNodes();
                            if (nodes.length > 0) tree.expandNode(nodes[0], mvvm.$expancategory, true);
                            //收起的时候让根节点处于展开状态
                            if (!mvvm.$expancategory) tree.expandNode(nodes[0], !mvvm.$expancategory, false);
                        }
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Product/Product', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                if (ret.data.Source) {
                                    mvvm.grid1.initList(ret.data.Source, ret.data.RecordTotal);
                                }
                                avalon.vmodels[vmid + "ListPage"].total = mvvm.grid1.total;
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                })
                mvvm.grid1.bindWatch()
                mvvm.getCategoryList()
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            },
            //采购产品选择
            PurchaseProductSelect: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this, mvvm, init = false, vmid = "PurchaseProductSelect";
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define(vmid, function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.loading = true;
                    vm.key = "";
                    vm.resumeTemp = []

                    vm.toEnter = function (e) {
                        if (e.keyCode == 13) mvvm.toSearch();
                    }
                    vm.toSearch = function () {
                        mvvm.addQuery("key", mvvm.key);
                    }
                    vm.listOpts = { //列表分页组件
                        pagesizeopts: [20, 30, 40, 50],
                        pagesize: 20,
                        paging: function () {
                            var m = mvvm, data = m.createQuery();
                            data.pageIndex = (this.currentindex + 1) || 1
                            data.pageSize = this.pagesize
                            m.loadData(data)
                        }
                    }
                    //vm.list = []
                    //router, router.path, "Product", modelFactory
                    vm.grid1 = createGrid({});
                    initQuerys(vm, function (data) {
                        mvvm.loadData(data);
                    })
                    vm.queryData = {
                        key: { label: "关键词", val: "" },
                        typeid: { label: "产品分类", val: "" }
                    }
                    //产品分类树配置加
                    vm.pCategoryTreeOpts = {
                        treeopts: {
                            async: {
                                url: ""
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    mvvm.addQuery("typeid", treeNode.Id);
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            }
                        }
                    }


                    vm.addAllTemp = function () {
                        mvvm.grid1.list.forEach(function (temp) {
                            temp.checked = false
                            var item = findArr(mvvm.resumeTemp, temp.Id);
                            if (item == null) mvvm.resumeTemp.push(temp.$model);
                        })
                        mvvm.grid1.list = []

                    }

                    vm.addResumeTemp = function (model, index) {
                        model.checked = false
                        var item = findArr(mvvm.resumeTemp, model.Id);
                        if (item == null) mvvm.resumeTemp.push(model.$model);
                        mvvm.grid1.list.removeAt(index)

                    }

                    vm.removeResumeTemp = function (model, index) {
                        var item = findArr(mvvm.grid1.list, model.Id);
                        if (item == null) mvvm.grid1.list.push(model.$model);
                        mvvm.resumeTemp.removeAt(index)
                    }
                    vm.getCategoryList = function () {
                        $.get('/Product/Category/', {}, function (ret) {
                            if (!ret.result) return;
                            ret.data.forEach(function (item) {
                                if (item.Id != 1) item.open = false;
                            });
                            avalon.vmodels.pSelectCategoryTree.datasource = ret.data;
                        })
                    }
                    //分类树展开、收起
                    vm.$expancategory = false;
                    vm.expanCategory = function () {
                        mvvm.$expancategory = !mvvm.$expancategory;
                        $(this).text(mvvm.$expancategory ? "- 收起" : "+ 展开");
                        var tree = $.fn.zTree.getZTreeObj("productSelectCategoryTree");
                        if (tree) {
                            var nodes = tree.getNodes();
                            if (nodes.length > 0) tree.expandNode(nodes[0], mvvm.$expancategory, true);
                            //收起的时候让根节点处于展开状态
                            if (!mvvm.$expancategory) tree.expandNode(nodes[0], !mvvm.$expancategory, false);
                        }
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Product/Product', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                if (ret.data.Source) {
                                    mvvm.grid1.initList(ret.data.Source, ret.data.RecordTotal);
                                }
                                avalon.vmodels[vmid + "ListPage"].total = mvvm.grid1.total;
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.watchCheckall = function () {
                        mvvm.grid1.$watch("checkall", function (n, o) {
                            if (n == false)
                                return;
                            mvvm.addAllTemp()
                            window.setTimeout(function () {
                                mvvm.grid1.checkall = false
                            }, 300)

                        });
                    }

                })
                mvvm.grid1.bindWatch()
                mvvm.getCategoryList()
                mvvm.watchCheckall();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            },
            ///采购询价
            PurchaseEnquiry: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this
                var mvvm = CBCRM.define('PurchaseEnquiry', function (vm) {
                    vm.lang = lang //语言
                    vm.entity = {}//询价数据
                    vm.entityList = []//询价列表
                    vm.productsList = []//产品数据
                    vm.productsDelList = []//产品删除数据
                    vm.PurchaseDetail = {}
                    vm.ADD = true
                    vm.DELETE = true
                    vm.showItem = {}//搜索条件 
                    vm.keyword = ''//供应商检索
                    vm.history = []//历史索搜
                    vm.queryHistory = {}
                    vm.units = []
                    vm.contacts = []
                    vm.show = false
                    vm.Isshow = false
                    vm.InShow = true
                    vm.toggle = false

                    vm.CustomerContactData = []//联系人数组
                    vm.ProductId = 0//产品ID
                    vm.purchasecompare = []//采购比价
                    vm.purchasecompareId = []//采购比价
                    vm.purchasecompareTag = []//采购比价
                    vm.purchasecompareList = []
                    vm.modelTypeIDNo = {}//单号
                    vm.modelTypeIDBatch = {}//批次
                    vm.PurchaseOrder = {}//采购订单
                    vm.OrderProductList = []//采购订单产品明细
                    vm.PurchaseOrderProducts = {}//采购订单产品
                    //选择产品OK
                    vm.selectProduct = function () {
                        var pvmid = "PurchaseProductSelect", pvm,
                            url = "/Product/PurchaseProductSelect",
                            dialog = openWin("选择产品", pvmid, url, 1100, 400, [{
                                name: "确定选择",
                                focus: true,
                                callback: function () {
                                    if (!pvm) {
                                        messageBox.warning("系统正在载入中，请稍候……");
                                        return false;
                                    }
                                    var list = pvm.resumeTemp;
                                    if (list.length == 0) {
                                        messageBox.warning("请选择数据！");
                                        return false;
                                    }
                                    var plist = mvvm.productsList;
                                    list.forEach(function (item) {
                                        for (var i = 0, l = plist.length; i < l; i++) {
                                            if (plist[i].$model.productId == item.No) return;
                                        }
                                        var model = modelFactory.create("PurchaseDetail")
                                        var map = {
                                            productName: "Name", standard: "Standard", productId: "Id", productNo: "No", units: "Units",
                                        }
                                        extendValue(model, item.$model, map);
                                        model.Id = 0;
                                        plist.push(model);
                                        var vitem = mvvm.productsList[mvvm.productsList.length - 1];
                                        mvvm.watchItem(vitem)
                                    });
                                }
                            }], function (tmpl, vmodel) {
                                pvm = vmodel;
                            });
                    }

                    vm.watchItem = function (item) {
                        function _watchPrice() {
                            var money = parseFloat(item.number) * parseFloat(item.price)
                            if (money && money >= 0) {
                                item.money = money
                            } else {
                                item.money = 0
                            }
                            mvvm.onSumCost()

                        }
                        ["price", "money", "number"].forEach(function (p) {
                            item.$watch(p, _watchPrice);
                        })
                    }
                    //计算预算合计
                    vm.onSumCost = function () {
                        var cost = 0
                        mvvm.productsList.$model.forEach(function (item) {
                            var currCost = 0
                            if (item.money) currCost = parseFloat(item.money)
                            cost = cost + currCost;
                        })
                        mvvm.entity.Total = cost
                        mvvm.entity.TotalMoney = parseFloat(mvvm.entity.Total) + parseFloat(mvvm.entity.TaxPosition) - parseFloat(mvvm.entity.Preferential)
                    }

                    //计算税额合计
                    vm.onSumTotalMoney = function () {
                        var TaxRate = 0
                        if (mvvm.entity.TaxRate != 0)
                            TaxRate = parseFloat(mvvm.entity.Total) * (parseFloat(mvvm.entity.TaxRate) / 100)
                        mvvm.entity.TaxPosition = TaxRate
                        mvvm.entity.TotalMoney = parseFloat(mvvm.entity.Total) + parseFloat(mvvm.entity.TaxPosition) - parseFloat(mvvm.entity.Preferential)
                    }



                    //浮动窗
                    vm.state = 0
                    vm.floatlistshow = false
                    vm.ShowImg = true
                    vm.setfloatlist = function () {
                        mvvm.floatlistshow = !mvvm.floatlistshow
                        if (mvvm.ShowImg == true)
                            mvvm.ShowImg = false
                        else
                            mvvm.ShowImg = true
                        fixtop()
                    }

                    vm.resumeTemp = []
                    vm.addResumeTemp = function (id, eid) {
                        var index = parseInt($(this).attr('index'))
                        mvvm.entityList.$model.forEach(function (item) {
                            if (item.Id == id) {
                                var Isbool = true;
                                if (mvvm.resumeTemp.$model.length > 0) {
                                    mvvm.resumeTemp.$model.forEach(function (temp) {
                                        if (temp.Id == id || temp.EnquiryBatch != eid) {
                                            Isbool = false
                                        }

                                    })
                                    if (Isbool) {
                                        mvvm.resumeTemp.push(item)
                                        mvvm.floatlistshow = true
                                        fixtop()
                                    }
                                } else {
                                    mvvm.resumeTemp.push(item)
                                    mvvm.floatlistshow = true
                                    fixtop()
                                }
                            }
                        })
                    }

                    vm.removeResumeTemp = function (index) {
                        mvvm.resumeTemp.removeAt(index)
                        fixtop()
                    }

                    //分页数据OK
                    vm.Purchasepaing = {
                        paging: function () {
                            var that = this
                            var data = avalon.mix(true, mvvm.createQuery(), { pageSize: that.pagesize, pageIndex: that.currentindex + 1 })
                            GetPurchaseEnquiryList(data);
                        }
                    }
                    initQuerys(vm, function (data, name, val, type) {
                        GetPurchaseEnquiryList(data);
                    });
                    //关键字搜索
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        if (mvvm.keyword != "") {
                            mvvm.addQuery("keyword", mvvm.keyword, mvvm.keyword);
                        }
                    }

                    vm.queryData = {
                        keyword: {
                            label: "关键词", val: "", valLabel: ""
                        },
                        dateTimes: {
                            label: "时间范围", val: "", valLabel: "",
                            items: [
                                { label: "不限", val: "", curr: true },
                                { label: "本月", val: "0", curr: false },
                                { label: "上月", val: "1", curr: false },
                                { label: "时间段", val: "2", curr: false }
                            ]
                        },
                        begindate: {
                            label: "起始时间", val: "", valLabel: ""
                        },
                        enddate: {
                            label: "结束时间", val: "", valLabel: ""
                        },
                    }
                    //检索时间范围
                    vm.datespan = false

                    vm.begindateopts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.addQuery("begindate", formatDate, "起始时间:" + formatDate);
                        }
                    }
                    vm.enddateopts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.addQuery("enddate", formatDate, "结束时间:" + formatDate);
                        }
                    }


                    vm.quoteTimeopts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.QuoteTime = formatDate
                        }
                    }

                    vm.enquiryTimeopt = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.EnquiryTime = formatDate
                        }
                    }


                    //点击多选框
                    vm.clickId = function (id) {
                        mvvm.ProductId = id
                    }
                    //新增OK
                    vm.doadd = function () {
                        var curr = CBCRM.memberShip
                        mvvm.toggle = false;
                        mvvm.InShow = true
                        mvvm.productsList = []
                        mvvm.entity = modelFactory.create('PurchaseEnquirys')
                        mvvm.entity.EmployeeId = curr.Id
                        mvvm.entity.EmployeeName = curr.FullName
                        mvvm.modelTypeIDBatch = modelFactory.create('ModelTypeID')
                        $.get('/Product/GetModelTypeID', { 'Name': 'PC', 'typeName': 'Batch' }, function (retBatch) {
                            if (retBatch.result) {
                                mvvm.entity.EnquiryBatch = retBatch.message
                                $.get('/Product/GetModelTypeID', { 'Name': 'CG', 'typeName': 'Enquiry' }, function (ret) {
                                    if (ret.result) {
                                        mvvm.entity.EnquiryNo = ret.message
                                    }
                                })
                            }
                        })
                        if (mvvm.units.length > 0)
                            mvvm.PurchaseDetail.units = mvvm.units[0].Id;
                        FormSubmit("新增采购询价单", false, true)
                    }

                    //新增复制OK
                    vm.docopy = function (id) {
                        mvvm.InShow = true
                        mvvm.toggle = true;
                        mvvm.entity = modelFactory.create('PurchaseEnquirys')

                        mvvm.productsList = []
                        $.get('/Product/GetPurchaseEnquiry', { 'id': id }, function (ret) {
                            if (ret.data) {
                                mvvm.entity = ret.data
                                mvvm.entity.Id = 0
                                mvvm.entity.SupplyId = 0
                                mvvm.entity.SupplyName = ''
                                mvvm.entity.ContactsId = 0
                                mvvm.entity.ContactsName = ''
                                mvvm.entity.ContactsTel = ''


                                mvvm.entity.Total = 0
                                mvvm.entity.TaxRate = 0
                                mvvm.entity.TaxPosition = 0
                                mvvm.entity.Preferential = 0
                                mvvm.entity.TotalMoney = 0


                                mvvm.CustomerContactData = []
                                $.get('/Product/GetModelTypeID', { 'Name': 'CG', 'typeName': 'Enquiry' }, function (ret) {
                                    if (ret.result) {
                                        mvvm.entity.EnquiryNo = ret.message
                                        $.get('/Product/GetPurchaseDetail', { 'id': id }, function (re) {
                                            if (re.data) {
                                                for (var i = 0, tmp; tmp = re.data[i]; i++) {
                                                    mvvm.PurchaseDetail = modelFactory.create('PurchaseDetail')
                                                    mvvm.PurchaseDetail.Id = tmp.Id
                                                    mvvm.PurchaseDetail.enquiryId = tmp.enquiryId
                                                    mvvm.PurchaseDetail.productName = tmp.productName
                                                    mvvm.PurchaseDetail.productId = tmp.productId
                                                    mvvm.PurchaseDetail.productNo = tmp.productNo
                                                    mvvm.PurchaseDetail.standard = tmp.standard
                                                    mvvm.PurchaseDetail.number = tmp.number
                                                    mvvm.PurchaseDetail.units = tmp.units
                                                    mvvm.productsList.push(mvvm.PurchaseDetail.$model)
                                                }
                                            }
                                        })

                                    }
                                })

                            }
                        })
                        FormSubmit("复制采购询价单", false, true)
                    }

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

                    //比价
                    vm.docompare = function () {
                        var deleteIds = {}
                        var i = 0;
                        if (mvvm.resumeTemp.$model.length > 0) {
                            mvvm.resumeTemp.$model.forEach(function (temp) {
                                deleteIds['deleteIds[' + i + ']'] = temp.Id;
                                i++;
                            });
                        } else {
                            mvvm.purchasecompareTag = []
                            mvvm.purchasecompare = []
                            mvvm.purchasecompareId = []
                            vm.purchasecompareList = []
                            messageBox.warning('请选择需要对比的供应商');
                            return false
                        }
                        mvvm.purchasecompareTag = []
                        mvvm.purchasecompare = []
                        mvvm.purchasecompareId = []
                        vm.purchasecompareList = []
                        $.get('/Product/PurchaseEnquiryCompareId', deleteIds, function (ret) {
                            if (ret.data)
                                mvvm.entity = ret.data
                            $.post('/Product/PurchaseEnquiryCompare/', deleteIds, function (re) {
                                if (re.result) {
                                    mvvm.purchasecompareTag = re.data.TagArray
                                    mvvm.purchasecompareId = re.data.IDArray
                                    for (var i = 0, tmp; tmp = re.data.ProductDetailArray[i]; i++) {
                                        mvvm.purchasecompare.push(tmp.SyncRoot)
                                    }
                                    for (var i = 0, tmps; tmps = re.data.PropertyArray[i]; i++) {
                                        mvvm.purchasecompareList.push(tmps.SyncRoot)
                                    }
                                    mvvm.resumeTemp = []
                                    fixtop()
                                }
                            });
                        });
                        FormOrderSubmit('采购价格对比');
                    }
                    //清空
                    vm.doclose = function () {
                        mvvm.resumeTemp = []
                        fixtop()
                    }



                    //删除OK
                    vm.productsDel = function () {
                        var index = parseInt($(this).attr("index"))
                        var con = mvvm.productsList.$model[index]
                        if (con.Id > 0) mvvm.productsDelList.push(con)
                        mvvm.productsList.removeAt(index)
                        mvvm.onSumRowMoney(con)
                    }

                    //询价人
                    vm.selectEmp = function () {
                        plugins.selectUser({
                            dataAuth: "6050101",
                            callback: function (us) {
                                var u = us[0];
                                mvvm.entity.EmployeeId = u.Id
                                mvvm.entity.EmployeeName = u.FullName
                            }
                        })
                    }
                    
                    //下拉联系人变化
                    vm.contactChange = function () {
                        var id = $(this).find('option:selected').val()
                        var name = $(this).find('option:selected').text()
                        var tel = $(this).find('option:selected').attr('title')
                        if (id) {
                            mvvm.entity.ContactsId = id
                            mvvm.entity.ContactsName = name
                            mvvm.entity.ContactsTel = tel
                        } else {
                            mvvm.entity.ContactsId = ''
                            mvvm.entity.ContactsName = ''
                            mvvm.entity.ContactsTel = ''
                        }
                    }

                    // 选择供应商
                    vm.selectSuplier = function () {
                        plugins.selectCustomer({
                            type:"contacts",
                            superiorCategoryId: 10133,
                            callback: function (cus,cons) {
                                var cu = cus[0], con = cons.length > 0 ? cons[0] : {Id:"",Name:""};
                                mvvm.entity.SupplyId = cu.Id
                                mvvm.entity.SupplyName = cu.Name
                                mvvm.entity.ContactsId = con.Id
                                mvvm.entity.ContactsName = con.Name
                                mvvm.entity.ContactsTel = con.MobileNumber1
                                //mvvm.setCustomerContacts(cu.Id)
                                mvvm.CustomerContactData = cu.Contacts || [];
                            }
                        })
                    }
                    //下拉联系人数据源
                    vm.setCustomerContacts = function (customerid) {
                        $.get('/Customer/Contacts', { 'customerId': customerid }, function (ret) {
                            mvvm.CustomerContactData = ret.data.contacts.Source
                        })
                    }
                    //编辑OK
                    vm.doedit = function (id) {
                        mvvm.InShow = false
                        mvvm.toggle = true
                        mvvm.entity = modelFactory.create('PurchaseEnquirys')
                        mvvm.productsList = []
                        $.get('/Product/GetPurchaseEnquiry', { 'id': id }, function (ret) {
                            if (ret.data) {
                                mvvm.entity = ret.data
                                $.get('/Product/GetPurchaseDetail', { 'id': id }, function (re) {
                                    if (re.data) {
                                        for (var i = 0, tmp; tmp = re.data[i]; i++) {
                                            mvvm.productsList.push(tmp)
                                            var vitem = mvvm.productsList[i];
                                            mvvm.watchItem(vitem)
                                        }
                                    }
                                })
                            }
                        })
                        FormSubmit("编辑采购询价单", true, false)

                    }
                    //查看
                    vm.doview = function (id) {
                        mvvm.entity = modelFactory.create('PurchaseEnquirys')
                        mvvm.productsList = []
                        $.get('/Product/GetPurchaseEnquiry', { 'id': id }, function (ret) {
                            if (ret.data)
                                mvvm.entity = ret.data
                            $.get('/Product/GetPurchaseDetail', { 'id': id }, function (re) {
                                if (re.data) {
                                    for (var i = 0, tmp; tmp = re.data[i]; i++) {
                                        for (var a = 0, m; m = mvvm.units[a]; a++) {
                                            if (m.Id == tmp.units)
                                                tmp.units = m.Data
                                        }
                                        mvvm.productsList.push(tmp)
                                    }
                                }
                            })
                        })
                        var dialog = messageBox.openHtml('采购询价单详情', '1000px', '350px', '');
                        var content = $(dialog.content())
                        var inputTmpl = $(tmpl).find("#viewTemplate").text()
                        content.html(inputTmpl)
                        avalon.scan(content[0], mvvm)
                    }
                    //删除OK
                    vm.dodel = function (item) {
                        var index = parseInt($(this).attr('index'))
                        var id = $(this).val()
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/Product/PurchaseEnquiryDelete/' + id, {}, function (ret) {
                                if (ret.result)
                                    mvvm.entityList.removeAt(index)
                                messageBox.succeed(ret.message)
                            })
                        });
                    }
                    //批量删除OK
                    vm.doalldel = function (ids) {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.post('/Product/PurchaseEnquiryAllDelete/', deleteIds, function (ret) {
                                if (ret.result) {
                                    GetPurchaseEnquiryList(mvvm.createQuery());
                                    messageBox.succeed(ret.message);
                                }
                            });
                        });
                    }
                })

                InitDictionary()
                function InitDictionary() {
                    $.get('/Product/GetProductDictionary/', {}, function (ret) {
                        mvvm.units = ret.data.unitsList;

                    })
                }

                function getFormatDate() {
                    var d = new Date();
                    var str = d.getFullYear() + "" + d.getMonth() + "" + d.getDate();
                    return str;
                }

                function GetPurchaseEnquiryList(data) {
                    $.get('/Product/PurchaseEnquiryList', data || {}, function (ret) {
                        if (ret.data.Source) {
                            mvvm.entityList = ret.data.Source
                            avalon.vmodels.upaing.total = ret.data.RecordTotal
                            mvvm.ADD = ret.data.ADD
                            mvvm.DELETE = ret.data.DELETE
                        }
                    })
                }
                //保存
                function FormSubmit(title, val1, val2) {
                    var dialog = mvvm.openTmpl({
                        title: title,
                        tmpl: tmpl,
                        tmplid: "formTemplate",
                        w: 800,
                        h: 400,
                        padding:"def2",
                        btns: [{
                            name: '生成订单',
                            focus: val1,
                            callback: function () {
                                if (val1 == false) {
                                    messageBox.warning('请先提交询价单！');
                                    return false
                                }
                                mvvm.PurchaseOrder = modelFactory.create('PurchaseOrder')
                                mvvm.PurchaseOrderProducts = modelFactory.create('PurchaseOrderProducts')
                                var model = mvvm.entity.$model
                                if (model.State == 0) {
                                    messageBox.warning('请设置选用！');
                                    return false
                                }
                                if (model.TotalMoney == 0) {
                                    messageBox.warning('请录入金额！');
                                    return false
                                }
                                $.get('/Product/GetModelTypeID', { 'Name': 'CGDD', 'typeName': 'PurchaseOrder' }, function (retBatch) {
                                    if (retBatch.result) {
                                        mvvm.PurchaseOrder.BillNo = retBatch.message
                                        mvvm.PurchaseOrder.PurchaseOrderTag = model.EnquiryTag
                                        mvvm.PurchaseOrder.SupplyId = model.SupplyId
                                        mvvm.PurchaseOrder.SupplyName = model.SupplyName
                                        mvvm.PurchaseOrder.ContactsId = model.ContactsId
                                        mvvm.PurchaseOrder.ContactsName = model.ContactsName
                                        mvvm.PurchaseOrder.DeliveryTime = GetDateTime()
                                        mvvm.PurchaseOrder.ActionTime = GetDateTime()
                                        mvvm.PurchaseOrder.StorageId = 0
                                        mvvm.PurchaseOrder.StorageName = ''

                                        var pic = 0
                                        for (var i = 0, tmp; tmp = mvvm.productsList[i]; i++) {
                                            mvvm.PurchaseOrderProducts.OrderId = 0
                                            mvvm.PurchaseOrderProducts.StorageId = 0
                                            mvvm.PurchaseOrderProducts.ProductId = tmp.productId
                                            mvvm.PurchaseOrderProducts.ProductNo = tmp.productNo
                                            mvvm.PurchaseOrderProducts.ProductName = tmp.productName
                                            mvvm.PurchaseOrderProducts.Standard = tmp.standard
                                            mvvm.PurchaseOrderProducts.Units = tmp.units
                                            mvvm.PurchaseOrderProducts.Number = tmp.number
                                            mvvm.PurchaseOrderProducts.Price = tmp.price
                                            mvvm.PurchaseOrderProducts.DiscountRate = ''
                                            mvvm.PurchaseOrderProducts.DiscountMoney = ''
                                            mvvm.PurchaseOrderProducts.Money = tmp.money
                                            mvvm.PurchaseOrderProducts.TaxRate = ''
                                            mvvm.PurchaseOrderProducts.TaxMoney = ''
                                            mvvm.PurchaseOrderProducts.TotalMony = tmp.money
                                            mvvm.PurchaseOrderProducts.Remarks = tmp.remarks
                                            mvvm.OrderProductList.push(mvvm.PurchaseOrderProducts.$model);
                                            pic += parseFloat(tmp.money)
                                        }
                                        mvvm.PurchaseOrder.PayMoney = pic
                                        mvvm.PurchaseOrder.CurPayMoney = ''
                                        var m = mvvm.PurchaseOrder.$model
                                        $.extend(m, jsonToSubmit("ProductList", mvvm.OrderProductList));
                                        delete m.ProductList
                                        $.post("/Product/PurchaseOrderAdd/0", m, function (ret) {
                                            if (ret.result) {
                                                messageBox.ok("生成订单成功！", function () {
                                                    if (dialog) dialog.close();
                                                });
                                            }
                                        });
                                    }
                                })
                                return false;
                            }
                        },
                        {
                            name: '提交',
                            focus: val2,
                            callback: function () {
                                var model = mvvm.entity.$model
                                if (model.EnquiryTag == "") {
                                    messageBox.warning('请输入标题！');
                                    return false
                                }
                                if (model.supplyName == "") {
                                    messageBox.warning('请选择供应商！');
                                    return false
                                }
                                $.extend(model, jsonToSubmit("poductList", mvvm.productsList))
                                $.extend(model, jsonToSubmit("poductDelList", mvvm.productsDelList))

                                var url = (model.Id == 0 ? "/Product/PurchaseEnquiryAdd/" : "/Product/PurchaseEnquiryUpdate/")
                                $.post(url + model.Id, model, function (ret) {
                                    if (ret.result) {
                                        GetPurchaseEnquiryList(mvvm.createQuery());
                                        messageBox.ok("数据保存成功！", function () {
                                            mvvm.productsList = []
                                            mvvm.productsDelList = []
                                            dialog.close();
                                        })
                                    }
                                    else {
                                        messageBox.fail(ret.message, function () { })
                                    }
                                })
                                return false
                            }
                        }
                        ]
                    });
                }
                //保存
                function FormOrderSubmit(title) {
                    var dialog = openTmpl({
                        vm: mvvm,
                        title: title,
                        tmpl: tmpl,
                        tmplid: "compareTemplate",
                        w: 800,
                        h: 400,
                        onclose: function () {
                            if (avalon.vmodels.employeeTreeId)
                                avalon.vmodels.employeeTreeId.destroy()
                            if (avalon.vmodels.suplierTree)
                                avalon.vmodels.suplierTree.destroy()

                        },
                        btns: [{
                            name: '生成订单',
                            focus: true,
                            callback: function () {
                                mvvm.PurchaseOrder = modelFactory.create('PurchaseOrder')
                                mvvm.PurchaseOrderProducts = modelFactory.create('PurchaseOrderProducts')
                                var Ids = {};
                                var i = 0
                                $('input[name="selectcheckbox"]').each(function () {
                                    var chk = $(this);
                                    if (chk.val() && chk.attr('checked')) {
                                        Ids['Ids[' + i + ']'] = chk.val();
                                        i++;
                                    }
                                });
                                Ids.length = i;
                                $.get('/Product/PurchaseOrderAllAdd/', Ids, function (retBatch) {
                                    if (retBatch.result) {
                                        messageBox.ok(retBatch.message, function () {

                                        });
                                    }
                                });
                            }
                        }]
                    });
                }

                window.onscroll = fixtop
                window.onresize = fixtop
                function fixtop() {
                    var tbheight = $('#tableinterview').height()
                    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop
                    var top = document.documentElement.clientHeight || document.body.clientHeight
                    top = top + scrollTop - tbheight
                    $('#tableinterview').css('top', top + 'px')
                }
                fill()
                function fill() {
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                }
            },
            ///采购订单
            PurchaseOrder: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this, vmid = this.vmid = "PurchaseOrder";
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.lang = lang
                    vm.entity = {}
                    vm.ADD = true
                    vm.DELETE = true;
                    vm.productsList = []
                    vm.PurchaseOrderProducts = {}
                    vm.productsDelList = []
                    var gridops = {
                        entityId: vmid,
                        url: that.path,
                        modelFactory: modelFactory
                    }
                    vm.units = []
                    vm.DiscountMoneyTotal = 0//折扣额总计
                    vm.MoneyTotal = 0//金额总计
                    vm.TaxMoneyTotal = 0//税额总计
                    vm.TotalMonyTotal = 0// 价税额总计
                    vm.grid1 = createGrid(gridops);
                    initQuerys(vm, function (data, name, val, type) {
                        mvvm.loadData(data);
                    });
                    //搜索条件OK
                    vm.queryData = {
                        keyword: {
                            label: "关键词", val: "", valLabel: ""
                        },
                        state: {
                            label: "订单状态", val: "", valLabel: "",
                            items: [
                                { label: "不限", val: "", curr: true },
                                { label: "未付款", val: "0", curr: false },
                                { label: "付款中", val: "1", curr: false },
                                { label: "付款完毕", val: "2", curr: false },
                                { label: "入库中", val: "3", curr: false },
                                { label: "入库完毕", val: "4", curr: false }
                            ]
                        },
                        dateTimes: {
                            label: "时间范围", val: "", valLabel: "",
                            items: [
                                { label: "不限", val: "", curr: true },
                                { label: "本月", val: "0", curr: false },
                                { label: "上月", val: "1", curr: false },
                                { label: "时间段", val: "2", curr: false }
                            ]
                        },
                        begindate: {
                            label: "起始时间", val: "", valLabel: ""
                        },
                        enddate: {
                            label: "结束时间", val: "", valLabel: ""
                        },
                    }
                    //查看OK
                    vm.doviews = function () {
                        var path = $(this).attr('path')
                        goto(path)
                    }
                    //检索时间范围
                    vm.datespan = false

                    vm.begindateopts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.addQuery("begindate", formatDate, "起始时间:" + formatDate);
                        }
                    }
                    vm.enddateopts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.addQuery("enddate", formatDate, "结束时间:" + formatDate);
                        }
                    }
                    //数据分页OK
                    vm.pagingops = {
                        paging: function () {
                            var data = mvvm.createQuery();
                            data.pageSize = this.pagesize
                            data.pageIndex = this.currentindex + 1
                            mvvm.loadData(data);
                        }
                    }
                    //数据获取OK
                    vm.loadData = function (data) {
                        $.post(that.path, data, function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            var list = ret.data.Source;
                            mvvm.grid1.initList(list, ret.data.RecordTotal);
                            var page = avalon.vmodels[vmid + "Page"];
                            if (page) page.total = ret.data.RecordTotal;
                        })
                    }
                    vm.CustomerContactData = []
                    //选联系人OK
                    vm.setCustomerContacts = function (customerid) {
                        $.get('/Customer/Contacts', { 'customerId': customerid }, function (ret) {
                            mvvm.CustomerContactData = ret.data.contacts.Source
                        })
                    }
                    //选择仓库OK
                    vm.contactChange = function () {
                        var id = $(this).find('option:selected').val()
                        var name = $(this).find('option:selected').text()
                        var tel = $(this).find('option:selected').attr('title')
                        if (id) {
                            mvvm.entity.StorageId = id
                            mvvm.entity.StorageName = name
                        } else {
                            mvvm.entity.StorageId = ''
                            mvvm.entity.StorageName = ''
                        }
                    }
                    // 选择供应商
                    vm.selectSuplier = function () {
                        plugins.selectCustomer({
                            type: "contacts",
                            superiorCategoryId: 10133,
                            callback: function (cus, cons) {
                                var cu = cus[0], con = cons.length > 0 ? cons[0] : { Id: "", Name: "" };
                                var entity = mvvm.entity;
                                entity.SupplyId = cu.Id
                                entity.SupplyName = cu.Name
                                entity.ContactsId = con.Id
                                entity.ContactsName = con.Name
                                //mvvm.setCustomerContacts(cu.Id)
                                mvvm.CustomerContactData = cu.Contacts || [];
                            }
                        })
                    }
                    
                    //选择产品OK
                    vm.selectProduct = function () {
                        var pvmid = "PurchaseProductSelect", pvm,
                            url = "/Product/PurchaseProductSelect",
                            dialog = openWin("选择产品", pvmid, url, 900, 500, [{
                                name: "确定选择",
                                focus: true,
                                callback: function () {
                                    if (!pvm) {
                                        messageBox.warning("系统正在载入中，请稍候……");
                                        return false;
                                    }
                                    var list = pvm.resumeTemp;
                                    if (list.length == 0) {
                                        messageBox.warning("请选择数据！");
                                        return false;
                                    }
                                    var plist = mvvm.entity.ProductList;
                                    list.forEach(function (item) {
                                        for (var i = 0, l = plist.length; i < l; i++) {
                                            if (plist[i].$model.productId == item.No) return;
                                        }
                                        var model = modelFactory.create("PurchaseOrderProducts")
                                        var map = {
                                            ProductName: "Name", Standard: "Standard", ProductId: "Id", ProductCategory: "CategoryId",
                                            ProductNo: "No", Units: "Units", Price: "StockPrice"
                                        }
                                        extendValue(model, item.$model, map);
                                        model.Id = 0;
                                        model.Number = 1;
                                        for (var a = 0, m; m = mvvm.units[a]; a++) {
                                            if (m.Id == model.Units)
                                                model.Units = m.Data
                                        }
                                        plist.push(model);
                                        var vitem = mvvm.entity.ProductList[mvvm.entity.ProductList.length - 1];
                                        mvvm.watchItem(vitem)
                                    });
                                }
                            }], function (tmpl, vmodel) {
                                pvm = vmodel;
                            });
                    }
                    //关键字搜索OK
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.addQuery("keyword", mvvm.queryData.keyword.val);
                    }
                    //新增OK
                    vm.doadd = function () {
                        mvvm.entity.ProductList = []
                        mvvm.DiscountMoneyTotal = 0//折扣额总计
                        mvvm.MoneyTotal = 0//金额总计
                        mvvm.TaxMoneyTotal = 0//税额总计
                        mvvm.TotalMonyTotal = 0// 价税额总计
                        mvvm.grid1.getEntity("", function (entity) {
                            entity.ActionBy = { Id: CBCRM.memberShip.Id, FullName: CBCRM.memberShip.FullName }
                            entity.ActionTime = entity.AddTime;
                            mvvm.entity = entity;
                            mvvm.PurchaseOrderProducts = modelFactory.create('PurchaseOrderProducts')
                            $.get('/Product/GetModelTypeID', { 'Name': 'CGDD', 'typeName': 'PurchaseOrder' }, function (retBatch) {
                                if (retBatch.result) {
                                    mvvm.entity.BillNo = retBatch.message
                                }
                            })
                            if (mvvm.units.length > 0)
                                mvvm.PurchaseOrderProducts.Units = mvvm.units[0].Id;
                            mvvm.showForm("新增采购订单");
                        });
                    }
                    //编辑OK
                    vm.doedit = function (id) {
                        mvvm.entity.ProductList = []
                        mvvm.DiscountMoneyTotal = 0//折扣额总计
                        mvvm.MoneyTotal = 0//金额总计
                        mvvm.TaxMoneyTotal = 0//税额总计
                        mvvm.TotalMonyTotal = 0// 价税额总计
                        mvvm.grid1.getEntity(id, function (entity) {
                            mvvm.entity = entity;
                            $.get('/Product/GetPurchaseOrderProducts', { 'id': id }, function (re) {
                                if (re.data) {
                                    mvvm.entity.ProductList = re.data
                                    for (var i = 0, tmp; tmp = mvvm.entity.ProductList[i]; i++) {
                                        mvvm.DiscountMoneyTotal = mvvm.DiscountMoneyTotal + tmp.DiscountMoney//折扣额总计
                                        mvvm.MoneyTotal = mvvm.MoneyTotal + tmp.Money//金额总计
                                        mvvm.TaxMoneyTotal = mvvm.TaxMoneyTotal + tmp.TaxMoney//税额总计
                                        mvvm.TotalMonyTotal = mvvm.TotalMonyTotal + tmp.TotalMony// 价税额总计
                                        var vitem = mvvm.entity.ProductList[i];
                                        mvvm.watchItem(vitem)
                                    }
                                }
                                mvvm.showForm("编辑采购订单");
                            });
                        });
                    }
                    //查看OK
                    vm.doview = function (id) {
                        mvvm.entity.ProductList = []
                        mvvm.DiscountMoneyTotal = 0//折扣额总计
                        mvvm.MoneyTotal = 0//金额总计
                        mvvm.TaxMoneyTotal = 0//税额总计
                        mvvm.TotalMonyTotal = 0// 价税额总计
                        mvvm.grid1.getEntity(id, function (entity) {
                            $.get('/Product/GetPurchaseOrderProducts', { 'id': id }, function (re) {
                                if (re.data) {
                                    entity.ProductList = re.data
                                    for (var i = 0, tmp; tmp = entity.ProductList[i]; i++) {
                                        for (var a = 0, m; m = mvvm.units[a]; a++) {
                                            if (m.Id == tmp.Units)
                                                tmp.Units = m.Data
                                        }
                                        mvvm.DiscountMoneyTotal = mvvm.DiscountMoneyTotal + tmp.DiscountMoney//折扣额总计
                                        mvvm.MoneyTotal = mvvm.MoneyTotal + tmp.Money//金额总计
                                        mvvm.TaxMoneyTotal = mvvm.TaxMoneyTotal + tmp.TaxMoney//税额总计
                                        mvvm.TotalMonyTotal = mvvm.TotalMonyTotal + tmp.TotalMony// 价税额总计
                                    }
                                }
                                mvvm.entity = entity;
                                openTmpl({ vm: mvvm, title: "采购订单详情", w: 1000, h: 300, tmplid: "viewTemplate", tmpl: tmpl });
                            });
                        });
                    }
                    //列表显示更多
                    vm.showindex = -1;
                    vm.showmore = function (index) {
                        if (index != mvvm.showindex) mvvm.showindex = index;
                        else mvvm.showindex = -1
                    }
                    vm.hidemore = function () {
                        mvvm.showindex = '-1'
                    }

                    vm.storageList = [];
                    vm.spaceList = [];
                    vm.getSpace = function () {
                        mvvm.spaceList = [];
                        $.get('/Product/GetStorageSpaceListAll/', function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            mvvm.spaceList = ret.data.list;
                        })
                    }
                    vm.getStorage = function () {
                        mvvm.storageList = [];
                        $.get('/Product/GetStorageList/', function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            mvvm.storageList = ret.data.list;
                        })
                    }

                    vm.PurchasePutStorageList = []
                    //入库明细查看OK
                    vm.doputview = function (id) {
                        mvvm.PurchasePutStorageList = []
                        $.get('/Product/GetPurchaseOrderByPutStorage', { 'id': id }, function (ret) {
                            if (ret.data) {
                                for (var i = 0, tmp; tmp = ret.data[i]; i++) {
                                    for (var a = 0, m; m = mvvm.units[a]; a++) {
                                        if (m.Id == tmp.Units)
                                            tmp.Units = m.Data
                                    }
                                    for (var a = 0, m; m = mvvm.storageList[a]; a++) {
                                        if (m.Id == tmp.StorageId)
                                            tmp.StorageId = m.Name
                                    }
                                    for (var a = 0, mp; mp = mvvm.spaceList[a]; a++) {
                                        if (mp.Id == tmp.SpaceId)
                                            tmp.SpaceId = mp.Name
                                    }
                                    mvvm.PurchasePutStorageList.push(tmp)

                                }
                                openTmpl({ vm: mvvm, title: "采购订单入库明细", w: 1000, h: 300, tmplid: "PutviewTemplate", tmpl: tmpl });
                            }
                        });
                    }
                    //跳转查看OK
                    vm.doOrderview = function (id) {
                        mvvm.entity.ProductList = []
                        mvvm.DiscountMoneyTotal = 0//折扣额总计
                        mvvm.MoneyTotal = 0//金额总计
                        mvvm.TaxMoneyTotal = 0//税额总计
                        mvvm.TotalMonyTotal = 0// 价税额总计
                        $.get('/Product/GetPurchaseOrderById', { 'id': id }, function (ret) {
                            if (ret.data) {
                                mvvm.entity = ret.data;
                                $.get('/Product/GetPurchaseOrderProducts', { 'id': id }, function (re) {
                                    if (re.data) {
                                        mvvm.entity.ProductList = re.data
                                        for (var i = 0, tmp; tmp = mvvm.entity.ProductList[i]; i++) {
                                            for (var a = 0, m; m = mvvm.units[a]; a++) {
                                                if (m.Id == tmp.Units)
                                                    tmp.Units = m.Data
                                            }
                                            mvvm.DiscountMoneyTotal = mvvm.DiscountMoneyTotal + tmp.DiscountMoney//折扣额总计
                                            mvvm.MoneyTotal = mvvm.MoneyTotal + tmp.Money//金额总计
                                            mvvm.TaxMoneyTotal = mvvm.TaxMoneyTotal + tmp.TaxMoney//税额总计
                                            mvvm.TotalMonyTotal = mvvm.TotalMonyTotal + tmp.TotalMony// 价税额总计
                                        }
                                    }
                                    openTmpl({ vm: mvvm, title: "采购订单详情", w: 800, h: 300, tmplid: "viewTemplate", tmpl: tmpl });
                                });
                            }
                        });
                    }
                    //删除OK
                    vm.productsDel = function () {
                        mvvm.DiscountMoneyTotal = 0//折扣额总计
                        mvvm.MoneyTotal = 0//金额总计
                        mvvm.TaxMoneyTotal = 0//税额总计
                        mvvm.TotalMonyTotal = 0// 价税额总计
                        var index = parseInt($(this).attr("index"))
                        var con = mvvm.entity.ProductList.$model[index]
                        if (con.Id > 0) mvvm.productsDelList.push(con)
                        mvvm.entity.ProductList.removeAt(index)

                        for (var i = 0, tmp; tmp = mvvm.entity.ProductList[i]; i++) {
                            mvvm.DiscountMoneyTotal = mvvm.DiscountMoneyTotal + parseInt(tmp.DiscountMoney)//折扣额总计
                            mvvm.MoneyTotal = mvvm.MoneyTotal + parseInt(tmp.Money)//金额总计
                            mvvm.TaxMoneyTotal = mvvm.TaxMoneyTotal + parseInt(tmp.TaxMoney)//税额总计
                            mvvm.TotalMonyTotal = mvvm.TotalMonyTotal + parseInt(tmp.TotalMony)// 价税额总计
                        }
                        mvvm.entity.PayMoney = mvvm.TotalMonyTotal
                    }
                    //保存按钮OK
                    vm.showForm = function (title) {
                        var btns = [{
                            name: "提交保存",
                            focus: true,
                            callback: function () {
                                var m = $.extend(true, {}, mvvm.entity.$model);
                                if (m.SupplyId == 0) {
                                    messageBox.error("请选择供应商！");
                                    return false;
                                }
                                if (!m.PurchaseOrderTag) {
                                    messageBox.error("请选输入标题！");
                                    return false;
                                }
                                $.extend(m, jsonToSubmit("ProductList", mvvm.entity.ProductList));
                                $.extend(m, jsonToSubmit("ActionBy", mvvm.entity.ActionBy))
                                delete m.ProductList
                                delete m.AddBy
                                delete m.ActionBy
                                var url = (m.Id == 0 ? "/Product/PurchaseOrderAdd/" : "/Product/PurchaseOrderUpdate/")
                                $.post(url + m.Id, m, function (ret) {
                                    CBCRM.showResult(ret);
                                    if (ret.result) {
                                        if (dialog) dialog.close();
                                        mvvm.loadData();
                                    }
                                });
                                return false;
                            }
                        }
                        ];
                        var dialog = openTmpl({
                            vm: mvvm, title: title, btns: btns, w: 1000, h: 400,
                            tmplid: "formTemplate", tmpl: tmpl,
                            onclose: function () {
                                destroyui(["actionByTree", "suplierTree"]);
                            }
                        });
                    }
                    //删除
                    vm.dodel = function (item) {
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/Product/' + vmid + 'Del/' + item.Id, {}, function (ret) {
                                CBCRM.showResult(ret);
                                if (ret.result)
                                    mvvm.loadData();
                            })
                        });
                    }
                    //批量删除
                    vm.doRemoveAll = function () {
                        var ids = mvvm.grid1.getCheckedIds("deleteIds");
                        if (ids.length == 0) {
                            messageBox.error("请选择数据！");
                            return;
                        }
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/Product/' + vmid + 'AllDel/', ids, function (ret) {
                                CBCRM.showResult(ret);
                                if (ret.result) mvvm.loadData();
                            })
                        });
                    }
                    //计算预算合计
                    vm.onSumRowMoney = function (item) {
                        var money = parseFloat(item.Number) * parseFloat(item.Price)//金额
                        if (money && money >= 0) {
                            item.Money = money
                        } else {
                            item.Money = 0
                        }
                        if (item.DiscountRate != 0)
                            item.DiscountMoney = parseFloat(item.Money) * (parseFloat(item.DiscountRate) / 100)//折扣额
                        if (item.TaxRate != 0)
                            item.TaxMoney = parseFloat(item.Money) * (parseFloat(item.TaxRate) / 100)//税额
                        item.TotalMony = parseFloat(item.Money) - parseFloat(item.DiscountMoney) + parseFloat(item.TaxMoney)//价税金额
                        mvvm.onSumCost()
                    }
                    //计算预算合计
                    vm.onSumCost = function () {
                        var cost = 0
                        var discount = 0
                        var tax = 0
                        var total = 0
                        mvvm.entity.ProductList.$model.forEach(function (item) {
                            if (item.DiscountMoney)
                                discount = discount + parseFloat(item.DiscountMoney)
                            if (item.Money)
                                cost = cost + parseFloat(item.Money)
                            if (item.TaxMoney)
                                tax = tax + parseFloat(item.TaxMoney)
                            if (item.TotalMony)
                                total = total + parseFloat(item.TotalMony)

                        })
                        mvvm.DiscountMoneyTotal = discount
                        mvvm.MoneyTotal = cost
                        mvvm.TaxMoneyTotal = tax
                        mvvm.TotalMonyTotal = total
                        mvvm.entity.PayMoney = total
                    }
                    vm.watchItem = function (item) {
                        function _watchPrice() {
                            var money = parseFloat(item.Number) * parseFloat(item.Price)//金额
                            if (money && money >= 0) {
                                item.Money = money
                            } else {
                                item.Money = 0
                            }
                            if (item.DiscountRate != 0)
                                item.DiscountMoney = parseFloat(item.Money) * (parseFloat(item.DiscountRate) / 100)//折扣额
                            if (item.TaxRate != 0)
                                item.TaxMoney = parseFloat(item.Money) * (parseFloat(item.TaxRate) / 100)//税额
                            item.TotalMony = parseFloat(item.Money) - parseFloat(item.DiscountMoney) + parseFloat(item.TaxMoney)//价税金额
                            mvvm.onSumCost()

                        }
                        ["Price", "Number", "DiscountRate", "TaxRate"].forEach(function (p) {
                            item.$watch(p, _watchPrice);
                        })
                    }
                    vm.computeTotal = function () {
                        var m = mvvm.entity, list = m.ProductList;
                        var total = 0, discount = 0, tax = 0, p = 0;//
                        list.forEach(function (item) {
                            if (item.Money) total += parseFloat(item.Money, 10);
                            if (item.DiscountMoney) discount += parseFloat(item.DiscountMoney, 10);
                            if (item.TaxMoney) tax += parseFloat(item.TaxMoney, 10);
                        });
                        m.TotalMoney = (total + discount).toFixed(2);
                        m.PreferentialMoney = discount.toFixed(2);
                        m.TaxMoney = tax.toFixed(2);
                        m.PayMoney = total;
                    }
                    //仓库OK
                    vm.storageList = [];
                    vm.getStorage = function (id) {
                        mvvm.storageList = [];
                        $.get('/Product/GetStorageList/', {}, function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            mvvm.storageList = ret.data.list;
                        })
                    }
                })

                InitDictionary()
                function InitDictionary() {
                    $.get('/Product/GetProductDictionary/', {}, function (ret) {
                        mvvm.units = ret.data.unitsList;

                    })
                }
                mvvm.grid1.bindWatch();
                mvvm.getStorage();
                mvvm.getSpace();

                //查看订单详情
                if (that.params.id && that.params.action == 'get') {
                    mvvm.doOrderview(that.params.id)
                }
                else {
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                }

            }
            ///采购付款
            , PurchasePay: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this, vmid = this.vmid = "PurchasePay";
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.lang = lang
                    vm.accounting = {}
                    vm.ADD = true
                    vm.DELETE = true
                    vm.receiptDetailList = []
                    vm.receiptDetailDelList = []

                    vm.PurchasePayList = []
                    vm.units = []
                    vm.totalmoney = 0
                    vm.entity = {}

                    var gridops = {
                        entityId: vmid,
                        url: that.path,
                        modelFactory: modelFactory
                    }
                    vm.grid1 = createGrid(gridops);
                    //数据获取OK
                    vm.loadData = function (data) {
                        $.post(that.path, data, function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            var list = ret.data.Source;
                            mvvm.grid1.initList(list, ret.data.RecordTotal);
                            var page = avalon.vmodels[vmid + "Page"];
                            if (page) page.total = ret.data.RecordTotal;
                        })
                    }

                    //数据分页OK
                    vm.pagingops = {
                        paging: function () {
                            var data = mvvm.createQuery();
                            data.pageSize = this.pagesize
                            data.pageIndex = this.currentindex + 1
                            mvvm.loadData(data);
                        }
                    }


                    initQuerys(vm, function (data, name, val, type) {
                        mvvm.loadData(data);
                    });
                    //搜索条件OK
                    vm.queryData = {
                        keyword: {
                            label: "关键词", val: "", valLabel: ""
                        },
                        state: {
                            label: "订单状态", val: "", valLabel: "",
                            items: [
                                { label: "不限", val: "", curr: true },
                                { label: "未付款", val: "0", curr: false },
                                { label: "付款中", val: "1", curr: false },
                                { label: "付款完毕", val: "2", curr: false },
                                { label: "入库中", val: "3", curr: false },
                                { label: "入库完毕", val: "4", curr: false }
                            ]
                        },
                        dateTimes: {
                            label: "时间范围", val: "", valLabel: "",
                            items: [
                                { label: "不限", val: "", curr: true },
                                { label: "本月", val: "0", curr: false },
                                { label: "上月", val: "1", curr: false },
                                { label: "时间段", val: "2", curr: false }
                            ]
                        },
                        begindate: {
                            label: "起始时间", val: "", valLabel: ""
                        },
                        enddate: {
                            label: "结束时间", val: "", valLabel: ""
                        },
                    }
                    //检索时间范围OK
                    vm.datespan = false

                    vm.begindateopts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.addQuery("begindate", formatDate, "起始时间:" + formatDate);
                        }
                    }
                    vm.enddateopts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.addQuery("enddate", formatDate, "结束时间:" + formatDate);
                        }
                    }


                    //查看OK
                    vm.doviews = function () {
                        var path = $(this).attr('path')
                        goto(path)
                    }
                    //查看订单OK
                    vm.doFrom = function (item) {
                        var path = '/Product/PurchaseOrder/' + item.Id + '/get'
                        goto(path)
                    }


                    //关键字搜索OK
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.addQuery("keyword", mvvm.queryData.keyword.val);
                    }

                    vm.view = function (con) {
                        var url = "/FinancialAffairs/Accounting/" + con.Id + "/get"
                        goto(url, true);
                    }

                    vm.SumAmount = 0
                    //查看OK
                    vm.doview = function (id) {
                        mvvm.SumAmount = 0
                        mvvm.PurchasePayList = []
                        mvvm.grid1.getEntity(id, function (entity) {
                            $.get('/FinancialAffairs/ReceiptsBillByOrderId', { 'id': id }, function (re) {
                                if (re.data) {
                                    mvvm.PurchasePayList = re.data
                                    for (var i = 0, tmp; tmp = re.data[i]; i++) {
                                        mvvm.SumAmount = mvvm.SumAmount + tmp.Amount
                                    }
                                }
                                openTmpl({ vm: mvvm, title: "采购付款单详情", w: 800, h: 300, tmplid: "payviewTemplate", tmpl: tmpl });
                            });
                        });
                    }

                    //更新后OK
                    vm.doeditview = function (id) {
                        mvvm.SumAmount = 0
                        $.get('/FinancialAffairs/ReceiptsBillByOrderId', { 'id': id }, function (re) {
                            if (re.data) {
                                mvvm.PurchasePayList = re.data
                                for (var i = 0, tmp; tmp = re.data[i]; i++) {
                                    mvvm.SumAmount = mvvm.SumAmount + tmp.Amount
                                }
                            }
                        });
                    }
                    //新增 OK
                    vm.doadd = function (oid) {
                        var url = "/FinancialAffairs/Accounting/" + oid + "/add"
                        goto(url, true);
                    }

                    vm.paymet = function (money, oid, type) {
                        $.post("/Product/PurchaseOrderUpdateByMoney/" + oid, { 'money': money, 'type': type }, function (ret) {
                            if (ret.result) {
                                mvvm.loadData(mvvm.createQuery());
                            }
                        });
                    }

                    //编辑
                    vm.doedit = function (id) {
                        var url = "/FinancialAffairs/Accounting/" + id + "/edit"
                        goto(url, true);
                    }

                    //删除
                    vm.dodel = function (id) {
                        var index = parseInt($(this).attr('index'));
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/Product/ReceiptsDelById/' + id, {}, function (ret) {
                                if (ret.result) {
                                    var tmp = mvvm.PurchasePayList[index]
                                    mvvm.SumAmount = parseFloat(mvvm.SumAmount) - parseFloat(tmp.Amount)
                                    mvvm.PurchasePayList.removeAt(index);
                                    mvvm.paymet(mvvm.SumAmount, tmp.OrderId, 1)
                                }
                                messageBox.succeed(ret.message);
                            })
                        });
                    }
                })
                mvvm.grid1.bindWatch();
                InitDictionary()
                function InitDictionary() {
                    $.get('/Product/GetProductDictionary/', {}, function (ret) {
                        mvvm.units = ret.data.unitsList;

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

            }
            //采购入库
            , PurchasePutStorage: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this, vmid = this.vmid = "PurchasePutStorage";
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.lang = lang
                    vm.entity = {}
                    vm.ADD = true
                    vm.DELETE = true;
                    var gridops = {
                        entityId: vmid,
                        url: that.path,
                        modelFactory: modelFactory
                    }
                    vm.PurchasePutStorageList = []
                    vm.grid1 = createGrid(gridops);
                    initQuerys(vm, function (data, name, val, type) {
                        mvvm.loadData(data);
                    });
                    //搜索条件OK
                    vm.queryData = {
                        keyword: {
                            label: "关键词：", val: "", valLabel: ""
                        },
                        dateTimes: {
                            label: "时间范围", val: "", valLabel: "",
                            items: [
                                { label: "不限", val: "", curr: true },
                                { label: "本月", val: "0", curr: false },
                                { label: "上月", val: "1", curr: false },
                                { label: "时间段", val: "2", curr: false }
                            ]
                        },
                        begindate: {
                            label: "起始时间", val: "", valLabel: ""
                        },
                        enddate: {
                            label: "结束时间", val: "", valLabel: ""
                        },
                    }
                    //检索时间范围OK
                    vm.datespan = false

                    vm.begindateopts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.addQuery("begindate", formatDate, "起始时间:" + formatDate);
                        }
                    }
                    vm.enddateopts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.addQuery("enddate", formatDate, "结束时间:" + formatDate);
                        }
                    }
                    //查看供应商OK
                    vm.doviews = function () {
                        var path = $(this).attr('path')
                        goto(path)
                    }

                    //查看订单OK
                    vm.doFrom = function (item) {
                        var path = '/Product/PurchaseOrder/' + item.FromId + '/get'
                        goto(path)
                    }

                    //数据分页OK
                    vm.pagingops = {
                        paging: function () {
                            var data = mvvm.createQuery();
                            data.pageSize = this.pagesize
                            data.pageIndex = this.currentindex + 1
                            mvvm.loadData(data);
                        }
                    }
                    //数据获取OK
                    vm.loadData = function (data) {
                        $.post(that.path, data, function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            var list = ret.data.Source;
                            mvvm.grid1.initList(list, ret.data.RecordTotal);
                            var page = avalon.vmodels[vmid + "Page"];
                            if (page) page.total = ret.data.RecordTotal;
                        })
                    }

                    //关键字搜索OK
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.addQuery("keyword", mvvm.queryData.keyword.val);
                    }
                    // 选择供应商
                    vm.selectSuplier = function () {
                        plugins.selectCustomer({
                            type: "contacts",
                            superiorCategoryId: 10133,
                            callback: function (cus, cons) {
                                var cu = cus[0];
                                mvvm.entity.SupplyId = cu.Id
                                mvvm.entity.SupplyName = cu.Name
                            }
                        })
                    }
                    //经办人
                    vm.selectActionBy = function () {
                        plugins.selectUser({
                            dataAuth: 5054000,
                            callback: function (us) {
                                var u = us[0];
                                var actionBy = mvvm.entity.ActionBy
                                actionBy.Id = u.Id
                                actionBy.FullName = u.FullName
                                mvvm.entity.ActionByGroup = u.GroupName
                            }
                        })
                    }

                    //新增
                    vm.doadd = function () {
                        mvvm.storages = 0;
                        mvvm.spaces = 0;
                        mvvm.PurchasePutStorageList = [];
                        mvvm.entity = modelFactory.create('PurchasePutStorage')
                        mvvm.grid1.getEntity("", function (entity) {
                            entity.ActionBy = { Id: CBCRM.memberShip.Id, FullName: CBCRM.memberShip.FullName, Group: CBCRM.memberShip.Group }
                            entity.AddBy = { Id: CBCRM.memberShip.Id, FullName: CBCRM.memberShip.FullName, Group: CBCRM.memberShip.Group }
                            entity.ActionByGroup = CBCRM.memberShip.Group
                            mvvm.entity = entity;
                            $.get('/Product/GetModelTypeID', { 'Name': 'CCRK', 'typeName': 'PurchasePutStorage' }, function (retBatch) {
                                if (retBatch.result) {
                                    mvvm.entity.BillNo = retBatch.message
                                }
                            })
                        });
                        mvvm.formSubmit("新增采购入库")
                    }
                    //编辑
                    vm.doedit = function (id) {
                        mvvm.PurchasePutStorageList = []
                        mvvm.grid1.getEntity(id, function (entity) {
                            mvvm.entity = entity;

                            $.get('/Product/GetPurchasePutStorageByBillId', { 'id': id }, function (re) {
                                if (re.data) {
                                    mvvm.PurchasePutStorageList = re.data
                                }
                            });
                            mvvm.formSubmit("编辑采购入库")
                        });

                    }
                    //查看
                    vm.doview = function (id) {
                        mvvm.PurchasePutStorageList = []
                        mvvm.grid1.getEntity(id, function (entity) {
                            mvvm.entity = entity;
                            $.get('/Product/GetPurchasePutStorageByBillId', { 'id': id }, function (re) {
                                if (re.data) {
                                    for (var i = 0, tmp; tmp = re.data[i]; i++) {
                                        for (var a = 0, m; m = mvvm.storageList[a]; a++) {
                                            if (m.Id == tmp.StorageId)
                                                tmp.StorageId = m.Name
                                        }
                                        for (var a = 0, mp; mp = mvvm.spaceList[a]; a++) {
                                            if (mp.Id == tmp.SpaceId)
                                                tmp.SpaceId = mp.Name
                                        }
                                        mvvm.PurchasePutStorageList.push(tmp)
                                    }

                                }

                            });
                        });
                        var dialog = messageBox.openHtml('采购入库查看详细', '1000px', '300px', '');
                        var content = $(dialog.content())
                        content.attr('ms-include', 'viewTemplates')
                        avalon.scan(content[0], mvvm)

                    }
                    //保存OK
                    vm.formSubmit = function (title) {
                        var btns = [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var msg = true
                                mvvm.PurchasePutStorageList.forEach(function (item) {
                                    if (item.StorageId == 0) {
                                        msg = false
                                    }
                                });
                                if (!msg) {
                                    messageBox.warning('请选择存放仓库！')
                                    return false
                                }
                                var model = $.extend(true, {}, mvvm.entity.$model);
                                $.extend(model, jsonToSubmit("list", mvvm.PurchasePutStorageList));
                                $.extend(model, jsonToSubmit("ActionBy", model.ActionBy));
                                delete model.list
                                delete model.ActionBy;
                                var url = (model.Id == 0 ? "/Product/PurchasePutStorageAdd/" : "/Product/PurchasePutStorageUpdate/");
                                $.post(url + model.Id, model, function (ret) {
                                    if (ret.result) {
                                        messageBox.ok(ret.message, function () {
                                            mvvm.loadData(mvvm.createQuery());
                                            if (dialog) dialog.close()
                                        });
                                    }
                                    else {
                                        messageBox.fail(ret.message, function () { });
                                    }
                                })

                                return false;
                            }
                        }]
                        var dialog = mvvm.openTmpl({
                            title: title, w: 1024, h: 400,padding:"def2",
                            tmplid: "formTemplate", tmpl: tmpl, btns: btns,
                            onclose: function () {
                                if (avalon.vmodels.actionByTree)
                                    avalon.vmodels.actionByTree.destroy()

                            }
                        });
                    }
                    vm.contractKey = ''
                    
                    vm.cgrid = createGrid({
                        url: "/Product/PurchaseOrder/",
                        createQuery: function () {
                            return { 'keyword': mvvm.contractKey }
                        }
                    });

                    vm.contractKey = ''
                    //选择订单
                    vm.selectContract = function () {
                        mvvm.contractKey = mvvm.entity.FromNo;
                        var btns = [{
                            name: '确定',
                            focus: true,
                            callback: function () {
                                var clist = mvvm.cgrid.getChecked();
                                if (clist.length == 0) {
                                    messageBox.warning('请选择采购订单')
                                } else {
                                    if (mvvm.contractdetailslist.length == 0) {
                                        messageBox.warning('数据加载中')
                                        return false
                                    }
                                    var centity = clist[0].$model;
                                    var entity = mvvm.entity;
                                    mvvm.entity.FromNo = centity.BillNo;
                                    mvvm.entity.FromId = centity.Id;
                                    mvvm.entity.SupplyId = centity.SupplyId
                                    mvvm.entity.SupplyName = centity.SupplyName
                                    mvvm.centity = centity;
                                    mvvm.getPutStoragelist(centity);
                                    if (dialog) dialog.close()
                                }
                                return false;
                            }
                        }];
                        var dialog = mvvm.openTmpl({
                            title: "选择采购订单", w: 1000,padding:"10px",
                            tmplid: "ContractListTemplate", tmpl: tmpl,
                            btns: btns, extParam: { top: 20 }
                        });
                        mvvm.cgrid.clear();
                        mvvm.cgrid.doSearch(mvvm.watchCgrid);
                    }

                    vm.searchContract = function () {
                        mvvm.cgrid.clear();
                        mvvm.cgrid.doSearch(mvvm.watchCgrid);
                    }
                    vm.watchCgrid = function () {
                        var list = mvvm.cgrid.list;
                        list.forEach(function (item) {
                            item.$watch("checked", function (n) {
                                if (!n) return;
                                list.forEach(function (c) {
                                    if (c.Id != item.Id) c.checked = false;
                                })
                                mvvm.getDetailslist(item.Id);
                            });
                        })
                        if (list.length > 0) list[0].checked = true;
                    }
                    vm.getPutStoragelist = function (centity) {
                        mvvm.PurchasePutStorageList = []
                        var moneytotal = 0;
                        mvvm.contractdetailslist.forEach(function (item) {
                            if (item.Number <= item.PutStorageNumber)
                                return
                            var model = $.extend(true, {}, modelFactory.create("StorageOutAndIn"))
                            var map = {
                                Id: "Id", ProductId: "ProductId", ProductNo: "ProductNo", ProductName: "ProductName", Price: "Price",
                                DiscountRate: "DiscountRate", DiscountMoney: "DiscountMoney", Money: "Money", TaxRate: "TaxRate", TaxMoney: "TaxMoney", TotalMony: "TotalMony"
                            }
                            extendValue(model, item, map);

                            model.Id = 0;
                            model.StorageId = 0;
                            model.SpaceId = 0
                            model.spaceList = [];
                            model.FromId = item.Id
                            model.FromNo = centity.BillNo
                            model.AddBy = {}
                            model.AddTime = "";
                            model.ValidDay = 365;
                            model.Type = '采购入库'
                            model.SupplyName = centity.SupplyName
                            model.SupplyId = centity.SupplyId
                            model.Number = parseInt(item.Number) - parseInt(item.PutStorageNumber)
                            model.count = model.Number
                            for (var a = 0, m; m = mvvm.units[a]; a++) {
                                if (m.Id == item.Units)
                                    model.Units = m.Data
                            }
                            mvvm.PurchasePutStorageList.push(model);
                            var vitem = mvvm.PurchasePutStorageList[mvvm.PurchasePutStorageList.length - 1];
                            moneytotal = moneytotal + item.TotalMony;
                            mvvm.watchItem(vitem);
                        });
                        if (mvvm.entity.TotalMoney > 0) {
                            mvvm.getNewTotal();;
                        } else {
                            mvvm.entity.TotalMoney = moneytotal;
                        }
                    }

                    vm.watchItem = function (item) {
                        item.$watch("Number", function (n) {
                            if (n) {

                                if (item.Number > item.count) {
                                    item.Number = item.count
                                    messageBox.warning('入库数量已超过订单数量')
                                }
                                var money = parseFloat(item.Number) * parseFloat(item.Price)//金额
                                if (money && money >= 0) {
                                    item.Money = money
                                } else {
                                    item.Money = 0
                                }
                                if (item.DiscountRate != 0)
                                    item.DiscountMoney = parseFloat(item.Money) * (parseFloat(item.DiscountRate) / 100)//折扣额
                                if (item.TaxRate != 0)
                                    item.TaxMoney = parseFloat(item.Money) * (parseFloat(item.TaxRate) / 100)//税额
                                item.TotalMony = parseFloat(item.Money) - parseFloat(item.DiscountMoney) + parseFloat(item.TaxMoney)//价税金额
                                mvvm.onSumCost()
                            } else {
                                item.Money = 0
                                item.DiscountMoney = 0
                                item.TaxMoney = 0
                                item.TotalMony = 0
                                mvvm.onSumCost()
                            }
                        })
                        item.$watch("ProductionTime", function (n) {
                            if (n && item.ValidDay) {
                                try {
                                    var d = new Date(n), d2 = new Date(d.valueOf() + item.ValidDay * 24 * 60 * 60 * 1000)
                                    var a = [d2.getFullYear(), d2.getMonth() + 1, d2.getDate()]
                                    a[1] = a[1] < 9 ? "0" + a[1] : a[1];
                                    a[2] = a[2] < 9 ? "0" + a[2] : a[2];
                                    item.ValidDate = a.join("-")
                                } catch (ex) {
                                    item.ValidDate = ""
                                }
                            } else {
                                item.ValidDate = ""
                            }
                        })
                        item.$watch("StorageId", function (n) {
                            item.spaceList = [];
                            if (!n) return;
                            mvvm.spaceList.forEach(function (items) {
                                if (items.StorageId == n) {
                                    item.spaceList.push(items.$model);
                                }
                            });
                            item.SpaceId = item.spaceList.length > 0 ? item.spaceList[0].Id : 0
                        });
                    }
                    vm.getNewTotal = function () {
                        mvvm.entity.TotalMoney = 0;
                        mvvm.PurchasePutStorageList.forEach(function (li) {
                            mvvm.entity.TotalMoney += parseFloat(li.TotalMony);
                        });
                    }

                    //计算预算合计
                    vm.onSumCost = function () {
                        var total = 0
                        mvvm.PurchasePutStorageList.$model.forEach(function (item) {
                            if (item.TotalMony)
                                total = total + parseFloat(item.TotalMony)
                        })
                        mvvm.entity.TotalMoney = total
                    }

                    //采购明细
                    vm.contractdetailslist = [];
                    vm.getDetailslist = function (id) {
                        mvvm.contractdetailslist = [];
                        $.get('/Product/GetPurchaseOrderProducts/', { "Id": id }, function (ret) {
                            mvvm.contractdetailslist = ret.data
                        })
                    }
                    vm.storageList = [];
                    vm.spaceList = [];
                    vm.getSpace = function () {
                        mvvm.spaceList = [];
                        $.get('/Product/GetStorageSpaceListAll/', function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            mvvm.spaceList = ret.data.list;
                        })
                    }
                    vm.getStorage = function () {
                        mvvm.storageList = [];
                        $.get('/Product/GetStorageList/', function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            mvvm.storageList = ret.data.list;
                        })
                    }


                    vm.storages = 0;//选择仓库
                    vm.storageAllList = [];
                    vm.getStorageAll = function () {
                        mvvm.storageAllList = [];
                        $.get('/Product/GetStorageList/', function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            mvvm.storageAllList = ret.data.list;
                        })
                    }

                    vm.selectStorage = function () {
                        var id = $(this).find('option:selected').val()
                        var name = $(this).find('option:selected').text()
                        mvvm.PurchasePutStorageList.forEach(function (item) {
                            item.StorageId = id
                        })

                    }

                    vm.hSN = false;//自动生成序列号
                    vm.bNumber = false;//自动生成批次号
                    vm.watchChecked = function () {
                        //自动生成序列号
                        mvvm.$watch("hSN", function (n) {
                            var count = 0, hval;
                            if (!n) _set();
                            else {
                                $.get('/Product/GetModelTypeID', { 'Name': 'XLH', 'typeName': 'PurchasePutStorageSN' }, function (ret) {
                                    if (ret.result) {
                                        hval = ret.message;
                                        _set();
                                    }
                                })
                            }
                            function _set() {
                                mvvm.PurchasePutStorageList.forEach(function (item) {
                                    count++
                                    item.SN = n ? (hval + "" + count) : "";
                                    item.HasSN = n;
                                })
                            }
                        });
                        //自动生成批次号
                        mvvm.$watch("bNumber", function (n) {
                            var bval = ''
                            if (n) {
                                $.get('/Product/GetModelTypeID', { 'Name': 'PCH', 'typeName': 'PurchasePutStoragePC' }, function (ret) {
                                    if (ret.result) {
                                        bval = ret.message
                                        _set();
                                    }
                                })
                            } else _set();
                            function _set() {
                                mvvm.PurchasePutStorageList.forEach(function (item) {
                                    item.BatchNumber = bval
                                })
                            }
                        });
                    }

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

                    //删除ok
                    vm.dodel = function (item) {
                        var index = parseInt($(this).attr('index'));
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/Product/PurchasePutStorageDelete/' + item.Id, {}, function (ret) {
                                if (ret.result)
                                    mvvm.loadData(mvvm.createQuery());
                                messageBox.succeed(ret.message);
                            })
                        });
                    }
                    //批量删除ok
                    vm.doalldel = function () {
                        var ids = mvvm.grid1.getCheckedIds("deleteIds");
                        if (ids.length == 0) {
                            messageBox.error("请选择数据！");
                            return;
                        }
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/Product/PurchasePutStorageAllDelete/', ids, function (ret) {
                                CBCRM.showResult(ret);
                                if (ret.result) mvvm.loadData();
                            })
                        });
                    }

                    //删除明细
                    vm.remove = function (index) {
                        mvvm.PurchasePutStorageList.removeAt(index)
                    }
                    vm.paymet = function (oid) {
                        $.post("/Product/PurchaseOrderUpdateByPutStorage/" + oid, function (ret) {
                            if (ret.result) {
                                mvvm.loadData(mvvm.createQuery());
                            }
                        });
                    }

                })
                mvvm.watchChecked();
                mvvm.grid1.init();
                mvvm.cgrid.init();
                InitDictionary()
                function InitDictionary() {
                    $.get('/Product/GetProductDictionary/', {}, function (ret) {
                        mvvm.units = ret.data.unitsList;

                    })
                }
                
                mvvm.getStorage();
                mvvm.getSpace();
                mvvm.getStorageAll();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            }
            //订单选择
            , PurchaseOrderSelect: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this, mvvm, init = false, vmid = "PurchaseOrderSelect";
                CBCRM = avalon.vmodels.CBCRM
                mvvm = CBCRM.define(vmid, function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.loading = true;
                    vm.key = "";
                    vm.toEnter = function (e) {
                        if (e.keyCode == 13) mvvm.toSearch();
                    }
                    vm.toSearch = function () {
                        mvvm.addQuery("key", mvvm.key);
                    }
                    vm.listOpts = { //列表分页组件
                        pagesizeopts: [20, 30, 40, 50],
                        pagesize: 20,
                        paging: function () {
                            var m = mvvm, data = m.createQuery();
                            data.pageIndex = (this.currentindex + 1) || 1
                            data.pageSize = this.pagesize
                            m.loadData(data)
                        }
                    }
                    vm.grid1 = createGrid({});
                    initQuerys(vm, function (data) {
                        mvvm.loadData(data);
                    })
                    vm.queryData = {
                        key: { label: "关键词", val: "" },
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Product/PurchaseOrder', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                if (ret.data.Source) {
                                    mvvm.grid1.initList(ret.data.Source, ret.data.RecordTotal);
                                }
                                avalon.vmodels[vmid + "Page"].total = mvvm.grid1.total;
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                }, true);
                mvvm.grid1.init()
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            }
            ///采购退款
            , ReturnedPurchase: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this
                var Mvvm = avalon.define('returnedpurchases', function (vm) {
                    //新增
                    vm.doadd = function () {
                        //Mvvm.entity = modelFactory.create('Purchase')

                        Mvvm.formSubmit("新增采购付款")
                    }
                    //编辑
                    vm.doedit = function () {
                        var id = $(this).val()
                        Mvvm.purchaseList.$model.forEach(function (item) {
                            if (item.Id == id) {
                                Mvvm.entity = item
                            }
                        })
                        Mvvm.formSubmit("编辑采购付款")
                    }
                    //查看
                    vm.doview = function () {
                        var id = $(this).val()
                        Mvvm.purchaseList.$model.forEach(function (item) {
                            if (item.Id == id) {
                                Mvvm.entity = item
                            }
                        })

                        var dialog = messageBox.openHtml('采购付款查看详细', '800px', '300px', '');
                        var content = $(dialog.content())
                        content.attr('ms-include', 'viewTemplate')
                        avalon.scan(content[0], Mvvm)

                    }
                    //删除
                    vm.dodel = function () {
                        var index = parseInt($(this).attr('index'));
                        var id = $(this).val();
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/Product/PurchaseDel/' + id, {}, function (ret) {
                                if (ret.result)
                                    Mvvm.purchaseList.removeAt(index);
                                messageBox.succeed(ret.message);
                            })
                        });
                    }
                    //批量删除
                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.post('/Product/PurchaseAllDel/', deleteIds, function (ret) {
                                if (ret.result) {
                                    getPurchaseList(queryData);
                                    messageBox.succeed(ret.message);
                                }
                            });
                        });
                    }
                    //保存
                    vm.formSubmit = function (title) {
                        var dialog = messageBox.openHtml(title, '930px', '400px', '', [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var model = Mvvm.entity.$model;
                                var url = (model.Id == 0 ? "/Product/PurchaseAdd/" : "/Product/PurchaseUpdate/");
                                $.post(url + model.Id, model, function (ret) {
                                    if (ret.result) {
                                        messageBox.ok(ret.message, function () { getPurchaseList(queryData); messageBox.close(); });
                                    }
                                    else {
                                        messageBox.fail(ret.message, function () { });
                                    }
                                })

                                return false;
                            }
                        }], function () {
                            //avalon.vmodels.porobeFeedbackPersonTree.destroy();
                            //avalon.vmodels.probeFeedbackshareToTree.destroy();
                        });

                        var content = $(dialog.content())
                        content.attr('ms-include', 'formTemplate')
                        avalon.scan(content[0], Mvvm)
                    }
                })
                require('commonui', function () {
                    CBCRM.fillContent(tmpl, lang, contentId, module, Mvvm)
                })

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

            }
            //采购退货
            , PurchaseReturned: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this, vmid = this.vmid = "PurchaseReturned";
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.lang = lang
                    vm.ADD = true;
                    vm.EDIT = true;
                    vm.DELETE = true;
                    vm.list = [];
                    vm.outlist = [];
                    vm.nowStorageIn = [];
                    vm.entity = {};
                    vm.centity = {};
                    vm.tab = "tab1";
                    vm.tabWidth = 1000;
                    vm.rWidth = $(window).width() - 205;
                    vm.tabChange = function (tab) {
                        mvvm.tab = tab;
                    }
                    vm.showindex = -1;
                    vm.showmore = function (index) {
                        mvvm.showindex = index == mvvm.showindex ? -1 : index;
                    }
                    initQuerys(vm, function (data, name, val, type) {
                        if ((name == "Ids" && type == "remove") || type == "clear") {
                            mvvm.selectFirstTreeNode();
                        }
                        mvvm.grid1.loadData(data);
                    });
                    vm.queryData = {
                        keyword: {
                            label: "关键词：", val: "", valLabel: ""
                        },
                        Ids: {
                            label: "仓库", val: "", valLabel: ""
                        },
                        starttime: {
                            label: "开始时间", val: "", valLabel: ""
                        },
                        endtime: {
                            label: "结束时间", val: "", valLabel: ""
                        }
                    }
                    vm.grid1 = createGrid({
                        entityId: "StorageOutAndInBill",
                        modelFactory: modelFactory,
                        url: "/Product/" + vmid,
                        pageid: vmid + "_grid1_page",
                        createQuery: vm.createQuery,
                        onRemove: function (ids) {
                            mvvm.dodel(ids);
                        }
                    });
                    //时间范围配置
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.addQuery("starttime", formatDate, "起始：" + formatDate);
                        }
                    }
                    vm.dateOpts2 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.addQuery("endtime", formatDate, "截止：" + formatDate);
                        }
                    }
                    //分类树
                    vm.storageTypeTreeOpts = {
                        treeopts: {
                            async: {
                                url: ""
                            },
                            data: {
                                keep: {
                                    parent: true
                                },
                                simpleData: {
                                    enable: true,
                                    idKey: 'Id'
                                },
                                key: {
                                    name: 'Name'
                                }
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    var id = treeNode.Id;
                                    if (id > 1) {
                                        if (treeNode.Ids) {
                                            mvvm.addQuery("Ids", treeNode.Ids, treeNode.Name);
                                        } else {
                                            mvvm.addQuery("Ids", treeNode.Id, treeNode.Name);
                                        }
                                    } else {
                                        mvvm.addQuery("Ids", "");
                                    }
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            },
                            url: false
                        }
                    }
                    vm.setTreeData = function () {
                        var atree = avalon.vmodels.storageTypeTree;
                        if (atree) {
                            var rows = [{ Id: 1, Name: "全部分类", open: true, checked: true }];
                            rows = rows.concat(mvvm.types.$model);
                            $.each(rows, function (i) {
                                if (i == 0) return;
                                this.pId = 1;
                            });
                            atree.datasource = rows;
                            mvvm.selectFirstTreeNode();
                        }
                    }
                    vm.selectFirstTreeNode = function () {
                        var tree = $.fn.zTree.getZTreeObj("storageTypeTree");
                        var nodes = tree.getNodes();
                        if (nodes.length > 0) {
                            tree.selectNode(nodes[0]);
                        }
                    };

                    vm.selectActionBy = function () {
                        plugins.selectUser({
                            dataAuth: 5055000,
                            callback: function (us) {
                                var u = us[0];
                                var actionBy = mvvm.entity.ActionBy
                                actionBy.Id = u.Id
                                actionBy.FullName = u.FullName
                                mvvm.entity.ActionByGroup = u.GroupName
                            }
                        })
                    }
                    //关键字搜索
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.addQuery("keyword", mvvm.queryData.keyword.val);
                    }
                    vm.clear = function () {
                        mvvm.clearQuery();
                    }

                    //查看详情
                    vm.doview = function (id) {
                        mvvm.grid1.getEntity(id, function (entity) {
                            entity.Total = 0;
                            mvvm.entity = entity;
                            mvvm.getOutList(entity.Id);
                            openTmpl({ vm: mvvm, title: "查看采购退货单", w: mvvm.rWidth, tmplid: "viewTemplate", tmpl: tmpl });
                        });
                    }
                    //新增
                    vm.doadd = function () {
                        mvvm.grid1.getEntity("", function (entity) {
                            entity.Toital = 0;
                            var u = CBCRM.memberShip.$model
                            extendValue(entity.ActionBy, u);
                            extendValue(entity.AddBy, u);
                            entity.ActionByGroup = u.Group;
                            entity.ActionTime = entity.ActionTime.substring(0, 10);
                            mvvm.entity = entity;
                            mvvm.outlist = [];
                            mvvm.getOutSum();
                            mvvm.showForm("新增采购退货单");
                        });
                    }
                    vm.doedit = function (id) {
                        mvvm.grid1.getEntity(id, function (entity) {
                            //暂时不做出库单修改
                            //entity.Total = 0;
                            //mvvm.entity = entity;
                            //mvvm.getOutList(entity.Id);
                            //mvvm.showForm("编辑采购退货单");
                        });
                    }
                    vm.dodel = function (ids) {
                        $.post("/Product/" + vmid + "Del", ids, function (ret) {
                            CBCRM.showResult(ret);
                            if (ret.result) {
                                mvvm.grid1.reloadData();
                            }
                        });
                    }
                    vm.showForm = function (title) {
                        var btns = [
                            {
                                name: "提交",
                                focus: true,
                                callback: function () {
                                    if (mvvm.outlist.length == 0) {
                                        messasgeBox.error("保存失败！<br />出库明细记录不能为空！");
                                        return false;
                                    }
                                    var m = $.extend(true, {}, mvvm.entity.$model);
                                    $.extend(m, jsonToSubmit("list", mvvm.outlist));
                                    $.extend(m, jsonToSubmit("ActionBy", m.ActionBy));
                                    delete m.AddBy;
                                    delete m.ActionBy;
                                    var url = m.Id ? "/Product/" + vmid + "Edit/" + m.Id : "/Product/" + vmid + "Add";
                                    $.post(url, m, function (ret) {
                                        CBCRM.showResult(ret);
                                        if (ret.result) {
                                            mvvm.grid1.reloadData();
                                            if (dialog) dialog.close();
                                        }
                                    });
                                    return false;
                                }
                            }
                        ]
                        var dialog = mvvm.openTmpl({
                            title: title, w: mvvm.rWidth, h: 400,
                            tmplid: "formTemplate", tmpl: tmpl,
                            btns: btns,
                            onclose: function () {
                                destroyui(["actionByTree"]);
                            }
                        });
                    }
                    vm.getOutList = function (billId) {
                        mvvm.outlist = [];
                        mvvm.getOutSum();
                        $.get("/Product/ProductStorageOutList/", { "type": "采购退货", billId: billId }, function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            var list = ret.data;
                            if (list) {
                                mvvm.outlist = list;
                                mvvm.getOutSum();
                            }
                        });
                    }
                    vm.removeOutList = function (index) {
                        mvvm.outlist.removeAt(index);
                    }
                    vm.fromNoEnter = function (e) {
                        if (e.keyCode == 13) mvvm.selectContract();
                    }
                    vm.watchItem = function (item) {
                        function _watchPrice() {
                            item.Money = item.Price && item.Number ? parseFloat(item.Price, 10) * parseFloat(item.Number, 10) : 0;
                            if (item.DiscountRate) {
                                item.DiscountMoney = parseFloat(item.DiscountRate, 10) / 100 * item.Money;
                                item.Money -= item.DiscountMoney;
                            } else {
                                item.DiscountMoney = 0;
                            }
                            if (item.TaxRate) {
                                item.TaxMoney = parseFloat(item.TaxRate, 10) / 100 * item.Money;
                            } else {
                                item.TaxMoney = 0;
                            }
                            item.TotalMony = item.Money + item.TaxMoney;
                            item.DiscountMoney = item.DiscountMoney.toFixed(2)
                            item.Money = item.Money.toFixed(2)
                            item.TaxMoney = item.TaxMoney.toFixed(2)
                            item.TotalMoney = item.TotalMony.toFixed(2)
                            mvvm.getOutSum();
                        }
                        ["Number"].forEach(function (p) {
                            item.$watch(p, _watchPrice);
                        })
                        item.$watch("Number", function (n) {
                            if (!n) return;
                            n = parseFloat(n, 10);
                            var m = parseFloat(item.InventoryNumber, 10);
                            if (n > m) {
                                messageBox.warning("超过了库存最大数量，强制改为最大值：" + m);
                                item.Number = m;
                            }
                        });
                        item.$watch("ProductionTime", function (n) {
                            if (n && item.ValidDay) {
                                try {
                                    var d = new Date(n), d2 = new Date(d.valueOf() + item.ValidDay * 24 * 60 * 60 * 1000)
                                    var a = [d2.getFullYear(), d2.getMonth() + 1, d2.getDate()]
                                    a[1] = a[1] < 9 ? "0" + a[1] : a[1];
                                    a[2] = a[2] < 9 ? "0" + a[2] : a[2];
                                    item.ValidDate = a.join("-")
                                } catch (ex) {
                                    item.ValidDate = ""
                                }
                            } else {
                                item.ValidDate = ""
                            }
                        })
                    }
                    //选择合同
                    vm.cgrid = createGrid({
                        url: "/Product/PurchaseOrder/",
                        createQuery: function () {
                            return { 'keyword': mvvm.contractKey, pageSize: "10" }
                        },
                        onDblClick: function (index, item) {
                            item.checked = true;
                        }
                    });
                    vm.contractKey = ''
                    vm.selectContract = function () {
                        mvvm.contractKey = mvvm.entity.FromNo;
                        var btns = [{
                            name: '确定',
                            focus: true,
                            callback: function () {
                                var clist = mvvm.cgrid.getChecked();
                                if (clist.length == 0) {
                                    messageBox.warning('请选择采购订单')
                                } else {
                                    var dlist = mvvm.contractdetailslist;
                                    if (dlist.length == 0) {
                                        messageBox.warning("无业务明细，如果正在加载，请稍后！");
                                        return false;
                                    }
                                    var d = findArr(dlist, function (item) { return item.InventoryNumber > 0 });
                                    if (d == null) {
                                        messageBox.warning("此订单产品已经没有库存！");
                                        return false;
                                    }
                                    var centity = clist[0].$model;
                                    var entity = mvvm.entity;
                                    entity.FromNo = centity.BillNo;
                                    entity.FromId = centity.Id;
                                    mvvm.centity = centity;
                                    mvvm.getOutListByInlist();
                                    if (dialog) dialog.close()
                                }
                                return false;
                            }
                        }];
                        var dialog = mvvm.openTmpl({
                             title: "选择采购订单", w: mvvm.rWidth,padding:"10px",
                            tmplid: "ContractListTemplate", tmpl: tmpl,
                            btns: btns, extParam: { top: 20 }
                        });
                        mvvm.cgrid.clear();
                        mvvm.cgrid.doSearch(mvvm.watchCgrid);
                    }
                    vm.searchContract = function () {
                        mvvm.cgrid.clear();
                        mvvm.contractdetailslist = [];
                        mvvm.cgrid.doSearch(mvvm.watchCgrid);
                    }
                    vm.keyEnter = function (e) {
                        if (e.keyCode == 13) mvvm.searchContract();
                    }
                    vm.watchCgrid = function () {
                        var list = mvvm.cgrid.list;
                        list.forEach(function (item) {
                            item.$watch("checked", function (n) {
                                if (!n) return;
                                list.forEach(function (c) {
                                    if (c.Id != item.Id) c.checked = false;
                                })
                                mvvm.getDetailslist(item.Id);
                            });
                        })
                        if (list.length > 0) list[0].checked = true;
                    }
                    vm.getOutListByInlist = function () {
                        $.post('/Product/GetReturnOutListByInlist/', { "id": mvvm.entity.FromId }, function (ret) {
                            if (ret.result) {
                                mvvm.outlist = ret.data;
                                mvvm.outlist.forEach(function (item) {
                                    mvvm.watchItem(item);
                                });
                                mvvm.getOutSum();
                            }
                        })
                    }
                    //合同的业务明细
                    vm.contractdetailslist = [];
                    vm.getDetailslist = function (id) {
                        mvvm.contractdetailslist = [];
                        $.get('/Product/ProductStorageInList/', { "fromId": id, type: "采购入库" }, function (ret) {
                            mvvm.contractdetailslist = ret.data
                        })
                    }
                    vm.getOutSum = function () {
                        var total = 0, totalMoney = 0;
                        mvvm.outlist.forEach(function (item) {
                            total += parseFloat(item.Number, 10);
                            totalMoney += parseFloat(item.TotalMony, 10);
                        });
                        var m = mvvm.entity;
                        m.Total = total;
                        m.TotalMoney = totalMoney;
                    }
                    //仓库列表
                    vm.types = [];
                    vm.$dicts = { types: 100112 };
                    vm.getDicts = function () {
                        $.post("/Product/ProductStorageGetTree/", null, function (ret) {
                            if (ret.result) {
                                vm.types = ret.data.list;
                                vm.setTreeData();
                            }
                        });
                    }
                    vm.destroy = function () {
                        mvvm.grid1.destroy();
                        mvvm.cgrid.destroy();
                        avalon.vmodels[vmid] = null
                    }
                })
                mvvm.grid1.init();
                mvvm.cgrid.init();
                mvvm.getDicts();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            }
            ///产品库存分布
            , ProductStorageView: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this, mvvm, init = false, vmid = "ProductStorageView";
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define(vmid, function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.loading = true;
                    vm.key = "";
                    vm.storagelist = [];
                    vm.storagecount = 5;
                    vm.toEnter = function (e) {
                        if (e.keyCode == 13) mvvm.toSearch();
                    }
                    vm.toSearch = function () {
                        mvvm.addQuery("keyword", mvvm.key, mvvm.key);
                    }
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm, data = m.createQuery();
                            data.pageIndex = (this.currentindex + 1) || 1
                            data.pageSize = this.pagesize
                            m.loadData(data)
                        }
                    }
                    vm.grid1 = createGrid({});
                    initQuerys(vm, function (data, name, val, type) {
                        mvvm.loadData(data);
                        if (type == "remove" || type == "clear") {
                            switch (name) {
                                case "typeid":
                                    mvvm.unSelectType();
                                    break;
                                case "keyword":
                                    mvvm.key = "";
                                    break;
                            }
                        }
                    })
                    vm.queryData = {
                        keyword: { label: "关键词", val: "", valLabel: "" },
                        typeid: { label: "产品分类", val: "", valLabel: "" },
                        reserve: {
                            label: "库存状况", val: "", valLabel: "",
                            items: [
                                { label: "不限", val: "", curr: true },
                                { label: "无库存", val: "1", curr: false },
                                { label: "有库存", val: "5", curr: false },
                                { label: "<30", val: "2", curr: false },
                                { label: "30-100", val: "3", curr: false },
                                { label: ">100", val: "4", curr: false }
                            ]
                        }
                    }
                    //产品分类树配置
                    vm.pCategoryTreeOpts = {
                        treeopts: {
                            async: {
                                url: ""
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    mvvm.addQuery("typeid", treeNode.Id, treeNode.Name);
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            }
                        }
                    }
                    vm.unSelectType = function () {
                        var tree = avalon.vmodels["pStorageListCategoryTree"];
                        if (tree && tree.$treeObj) {
                            tree.$treeObj.cancelSelectedNode()
                        }
                    }
                    vm.getCategoryList = function () {
                        $.get('/Product/Category/', {}, function (ret) {
                            if (!ret.result) return;
                            ret.data.forEach(function (item) {
                                if (item.Id != 1) item.open = false;
                            });
                            avalon.vmodels.pStorageListCategoryTree.datasource = ret.data;
                        })
                    }
                    //分类树展开、收起
                    vm.$expancategory = false;
                    vm.expanCategory = function () {
                        mvvm.$expancategory = !mvvm.$expancategory;
                        $(this).text(mvvm.$expancategory ? "- 收起" : "+ 展开");
                        var tree = $.fn.zTree.getZTreeObj("storageListCategoryTree");
                        if (tree) {
                            var nodes = tree.getNodes();
                            if (nodes.length > 0) tree.expandNode(nodes[0], mvvm.$expancategory, true);
                            //收起的时候让根节点处于展开状态
                            if (!mvvm.$expancategory) tree.expandNode(nodes[0], !mvvm.$expancategory, false);
                        }
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Product/ProductStorageView', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.data) {
                                if (ret.data.storageinfo) {
                                    mvvm.grid1.initList(ret.data.storageinfo, ret.data.RecordTotal);
                                }

                                if (ret.data.storagelist) {
                                    mvvm.storagelist = ret.data.storagelist;
                                }
                                if (ret.data.storagecount) {
                                    mvvm.storagecount = ret.data.storagecount;
                                }
                                avalon.vmodels[vmid + "ListPage"].total = ret.data.RecordTotal;
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.reloadData = function () {
                        var m = mvvm, data = m.createQuery(), page = avalon.vmodels[vmid + "Page"];
                        if (page) {
                            data.pageIndex = page.currentindex
                            data.pageSize = page.pagesize
                        }
                        m.loadData(data)
                    }
                    vm.$initDialog = null;
                    vm.closeInitDialog = function () {
                        if (mvvm.$initDialog) {
                            mvvm.$initDialog.close();
                            mvvm.$initDialog = null;
                        }
                    }
                })
                mvvm.grid1.bindWatch()
                mvvm.getCategoryList()
                function destroy() {
                    destroyui(["pStorageListCategoryTree"])
                    avalon.vmodels[vmid] = null;
                }
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                CBCRM.onLoadModuleBefore = function (data) {
                    destroy();
                }
            }
            //销售出库
            , ProductStorageSalesOut: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this, meun, vmid = this.vmid = "ProductStorageSalesOut";
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.lang = lang
                    vm.ADD = true;
                    vm.EDIT = true;
                    vm.DELETE = true;
                    vm.list = [];
                    vm.outlist = [];
                    vm.nowStorageIn = [];
                    vm.entity = {};
                    vm.centity = {};
                    vm.tab = "tab1";
                    vm.tabWidth = 1000;
                    vm.rWidth = $(window).width() - 205;
                    vm.tabChange = function (tab) {
                        mvvm.tab = tab;
                    }
                    vm.showindex = -1;
                    vm.showmore = function (index) {
                        mvvm.showindex = index == mvvm.showindex ? -1 : index;
                    }
                    initQuerys(vm, function (data, name, val, type) {
                        if ((name == "Ids" && type == "remove") || type == "clear") {
                            mvvm.selectFirstTreeNode();
                        }
                        mvvm.grid1.loadData(data);
                    });
                    vm.queryData = {
                        keyword: {
                            label: "关键词：", val: "", valLabel: ""
                        },
                        Ids: {
                            label: "仓库", val: "", valLabel: ""
                        },
                        starttime: {
                            label: "开始时间", val: "", valLabel: ""
                        },
                        endtime: {
                            label: "结束时间", val: "", valLabel: ""
                        }
                    }
                    vm.grid1 = createGrid({
                        entityId: "StorageOutAndInBill",
                        modelFactory: modelFactory,
                        url: "/Product/" + vmid,
                        pageid: vmid + "_grid1_page",
                        createQuery: vm.createQuery,
                        onRemove: function (ids) {
                            mvvm.dodel(ids);
                        }
                    });
                    vm.pageOps = vm.grid1.$pageOps;
                    //时间范围配置
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.addQuery("starttime", formatDate, "起始：" + formatDate);
                        }
                    }
                    vm.dateOpts2 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.addQuery("endtime", formatDate, "截止：" + formatDate);
                        }
                    }
                    //分类树
                    vm.storageTypeTreeOpts = {
                        treeopts: {
                            async: {
                                url: ""
                            },
                            data: {
                                keep: {
                                    parent: true
                                },
                                simpleData: {
                                    enable: true,
                                    idKey: 'Id'
                                },
                                key: {
                                    name: 'Name'
                                }
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    var id = treeNode.Id;
                                    if (id > 1) {
                                        if (treeNode.Ids) {
                                            mvvm.addQuery("Ids", treeNode.Ids, treeNode.Name);
                                        } else {
                                            mvvm.addQuery("Ids", treeNode.Id, treeNode.Name);
                                        }
                                    } else {
                                        mvvm.addQuery("Ids", "");
                                    }
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            },
                            url: false
                        }
                    }
                    vm.setTreeData = function () {
                        var atree = avalon.vmodels.storageTypeTree;
                        if (atree) {
                            var rows = [{ Id: 1, Name: "全部分类", open: true, checked: true }];
                            rows = rows.concat(mvvm.types.$model);
                            $.each(rows, function (i) {
                                if (i == 0) return;
                                this.pId = 1;
                            });
                            atree.datasource = rows;
                            mvvm.selectFirstTreeNode();
                        }
                    }
                    vm.selectFirstTreeNode = function () {
                        var tree = $.fn.zTree.getZTreeObj("storageTypeTree");
                        var nodes = tree.getNodes();
                        if (nodes.length > 0) {
                            tree.selectNode(nodes[0]);
                        }
                    };
                    //经办人
                    vm.selectActionBy = function () {
                        plugins.selectUser({
                            dataAuth: 5069500,
                            callback: function (us) {
                                var u = us[0];
                                var actionBy = mvvm.entity.ActionBy
                                actionBy.Id = u.Id
                                actionBy.FullName = u.FullName
                                mvvm.entity.ActionByGroup = u.GroupName
                            }
                        })
                    }
                    
                    //关键字搜索
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.addQuery("keyword", mvvm.queryData.keyword.val);
                    }
                    vm.clear = function () {
                        mvvm.clearQuery();
                    }

                    //查看详情
                    vm.doview = function (id) {
                        mvvm.showindex = -1;
                        mvvm.grid1.getEntity(id, function (entity) {
                            entity.Total = 0;
                            mvvm.entity = entity;
                            mvvm.getOutList(entity.Id);
                            openTmpl({ vm: mvvm, title: "查看销售出库单", w: mvvm.rWidth, tmplid: "viewTemplate", tmpl: tmpl });
                        });
                    }
                    //新增
                    vm.doadd = function (cb) {
                        mvvm.grid1.getEntity("", function (entity) {
                            entity.Toital = 0;
                            var u = CBCRM.memberShip.$model
                            extendValue(entity.ActionBy, u);
                            extendValue(entity.AddBy, u);
                            entity.ActionByGroup = u.Group;
                            entity.ActionTime = entity.ActionTime.substring(0, 10);
                            mvvm.entity = entity;
                            mvvm.outlist = [];
                            mvvm.getOutSum();
                            mvvm.showForm("新增销售出库单");
                            if (typeof (cb) == "function") cb(mvvm.entity);
                        });
                    }
                    vm.doedit = function (id) {
                        mvvm.grid1.getEntity(id, function (entity) {
                            //暂时不做出库单修改
                            //entity.Total = 0;
                            //mvvm.entity = entity;
                            //mvvm.getOutList(entity.Id);
                            //mvvm.showForm("编辑销售出库单");
                        });
                    }
                    vm.dodel = function (ids) {
                        $.post("/Product/" + vmid + "Del", ids, function (ret) {
                            CBCRM.showResult(ret);
                            if (ret.result) {
                                mvvm.grid1.reloadData();
                            }
                        });
                    }
                    vm.showForm = function (title) {
                        mvvm.showindex = -1;
                        var btns = [
                            {
                                name: "提交",
                                focus: true,
                                callback: function () {
                                    if (mvvm.outlist.length == 0) {
                                        messasgeBox.error("保存失败！<br />出库明细记录不能为空！");
                                        return false;
                                    }
                                    var m = $.extend(true, {}, mvvm.entity.$model);
                                    $.extend(m, jsonToSubmit("list", mvvm.outlist));
                                    $.extend(m, jsonToSubmit("ActionBy", m.ActionBy));
                                    delete m.AddBy;
                                    delete m.ActionBy;
                                    var url = m.Id ? "/Product/" + vmid + "Edit/" + m.Id : "/Product/" + vmid + "Add";
                                    $.post(url, m, function (ret) {
                                        CBCRM.showResult(ret);
                                        if (ret.result) {
                                            mvvm.grid1.reloadData();
                                            if (dialog) dialog.close();
                                        }
                                    });
                                    return false;
                                }
                            }
                        ]
                        var dialog = openTmpl({
                            vm: mvvm, title: title, w: mvvm.rWidth, h: 400,
                            tmplid: "formTemplate", tmpl: tmpl, btns: btns,
                            onclose: function () {
                                destroyui(["actionByTree"]);
                                if (action == "add") {
                                    var fromvm = avalon.vmodels.marketingcontract;
                                    if (fromvm)
                                        fromvm.GetContractRelevanceList(mvvm.entity.FromId);
                                }
                            }
                        });
                    }
                    vm.getOutList = function (billId) {
                        mvvm.outlist = [];
                        mvvm.getOutSum();
                        $.get("/Product/ProductStorageOutList/", { "type": "销售出库", billId: billId }, function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            var list = ret.data;
                            if (list) {
                                mvvm.outlist = list;
                                mvvm.getOutSum();
                            }
                        });
                    }
                    vm.removeOutList = function (index) {
                        mvvm.outlist.removeAt(index);
                    }
                    vm.fromNoEnter = function (e) {
                        if (e.keyCode == 13) mvvm.selectContract();
                    }
                    vm.watchItem = function (item) {
                        function _watchPrice() {
                            item.Money = item.Price && item.Number ? parseFloat(item.Price, 10) * parseFloat(item.Number, 10) : 0;
                            if (item.DiscountRate) {
                                item.DiscountMoney = parseFloat(item.DiscountRate, 10) / 100 * item.Money;
                                item.Money -= item.DiscountMoney;
                            } else {
                                item.DiscountMoney = 0;
                            }
                            if (item.TaxRate) {
                                item.TaxMoney = parseFloat(item.TaxRate, 10) / 100 * item.Money;
                            } else {
                                item.TaxMoney = 0;
                            }
                            item.TotalMony = item.Money + item.TaxMoney;
                            item.DiscountMoney = item.DiscountMoney.toFixed(2)
                            item.Money = item.Money.toFixed(2)
                            item.TaxMoney = item.TaxMoney.toFixed(2)
                            item.TotalMoney = item.TotalMony.toFixed(2)
                            mvvm.getOutSum();
                        }
                        ["Number"].forEach(function (p) {
                            item.$watch(p, _watchPrice);
                        })
                        item.$watch("Number", function (n) {
                            if (!n) return;
                            n = parseFloat(n, 10);
                            var m = parseFloat(item.InventoryNumber, 10);
                            if (n > m) {
                                messageBox.warning("超过了库存最大数量，强制改为最大值：" + m);
                                item.Number = m;
                            }
                        });
                        item.$watch("ProductionTime", function (n) {
                            if (n && item.ValidDay) {
                                try {
                                    var d = new Date(n), d2 = new Date(d.valueOf() + item.ValidDay * 24 * 60 * 60 * 1000)
                                    var a = [d2.getFullYear(), d2.getMonth() + 1, d2.getDate()]
                                    a[1] = a[1] < 9 ? "0" + a[1] : a[1];
                                    a[2] = a[2] < 9 ? "0" + a[2] : a[2];
                                    item.ValidDate = a.join("-")
                                } catch (ex) {
                                    item.ValidDate = ""
                                }
                            } else {
                                item.ValidDate = ""
                            }
                        })
                    }
                    //选择合同
                    vm.cgrid = createGrid({
                        url: "/Market/Contract/",
                        createQuery: function () {
                            return { 'key': mvvm.contractKey, pageSize: "10" }
                        },
                        onDblClick: function (index, item) {
                            item.checked = true;
                        }
                    });
                    vm.contractKey = ''
                    vm.selectContract = function () {
                        mvvm.showindex = -1;
                        mvvm.contractKey = mvvm.entity.FromNo;
                        var btns = [{
                            name: '确定',
                            focus: true,
                            callback: function () {
                                var clist = mvvm.cgrid.getChecked();
                                if (clist.length == 0) {
                                    messageBox.warning('请选择合同订单')
                                } else {
                                    var dlist = mvvm.contractdetailslist;
                                    if (dlist.length == 0) {
                                        messageBox.warning("无业务明细，如果正在加载，请稍后！");
                                        return false;
                                    }
                                    var d = findArr(dlist, function (item) { return item.Num > item.OutNum });
                                    if (d == null) {
                                        messageBox.warning("此订单已经全部出库！");
                                        return false;
                                    }
                                    var centity = clist[0].$model;
                                    var entity = mvvm.entity;
                                    entity.FromNo = centity.ContractNum;
                                    entity.FromId = centity.Id;
                                    mvvm.centity = centity;
                                    mvvm.getOutListByInlist();
                                    if (dialog) dialog.close()
                                    mvvm.showindex = -1;
                                }
                                return false;
                            }
                        }];
                        var dialog = mvvm.openTmpl({
                            title: "选择合同业务", w: mvvm.rWidth,padding:"10px",
                            tmplid: "ContractListTemplate", tmpl: tmpl,
                            btns: btns, extParam: { top: 20 }
                        });
                        mvvm.cgrid.clear();
                        mvvm.cgrid.doSearch(mvvm.watchCgrid);
                    }
                    vm.searchContract = function () {
                        mvvm.cgrid.clear();
                        mvvm.contractdetailslist = [];
                        mvvm.cgrid.doSearch(mvvm.watchCgrid);
                    }
                    vm.keyEnter = function (e) {
                        if (e.keyCode == 13) mvvm.searchContract();
                    }
                    vm.watchCgrid = function () {
                        var list = mvvm.cgrid.list;
                        list.forEach(function (item) {
                            item.$watch("checked", function (n) {
                                if (!n) return;
                                list.forEach(function (c) {
                                    if (c.Id != item.Id) c.checked = false;
                                })
                                mvvm.getDetailslist(item.Id);
                            });
                        })
                        if (list.length > 0) list[0].checked = true;
                    }
                    vm.getOutListByInlist = function () {
                        $.post('/Product/GetOutListByInlist/', { "id": mvvm.entity.FromId }, function (ret) {
                            if (ret.result) {
                                mvvm.outlist = ret.data;
                                mvvm.outlist.forEach(function (item) {
                                    mvvm.watchItem(item);
                                });
                                mvvm.getOutSum();
                            }
                        })
                    }
                    //合同的业务明细
                    vm.contractdetailslist = [];
                    vm.getDetailslist = function (id) {
                        mvvm.contractdetailslist = [];
                        $.get('/Market/GetContractRelevance/', { "Id": id }, function (ret) {
                            mvvm.contractdetailslist = ret.data.contractDetailsList
                        })
                    }
                    vm.getOutSum = function () {
                        var total = 0, totalMoney = 0;
                        mvvm.outlist.forEach(function (item) {
                            total += parseFloat(item.Number, 10);
                            totalMoney += parseFloat(item.TotalMony, 10);
                        });
                        var m = mvvm.entity;
                        m.Total = total;
                        m.TotalMoney = totalMoney;
                    }
                    //仓库列表
                    vm.types = [];
                    vm.$dicts = { types: 100112 };
                    vm.getDicts = function () {
                        $.post("/Product/ProductStorageGetTree/", null, function (ret) {
                            if (ret.result) {
                                vm.types = ret.data.list;
                                vm.setTreeData();
                            }
                        });
                    }
                    vm.destroy = function () {
                        mvvm.grid1.destroy();
                        mvvm.cgrid.destroy();
                    }
                })
                var action = this.params.action, paramid = this.params.id;
                mvvm.grid1.init();
                mvvm.cgrid.init();
                mvvm.getDicts();
                switch (action) {
                    case "add":
                        mvvm.doadd(function (entity) {
                            var a = paramid.split(",");
                            entity.FromId = a[0];
                            if (a.length > 1) entity.FromNo = a[1];
                            mvvm.getOutListByInlist();
                        });
                        break;
                    default:
                        fill();
                        break;
                }
                function fill() {
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                }

            }
            //其它入库
            , ProductStorageOtherIn: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this, vmid = this.vmid = "ProductStorageOtherIn";
                destroy();
                var mvvm = avalon.define(vmid, function (vm) {
                    vm.lang = lang
                    vm.list = [];
                    vm.inlist = [];
                    vm.nowStorageIn = [];
                    vm.entity = {};
                    vm.tab = "tab1";
                    vm.tabWidth = 1000;
                    vm.tabChange = function (tab) {
                        mvvm.tab = tab;
                    }
                    //initGridvm.call(that, vm, vm.list, "Storage", that.path, modelFactory);
                    vm.grid1 = createGrid({
                        listkey: "list",
                        totalkey: "recordTotal",
                        pageid: vmid + "_grid1_page",
                        url: "/Product/ProductStorageOtherIn/",
                        createQuery: function () {
                            return mvvm.createQuery();
                        },
                        onRemove: function (dids, ids) {
                            $.post("/Product/ProductStorageInitDel", { id: ids[0] }, function (ret) {
                                CBCRM.showResult(ret);
                                if (ret.result) mvvm.grid1.reloadData();
                            });
                        },
                        onView: function (entity) {
                            mvvm.nowStorageIn = [];
                            var sinfo = {
                                BillNo: entity.BillNo,
                                ActionTime: entity.ActionTime,
                                Type: entity.Type,
                                StorageName: entity.StorageName,
                                ActionByGroup: entity.ActionByGroup,
                                TotalMoney: entity.TotalMoney,
                                FullName: entity.FullName
                            }
                            mvvm.nowStorageIn.push(sinfo);
                            mvvm.getOutAndIn(entity.Id);
                            openTmpl({ vm: mvvm, title: "查看入库详情", w: mvvm.tabWidth, tmplid: "viewTemplate", tmpl: tmpl });
                        }
                    })
                    initQuerys(vm, function (data, name, val, type) {
                        if (name == "typeId" && type == "remove") {
                            mvvm.selectFirstTreeNode();
                        }
                        mvvm.grid1.loadData(data);
                    });
                    vm.queryData = {
                        keyword: {
                            label: "关键词：", val: "", valLabel: ""
                        },
                        Ids: {
                            label: "仓库", val: "", valLabel: ""
                        },
                        Type: {
                            label: "入库类型", val: "", valLabel: "",
                            items: []
                        },
                        starttime: {
                            label: "开始时间", val: "", valLabel: ""
                        },
                        endtime: {
                            label: "结束时间", val: "", valLabel: ""
                        }
                    }
                    //分类树
                    vm.storageTypeTreeOpts = {
                        treeopts: {
                            async: {
                                url: ""
                            },
                            data: {
                                keep: {
                                    parent: true
                                },
                                simpleData: {
                                    enable: true,
                                    idKey: 'Id'
                                },
                                key: {
                                    name: 'Name'
                                }
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    var id = treeNode.Id;
                                    if (id > 1) {
                                        if (treeNode.Ids) {
                                            mvvm.addQuery("Ids", treeNode.Ids, treeNode.Name);
                                        } else {
                                            mvvm.addQuery("Ids", treeNode.Id, treeNode.Name);
                                        }
                                    } else {
                                        mvvm.addQuery("Ids", "");
                                    }
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            },
                            url: false
                        }
                    }
                    vm.setTreeData = function () {
                        var atree = avalon.vmodels.storageTypeTree;
                        if (atree) {
                            var rows = [{ Id: 1, Name: "全部分类", open: true, checked: true }];
                            rows = rows.concat(mvvm.types.$model);
                            $.each(rows, function (i) {
                                if (i == 0) return;
                                this.pId = 1;
                            });
                            atree.datasource = rows;
                            mvvm.selectFirstTreeNode();
                        }
                    }
                    vm.selectFirstTreeNode = function () {
                        var tree = $.fn.zTree.getZTreeObj("storageTypeTree");
                        var nodes = tree.getNodes();
                        if (nodes.length > 0) {
                            tree.selectNode(nodes[0]);
                        }
                    };

                    //分类
                    vm.typeList = [];
                    //关键字搜索
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.addQuery("keyword", mvvm.queryData.keyword.val);
                    }

                    vm.getOutAndIn = function (id) {
                        $.get("/Product/ProductStorageOtherInList/", { "id": id }, function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            if (ret.data.list)
                                mvvm.inlist = ret.data.list;
                        });
                    }
                    vm.getTypeList = function (id) {
                        $.get("/Product/StorageInOutType/", { "direcTion": 0 }, function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            if (ret.data.list)
                                mvvm.queryData.Type.items = ret.data.list;
                        });
                    }
                    //仓库列表
                    vm.types = [];
                    vm.$dicts = { types: 100112 };
                    vm.getDicts = function () {
                        $.post("/Product/ProductStorageGetTree/", null, function (ret) {
                            if (ret.result) {
                                vm.types = ret.data.list;
                                vm.setTreeData();
                            }
                        });
                    }
                })
                function destroy() {
                    avalon.vmodels[vmid] = null
                }
                mvvm.grid1.init();
                mvvm.getDicts();
                mvvm.getTypeList();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                CBCRM.onLoadModuleBefore = function (data) {
                    if (data.moduleName == "Upload") return;
                    destroy();
                }
            }
            //其它出库
            , ProductStorageOtherOut: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this, vmid = this.vmid = "ProductStorageOtherOut";
                destroy();
                var mvvm = avalon.define(vmid, function (vm) {
                    vm.lang = lang
                    vm.list = [];
                    vm.inlist = [];
                    vm.nowStorageIn = [];
                    vm.entity = {};
                    vm.tab = "tab1";
                    vm.tabWidth = 1000;
                    vm.tabChange = function (tab) {
                        mvvm.tab = tab;
                    }
                    initGridvm.call(that, vm, vm.list, "Storage", that.path, modelFactory);
                    initQuerys(vm, function (data, name, val, type) {
                        if (name == "typeId" && type == "remove") {
                            mvvm.selectFirstTreeNode();
                        }
                        mvvm.loadData(data);
                    });
                    vm.queryData = {
                        keyword: {
                            label: "关键词：", val: "", valLabel: ""
                        },
                        Ids: {
                            label: "仓库", val: "", valLabel: ""
                        },
                        Type: {
                            label: "入库类型", val: "", valLabel: "",
                            items: []
                        },
                        starttime: {
                            label: "开始时间", val: "", valLabel: ""
                        },
                        endtime: {
                            label: "结束时间", val: "", valLabel: ""
                        }
                    }
                    vm.storagepaing = {
                        paging: function () {
                            var data = mvvm.createQuery();
                            data.pageSize = this.pagesize
                            data.pageIndex = this.currentindex + 1
                            mvvm.loadData(data);
                        }
                    }
                    //分类树
                    vm.storageTypeTreeOpts = {
                        treeopts: {
                            async: {
                                url: ""
                            },
                            data: {
                                keep: {
                                    parent: true
                                },
                                simpleData: {
                                    enable: true,
                                    idKey: 'Id'
                                },
                                key: {
                                    name: 'Name'
                                }
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    var id = treeNode.Id;
                                    if (id > 1) {
                                        if (treeNode.Ids) {
                                            mvvm.addQuery("Ids", treeNode.Ids, treeNode.Name);
                                        } else {
                                            mvvm.addQuery("Ids", treeNode.Id, treeNode.Name);
                                        }
                                    } else {
                                        mvvm.addQuery("Ids", "");
                                    }
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            },
                            url: false
                        }
                    }
                    vm.setTreeData = function () {
                        var atree = avalon.vmodels.storageTypeTree;
                        if (atree) {
                            var rows = [{ Id: 1, Name: "全部分类", open: true, checked: true }];
                            rows = rows.concat(mvvm.types.$model);
                            $.each(rows, function (i) {
                                if (i == 0) return;
                                this.pId = 1;
                            });
                            atree.datasource = rows;
                            mvvm.selectFirstTreeNode();
                        }
                    }
                    vm.selectFirstTreeNode = function () {
                        var tree = $.fn.zTree.getZTreeObj("storageTypeTree");
                        var nodes = tree.getNodes();
                        if (nodes.length > 0) {
                            tree.selectNode(nodes[0]);
                        }
                    };

                    //分类管理
                    vm.typeDeleteids = [];
                    vm.typeList = [];
                    vm.typeManage = function () {
                        mvvm.typeList = [];
                        mvvm.typeDeleteids = [];
                        mvvm.types.$model.forEach(function (item, i) {
                            mvvm.typeList.push(item);
                        });
                        var btns = [{
                            name: "提交保存",
                            focus: true,
                            callback: function () {
                                var data = jsonToSubmit("dicts", mvvm.typeList);
                                if (mvvm.typeDeleteids.length > 0) $.extend(data, jsonToSubmit("deleteIds", mvvm.typeDeleteids));
                                $.post("/Settings/DictionaryListSave/", data, function (ret) {
                                    CBCRM.showResult(ret);
                                    if (ret.result) {
                                        if (dialog) dialog.close();
                                        mvvm.getDicts();
                                    }
                                });
                                return false;
                            }
                        }];
                        var dialog = openTmpl({
                            title: "分类管理",
                            vm: mvvm,
                            tmplid: "typeTmpl",
                            tmpl: tmpl,
                            btns: btns
                        });
                    }
                    vm.addType = function () {
                        var entity = $.extend(true, {}, modelFactory.create("Dictionary"));
                        entity.DictionaryId = mvvm.$dicts.types;
                        var arr = mvvm.types
                        if (entity.Name == null) entity.Name = entity.Data;
                        entity.Sort = arr.length == 0 ? 1 : parseInt(arr[arr.length - 1].Sort, 10) + 1;
                        mvvm.typeList.push(entity);
                    }
                    //移除分类
                    vm.removeType = function (index) {
                        var item = mvvm.typeList[index];
                        if (!item.Id) mvvm.typeList.removeAt(index);
                        else {
                            $.post("/Product/ProductStorageCheckType/", { typeId: item.Id }, function (ret) {
                                if (!ret.result) return CBCRM.showResult(ret);
                                mvvm.typeList.removeAt(index);
                                mvvm.typeDeleteids.push(item.Id);
                            });
                        }
                    }
                    //读取数据
                    vm.loadData = function (data) {
                        $.post(that.path, data, function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            var list = ret.data.list;
                            mvvm.list = mvvm.initChecked(list);
                            var page = avalon.vmodels.storagepage;
                            if (page) page.total = ret.data.recordTotal;
                        })
                    }
                    vm.reloadData = function () {
                        mvvm.storagepaing.currentindex -= 1;
                        mvvm.storagepaing.paging();
                    }
                    //关键字搜索
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.addQuery("keyword", mvvm.queryData.keyword.val);
                    }
                    vm.clear = function () {
                        mvvm.queryData.keyword.val = '';
                        mvvm.queryData.Id.val = '';
                        mvvm.queryData.Ids.val = '';
                        mvvm.queryData.starttime.val = '';
                        mvvm.queryData.endtime.val = '';
                        mvvm.addQuery("keyword", mvvm.queryData.keyword.val);
                    }

                    //查看详情
                    vm.doview = function (id) {
                        mvvm.getEntity(id, function (entity) {
                            mvvm.nowStorageIn = [];
                            var sinfo = {
                                BillNo: entity.BillNo,
                                ActionTime: entity.ActionTime,
                                Type: entity.Type,
                                StorageName: entity.StorageName,
                                ActionByGroup: entity.ActionByGroup,
                                TotalMoney: entity.TotalMoney,
                                FullName: entity.FullName
                            }
                            mvvm.nowStorageIn.push(sinfo);
                            mvvm.getOutAndIn(entity.Id);
                            var htmltmpl = $(tmpl).find("#viewTemplate").text();
                            openTmpl({ vm: mvvm, title: "查看出库详情", w: mvvm.tabWidth, tmplid: htmltmpl, iscontent: true });
                        });
                    }
                    vm.getOutAndIn = function (id) {
                        $.get("/Product/ProductStorageOtherInList/", { "id": id }, function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            if (ret.data.list)
                                mvvm.inlist = ret.data.list;
                        });
                    }
                    vm.getTypeList = function (id) {
                        $.get("/Product/StorageInOutType/", { "direcTion": 1 }, function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            if (ret.data.list)
                                mvvm.queryData.Type.items = ret.data.list;
                        });
                    }
                    //仓库列表
                    vm.types = [];
                    vm.$dicts = { types: 100112 };
                    vm.getDicts = function () {
                        $.post("/Product/ProductStorageGetTree/", null, function (ret) {
                            if (ret.result) {
                                vm.types = ret.data.list;
                                vm.setTreeData();
                            }
                        });
                    }
                })
                function destroy() {
                    avalon.vmodels[vmid] = null
                }
                mvvm.getDicts();
                mvvm.getTypeList();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                CBCRM.onLoadModuleBefore = function (data) {
                    if (data.moduleName == "Upload") return;
                    destroy();
                }
            }
            //库存上限报警
            , ProductStorageMaxWarn: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this, mvvm, init = false, vmid = "ProductStorageMaxWarn";
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define(vmid, function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.loading = true;
                    vm.STORAGEINIT = true;
                    vm.key = "";
                    vm.toEnter = function (e) {
                        if (e.keyCode == 13) mvvm.toSearch();
                    }
                    vm.toSearch = function () {
                        mvvm.addQuery("key", mvvm.key, mvvm.key);
                    }
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm, data = m.createQuery();
                            data.pageIndex = (this.currentindex + 1) || 1
                            data.pageSize = this.pagesize
                            m.loadData(data)
                        }
                    }
                    vm.grid1 = createGrid({});
                    initQuerys(vm, function (data, name, val, type) {
                        mvvm.loadData(data);
                        if (type == "remove" || type == "clear") {
                            switch (name) {
                                case "typeid":
                                    mvvm.unSelectType();
                                    break;
                                case "key":
                                    mvvm.key = "";
                                    break;
                            }
                        }
                    })
                    vm.queryData = {
                        key: { label: "关键词", val: "", valLabel: "" },
                        typeid: { label: "产品分类", val: "", valLabel: "" },
                    }
                    //产品分类树配置
                    vm.pCategoryTreeOpts = {
                        treeopts: {
                            async: {
                                url: ""
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    mvvm.addQuery("typeid", treeNode.Id, treeNode.Name);
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            }
                        }
                    }
                    vm.unSelectType = function () {
                        var tree = avalon.vmodels["pStorageListCategoryTree"];
                        if (tree && tree.$treeObj) {
                            tree.$treeObj.cancelSelectedNode()
                        }
                    }
                    vm.getCategoryList = function () {
                        $.get('/Product/Category/', {}, function (ret) {
                            if (!ret.result) return;
                            ret.data.forEach(function (item) {
                                if (item.Id != 1) item.open = false;
                            });
                            avalon.vmodels.pStorageListCategoryTree.datasource = ret.data;
                        })
                    }
                    //分类树展开、收起
                    vm.$expancategory = false;
                    vm.expanCategory = function () {
                        mvvm.$expancategory = !mvvm.$expancategory;
                        $(this).text(mvvm.$expancategory ? "- 收起" : "+ 展开");
                        var tree = $.fn.zTree.getZTreeObj("storageListCategoryTree");
                        if (tree) {
                            var nodes = tree.getNodes();
                            if (nodes.length > 0) tree.expandNode(nodes[0], mvvm.$expancategory, true);
                            //收起的时候让根节点处于展开状态
                            if (!mvvm.$expancategory) tree.expandNode(nodes[0], !mvvm.$expancategory, false);
                        }
                    }
                    vm.loadData = function (param) {
                        param.wartype = 1;
                        mvvm.loading = true;
                        $.post('/Product/ProductStorageWarning', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                if (ret.data.list) {
                                    mvvm.grid1.initList(ret.data.list, ret.data.RecordTotal);
                                }
                                avalon.vmodels[vmid + "ListPage"].total = mvvm.grid1.total;
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.reloadData = function () {
                        var m = mvvm, data = m.createQuery(), page = avalon.vmodels[vmid + "Page"];
                        if (page) {
                            data.pageIndex = page.currentindex
                            data.pageSize = page.pagesize
                        }
                        m.loadData(data)
                    }
                    vm.$initDialog = null;
                    vm.closeInitDialog = function () {
                        if (mvvm.$initDialog) {
                            mvvm.$initDialog.close();
                            mvvm.$initDialog = null;
                        }
                    }
                })
                mvvm.grid1.bindWatch()
                mvvm.getCategoryList()
                function destroy() {
                    //destroyui(["pStorageListCategoryTree"])
                    avalon.vmodels[vmid] = null;
                }
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                CBCRM.onLoadModuleBefore = function (data) {
                    destroy();
                }
            }
            //库存下限报警
            , ProductStorageMinWarn: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this, mvvm, init = false, vmid = "ProductStorageMinWarn";
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define(vmid, function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.loading = true;
                    vm.STORAGEINIT = true;
                    vm.key = "";
                    vm.toEnter = function (e) {
                        if (e.keyCode == 13) mvvm.toSearch();
                    }
                    vm.toSearch = function () {
                        mvvm.addQuery("key", mvvm.key, mvvm.key);
                    }
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm, data = m.createQuery();
                            data.pageIndex = (this.currentindex + 1) || 1
                            data.pageSize = this.pagesize
                            m.loadData(data)
                        }
                    }
                    vm.grid1 = createGrid({});
                    initQuerys(vm, function (data, name, val, type) {
                        mvvm.loadData(data);
                        if (type == "remove" || type == "clear") {
                            switch (name) {
                                case "typeid":
                                    mvvm.unSelectType();
                                    break;
                                case "key":
                                    mvvm.key = "";
                                    break;
                            }
                        }
                    })
                    vm.queryData = {
                        key: { label: "关键词", val: "", valLabel: "" },
                        typeid: { label: "产品分类", val: "", valLabel: "" }
                    }
                    //产品分类树配置
                    vm.pCategoryTreeOpts = {
                        treeopts: {
                            async: {
                                url: ""
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    mvvm.addQuery("typeid", treeNode.Id, treeNode.Name);
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            }
                        }
                    }
                    vm.unSelectType = function () {
                        var tree = avalon.vmodels["pStorageListCategoryTree"];
                        if (tree && tree.$treeObj) {
                            tree.$treeObj.cancelSelectedNode()
                        }
                    }
                    vm.getCategoryList = function () {
                        $.get('/Product/Category/', {}, function (ret) {
                            if (!ret.result) return;
                            ret.data.forEach(function (item) {
                                if (item.Id != 1) item.open = false;
                            });
                            avalon.vmodels.pStorageListCategoryTree.datasource = ret.data;
                        })
                    }
                    //分类树展开、收起
                    vm.$expancategory = false;
                    vm.expanCategory = function () {
                        mvvm.$expancategory = !mvvm.$expancategory;
                        $(this).text(mvvm.$expancategory ? "- 收起" : "+ 展开");
                        var tree = $.fn.zTree.getZTreeObj("storageListCategoryTree");
                        if (tree) {
                            var nodes = tree.getNodes();
                            if (nodes.length > 0) tree.expandNode(nodes[0], mvvm.$expancategory, true);
                            //收起的时候让根节点处于展开状态
                            if (!mvvm.$expancategory) tree.expandNode(nodes[0], !mvvm.$expancategory, false);
                        }
                    }
                    vm.loadData = function (param) {
                        param.wartype = 2;
                        mvvm.loading = true;
                        $.post('/Product/ProductStorageWarning', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                if (ret.data.list) {
                                    mvvm.grid1.initList(ret.data.list, ret.data.RecordTotal);
                                }
                                avalon.vmodels[vmid + "ListPage"].total = mvvm.grid1.total;
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.reloadData = function () {
                        var m = mvvm, data = m.createQuery(), page = avalon.vmodels[vmid + "Page"];
                        if (page) {
                            data.pageIndex = page.currentindex
                            data.pageSize = page.pagesize
                        }
                        m.loadData(data)
                    }
                    vm.$initDialog = null;
                    vm.closeInitDialog = function () {
                        if (mvvm.$initDialog) {
                            mvvm.$initDialog.close();
                            mvvm.$initDialog = null;
                        }
                    }
                })
                mvvm.grid1.bindWatch()
                mvvm.getCategoryList()
                function destroy() {
                    //destroyui(["pStorageListCategoryTree"])
                    avalon.vmodels[vmid] = null;
                }
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                CBCRM.onLoadModuleBefore = function (data) {
                    destroy();
                }
            }
            //仓库调拨
            , ProductStorageTransfer: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this, vmid = this.vmid = "ProductStorageTransfer";
                var showdialog = null;
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.lang = lang;
                    vm.list = [];
                    vm.inlist = [];
                    vm.spaceList = [];
                    vm.storagetranslist = [];
                    vm.sinlist = [];
                    vm.soutlist = [];
                    vm.entity = {};
                    vm.ADD = true;
                    vm.tab = "tab1";
                    vm.tabWidth = 1000;
                    vm.tabChange = function (tab) {
                        mvvm.tab = tab;
                    }
                    var gridops = {
                        entityId: "StorageTrans",
                        url: that.path,
                        modelFactory: modelFactory
                    }
                    //经手人
                    vm.selectActionBy = function () {
                        plugins.selectUser({
                            dataAuth: 104000000,
                            callback: function (us) {
                                var u = us[0];
                                mvvm.entity.$model.ActionUser = u.Id;
                                mvvm.entity.ActionUserName = u.FullName;
                            }
                        })
                    }
                    
                    vm.getSpace = function (id) {
                        mvvm.spaceList = [];
                        var data = { storageId: id };
                        $.get('/Product/GetStorageSpaceList/', data, function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            mvvm.spaceList = ret.data.list;
                            mvvm.list.forEach(function (item) {
                                item.SpaceId = mvvm.spaceList.length == 1 ? mvvm.spaceList[0].Id : ""
                            })
                        })
                    }
                    vm.grid1 = createGrid(gridops);
                    initQuerys(vm, function (data, name, val, type) {
                        if (name == "typeId" && type == "remove") {
                            mvvm.selectFirstTreeNode();
                        }
                        mvvm.loadData(data);
                    });
                    vm.queryData = {
                        keyword: {
                            label: "关键词", val: "", valLabel: ""
                        },
                        StorageId: {
                            label: "仓库", val: "", valLabel: ""
                        },
                        State: {
                            label: "调拨状态", val: "", valLabel: "",
                            items: [
                                { label: "转运中", val: "1", curr: false },
                                { label: "已到达", val: "2", curr: false }
                            ]
                        },
                        starttime: {
                            label: "开始时间", val: "", valLabel: ""
                        },
                        endtime: {
                            label: "结束时间", val: "", valLabel: ""
                        }
                    }
                    vm.storagepaing = {
                        paging: function () {
                            var data = mvvm.createQuery();
                            data.pageSize = this.pagesize
                            data.pageIndex = this.currentindex + 1
                            mvvm.loadData(data);
                        }
                    }
                    //分类树
                    vm.storageTypeTreeOpts = {
                        treeopts: {
                            async: {
                                url: ""
                            },
                            data: {
                                keep: {
                                    parent: true
                                },
                                simpleData: {
                                    enable: true,
                                    idKey: 'Id'
                                },
                                key: {
                                    name: 'Name'
                                }
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    var id = treeNode.Id;
                                    if (id == 1) {
                                        mvvm.addQuery("StorageId", "");
                                    } else {
                                        if (treeNode.Ids) {
                                            if (treeNode.Ids != "")
                                                mvvm.addQuery("StorageId", treeNode.Ids, treeNode.Name);
                                            else
                                                mvvm.addQuery("StorageId", "0", treeNode.Name);
                                        } else
                                            mvvm.addQuery("StorageId", treeNode.Id, treeNode.Name);
                                    }
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            },
                            url: false
                        }
                    }
                    vm.setTreeData = function () {
                        var atree = avalon.vmodels.storageTypeTree;
                        if (atree) {
                            var rows = [{ Id: 1, Name: "全部分类", open: true, checked: true }];
                            rows = rows.concat(mvvm.types.$model);
                            $.each(rows, function (i) {
                                if (i == 0) return;
                                this.pId = 1;
                            });
                            atree.datasource = rows;
                            mvvm.selectFirstTreeNode();
                        }
                    }
                    vm.selectFirstTreeNode = function () {
                        var tree = $.fn.zTree.getZTreeObj("storageTypeTree");
                        var nodes = tree.getNodes();
                        if (nodes.length > 0) {
                            tree.selectNode(nodes[0]);
                        }
                    };

                    //分类管理
                    vm.typeDeleteids = [];
                    vm.typeList = [];
                    vm.typeManage = function () {
                        mvvm.typeList = [];
                        mvvm.typeDeleteids = [];
                        mvvm.types.$model.forEach(function (item, i) {
                            mvvm.typeList.push(item);
                        });
                        var btns = [{
                            name: "提交保存",
                            focus: true,
                            callback: function () {
                                var data = jsonToSubmit("dicts", mvvm.typeList);
                                if (mvvm.typeDeleteids.length > 0) $.extend(data, jsonToSubmit("deleteIds", mvvm.typeDeleteids));
                                $.post("/Settings/DictionaryListSave/", data, function (ret) {
                                    CBCRM.showResult(ret);
                                    if (ret.result) {
                                        if (dialog) dialog.close();
                                        mvvm.getDicts();
                                    }
                                });
                                return false;
                            }
                        }];
                        var dialog = openTmpl({
                            title: "分类管理",
                            vm: mvvm,
                            tmplid: "typeTmpl",
                            tmpl: tmpl,
                            btns: btns
                        });
                    }
                    vm.addType = function () {
                        var entity = $.extend(true, {}, modelFactory.create("Dictionary"));
                        entity.DictionaryId = mvvm.$dicts.types;
                        var arr = mvvm.types
                        if (entity.Name == null) entity.Name = entity.Data;
                        entity.Sort = arr.length == 0 ? 1 : parseInt(arr[arr.length - 1].Sort, 10) + 1;
                        mvvm.typeList.push(entity);
                    }
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm, data = m.createQuery();
                            data.pageIndex = (this.currentindex + 1) || 1
                            data.pageSize = this.pagesize
                            m.loadData(data)
                        }
                    }
                    //移除分类
                    vm.removeType = function (index) {
                        var item = mvvm.typeList[index];
                        if (!item.Id) mvvm.typeList.removeAt(index);
                        else {
                            $.post("/Product/ProductStorageCheckType/", { typeId: item.Id }, function (ret) {
                                if (!ret.result) return CBCRM.showResult(ret);
                                mvvm.typeList.removeAt(index);
                                mvvm.typeDeleteids.push(item.Id);
                            });
                        }
                    }
                    //读取数据
                    vm.loadData = function (data) {
                        $.post(that.path, data, function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                if (ret.data.list) {
                                    mvvm.grid1.initList(ret.data.list, ret.data.RecordTotal);
                                }
                                avalon.vmodels[vmid + "ListPage"].total = ret.data.RecordTotal;
                            } else {
                                CBCRM.showResult(ret);
                            }
                        })
                    }
                    vm.reloadData = function () {
                        mvvm.storagepaing.currentindex -= 1;
                        mvvm.storagepaing.paging();
                    }
                    //关键字搜索
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.addQuery("keyword", mvvm.queryData.keyword.val, "关键字：" + mvvm.queryData.keyword.val);
                    }
                    vm.clear = function () {
                        mvvm.queryData.keyword.val = '';
                        mvvm.queryData.starttime.val = '';
                        mvvm.queryData.endtime.val = '';
                        mvvm.addQuery("keyword", mvvm.queryData.keyword.val);
                    }

                    //查看详情
                    vm.doview = function (id) {
                        mvvm.storagetranslist = [];
                        mvvm.sinlist = [];
                        mvvm.soutlist = [];
                        mvvm.getOutAndIn(id);
                        var htmltmpl = $(tmpl).find("#viewTemplate").text();
                        showdialog = openTmpl({ vm: mvvm, title: "查看调拨详情", w: vm.tabWidth, tmplid: htmltmpl, iscontent: true });
                    }
                    //新增
                    vm.doadd = function () {
                        mvvm.grid1.getEntity("", function (entity) {
                            mvvm.entity = entity;
                            mvvm.entity.TotalMoney = 0;
                            mvvm.entity.Number = 0;
                            var user = CBCRM.memberShip;
                            mvvm.entity.ActionUser = user.Id;
                            mvvm.entity.ActionUserName = user.FullName;
                            mvvm.showForm("新增仓库调拨");
                        });
                        mvvm.bindWatch();
                    }
                    vm.showForm = function (title) {
                        var htmltmpl = $(tmpl).find("#formTemplate").text();
                        var btns = [{
                            name: "提交",
                            focus: true,
                            callback: function () {
                                var m = $.extend(true, {}, mvvm.entity.$model);
                                if (!m.InStorageId) {
                                    messageBox.error("请选择入库仓库！");
                                    return false;
                                }
                                if (!m.OutStorageId) {
                                    messageBox.error("请选择出库仓库！");
                                    return false;
                                }
                                var billmodel = $.extend(true, {}, modelFactory.create("StorageOutAndIn"))
                                $.extend(m, jsonToSubmit("billmodel", billmodel));
                                $.extend(m, jsonToSubmit("billinmodel", billmodel));
                                $.extend(m, jsonToSubmit("outlist", mvvm.inlist));
                                $.extend(m, jsonToSubmit("inlist", mvvm.inlist));
                                var url = "/Product/ProductStorageTransAdd/";
                                $.post(url, m, function (ret) {
                                    CBCRM.showResult(ret);
                                    if (ret.result) {
                                        if (dialog) dialog.close();
                                        mvvm.reloadData();
                                    }
                                });
                                return false;
                            }
                        }];
                        var dialog = mvvm.openTmpl({
                            title: title, w: mvvm.tabWidth,
                            extParam: {top:50},
                            tmplid: "formTemplate", tmpl: tmpl, btns: btns
                        });
                    }
                    vm.selectProduct = function () {
                        if (mvvm.entity.OutStorageId > 0) {
                            var pvmid = "ProductTransSelectList", pvm,
                                url = "/Product/ProductTransSelectList",
                                dialog = openWin("选择产品", pvmid, url, 900, 400, [{
                                    name: "确定选择",
                                    focus: true,
                                    callback: function () {
                                        if (!pvm) {
                                            messageBox.warning("系统正在载入中，请稍候……");
                                            return false;
                                        }
                                        var inlist = pvm.grid1.getChecked();
                                        if (inlist.length == 0) {
                                            messageBox.warning("请选择数据！");
                                            return false;
                                        }
                                        inlist.forEach(function (item) {
                                            for (var i = 0, l = mvvm.inlist.length; i < l; i++) {
                                                if (mvvm.inlist[i].InId == item.Id) return;
                                            }
                                            var model = $.extend(true, {}, modelFactory.create("StorageOutAndIn"))
                                            var map = {
                                                ProductId: "Id", ProductNo: "No", ProductName: "Name", Price: "StockPrice",
                                                ProductCategory: "CategoryName", Units: "UnitsDisplay"
                                            }
                                            //extendValue(model, item.$model, map);
                                            model.Id = item.Id;
                                            model.StorageId = mvvm.entity.InStorageId;
                                            model.InId = item.Id;
                                            if (mvvm.spaceList.length == 1) model.SpaceId = mvvm.spaceList[0].Id
                                            //model.SpaceId = item.SpaceId;
                                            model.SpaceName = item.SpaceName;
                                            model.ProductId = item.ProductId;
                                            model.ProductNo = item.ProductNo;
                                            model.ProductName = item.ProductName;
                                            model.ProductCategory = item.ProductCategory;
                                            model.Standard = item.Standard;
                                            model.Number = item.InventoryNumber;
                                            model.InventoryNumber = item.InventoryNumber;
                                            model.Units = item.Units;
                                            model.Price = item.Price;
                                            model.DiscountMoney = item.DiscountMoney;
                                            model.Mony = item.Price * model.Number;
                                            model.DiscountRate = item.DiscountRate;
                                            model.TaxRate = item.TaxRate;
                                            if (item.DiscountRate) {
                                                model.DiscountMoney = parseFloat(item.DiscountRate, 10) / 100 * model.Price * model.Number;
                                                model.Mony -= model.DiscountMoney;
                                            } else {
                                                model.DiscountMoney = 0;
                                            }
                                            if (item.TaxRate) {
                                                model.TaxMoney = parseFloat(item.TaxRate, 10) / 100 * item.Mony;
                                            } else {
                                                model.TaxMoney = 0;
                                            }
                                            model.TotalMoney = model.Mony + model.TaxMoney;

                                            model.DiscountMoney = model.DiscountMoney.toFixed(2);
                                            model.Money = model.Mony;
                                            model.Mony = model.Mony.toFixed(2);
                                            model.TaxMoney = model.TaxMoney.toFixed(2);
                                            model.TotalMoney = model.TotalMoney.toFixed(2);
                                            model.TotalMony = model.TotalMoney;
                                            model.AddBy = {};
                                            model.AddTime = "";
                                            model.ValidDay = 365;
                                            mvvm.inlist.push(model);
                                            var vitem = mvvm.inlist[mvvm.inlist.length - 1];
                                            mvvm.watchItem(vitem);
                                        });
                                        mvvm.getNewTotal();
                                    }
                                }], function (tmpl, vmodel) {
                                    vmodel.queryData.storageid.val = mvvm.entity.OutStorageId;
                                    pvm = vmodel, pageOps = pvm.listOpts;
                                    pageOps.pagesize = 20;
                                });
                        } else {
                            messageBox.error("请选择出库仓库");
                        }
                        //mvvm.bindWatch();
                    }
                    vm.getOutAndIn = function (id) {
                        $.get("/Product/ProductTransferDetail/", { "id": id }, function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            if (ret.data.storagetranslist)
                                mvvm.storagetranslist.push(ret.data.storagetranslist);
                            if (ret.data.sinlist)
                                mvvm.sinlist = ret.data.sinlist;
                            if (ret.data.soutlist)
                                mvvm.soutlist = ret.data.soutlist;
                        });
                    }
                    vm.doarrival = function (id, insname, arrivaltime) {
                        messageBox.confirm('确认产品已经到达[' + insname + ']仓库？', function () {
                            $.post('/Product/ProductTransferArriva/' + id, { 'arrivaltime': arrivaltime }, function (ret) {
                                CBCRM.showResult(ret);
                                if (ret.result) {
                                    mvvm.reloadData();
                                    if (showdialog) {
                                        showdialog.close();
                                        showdialog = null;
                                    }
                                }
                            })
                        });
                    }
                    vm.getNewTotal = function () {
                        mvvm.entity.TotalMoney = 0;
                        mvvm.entity.Number = 0;
                        mvvm.inlist.forEach(function (li) {
                            mvvm.entity.TotalMoney += parseFloat(li.TotalMoney);
                            mvvm.entity.Number += Number(li.Number);
                        });
                    }
                    vm.watchItem = function (item) {
                        function _watchPrice() {
                            if (item.InventoryNumber < item.Number) {
                                messageBox.error("当前仓库的" + item.ProductName + "库存不足");
                                item.Number = item.InventoryNumber;
                                return false;
                            }
                            item.Mony = item.Price * item.Number;
                            if (item.DiscountRate) {
                                item.DiscountMoney = parseFloat(item.DiscountRate, 10) / 100 * item.Mony;
                                item.Mony -= item.DiscountMoney;
                            } else {
                                item.DiscountMoney = 0;
                            }
                            if (item.TaxRate) {
                                item.TaxMoney = parseFloat(item.TaxRate, 10) / 100 * item.Mony;
                            } else {
                                item.TaxMoney = 0;
                            }
                            item.TotalMony = item.Mony + item.TaxMoney;
                            item.DiscountMoney = item.DiscountMoney.toFixed(2)
                            item.Mony = item.Mony.toFixed(2)
                            item.TaxMoney = item.TaxMoney.toFixed(2)
                            item.TotalMoney = item.TotalMony.toFixed(2);
                            item.TotalMony = item.TotalMony;
                            mvvm.getNewTotal();
                        }
                        ["Price", "Number", "DiscountRate", "TaxRate"].forEach(function (p) {
                            item.$watch(p, _watchPrice);
                        })
                        item.$watch("ProductionTime", function (n) {
                            if (n && item.ValidDay) {
                                try {
                                    var d = new Date(n), d2 = new Date(d.valueOf() + item.ValidDay * 24 * 60 * 60 * 1000)
                                    var a = [d2.getFullYear(), d2.getMonth() + 1, d2.getDate()]
                                    a[1] = a[1] < 9 ? "0" + a[1] : a[1];
                                    a[2] = a[2] < 9 ? "0" + a[2] : a[2];
                                    item.ValidDate = a.join("-")
                                } catch (ex) {
                                    item.ValidDate = ""
                                }
                            } else {
                                item.ValidDate = ""
                            }
                        })
                    }
                    vm.remove = function (index) {
                        mvvm.inlist.removeAt(index);
                        mvvm.getNewTotal();
                    }

                    //仓库列表
                    vm.types = [];
                    vm.$dicts = { types: 100112 };
                    vm.getDicts = function () {
                        $.post("/Product/ProductStorageGetTree/", null, function (ret) {
                            if (ret.result) {
                                vm.types = ret.data.list;
                                vm.setTreeData();
                            }
                        });
                    }
                    vm.bindWatch = function () {
                        mvvm.entity.$watch("InStorageId", function (n) {
                            if (mvvm.entity.InStorageId == mvvm.entity.OutStorageId) {
                                messageBox.warning("入库仓库不能和出库仓库一致");
                                mvvm.entity.InStorageId = 0;
                                return false;
                            }
                            mvvm.spaceList = [];
                            if (!n) {
                                mvvm.list.forEach(function (item) {
                                    item.SpaceId = ""
                                })
                                return;
                            }
                            mvvm.getSpace(n);
                        });

                        mvvm.entity.$watch("OutStorageId", function (n, o) {
                            if (mvvm.entity.InStorageId == mvvm.entity.OutStorageId) {
                                messageBox.warning("入库仓库不能和出库仓库一致");
                                mvvm.entity.InStorageId = 0;
                                return false;
                            }
                            if (o != n) {
                                mvvm.entity.InStorageId = 0;
                                mvvm.inlist = [];
                                mvvm.getNewTotal();
                            }
                        });

                    }
                })
                mvvm.grid1.init();
                mvvm.getDicts();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            }
            //仓库调拨备选产品列表
            , ProductTransSelectList: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this, mvvm, init = false, vmid = "ProductTransSelectList";
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define(vmid, function (vm) {
                    vm.$skipArray = ['lang'];
                    vm.lang = lang;
                    vm.loading = true;
                    vm.key = "";
                    vm.toEnter = function (e) {
                        if (e.keyCode == 13) mvvm.toSearch();
                    }
                    vm.toSearch = function () {
                        mvvm.addQuery("key", mvvm.key, "关键词:" + mvvm.key);
                    }
                    vm.listOpts = { //列表分页组件
                        pagesizeopts: [20, 30, 40, 50],
                        pagesize: 20,
                        paging: function () {
                            var m = mvvm, data = m.createQuery();
                            data.pageIndex = (this.currentindex + 1) || 1
                            data.pageSize = this.pagesize
                            m.loadData(data)
                        }
                    }
                    vm.grid1 = createGrid({});
                    initQuerys(vm, function (data) {
                        mvvm.loadData(data);
                    })
                    vm.queryData = {
                        key: { label: "关键词", val: "", valLabel: "" },
                        typeid: { label: "产品分类", val: "", valLabel: "" },
                        storageid: { label: "出库仓库ID", val: "", valLabel: "" }
                    }
                    vm.pClearQuery = function () {
                        vm.queryData.typeid.val = "";
                        mvvm.addQuery("key", "");
                    }
                    //产品分类树配置加
                    vm.pCategoryTreeOpts = {
                        treeopts: {
                            async: {
                                url: ""
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    if (treeNode.Id > 1)
                                        mvvm.addQuery("typeid", treeNode.Id, treeNode.Name);
                                    else
                                        mvvm.addQuery("typeid", "");
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            }
                        }
                    }
                    vm.getCategoryList = function () {
                        $.get('/Product/Category/', {}, function (ret) {
                            if (!ret.result) return;
                            ret.data.forEach(function (item) {
                                if (item.Id != 1) item.open = false;
                            });
                            avalon.vmodels.pSelectCategoryTree.datasource = ret.data;
                        })
                    }
                    //分类树展开、收起
                    vm.$expancategory = false;
                    vm.expanCategory = function () {
                        mvvm.$expancategory = !mvvm.$expancategory;
                        $(this).text(mvvm.$expancategory ? "- 收起" : "+ 展开");
                        var tree = $.fn.zTree.getZTreeObj("productSelectCategoryTree");
                        if (tree) {
                            var nodes = tree.getNodes();
                            if (nodes.length > 0) tree.expandNode(nodes[0], mvvm.$expancategory, true);
                            //收起的时候让根节点处于展开状态
                            if (!mvvm.$expancategory) tree.expandNode(nodes[0], !mvvm.$expancategory, false);
                        }
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Product/ProductTransSelectList', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                if (ret.data.list) {
                                    mvvm.grid1.initList(ret.data.list, ret.data.RecordTotal);
                                }
                                avalon.vmodels[vmid + "ListPage"].total = mvvm.grid1.total;
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                })
                mvvm.grid1.bindWatch();
                mvvm.getCategoryList();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            }
            //仓库盘点
            , ProductStorageCheck: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this, vmid = this.vmid = "ProductStorageCheck";
                var showdialog = null;
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.destroy=function() {
                        mvvm.destroyui(["pStorageListCategoryTree"])
                    }
                    vm.lang = lang;
                    vm.inlist = [];   //盘点添加明细
                    vm.showlist = [];   //盘点显示明细
                    vm.storagecheck = [];
                    vm.entity = {};
                    vm.ADD = true;
                    vm.tab = "tab1";
                    vm.tabWidth = 1000;
                    vm.tabChange = function (tab) {
                        mvvm.tab = tab;
                    }
                    var gridops = {
                        entityId: "StorageCheck",
                        url: that.path,
                        modelFactory: modelFactory
                    }
                    //经办人
                    vm.selectActionBy = function () {
                        plugins.selectUser({
                            dataAuth: 104000000,
                            callback: function (us) {
                                var u = us[0];
                                mvvm.entity.ActionBy.Id = u.Id;
                                mvvm.entity.ActionBy.FullName = u.FullName;
                            }
                        })
                    }
                    vm.UserGroupTreeOpts = {
                        treeopts: {
                            check: {
                                enable: true,
                                chkStyle: "radio",
                                radioType: "all"
                            },
                            callback: {
                                onCheck: function (event, treeId, treeNode) {
                                    tree = $.fn.zTree.getZTreeObj(treeId),
                                    nodes = tree.getCheckedNodes(true);
                                    if (nodes.length > 0) {
                                        //mvvm.entity.ActionBy = nodes[0];
                                        mvvm.entity.ActionBy.Id = nodes[0].Id;
                                        mvvm.entity.ActionBy.FullName = nodes[0].Name;
                                    }
                                }
                            },
                            async: {
                                url: function (treeId, treeNode) {
                                    return "/Settings/GetGroupPostUser/104000000/"
                                },
                                dataFilter: notMemberFilter
                            }
                        }
                    }
                    vm.grid1 = createGrid(gridops);
                    initQuerys(vm, function (data, name, val, type) {
                        if (name == "typeId" && type == "remove") {
                            mvvm.selectFirstTreeNode();
                        }
                        mvvm.loadData(data);
                    });
                    vm.queryData = {
                        keyword: {
                            label: "关键字", val: "", valLabel: ""
                        },
                        storageid: {
                            label: "仓库", val: "", valLabel: ""
                        },
                        starttime: {
                            label: "开始时间", val: "", valLabel: ""
                        },
                        endtime: {
                            label: "结束时间", val: "", valLabel: ""
                        }
                    }
                    vm.storagepaing = {
                        paging: function () {
                            var data = mvvm.createQuery();
                            data.pageSize = this.pagesize
                            data.pageIndex = this.currentindex + 1
                            mvvm.loadData(data);
                        }
                    }

                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm, data = m.createQuery();
                            data.pageIndex = (this.currentindex + 1) || 1
                            data.pageSize = this.pagesize
                            m.loadData(data)
                        }
                    }
                    vm.storagepaing = {
                        paging: function () {
                            var data = mvvm.createQuery();
                            data.pageSize = this.pagesize
                            data.pageIndex = this.currentindex + 1
                            mvvm.loadData(data);
                        }
                    }
                    //分类树
                    vm.storageTypeTreeOpts = {
                        treeopts: {
                            async: {
                                url: ""
                            },
                            data: {
                                keep: {
                                    parent: true
                                },
                                simpleData: {
                                    enable: true,
                                    idKey: 'Id'
                                },
                                key: {
                                    name: 'Name'
                                }
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    var id = treeNode.Id;
                                    if (id <= 1) {
                                        mvvm.addQuery("storageid", "");
                                    } else {
                                        if (id > 0) {
                                            if (treeNode.Ids)
                                                mvvm.addQuery("storageid", treeNode.Ids, treeNode.Name);
                                            else
                                                mvvm.addQuery("storageid", treeNode.Id, treeNode.Name);
                                        } else
                                            mvvm.addQuery("storageid", treeNode.Id, treeNode.Name);
                                    }
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            },
                            url: false
                        }
                    }
                    vm.setTreeData = function () {
                        var atree = avalon.vmodels.storageTypeTree;
                        if (atree) {
                            var rows = [{ Id: 1, Name: "全部分类", open: true, checked: true }];
                            rows = rows.concat(mvvm.types.$model);
                            $.each(rows, function (i) {
                                if (i == 0) return;
                                this.pId = 1;
                            });
                            atree.datasource = rows;
                            mvvm.selectFirstTreeNode();
                        }
                    }
                    vm.selectFirstTreeNode = function () {
                        var tree = $.fn.zTree.getZTreeObj("storageTypeTree");
                        var nodes = tree.getNodes();
                        if (nodes.length > 0) {
                            tree.selectNode(nodes[0]);
                        }
                    };

                    //分类管理
                    vm.typeDeleteids = [];
                    vm.typeList = [];
                    vm.typeManage = function () {
                        mvvm.typeList = [];
                        mvvm.typeDeleteids = [];
                        mvvm.types.$model.forEach(function (item, i) {
                            mvvm.typeList.push(item);
                        });
                        var btns = [{
                            name: "提交保存",
                            focus: true,
                            callback: function () {
                                var data = jsonToSubmit("dicts", mvvm.typeList);
                                if (mvvm.typeDeleteids.length > 0) $.extend(data, jsonToSubmit("deleteIds", mvvm.typeDeleteids));
                                $.post("/Settings/DictionaryListSave/", data, function (ret) {
                                    CBCRM.showResult(ret);
                                    if (ret.result) {
                                        if (dialog) dialog.close();
                                        mvvm.getDicts();
                                    }
                                });
                                return false;
                            }
                        }];
                        var dialog = openTmpl({
                            title: "分类管理",
                            vm: mvvm,
                            tmplid: "typeTmpl",
                            tmpl: tmpl,
                            btns: btns
                        });
                    }
                    vm.addType = function () {
                        var entity = $.extend(true, {}, modelFactory.create("Dictionary"));
                        entity.DictionaryId = mvvm.$dicts.types;
                        var arr = mvvm.types
                        if (entity.Name == null) entity.Name = entity.Data;
                        entity.Sort = arr.length == 0 ? 1 : parseInt(arr[arr.length - 1].Sort, 10) + 1;
                        mvvm.typeList.push(entity);
                    }
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm, data = m.createQuery();
                            data.pageIndex = (this.currentindex + 1) || 1
                            data.pageSize = this.pagesize
                            m.loadData(data)
                        }
                    }
                    //移除分类
                    vm.removeType = function (index) {
                        var item = mvvm.typeList[index];
                        if (!item.Id) mvvm.typeList.removeAt(index);
                        else {
                            $.post("/Product/ProductStorageCheckType/", { typeId: item.Id }, function (ret) {
                                if (!ret.result) return CBCRM.showResult(ret);
                                mvvm.typeList.removeAt(index);
                                mvvm.typeDeleteids.push(item.Id);
                            });
                        }
                    }

                    //读取数据
                    vm.loadData = function (data) {
                        $.post(that.path, data, function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                if (ret.data.Source) {
                                    mvvm.grid1.initList(ret.data.Source, ret.data.RecordTotal);
                                }
                                avalon.vmodels[vmid + "ListPage"].total = ret.data.RecordTotal;
                            } else {
                                CBCRM.showResult(ret);
                            }
                        })
                    }
                    vm.reloadData = function () {
                        mvvm.storagepaing.currentindex -= 1;
                        mvvm.storagepaing.paging();
                    }
                    //关键字搜索
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.addQuery("keyword", mvvm.queryData.keyword.val, "关键字");
                    }
                    vm.clear = function () {
                        mvvm.queryData.keyword.val = '';
                        mvvm.queryData.starttime.val = '';
                        mvvm.queryData.endtime.val = '';
                        mvvm.addQuery("keyword", mvvm.queryData.keyword.val);
                    }

                    //查看详情
                    vm.doview = function (id) {
                        mvvm.storagecheck = [];
                        mvvm.showlist = [];
                        mvvm.getCheckDetail(id);
                        var htmltmpl = $(tmpl).find("#viewTemplate").text();
                        showdialog = openTmpl({ vm: mvvm, title: "查看盘点详情", w: vm.tabWidth, tmplid: htmltmpl, iscontent: true });
                    }
                    //新增
                    vm.doadd = function () {
                        mvvm.grid1.getEntity("", function (entity) {
                            mvvm.entity = entity;
                            var user = CBCRM.memberShip;
                            mvvm.entity.ActionBy.Id = user.Id;
                            mvvm.entity.ActionBy.FullName = user.FullName;
                            mvvm.showForm("新增盘点记录");
                        });
                    }
                    vm.showForm = function (title) {
                        var htmltmpl = $(tmpl).find("#formTemplate").text();
                        var btns = [{
                            name: "提交",
                            focus: true,
                            callback: function () {
                                for (var i = 0; i < mvvm.inlist.length; i++) {
                                    if (!mvvm.inlist[i].ischecked) {
                                        messageBox.error("请先核对【" + mvvm.inlist[i].StorageName + "】的【" + mvvm.inlist[i].ProductName + "】库存");
                                        return false;
                                    }
                                }
                                var m = $.extend(true, {}, mvvm.entity.$model);
                                $.extend(m, jsonToSubmit("ActionBy", m.ActionBy));
                                delete m.ActionBy
                                delete m.AddBy
                                $.extend(m, jsonToSubmit("inlist", mvvm.inlist));
                                var url = "/Product/ProductStorageAddInventory/";
                                $.post(url, m, function (ret) {
                                    CBCRM.showResult(ret);
                                    if (ret.result) {
                                        if (dialog) dialog.close();
                                        mvvm.reloadData();
                                    }
                                });
                                return false;
                            }
                        }];
                        var dialog = openTmpl({
                            vm: mvvm, title: title, btns: btns, w: mvvm.tabWidth, tmplid: htmltmpl, iscontent: true, onclose: function () {
                                destroyui(["setUser"]);
                            }
                        });
                    }
                    vm.selectProduct = function () {
                        var pvmid = "ProductCheckSelectList", pvm,
                            url = "/Product/ProductCheckSelectList",
                            dialog = openWin("选择产品", pvmid, url, 900, 400, [{
                                name: "确定选择",
                                focus: true,
                                callback: function () {
                                    if (!pvm) {
                                        messageBox.warning("系统正在载入中，请稍候……");
                                        return false;
                                    }
                                    var inlist = pvm.grid1.getChecked();
                                    if (inlist.length == 0) {
                                        messageBox.warning("请选择数据！");
                                        return false;
                                    }
                                    inlist.forEach(function (item) {
                                        for (var i = 0, l = mvvm.inlist.length; i < l; i++) {
                                            if (mvvm.inlist[i].ProductId == item.Id) return;
                                        }
                                        var model = $.extend(true, {}, modelFactory.create("StorageInventory"));
                                        model.Id = 0;
                                        model.StorageId = item.StorageId;
                                        model.StorageName = item.StorageName;
                                        model.SpaceId = item.SpaceId;
                                        model.SpaceName = item.SpaceName;
                                        model.ProductCategory = item.ProductCategory;
                                        model.ProductId = item.ProductId;
                                        model.ProductNo = item.ProductNo;
                                        model.ProductName = item.ProductName;
                                        model.Standard = item.Standard;
                                        model.Units = item.Units;
                                        model.AccountNumber = item.InventoryNumber;
                                        model.RealNumber = "";
                                        model.Differences = "";
                                        model.ActionBy = {};
                                        model.AddBy = {};
                                        model.ischecked = 0;
                                        mvvm.inlist.push(model);
                                        var vitem = mvvm.inlist[mvvm.inlist.length - 1];
                                        mvvm.watchItem(vitem);
                                    });
                                }
                            }], function (tmpl, vmodel) {
                                pvm = vmodel, pageOps = pvm.listOpts;
                                pageOps.pagesize = 20;
                            });
                    }
                    vm.getCheckDetail = function (id) {
                        $.get("/Product/ProductCheckDetail/", { "id": id, "type": 0, "storageid": mvvm.queryData.storageid.val }, function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            if (ret.data.StorageCheck)
                                mvvm.storagecheck.push(ret.data.StorageCheck);
                            if (ret.data.list)
                                mvvm.showlist = ret.data.list;
                            avalon.vmodels["StorageInventoryListPage"].total = ret.data.RecordTotal;
                        });
                    }
                    vm.watchItem = function (item) {
                        function _watchNumber() {
                            if (item.RealNumber) {
                                item.Differences = Number(item.RealNumber) - Number(item.AccountNumber);
                                item.ischecked = 1;
                            }
                            else {
                                item.ischecked = 0;
                            }
                        }
                        ["RealNumber"].forEach(function (p) {
                            item.$watch(p, _watchNumber);
                        })
                    }
                    vm.remove = function (index) {
                        mvvm.inlist.removeAt(index);
                    }

                    //仓库列表
                    vm.types = [];
                    vm.$dicts = { types: 100112 };
                    vm.getDicts = function () {
                        $.post("/Product/ProductStorageGetTree/", null, function (ret) {
                            if (ret.result) {
                                vm.types = ret.data.list;
                                vm.setTreeData();
                            }
                        });
                    }
                })
                mvvm.grid1.init();
                
                mvvm.getDicts();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            }
            //仓库调拨备选产品列表
            , ProductCheckSelectList: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this, mvvm, init = false, vmid = "ProductCheckSelectList";
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define(vmid, function (vm) {
                    vm.$skipArray = ['lang'];
                    vm.lang = lang;
                    vm.loading = true;
                    vm.key = "";
                    vm.toEnter = function (e) {
                        if (e.keyCode == 13) mvvm.toSearch();
                    }
                    vm.toSearch = function () {
                        mvvm.addQuery("key", mvvm.key);
                    }
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm, data = m.createQuery();
                            data.pageIndex = (this.currentindex + 1) || 1
                            data.pageSize = this.pagesize
                            m.loadData(data)
                        }
                    }
                    vm.grid1 = createGrid({});
                    initQuerys(vm, function (data) {
                        mvvm.loadData(data);
                    })
                    vm.queryData = {
                        key: { label: "关键词", val: "", valLabel: "" },
                        typeid: { label: "产品分类", val: "", valLabel: "" }
                    }
                    //产品分类树配置加
                    vm.pCategoryTreeOpts = {
                        treeopts: {
                            async: {
                                url: ""
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    if (treeNode.Id > 1)
                                        mvvm.addQuery("typeid", treeNode.Id, treeNode.Name);
                                    else
                                        mvvm.addQuery("typeid", "");
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            }
                        }
                    }
                    vm.getCategoryList = function () {
                        $.get('/Product/Category/', {}, function (ret) {
                            if (!ret.result) return;
                            ret.data.forEach(function (item) {
                                if (item.Id != 1) item.open = false;
                            });
                            avalon.vmodels.pSelectCategoryTree.datasource = ret.data;
                        })
                    }
                    //分类树展开、收起
                    vm.$expancategory = false;
                    vm.expanCategory = function () {
                        mvvm.$expancategory = !mvvm.$expancategory;
                        $(this).text(mvvm.$expancategory ? "- 收起" : "+ 展开");
                        var tree = $.fn.zTree.getZTreeObj("productSelectCategoryTree");
                        if (tree) {
                            var nodes = tree.getNodes();
                            if (nodes.length > 0) tree.expandNode(nodes[0], mvvm.$expancategory, true);
                            //收起的时候让根节点处于展开状态
                            if (!mvvm.$expancategory) tree.expandNode(nodes[0], !mvvm.$expancategory, false);
                        }
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Product/ProductCheckSelectList', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                if (ret.data.list) {
                                    mvvm.grid1.initList(ret.data.list, ret.data.RecordTotal);
                                }
                                avalon.vmodels[vmid + "ListPage"].total = mvvm.grid1.total;
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                })
                mvvm.grid1.bindWatch();
                mvvm.getCategoryList();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            }
            //仓库盘盈
            , ProductStorageCheckGain: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this, vmid = this.vmid = "ProductStorageCheckGain";
                destroy();
                var showdialog = null;
                var mvvm = avalon.define(vmid, function (vm) {
                    vm.lang = lang;
                    vm.showlist = [];   //盘点显示明细
                    vm.storagecheck = [];
                    vm.entity = {};
                    vm.tabWidth = 1000;
                    var gridops = {
                        entityId: "StorageCheck",
                        url: that.path,
                        modelFactory: modelFactory
                    }
                    vm.grid1 = createGrid(gridops);
                    initQuerys(vm, function (data, name, val, type) {
                        if (name == "typeId" && type == "remove") {
                            mvvm.selectFirstTreeNode();
                        }
                        mvvm.loadData(data);
                    });
                    vm.queryData = {
                        keyword: {
                            label: "关键字", val: "", valLabel: ""
                        },
                        StorageId: {
                            label: "仓库", val: "", valLabel: ""
                        },
                        starttime: {
                            label: "开始时间", val: "", valLabel: ""
                        },
                        endtime: {
                            label: "结束时间", val: "", valLabel: ""
                        },
                        type: {
                            label: "盘点盈亏", val: "", valLabel: ""
                        }
                    }
                    vm.storagepaing = {
                        paging: function () {
                            var data = mvvm.createQuery();
                            data.pageSize = this.pagesize
                            data.pageIndex = this.currentindex + 1
                            mvvm.loadData(data);
                        }
                    }
                    //分类树
                    vm.storageTypeTreeOpts = {
                        treeopts: {
                            async: {
                                url: ""
                            },
                            data: {
                                keep: {
                                    parent: true
                                },
                                simpleData: {
                                    enable: true,
                                    idKey: 'Id'
                                },
                                key: {
                                    name: 'Name'
                                }
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    var id = treeNode.Id;
                                    if (id == 1) {
                                        mvvm.addQuery("StorageId", "");
                                    } else {
                                        if (treeNode.Ids) {
                                            if (treeNode.Ids != "")
                                                mvvm.addQuery("StorageId", treeNode.Ids, treeNode.Name);
                                            else
                                                mvvm.addQuery("StorageId", "0", treeNode.Name);
                                        } else
                                            mvvm.addQuery("StorageId", treeNode.Id, treeNode.Name);
                                    }
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            },
                            url: false
                        }
                    }
                    vm.setTreeData = function () {
                        var atree = avalon.vmodels.storageTypeTree;
                        if (atree) {
                            var rows = [{ Id: 1, Name: "全部分类", open: true, checked: true }];
                            rows = rows.concat(mvvm.types.$model);
                            $.each(rows, function (i) {
                                if (i == 0) return;
                                this.pId = 1;
                            });
                            atree.datasource = rows;
                            mvvm.selectFirstTreeNode();
                        }
                    }
                    vm.selectFirstTreeNode = function () {
                        var tree = $.fn.zTree.getZTreeObj("storageTypeTree");
                        var nodes = tree.getNodes();
                        if (nodes.length > 0) {
                            tree.selectNode(nodes[0]);
                        }
                    };

                    //分类管理
                    vm.typeDeleteids = [];
                    vm.typeList = [];
                    vm.typeManage = function () {
                        mvvm.typeList = [];
                        mvvm.typeDeleteids = [];
                        mvvm.types.$model.forEach(function (item, i) {
                            mvvm.typeList.push(item);
                        });
                        var btns = [{
                            name: "提交保存",
                            focus: true,
                            callback: function () {
                                var data = jsonToSubmit("dicts", mvvm.typeList);
                                if (mvvm.typeDeleteids.length > 0) $.extend(data, jsonToSubmit("deleteIds", mvvm.typeDeleteids));
                                $.post("/Settings/DictionaryListSave/", data, function (ret) {
                                    CBCRM.showResult(ret);
                                    if (ret.result) {
                                        if (dialog) dialog.close();
                                        mvvm.getDicts();
                                    }
                                });
                                return false;
                            }
                        }];
                        var dialog = openTmpl({
                            title: "分类管理",
                            vm: mvvm,
                            tmplid: "typeTmpl",
                            tmpl: tmpl,
                            btns: btns
                        });
                    }
                    vm.addType = function () {
                        var entity = $.extend(true, {}, modelFactory.create("Dictionary"));
                        entity.DictionaryId = mvvm.$dicts.types;
                        var arr = mvvm.types
                        if (entity.Name == null) entity.Name = entity.Data;
                        entity.Sort = arr.length == 0 ? 1 : parseInt(arr[arr.length - 1].Sort, 10) + 1;
                        mvvm.typeList.push(entity);
                    }
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm, data = m.createQuery();
                            data.pageIndex = (this.currentindex + 1) || 1
                            data.pageSize = this.pagesize
                            m.loadData(data)
                        }
                    }
                    //移除分类
                    vm.removeType = function (index) {
                        var item = mvvm.typeList[index];
                        if (!item.Id) mvvm.typeList.removeAt(index);
                        else {
                            $.post("/Product/ProductStorageCheckType/", { typeId: item.Id }, function (ret) {
                                if (!ret.result) return CBCRM.showResult(ret);
                                mvvm.typeList.removeAt(index);
                                mvvm.typeDeleteids.push(item.Id);
                            });
                        }
                    }
                    //读取数据
                    vm.loadData = function (data) {
                        data.type = 1;
                        $.post('/Product/ProductStorageCheck', data, function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                if (ret.data.Source) {
                                    mvvm.grid1.initList(ret.data.Source, ret.data.RecordTotal);
                                }
                                avalon.vmodels[vmid + "ListPage"].total = ret.data.RecordTotal;
                            } else {
                                CBCRM.showResult(ret);
                            }
                        })
                    }
                    vm.reloadData = function () {
                        mvvm.storagepaing.currentindex -= 1;
                        mvvm.storagepaing.paging();
                    }
                    //关键字搜索
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.addQuery("keyword", mvvm.queryData.keyword.val, "关键字：" + mvvm.queryData.keyword.val);
                    }
                    vm.clear = function () {
                        mvvm.queryData.keyword.val = '';
                        mvvm.queryData.starttime.val = '';
                        mvvm.queryData.endtime.val = '';
                        mvvm.addQuery("keyword", mvvm.queryData.keyword.val);
                    }

                    //查看详情
                    vm.doview = function (id) {
                        mvvm.storagecheck = [];
                        mvvm.showlist = [];
                        mvvm.getCheckDetail(id);
                        var htmltmpl = $(tmpl).find("#viewTemplate").text();
                        showdialog = openTmpl({ vm: mvvm, title: "查看盘点详情", w: vm.tabWidth, tmplid: htmltmpl, iscontent: true });
                    }
                    vm.getCheckDetail = function (id) {
                        $.get("/Product/ProductCheckDetail/", { "id": id, "type": 1, "storageid": mvvm.queryData.StorageId.val }, function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            if (ret.data.StorageCheck)
                                mvvm.storagecheck.push(ret.data.StorageCheck);
                            if (ret.data.list)
                                mvvm.showlist = ret.data.list;
                            avalon.vmodels["StorageInventoryListPage"].total = ret.data.RecordTotal;
                        });
                    }

                    //仓库列表
                    vm.types = [];
                    vm.$dicts = { types: 100112 };
                    vm.getDicts = function () {
                        $.post("/Product/ProductStorageGetTree/", null, function (ret) {
                            if (ret.result) {
                                vm.types = ret.data.list;
                                vm.setTreeData();
                            }
                        });
                    }
                })
                mvvm.grid1.bindWatch();
                function destroy() {
                    avalon.vmodels[vmid] = null
                }
                mvvm.getDicts();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                CBCRM.onLoadModuleBefore = function (data) {
                    if (data.moduleName == "Upload") return;
                    destroy();
                }
            }
            //仓库盘亏
            , ProductStorageCheckLoss: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this, vmid = this.vmid = "ProductStorageCheckLoss";
                destroy();
                var showdialog = null;
                var mvvm = avalon.define(vmid, function (vm) {
                    vm.lang = lang;
                    vm.showlist = [];   //盘点显示明细
                    vm.storagecheck = [];
                    vm.entity = {};
                    vm.tabWidth = 1000;
                    var gridops = {
                        entityId: "StorageCheck",
                        url: that.path,
                        modelFactory: modelFactory
                    }
                    vm.grid1 = createGrid(gridops);
                    initQuerys(vm, function (data, name, val, type) {
                        if (name == "typeId" && type == "remove") {
                            mvvm.selectFirstTreeNode();
                        }
                        mvvm.loadData(data);
                    });
                    vm.queryData = {
                        keyword: {
                            label: "盘点编号", val: "", valLabel: ""
                        },
                        StorageId: {
                            label: "仓库", val: "", valLabel: ""
                        },
                        space: {
                            label: "仓位", val: "", valLabel: ""
                        },
                        starttime: {
                            label: "开始时间", val: "", valLabel: ""
                        },
                        endtime: {
                            label: "结束时间", val: "", valLabel: ""
                        },
                        type: {
                            label: "盘点盈亏", val: "", valLabel: ""
                        }
                    }
                    vm.storagepaing = {
                        paging: function () {
                            var data = mvvm.createQuery();
                            data.pageSize = this.pagesize
                            data.pageIndex = this.currentindex + 1
                            mvvm.loadData(data);
                        }
                    }
                    //分类树
                    vm.storageTypeTreeOpts = {
                        treeopts: {
                            async: {
                                url: ""
                            },
                            data: {
                                keep: {
                                    parent: true
                                },
                                simpleData: {
                                    enable: true,
                                    idKey: 'Id'
                                },
                                key: {
                                    name: 'Name'
                                }
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    var id = treeNode.Id;
                                    if (id == 1) {
                                        mvvm.addQuery("StorageId", "");
                                    } else {
                                        if (treeNode.Ids) {
                                            if (treeNode.Ids != "")
                                                mvvm.addQuery("StorageId", treeNode.Ids, treeNode.Name);
                                            else
                                                mvvm.addQuery("StorageId", "0", treeNode.Name);
                                        } else
                                            mvvm.addQuery("StorageId", treeNode.Id, treeNode.Name);
                                    }
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            },
                            url: false
                        }
                    }
                    vm.setTreeData = function () {
                        var atree = avalon.vmodels.storageTypeTree;
                        if (atree) {
                            var rows = [{ Id: 1, Name: "全部分类", open: true, checked: true }];
                            rows = rows.concat(mvvm.types.$model);
                            $.each(rows, function (i) {
                                if (i == 0) return;
                                this.pId = 1;
                            });
                            atree.datasource = rows;
                            mvvm.selectFirstTreeNode();
                        }
                    }
                    vm.selectFirstTreeNode = function () {
                        var tree = $.fn.zTree.getZTreeObj("storageTypeTree");
                        var nodes = tree.getNodes();
                        if (nodes.length > 0) {
                            tree.selectNode(nodes[0]);
                        }
                    };

                    //分类管理
                    vm.typeDeleteids = [];
                    vm.typeList = [];
                    vm.typeManage = function () {
                        mvvm.typeList = [];
                        mvvm.typeDeleteids = [];
                        mvvm.types.$model.forEach(function (item, i) {
                            mvvm.typeList.push(item);
                        });
                        var btns = [{
                            name: "提交保存",
                            focus: true,
                            callback: function () {
                                var data = jsonToSubmit("dicts", mvvm.typeList);
                                if (mvvm.typeDeleteids.length > 0) $.extend(data, jsonToSubmit("deleteIds", mvvm.typeDeleteids));
                                $.post("/Settings/DictionaryListSave/", data, function (ret) {
                                    CBCRM.showResult(ret);
                                    if (ret.result) {
                                        if (dialog) dialog.close();
                                        mvvm.getDicts();
                                    }
                                });
                                return false;
                            }
                        }];
                        var dialog = openTmpl({
                            title: "分类管理",
                            vm: mvvm,
                            tmplid: "typeTmpl",
                            tmpl: tmpl,
                            btns: btns
                        });
                    }
                    vm.addType = function () {
                        var entity = $.extend(true, {}, modelFactory.create("Dictionary"));
                        entity.DictionaryId = mvvm.$dicts.types;
                        var arr = mvvm.types
                        if (entity.Name == null) entity.Name = entity.Data;
                        entity.Sort = arr.length == 0 ? 1 : parseInt(arr[arr.length - 1].Sort, 10) + 1;
                        mvvm.typeList.push(entity);
                    }
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm, data = m.createQuery();
                            data.pageIndex = (this.currentindex + 1) || 1
                            data.pageSize = this.pagesize
                            m.loadData(data)
                        }
                    }
                    //移除分类
                    vm.removeType = function (index) {
                        var item = mvvm.typeList[index];
                        if (!item.Id) mvvm.typeList.removeAt(index);
                        else {
                            $.post("/Product/ProductStorageCheckType/", { typeId: item.Id }, function (ret) {
                                if (!ret.result) return CBCRM.showResult(ret);
                                mvvm.typeList.removeAt(index);
                                mvvm.typeDeleteids.push(item.Id);
                            });
                        }
                    }
                    //读取数据
                    vm.loadData = function (data) {
                        data.type = 2;
                        $.post('/Product/ProductStorageCheck', data, function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                if (ret.data.Source) {
                                    mvvm.grid1.initList(ret.data.Source, ret.data.RecordTotal);
                                }
                                avalon.vmodels[vmid + "ListPage"].total = ret.data.RecordTotal;
                            } else {
                                CBCRM.showResult(ret);
                            }
                        })
                    }
                    vm.reloadData = function () {
                        mvvm.storagepaing.currentindex -= 1;
                        mvvm.storagepaing.paging();
                    }
                    //关键字搜索
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.addQuery("keyword", mvvm.queryData.keyword.val, "关键字：" + mvvm.queryData.keyword.val);
                    }
                    vm.clear = function () {
                        mvvm.queryData.keyword.val = '';
                        mvvm.queryData.starttime.val = '';
                        mvvm.queryData.endtime.val = '';
                        mvvm.addQuery("keyword", mvvm.queryData.keyword.val);
                    }

                    //查看详情
                    vm.doview = function (id) {
                        mvvm.storagecheck = [];
                        mvvm.showlist = [];
                        mvvm.getCheckDetail(id);
                        var htmltmpl = $(tmpl).find("#viewTemplate").text();
                        showdialog = openTmpl({ vm: mvvm, title: "查看盘点详情", w: vm.tabWidth, tmplid: htmltmpl, iscontent: true });
                    }
                    vm.getCheckDetail = function (id) {
                        $.get("/Product/ProductCheckDetail/", { "id": id, "type": 2, "storageid": mvvm.queryData.StorageId.val }, function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            if (ret.data.StorageCheck)
                                mvvm.storagecheck.push(ret.data.StorageCheck);
                            if (ret.data.list)
                                mvvm.showlist = ret.data.list;
                            avalon.vmodels["StorageInventoryListPage"].total = ret.data.RecordTotal;
                        });
                    }

                    //仓库列表
                    vm.types = [];
                    vm.$dicts = { types: 100112 };
                    vm.getDicts = function () {
                        $.post("/Product/ProductStorageGetTree/", null, function (ret) {
                            if (ret.result) {
                                vm.types = ret.data.list;
                                vm.setTreeData();
                            }
                        });
                    }
                })
                mvvm.grid1.bindWatch();
                function destroy() {
                    avalon.vmodels[vmid] = null
                }
                mvvm.getDicts();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                CBCRM.onLoadModuleBefore = function (data) {
                    if (data.moduleName == "Upload") return;
                    destroy();
                }
            }
            , ContractSelectOutAndInList: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this, mvvm, init = false, vmid = "ContractSelectOutAndInList";
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define(vmid, function (vm) {
                    vm.$skipArray = ['lang'];
                    vm.lang = lang;
                    vm.loading = true;
                    vm.key = "";
                    vm.toEnter = function (e) {
                        if (e.keyCode == 13) mvvm.toSearch();
                    }
                    vm.toSearch = function () {
                        mvvm.addQuery("key", mvvm.key);
                    }
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm, data = m.createQuery();
                            data.pageIndex = (this.currentindex + 1) || 1
                            data.pageSize = this.pagesize
                            m.loadData(data)
                        }
                    }
                    vm.grid1 = createGrid({});
                    initQuerys(vm, function (data) {
                        mvvm.loadData(data);
                    })
                    vm.queryData = {
                        key: { label: "关键词", val: "", valLabel: "" },
                        categorys: { label: "产品分类", val: "", valLabel: "" }
                    }
                    //产品分类树配置加
                    vm.pCategoryTreeOpts = {
                        treeopts: {
                            async: {
                                url: ""
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    if (treeNode.Id > 1) {
                                        var categorys = getNodeIds(treeNode, null, "Name");
                                        mvvm.addQuery("typeid", categorys, treeNode.Name);
                                    }
                                    else
                                        mvvm.addQuery("typeid", "");
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            }
                        }
                    }
                    vm.getCategoryList = function () {
                        $.get('/Product/Category/', {}, function (ret) {
                            if (!ret.result) return;
                            ret.data.forEach(function (item) {
                                if (item.Id != 1) item.open = false;
                            });
                            avalon.vmodels.pSelectCategoryTree.datasource = ret.data;
                        })
                    }
                    //分类树展开、收起
                    vm.$expancategory = false;
                    vm.expanCategory = function () {
                        mvvm.$expancategory = !mvvm.$expancategory;
                        $(this).text(mvvm.$expancategory ? "- 收起" : "+ 展开");
                        var tree = $.fn.zTree.getZTreeObj("productSelectCategoryTree");
                        if (tree) {
                            var nodes = tree.getNodes();
                            if (nodes.length > 0) tree.expandNode(nodes[0], mvvm.$expancategory, true);
                            //收起的时候让根节点处于展开状态
                            if (!mvvm.$expancategory) tree.expandNode(nodes[0], !mvvm.$expancategory, false);
                        }
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        if (param.categorys) {
                            $.extend(param, jsonToSubmit("categorys", param.categorys));
                            delete param.categorys;
                        }
                        $.post('/Product/ContractSelectOutAndInList', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                if (ret.data.list) {
                                    mvvm.grid1.initList(ret.data.list, ret.data.RecordTotal);
                                }
                                avalon.vmodels[vmid + "ListPage"].total = mvvm.grid1.total;
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                })
                mvvm.grid1.bindWatch();
                mvvm.getCategoryList();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            }
        }
        return Product;
    });