define('Office', [
    'modelFactory',
    'plugins',
    'json',
    'dialog',
    'common',
    'leftMenu',
    'jscal2',
    'kindedit',
    'upload',
    'fusionCharts',
    'slides', 'wgCal', 'jcal', 'jqselect', 'cookie', 'fancyBox', 'bjqs', 'cbcalendar'],
    function (modelFactory,plugins) {
        var groupPostFilter = function (treeId, parentNode, responseData) {
            var groups = [];
            if (responseData.data && responseData.data.groups.length) {
                responseData.data.groups.forEach(function (item, i) {
                    var m = {
                        Id: item.Id, Name: item.Name, ParentId: item.ParentId, iconSkin: item.iconSkin,
                        open: i === 0
                    }
                    groups.push(m);
                    item.Posts.forEach(function (item2, j) {
                        var mm = {
                            Id: item2.Id, Name: item2.Name, ParentId: item2.Group, iconSkin: item2.iconSkin,
                            open: j === 0
                        }
                        groups = groups.concat(mm);
                        item2.Users.forEach(function (item3) {
                            var mmm = {
                                Id: item3.Id, Name: item3.FullName, ParentId: item3.PositionId, iconSkin: item3.iconSkin
                            }
                            groups = groups.concat(mmm);
                        });
                    });
                });
            }
            return groups;
        },
        //过滤掉没有人员的职位
        groupPostFilter2 = function (treeId, parentNode, responseData) {
            var CBCRM = avalon.vmodels.CBCRM
            var ret = [], len = 0, curr, phasEmp = false, ghasEmp = false;
            if (responseData.data && responseData.data.groups.length)
                len = responseData.data.groups.length
            while (len) {
                curr = responseData.data.groups[--len]
                curr.nocheck = true
                ghasEmp = false
                curr.Posts.forEach(function (p, i) {
                    phasEmp = p.Users.length > 0;
                    if (phasEmp) ghasEmp = true;
                    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 (phasEmp) {
                        ret.push(p)
                    }
                })
                ret.push(curr)
            }
            return ret
        },
            //下拉配置过滤数据 只可选员工
            notMemberFilter = function (treeId, parentNode, responseData) {
                var CBCRM = avalon.vmodels.CBCRM
                var ret = [], len = 0, curr, hasEmp = false
                if (responseData.data && responseData.data.groups.length)
                    len = responseData.data.groups.length
                while (len) {
                    curr = responseData.data.groups[--len]
                    curr.nocheck = true
                    hasEmp = false
                    curr.Posts.forEach(function (p, i) {
                        curr.Posts[i].ParentId = p.Boss ? p.Boss.Id : p.Group
                        curr.Posts[i].nocheck = true
                        p.Users.forEach(function (u, i) {
                            var u = p.Users[i]
                            if (u.Id === CBCRM.memberShip.Id) return true
                            u.ParentId = u.PositionId
                            u.Name = u.FullName
                            ret.push(u)
                        })
                        if (!hasEmp) {
                            hasEmp = p.Users.length > 0
                        }
                        if (hasEmp) {
                            ret.push(p)
                        }
                    })
                    if (hasEmp) ret.push(curr)
                }
                return ret
            },
            //只要部门和用户
            notPostFilter = function (treeId, parentNode, responseData) {
                var CBCRM = avalon.vmodels.CBCRM
                var ret = [], len = 0, curr, hasEmp = false
                if (responseData.data && responseData.data.groups.length)
                    len = responseData.data.groups.length
                while (len) {
                    curr = responseData.data.groups[--len]
                    curr.nocheck = true
                    hasEmp = false
                    curr.Posts.forEach(function (p, i) {
                        p.Users.forEach(function (u, i) {
                            if (u.Id === CBCRM.memberShip.Id) return true
                            u.ParentId = p.Boss ? p.Boss.Id : p.Group
                            u.Post = p.Name;
                            u.Name = u.FullName + "(" + u.Post + ")";
                            ret.push(u)
                        })
                        if (!hasEmp) {
                            hasEmp = p.Users.length > 0
                        }
                    })
                    ret.push(curr);
                }
                return ret
            },
            getCarBusy = function (tarr, queryTime, item) {
                var busy = {};
                if (!queryTime || !item.BeginTime || !item.EndTime) return busy;
                var qt = queryTime,
                    ut1 = new Date(item.BeginTime), ut2 = new Date(item.EndTime);
                for (var k in tarr) {
                    var t = tarr[k];
                    var qt1 = new Date(qt + " " + t[0]), qt2 = new Date(qt + " " + t[1]);
                    if ((qt1 >= ut1 && qt1 <= ut2) || (qt2 > ut1 && qt2 < ut2)) busy[k] = true;
                }
                return busy;
            },
            formatArticlesUrl = function (list) {
                if (!list || !$.isArray(list)) return false;
                list.forEach(function (item) {
                    if (item.Url && item.Url!="http://") {
                        item.aurl = item.Url;
                        item.atarget = "_blank";
                    } else {
                        item.aurl = '#/Office/ArticlesView/' + item.Id;
                        item.atarget = "_self";
                    }
                });
            }

        var Office = {
            /// <summary>
            /// 工作台
            /// </summary>
            Index: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM;
                var mvvm = CBCRM.define('Index', function (vm) {
                    vm.lang = lang
                    vm.$skipArray = ['lang']
                    vm.keyword = ''
                    vm.path = '#/Office/ArticlesList/'
                    vm.search = function () {
                        mvvm.path = '#/Office/ArticlesList/0/' + encodeURI(mvvm.keyword)
                    }
                    vm.focusList = [];
                    vm.focusTop = {}
                    vm.report = []
                    vm.calendar = []
                    vm.goto = goto;
                    vm.addReport = function (typeid) {
                        var url = "/Office/DailyReport/" + typeid + "/add";
                        goto(url);
                    }
                });

                function initWithData() {
                    $.get('/Office/ArticlesOther/', {}, function (ret) {
                        if (ret.result) {
                            formatArticlesUrl(ret.data.focusList);
                            mvvm.focusList = ret.data.focusList;
                            if (mvvm.focusList.length > 0)
                                mvvm.focusTop = mvvm.focusList[0];
                            var h = mvvm.focusList.length > 0 ? mvvm.focusList.$model[0].Title : '';
                            //slideShow(h);
                        }
                    });
                    $.get('/Office/Index/', {}, function (ret) {
                        mvvm.report = ret.data.report;
                        mvvm.calendar = ret.data.calendar;
                    })
                }
                initWithData();

                avalon.filters.typeName = function (val) {
                    var ret = ''
                    switch (val) {
                        case 1: ret = "日报"; break;
                        case 2: ret = "周报"; break;
                        case 3: ret = "月报"; break;
                        case 4: ret = "季报"; break;
                        case 5: ret = "年报"; break;
                    }
                    return ret;
                }

                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                $('#sbOffices').selectbox()
                $('#sbOffices_input').removeAttr('readonly')
            },

            ArticlesIndex: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM;
                var mvvm = CBCRM.define('ArticlesIndex', function (vm) {
                    vm.articlesTypeList = []
                    vm.articlesTypeList1 = [];
                    vm.key = "";
                    vm.focusType={};
                    vm.focusList = []
                    vm.slidelist = [];
                    vm.focusTop = {}
                    vm.path = "";
                    vm.tabChange = function () {
                        var t = $(this);
                        $("#left li").removeClass('selected');
                        t.parent('li').addClass('selected');
                    }
                    vm.Newsearch = function () {
                        mvvm.path = '#/Office/ArticlesList/0/' + encodeURI(mvvm.key)
                    }
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) {
                            mvvm.Newsearch();
                        }
                    }
                });  
                 
                //初始化数据
                function initWithData() {
                   // mvvm.showItem = avalon.mix({}, queryData);
                    //mvvm.entity = modelFactory.create('Articles');
                   // mvvm.entityType = modelFactory.create('ArticlesType');

                    initWithCategory();
                    initWithOther();
                }
                initWithData();
                function initWithCategory() {
                    $.get('/Office/Articles/', {}, function (ret) {
                        if (!ret.result) {
                            //CBCRM.showResult(ret);
                            return;
                        }
                        ret.data.ArticlesTypeList.forEach(function (item) {
                            if(item.Articles)formatArticlesUrl(item.Articles);
                        })
                        mvvm.articlesTypeList = ret.data.ArticlesTypeList;
                        ret.data.ArticlesTypeList.forEach(function (item) {
                            if (item.Name != '通知公告')
                                mvvm.articlesTypeList1.push(item);
                            else
                                mvvm.focusType = item;
                        })
                    });
                }
                function initWithOther() {
                    $.get('/Office/ArticlesNotic/', {}, function (ret) {
                        if (ret.result && ret.data) {
                            formatArticlesUrl(ret.data.focusList);
                            formatArticlesUrl(ret.data.toutiaolist);
                            formatArticlesUrl(ret.data.slidelist);
                            mvvm.focusList = ret.data.focusList;
                            mvvm.slidelist = ret.data.slidelist;
                            if (ret.data.toutiaolist.length > 0)
                                mvvm.focusTop = ret.data.toutiaolist[0];
                            //var h = mvvm.focusList.length > 0 ? mvvm.focusList.$model[0].Title : '';
                            //slideShow(h);

                        } else {
                            CBCRM.showResult(ret);
                        }
                        fill();
                    });
                } 
                
                function fill() {
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
                    avalon.nextTick(function () {
                        //图片滚动
                        $('#banner-slide').bjqs({
                            animtype: 'slide',
                            height: 310,
                            width: 360,
                            responsive: true,
                            randomstart: true
                        });
                        $("#banner-slide").hover(function () {
                            $("ul.bjqs-controls.v-centered li a").show();
                        }, function () {
                            $("ul.bjqs-controls.v-centered li a").hide();
                        })

                        $('#left_menu_top').html('<h>新闻中心</h><a href="#/Office/Articles" title="新闻管理" class="setico" style="margin-top:12px;"></a>').show()
                    })
                }
            },
            /// <summary>
            /// 新闻中心
            /// </summary>
            Articles: function (tmpl, lang, contentId, module) {

                var CBCRM = avalon.vmodels.CBCRM;
                var kind, request = this.params;
                var mvvm = CBCRM.define('Articles', function (vm) {
                    vm.lang = lang
                    vm.tmpl = tmpl;
                    vm.modelFactory = modelFactory;
                    vm.keyword = ''
                    vm.articlesTypeList = []
                    vm.artclesList = []
                    vm.focusList = []
                    vm.focusTop = {}
                    vm.entity = {}
                    vm.entityType = {}
                    vm.showItem = {}
                    vm.history = []
                    vm.tabName = 'all'
                    vm.isadd = true
                    vm.ADD = false
                    vm.DELETE = false
                    vm.CATEGORYADD = false
                
                    vm.commentList = [];
                    vm.tabChange = function () {
                        var t = $(this);
                        $("#left li").removeClass('selected');
                        t.parent('li').addClass('selected');
                        if (t.attr('tabName') == 'system') {
                            mvvm.showItem.type = t.attr('value');
                            mvvm.tabName = 'all';
                            initWithPageList(mvvm.showItem.$model);
                        }
                        else if (t.attr('tabName') == 'pinglun')
                        {
                            mvvm.tabName = 'pinglun';
                            mvvm.showItem.key = '';
                            GetCommentList(mvvm.showItem.$model);
                        }
                        else
                            mvvm.tabName = t.attr('tabName');
                    }
                    
                    //标签页
                    vm.tab = "tab1";
                    vm.tabWidth = 830;
                    vm.showTab = function (tab) {
                        mvvm.tab = tab;
                    }

                    //分页
                    vm.userpaing = {
                        paging: function () {
                            var that = this
                            mvvm.showItem.pageSize = that.pagesize
                            mvvm.showItem.pageIndex = that.currentindex + 1
                            initWithPageList(mvvm.showItem.$model);
                        }
                    }

                    //分页
                    vm.pinglunpaing = {
                        paging: function () {
                            var that = this
                            mvvm.showItem.pageSize = that.pagesize
                            mvvm.showItem.pageIndex = that.currentindex + 1
                           // mvvm.showItem.ArticlesId = mvvm.entity.$model.Id;
                            GetCommentList(mvvm.showItem.$model);
                        }
                    }

                    //单选员工
                    vm.selectUser = function () {
                        plugins.selectUser({
                            isJoin: true,
                            callback: function (us) {
                                var u = us[0];
                                mvvm.entity.Author = u.FullName;
                            }
                        });
                    }
                    //清空所有查询条件
                    vm.clear = function () {
                        mvvm.showItem = avalon.mix({}, queryData);
                        initWithPageList(mvvm.showItem.$model);
                    }
                    //移除单个查询条件
                    vm.remove = function () {
                        var th = $(this);
                        var itemName = th.attr('item-name');
                        switch (itemName) {
                            case 'category': mvvm.showItem.category = mvvm.showItem.categoryName = ''; break;
                            case 'type': mvvm.showItem.type = mvvm.showItem.typeName = ''; break;
                        }
                        initWithPageList(mvvm.showItem.$model);
                    }
                    //关键字搜索
                    vm.search = function () {
                        if (mvvm.keyword) {
                            mvvm.showItem.key = mvvm.showItem.keyName = mvvm.keyword;
                            initWithPageList(mvvm.showItem.$model);
                            if (mvvm.history.length = 3)
                                mvvm.history.removeAt(2);
                            mvvm.history.unshift(mvvm.keyword);
                        }
                        else messageBox.warning('请输入标题等关键字');
                    }
                    //历史搜索
                    vm.historyClick = function () {
                        mvvm.keyword = $(this).val();
                        mvvm.showItem.key = mvvm.showItem.keyName = mvvm.keyword;
                        initWithPageList(mvvm.showItem.$model);
                    }
                    //分类检索
                    vm.itemSearch = function () {
                        var th = $(this);
                        var itemName = th.attr('item-name');
                        var val = th.attr('value');
                        var text = th.text();
                        th.addClass('selected').siblings().removeClass('selected')
                        switch (itemName) {
                            case 'category':
                                mvvm.showItem.category = mvvm.showItem.categoryName = '';
                                if (val != '0') {
                                    mvvm.showItem.category = val;
                                    mvvm.showItem.categoryName = text;
                                }
                                break;
                            case 'type':
                                mvvm.showItem.type = mvvm.showItem.typeName = '';
                                if (val != '0') {
                                    mvvm.showItem.type = val;
                                    mvvm.showItem.typeName = text;
                                }
                                break;
                        }
                        initWithPageList(mvvm.showItem.$model);
                    }
                    //新增
                    vm.doadd = function () {
                        
                        mvvm.entity = modelFactory.create('Articles');
                        mvvm.entity.Category = [];
                        mvvm.entity.Author = CBCRM.memberShip.FullName;
                        //初始化分类
                        if (mvvm.articlesTypeList.length > 0)
                            mvvm.entity.TypeId = mvvm.articlesTypeList.$model[0].Id
                       
                        NewsWindow("新增新闻");
                         
                        //编辑器
                       
                    }
                    //编辑
                    vm.doedit = function (id) {
                        $.get('/Office/ArticlesDetail/' + id, {}, function (ret) {
                            mvvm.entity = ret.data;
                            mvvm.entity.UpDateTime = GetDateTime();
                            if (mvvm.entity.Category)
                                mvvm.entity.Category = mvvm.entity.Category.split(',');
                            else
                                mvvm.entity.Category = [];
                            
                            //编辑器
                            
                            NewsWindow("编辑新闻");
                        })
                    }
                    //查看
                    vm.doview = function (id) {
                        doView(id)
                    }
                    //删除
                    vm.dodel = function (id) {
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.get('/Office/ArticlesDel/' + id, {}, function (ret) {
                                if (ret.result) {
                                    initWithPageList(mvvm.showItem.$model);
                                }
                            })
                        });
                    }
                    //批量删除
                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        if (deleteIds.length == 0) {
                            messageBox.error("请选择数据！");
                            return;
                        }
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.get('/Office/ArticlesDelAll/', deleteIds, function (ret) {
                                if (ret.result) {
                                    initWithPageList(mvvm.showItem.$model);
                                    messageBox.succeed(ret.message);
                                }
                            });
                        });
                    }
                    //推送
                    vm.doPush = function () {
                        var ids = checkAll(null, true);
                        if (ids.length == 0) {
                            messageBox.error("请选择数据！");
                            return;
                        }
                        messageBox.confirm('确定要推送选中的数据吗？', function () {
                            var ld=CBCRM.loading("正在推送……")
                            $.post('/Office/ArticlesPush/', { ids: ids.join(",") }, function (ret) {
                                ld.close();
                                var icon;
                                if (!ret || !ret.result) icon = "error";
                                else {
                                    if (ret.data.ok == 0) icon = "error";
                                    else if (ret.data.fail == 0) icon = "succeed";
                                    else icon = "warning";
                                    messageBox.notice(icon, ret.message);
                                }
                            });
                        });
                    }
                    vm.delpinglun = function () {
                        var id = $(this).val();
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/Office/ArticlesCommentDel/' + id, {}, function (ret) {
                                if (ret.result) {
                                    GetCommentList(mvvm.showItem.$model);
                                }
                            })
                        });
                    }

                    //批量删除
                    vm.doalldelpinglun = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.post('/Office/ArticlesCommentDelAll/', deleteIds, function (ret) {
                                if (ret.result) {
                                    GetCommentList(mvvm.showItem.$model);
                                    messageBox.succeed(ret.message);
                                }
                            });
                        });
                    }

                    //插入图片
                    vm.open = function () {
                        var type = $(this).attr('val');
                        var uploadModule
                        var dialog
                        CBCRM.fillContentBefore = function (tmpl, lang, contentId, module, mvvm) {
                            dialog = messageBox.openHtml('上传文件', '1000px', '500px', tmpl);
                            avalon.scan(dialog.content(), mvvm);
                            return false;
                        }
                        CBCRM.loadModule('/Upload/Center')
                        CBCRM.onModuleReady = function (data) {
                            avalon.vmodels.upload.itemSelected = function (node, data, file) {
                                var src = '/Upload/' + file.Path;
                                switch (type) {
                                    case "image":
                                        mvvm.entity.DefaultImg = src;
                                        if (dialog) dialog.close();
                                        break;
                                    case "attr":
                                        mvvm.entity.Attachment = src;
                                        if (dialog) dialog.close();
                                        break;
                                    case "insert":
                                        if (isImage(src)) {
                                            var image = new Image();
                                            image.src = src;
                                            kind.insertHtml('<img src="/Upload/' + file.Path + '" width="' + image.width + '" height="' + image.height + '" />');
                                            if (dialog) dialog.close();
                                        }
                                        else messageBox.error("操作失败,尝试插入的文件不是图片格式!");
                                        break;
                                }
                            }
                        }
                    }
                    //返回
                    vm.back = function () {
                        mvvm.tabName = 'all'
                        mvvm.entity = modelFactory.create('Articles');
                    }
                    //新增新闻分类
                    vm.addCategory = function () {
                        mvvm.isadd = true;
                        mvvm.entityType = modelFactory.create('ArticlesType');
                        InCometWindow("新增新闻分类");
                    }
                    //编辑新闻分类
                    vm.editCategory = function () {
                        var id = $(this).val()
                        mvvm.isadd = false;
                        $.get('/Office/ArticlesTypeDetail/' + id, {}, function (ret) {
                            mvvm.entityType = ret.data;
                        });
                        InCometWindow("编辑新闻分类");
                    }

                    vm.saveSort = function () {
                        mvvm.articlesTypeList.$model.forEach(function (item) {
                            
                            $.post("/Office/ArticlesTypeEdit/" + item.Id, item, function (ret) {
                               
                            });
                        })
                        messageBox.ok("保存成功");
                        initWithCategory();
                    }

                    //删除新闻分类
                    vm.delCategory = function () {
                        var id = $(this).val()
                        messageBox.confirm('确定删除新闻分类吗?', function () {
                            $.get('/Office/ArticlesTypeDel/' + id, {}, function (ret) {
                                if (ret.result)
                                    initWithCategory();
                            });
                        });
                    }
                    //提交新闻分类
                    vm.postCategory = function () {
                        var model = mvvm.entityType.$model;
                        if (model.Id == 0 && !mvvm.CATEGORYADD) {
                            messageBox.error("很抱歉，您没有此功能的权限"); return;
                        }
                        if (model.Name == '') {
                            messageBox.warning('请填写新闻分类'); return;
                        }
                        var reg = new RegExp(/^\d+$/);
                        if (!reg.test(model.Sort)) {
                            messageBox.warning('请填写正确的排序数字'); return;
                        }
                        var url = model.Id == 0 ? "/Office/ArticlesTypeAdd/" : "/Office/ArticlesTypeEdit/";
                        $.post(url + model.Id, model, function (ret) {
                            if (ret.result) {
                                messageBox.ok(ret.message);
                                mvvm.entityType = modelFactory.create('ArticlesType');
                                var indialog = art.dialog.list['EditTypeTemplate']
                                if (indialog) indialog.close()
                                initWithCategory();
                            }
                            else messageBox.fail(ret.message);
                        });
                    }
                })

                //构建查询对象
                var queryData = {
                    key: '',
                    keyName: '',
                    category: '',
                    categoryName: '',
                    type: '',
                    typeName: '',
                    pageSize: 20,
                    pageIndex: 1,
                }
                function InCometWindow(title) {
                    var dialog = messageBox.openHtml(title, '300px', '150px', '', [{
                        name: '确定',
                        focus: true,
                        callback: function () {

                            mvvm.postCategory();

                            return false;
                }
                    }], function () {

                    }, 'EditTypeTemplate'

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

                function ViewNewsWindow(title) {
                    var dialog = mvvm.openTmpl({
                        title: title, w: 800, h: 600,
                        tmplid:"viewNewsTemplate"
                    })
                }
                function NewsWindow(title) {
                    mvvm.tab = "tab1";
                    var btns=[{
                        name: '确定',
                        focus: true,
                        callback: function () {
                            var model = mvvm.entity.$model;
                            model.ArtContent = kind.html();
                            model.Category = model.Category.toString();
                            var url = model.Id == 0 ? "/Office/ArticlesAdd/" : "/Office/ArticlesEdit/";
                            if (!model.Title) {
                                messageBox.error('请填写文章标题!');
                                return false;
                            }
                            $.post(url + model.Id, model, function (ret) {
                                if (ret.result) {
                                    mvvm.tabName = 'all';
                                    initWithPageList(mvvm.showItem.$model);
                                    function _close() {
                                        if (dialog) dialog.close()
                                    }
                                    if (!model.Id && ret.data.PushToApp && !ret.data.PushOk) {
                                        messageBox.notice("warning", ret.message, _close);
                                    } else {
                                        messageBox.ok(ret.message, _close);
                                    }
                                    
                                }
                                else
                                    messageBox.error(ret.message);
                            });
                            return false;
                        }
                    }]
                    var dialog = mvvm.openTmpl({
                        title: title, w: mvvm.tabWidth + 20, h: 675,
                        tmplid: "EditNewsTemplate", btns: btns,
                        onclose: function () {
                            destroyui("belongToTree")
                        },
                        onScan: setEditor
                    });
                }
                function setEditor() {
                    kind = ketool.full("ArtContent", 730, 420);
                    if (kind) kind.html(mvvm.entity.$model.ArtContent);
                }
                function GetCommentList(data) {
                    $.get('/Office/ArticlesComment/', data || {}, function (ret) {
                        mvvm.commentList = ret.data.pinglun;
                        avalon.vmodels.ppaing.total = ret.data.RecordTotal;
                    })
                }
                //初始化数据
                function initWithData() {
                    mvvm.showItem = avalon.mix({}, queryData);
                    mvvm.entity = modelFactory.create('Articles');
                    mvvm.entityType = modelFactory.create('ArticlesType');

                    initWithCategory();
                    initWithOther();
                }
                initWithData();
                //拉取列表
                function initWithPageList(data) {
                    $.get('/Office/ArticlesList/', data || {}, function (ret) {
                        mvvm.artclesList = ret.data.Source;
                        mvvm.ADD = ret.data.ADD;
                        mvvm.DELETE = ret.data.DELETE;
                        avalon.vmodels.upaing.total = ret.data.RecordTotal; //分页总数
                    });
                }
                function initWithOther() {
                    $.get('/Office/ArticlesOther/', {}, function (ret) {
                        mvvm.focusList = ret.data.focusList;
                        if (mvvm.focusList.length > 0)
                            mvvm.focusTop = mvvm.focusList[0];
                        var h = mvvm.focusList.length > 0 ? mvvm.focusList.$model[0].Title : '';
                        //slideShow(h);
                    });
                }
                function initWithCategory() {
                    $.get('/Office/Articles/', {}, function (ret) {
                        mvvm.articlesTypeList = ret.data.ArticlesTypeList;
                        mvvm.CATEGORYADD = ret.data.CATEGORYADD;
                    });
                }
                function doView(id) {
                    $.get('/Office/ArticlesDetail/' + id, {}, function (ret) {
                        mvvm.entity = ret.data;
                    });
                    
                    ViewNewsWindow("查看新闻详情");
                }

                avalon.filters.typeItem = function (val) {
                    var result = '';
                    mvvm.articlesTypeList.$model.forEach(function (item) {
                        if (item.Id == val)
                            result = item.Name;
                    });
                    return result;
                }

                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                $('#left_menu_top').html('<h>新闻管理</h><a href="#/Office/ArticlesIndex" title="新闻中心" class="setlistico" style="margin-top:12px;"></a>').show()
            },

            ArticlesView: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM;
                var request = this; 
                
                var mvvm = CBCRM.define('ArticlesView', function (vm) {
                    vm.entity = {}
                    vm.comment = {};
                    vm.articlesTypeList = []
                    vm.commentList = [];
                    vm.userList = [];
                    vm.requestTId = 0;
                    vm.showItem = {}
                    vm.key = "";
                    vm.path = "";
                    vm.boolPinglun = false;
                    vm.typeName="通知公告"
                    vm.Newsearch = function () {
                        mvvm.path = '#/Office/ArticlesList/0/' + encodeURI(mvvm.key)
                    }
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) {
                            mvvm.Newsearch();
                        }
                    }
                    vm.submit = function () {

                        var model = mvvm.comment.$model;
                        model.ArticlesId = mvvm.entity.$model.Id;
                        model.EmpId = CBCRM.memberShip.Id;
                        if (mvvm.comment.$model.Point)
                            model.Point = 1
                        else
                            model.Point = 0;
                        if (model.ComContent) {

                            $.post('/Office/ArticlesCommentAdd', model, function (ret) {
                                messageBox.succeed(ret.message);
                                GetCommentList(mvvm.showItem.$model);
                            })
                        }
                        else
                            messageBox.error("评论内容不能为空");
                       
                        
                    }

                    vm.aboutArticlesList =[] //相关资讯
                    vm.doview = function () {
                        var id = $(this).attr('id')
                        request.params.id = id
                        GetModel()
                    }

                    //分页
                    vm.userpaing = {
                        initload:false,
                        paging: function () {
                            var that = this
                            mvvm.showItem.pageSize = that.pagesize
                            mvvm.showItem.pageIndex = that.currentindex + 1
                            mvvm.showItem.ArticlesId = mvvm.entity.$model.Id;
                            GetCommentList(mvvm.showItem.$model);
                        }
                    }
                }); 
                initWithCategory();
                GetModel();
                function GetModel() {
                    var id = request.params.id;
                    $.get('/Office/ArticlesDetail/' + id, {}, function (ret) {
                        mvvm.entity = ret.data;
                        mvvm.requestTId = mvvm.entity.TypeId;
                        mvvm.showItem.ArticlesId = mvvm.entity.Id;
                        GetCommentList(mvvm.showItem.$model);
                        GetAboutArticles(mvvm.entity.TypeId, mvvm.entity.Id, 6);
                        mvvm.boolPinglun = IsAllowPinglun(mvvm.entity.$model.Category);
                    }) 
                }
                

                function IsAllowPinglun(s)
                {
                    var b = false;
                    var str = s.split(',');
                    for(var i=0;i<str.length;i++)
                    {
                        if (str[i] == 1) {
                            b = true;
                            break;
                        }
                    }
                    return b;
                }

                //构建查询对象
                var queryData = {
                    ArticlesId: 0,
                    pageSize: 20,
                    pageIndex: 1,
                }
                mvvm.showItem = avalon.mix({}, queryData);

                function GetCommentList(data) {
                    $.get('/Office/ArticlesComment/', data || {}, function (ret) {
                        if (ret.data) {
                            ret.data.pinglun.forEach(function (item) {
                                if (!item.EmpPicture) {
                                    item.EmpPicture = "/Content/Themes/Base/Images/" + (item.EmpSex ? "lady" : "man") + "_default.png";
                                }
                            })
                            mvvm.commentList = ret.data.pinglun;
                            avalon.vmodels.upaing.total = ret.data.RecordTotal;
                            mvvm.entity.CommentCount = ret.data.RecordTotal;
                        }
                    })
                }
            
                function initWithCategory() {
                    $.get('/Office/Articles/', {}, function (ret) {
                        mvvm.articlesTypeList = ret.data.ArticlesTypeList;
                        mvvm.articlesTypeList.$model.forEach(function (i) {
                            if (i.Id == mvvm.entity.$model.TypeId)
                                mvvm.typeName = i.Name;
                        })
                    });
                }
                
                function GetAboutArticles(typeid,articlesid,topn) {
                    $.get('/Office/ArticlesAbout/', { 'typeid': typeid, 'articlesid': articlesid, 'topn': topn }, function (ret) {
                        mvvm.aboutArticlesList = ret.data; 
                    });
                }

                mvvm.entity = modelFactory.create('Articles');
                mvvm.comment = modelFactory.create("ArticlesComment"); 
                require('commonui', function () {
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                    avalon.nextTick(function(){
                        $('#left_menu_top').html('<h>新闻中心</h><a href="#/Office/Articles" title="新闻管理" class="setico" style="margin-top:12px;"></a>').show()
                    })
                });
                 
            },

            ArticlesList: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM;
                var request = this;
                var mvvm = avalon.define('ArticlesList', function (vm) {
                    vm.entity = {}
                    vm.articlesTypeList = []
                    
                    vm.artclesList = []
                    vm.typeName = "全部新闻";
                    vm.showItem = {}
                    vm.requestId=0;
                    vm.tabChange = function () { 
                        var t = $(this);
                        mvvm.typeName = t.attr("data");
                        $("#left li").removeClass('selected');
                        t.parent('li').addClass('selected'); 
                            mvvm.showItem.type = t.attr('value'); 
                            initWithPageList(mvvm.showItem.$model);
                        
                    }
                    vm.NewsSearch = function () {  
                        initWithPageList(mvvm.showItem.$model);
                    }
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) {
                            mvvm.Newsearch();
                        }
                    } 
                    //分页
                    vm.userpaing = {
                        paging: function () {
                            var that = this
                            if (request.params.Tid && request.params.Tid != 0)
                                mvvm.showItem.type = request.params.Tid;
                            
                            if (request.params.key) {
                                mvvm.showItem.key = decodeURI(request.params.key);
                                mvvm.typeName = "搜索结果";
                            }
                            mvvm.showItem.pageSize = that.pagesize
                            mvvm.showItem.pageIndex = that.currentindex + 1
                            initWithPageList(mvvm.showItem.$model);
                        }
                    }
                });
                //构建查询对象
                var queryData = {
                    key: '',
                    keyName: '',
                    category: '',
                    categoryName: '',
                    type: '',
                    typeName: '',
                    pageSize: 20,
                    pageIndex: 1,
                }
               
                initWithCategory();
                function initWithCategory() {
                    $.get('/Office/Articles/', {}, function (ret) {
                        if (!ret.result) return CBCRM.showResult(ret);
                        mvvm.articlesTypeList = ret.data.ArticlesTypeList;
                        mvvm.articlesTypeList.$model.forEach(function (i) {
                            if (i.Id == request.params.Tid)
                                mvvm.typeName = i.Name; 
                        })

                    });
                    mvvm.showItem = avalon.mix({}, queryData);
                    
                   
                } 
                
                //function InitSelectMenu()
                //{
                //    var Tid =0;
                //    if(request.params.Tid)
                //        Tid = request.params.Tid;
                //    $("#left li").removeClass('selected');
                //    $("#li" + Tid).addClass('selected');
                //}
                if (request.params.Tid) {
                    mvvm.requestId = request.params.Tid; 
                }
                        
                  
                
                //读取列表
                function initWithPageList(data) {
                    $.get('/Office/ArticlesList/', data || {}, function (ret) {
                        if (!ret.result) return CBCRM.showResult(ret);
                        formatArticlesUrl(ret.data.Source)
                        mvvm.artclesList = ret.data.Source;
                        avalon.vmodels.upaing.total = ret.data.RecordTotal; //分页总数
                    });
                }

                
                avalon.filters.NewsMonth = function (val) {
                    var result = '';
                    mvvm.artclesList.$model.forEach(function (item) {
                        if (item.Id == val)
                            result = item.AddTime.substring(5,7);
                    });
                    return result;
                }


                avalon.filters.NewsDay = function (val) {
                    var result1 = '';
                    mvvm.artclesList.$model.forEach(function (item) {
                        if (item.Id == val)
                            result1 = item.AddTime.substring(8, 10);
                    });
                    return result1;
                }

                
                mvvm.entity = modelFactory.create('Articles');
                require('commonui', function () {
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                    $('#left_menu_top').html('<h>新闻中心</h><a href="#/Office/Articles" title="新闻管理" class="setico" style="margin-top:12px;"></a>').show()
                });
                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.Index = null 
                } 
            },
            /// <summary>
            /// 日程任务
            /// </summary>
            Calendar: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM;
                var request = this.params;
                var mvvm = avalon.define('Calendar', function (vm) {
                    vm.lang = lang
                    vm.$skipArray = ['lang']
                    vm.entity = {}
                    vm.entityList = []
                    vm.pageList = []
                    vm.viewCustomer = function () {
                        var vm = this.$vmodel,
                        item = vm[vm.$itemName]
                        goto('/Customer/DetailCustomer/' + item.CustomId)
                    }
                    vm.entityCategory = {}
                    vm.entityCategoryList = []
                    vm.salasList = []
                    vm.queryData = {}
                    vm.contactList = []
                    vm.contactValue = ''
                    vm.showAdd = false
                    vm.youxian = []
                    vm.ADD = false
                    vm.DELETE = false
                    vm.showOnlyList = false
                    vm.showOnly = true
                    vm.showCustomer = true
                    vm.showBigImage = function () {
                        var val = $(this).attr('val')
                        art.dialog({ title: '查看大图', content: '<img src="' + val + '" />' })
                    }
                    //热度
                    vm.hotOpts = {
                        val: 10,
                        valChanged: function (val) {
                            mvvm.entity.Completion = val
                        }
                    }
                    //分页
                    vm.userpaing = {
                        paging: function () {
                            var that = this
                            mvvm.queryData.pageSize = that.pagesize
                            mvvm.queryData.pageIndex = that.currentindex + 1
                            if (request.cid && request.cid != 0)
                                mvvm.queryData.customerId = request.cid;
                            initWithPageList(mvvm.queryData.$model);
                        }
                    }
                    //选客户/联系人
                    vm.pCustomerOpts = {
                        treeopts: {
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    var zTree = $.fn.zTree.getZTreeObj(treeId)
                                        , parentTreeNode = zTree.getNodeByTId(treeNode.parentTId)
                                    if (parentTreeNode) {
                                        mvvm.entity.CustomId = parentTreeNode.Id;
                                        mvvm.entity.CustomName = parentTreeNode.Name;
                                        mvvm.entity.CustomMan = treeNode.Name || '';
                                        initWithSalas(parentTreeNode.Id)
                                    } else {
                                        mvvm.entity.CustomId = treeNode.Id;
                                        mvvm.entity.CustomName = treeNode.Name;
                                        mvvm.entity.CustomMan = '';
                                        initWithSalas(treeNode.Id)
                                    }

                                }
                            },
                            async: {
                                url: function (treeId) {
                                    if (mvvm.customer.Id && mvvm.customer.Name)
                                        return '/Customer/GetCustomerContacts?customerName=' + mvvm.customer.Name
                                    else {
                                        var url = '/Customer/GetCustomerContacts',
                                        vm = avalon.vmodels[treeId.replace('zTree', '')]
                                        if (vm && vm.q != vm.qcopy) {
                                            if (avalon.vmodels.CBCRM.$debug)
                                                avalon.log('customerName : ' + vm.q)
                                            url += '?customerName=' + vm.q
                                        }
                                        return url
                                    }
                                },
                                dataFilter: function (treeId, parentNode, responseData) {
                                    var ret = [], len, curr
                                    var list = responseData.data;
                                    if (list && list.customers.length) {
                                        list.customers.forEach(function (item) {
                                            item.icon = '/Content/themes/base/images/ico/tree_customercategory0.png'
                                            ret.push(item);
                                            if (item.Contacts && item.Contacts.length) {
                                                item.Contacts.forEach(function (itemChild) {
                                                    itemChild.icon = '/Content/themes/base/images/ico/tree_customercategory0.png'
                                                    itemChild.ParentId = item.Id
                                                    ret.push(itemChild)
                                                })
                                            }
                                        })
                                    }
                                    return ret
                                }
                            }
                        }
                    }
                    //单选员工
                    vm.belongToOpts = {
                        treeopts: {
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    if (treeNode.iconSkin !== 'emp') {
                                        alert('请选择归属员工')
                                        return
                                    }
                                    mvvm.entity.Attendees = treeNode.Id;
                                    mvvm.entity.AttendeeNames = treeNode.Name;
                                }
                            },
                            async: {
                                url: function (treeId, treeNode) {
                                    return "/Settings/GetGroupPostUser/4030000"
                                },
                                dataFilter: groupPostFilter
                            }
                        }
                    }
                    //选择部门、职位、员工
                    vm.downToOpts = {
                        treeopts: {
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    var ids = getNodeIds(treeNode, "emp");
                                    op.extParam = [{ name: "ids", value: ids }];
                                    op.url = "/Office/CalendarList/" + treeNode.Id;
                                    var p = $("#gridcontainer").bcalendar(op).BcalGetOp();
                                    $('#downname').html(treeNode.Name);
                                    mvvm.queryData.ids = ids;
                                    //日历参数
                                    //mvvm.queryData.showdate = p.showdate;
                                    //mvvm.queryData.viewtype = p.viewtype;
                                    //mvvm.queryData.timezone = p.timezone;
                                    mvvm.queryData.vstart = p.vstart;
                                    mvvm.queryData.vend = p.vend;
                                    initWithPageList(mvvm.queryData.$model);
                                }
                            },
                            async: {
                                url: function (treeId, treeNode) {
                                    return "/Settings/GetGroupPostUser/4030000"
                                },
                                dataFilter: groupPostFilter
                            }
                        }
                    }

             
                    vm.birthdayOpts = {
                        format: '%Y-%m-%d %H:%M',
                        onSelect: function (date, formatDate, format) { }
                    }
                    vm.birthdayOpts2 = {
                        format: '%Y-%m-%d %H:%M',
                        onSelect: function (date, formatDate, format) { }
                    }
                    //多选员工
                    vm.shareToOpts = {
                        treeopts: {
                            callback: {
                                onCheck: function (e, treeId, treeNode) {
                                    var treeObj = $.fn.zTree.getZTreeObj(treeId);
                                    var nodes = treeObj.getCheckedNodes(true);
                                    var names = [];
                                    var ids = [];
                                    nodes.forEach(function (n) {
                                        if (n.iconSkin === 'emp') {
                                            names.push(n.Name)
                                            ids.push(n.Id)
                                        }
                                    })
                                    mvvm.entity.OtherAttendee = ids
                                    mvvm.entity.OtherAttendeeNames = names.join(',')
                                }
                            },
                            async: {
                                url: function (treeId, treeNode) {
                                    return "/Settings/GetGroupPostUser/4030000"
                                },
                                dataFilter: groupPostFilter
                            },
                            check: {
                                enable: true,
                                chkboxType: { "Y": "s", "N": "ps" }
                            }
                        }
                    }

                    vm.categoryChange = function () {
                        mvvm.entityCategory = modelFactory.create('CalCategory');
                        var color = mvvm.entityCategory.$model.CategoryColor;
                        //设置颜色
                        if ($('#colorLayer').html() == '') {
                            $('#colorLayer').colorselect({ title: '选择颜色', index: color, hiddenid: "colorValue" });
                        } else {
                            $('.leftdiv').css('background', colorWithIndex(color));
                        }
                        mvvm.showAdd = true;
                    }
                    vm.categoryBack = function () {
                        mvvm.showAdd = false;
                    }
                    vm.categorySubmit = function () {
                        var model = mvvm.entityCategory.$model;
                        if (model.CategoryName) {
                            model.CategoryColor = $('#colorValue').val();
                            var url = model.Id == 0 ? "/Office/CategoryAdd/" : ("/Office/CategoryEdit/" + model.Id);
                            $.post(url, model, function (ret) {
                                if (ret.result) {
                                    mvvm.entityCategoryList = ret.data;
                                    mvvm.showAdd = false;
                                }
                            })
                        }
                        else alert('请填写分类名称');
                    }
                    vm.categoryDetail = function () {
                        mvvm.showAdd = true;
                        var val = $(this).val();
                        $.get('/Office/CategoryDetail/' + val, {}, function (ret) {
                            mvvm.entityCategory = ret.data;
                            var color = mvvm.entityCategory.$model.CategoryColor;
                            //设置颜色
                            if ($('#colorLayer').html() == '') {
                                $('#colorLayer').colorselect({ title: '选择颜色', index: color, hiddenid: "colorValue" });
                            } else {
                                $('.leftdiv').css('background', colorWithIndex(color));
                            }
                        });
                    }
                    vm.categoryDel = function () {
                        if (confirm('确定删除日程分类吗？')) {
                            var i = parseInt($(this).attr('index'));
                            var id = $(this).val();
                            mvvm.entityCategoryList.removeAt(i);
                            $.get('/Office/CategoryDelete/' + id, {}, function (ret) { });
                        }
                    }
                    vm.categorySelect = function () {
                        var val = $(this).val();
                        mvvm.entity.CategoryId = parseInt(val);
                    }
                    vm.showMobile = false
                    //新增
                    vm.doadd = function () {
                        mvvm.showMobile = false;
                        var st = new Date();
                        var ed = new Date();
                        ed = new Date(ed.getTime() + 3600000);
                        mvvm.entity = modelFactory.create('Calendar');
                        wdCalendarOpen('新增日程', st, ed, 0);
                    }
                    //查看
                    vm.doview = function () {
                        mvvm.showMobile = true;
                        var id = $(this).val();
                        doView(id);

                        $('.fancybox').fancybox();
                    }
                    //编辑
                    vm.doedit = function () {
                        mvvm.showMobile = true;
                        var id = $(this).val();
                        wdCalendarOpen('编辑日程', '', '', id);
                    }
                    //删除
                    vm.dodel = function () {
                        var id = $(this).val();
                        var i = parseInt($(this).attr('index'));
                        messageBox.confirm('确定删除此数据吗？', function () {
                            mvvm.pageList.removeAt(i);
                            $.get('/Office/CalendarDelete/' + id, {}, function (ret) { $("#gridcontainer").reload(); });
                        });
                    }
                    //批量删除
                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.get('/Office/CalendarDelAll/', deleteIds, function (ret) {
                                if (ret.result) {
                                    $("#gridcontainer").reload();
                                    initWithPageList();
                                }
                            });
                        });
                    }
                    vm.customer = { Id: '', Name: '' }
                    vm.openimage = function () {
                        var path = $(this).attr('path');
                        art.dialog({ content: '<img src="' + path + '" />', title: '行动图片' });
                    }

                    /*查看地图*/
                    vm.$mapLoaded = false;
                    vm.$map = null;
                    vm.Address = "";
                    vm.loadMap = function (callback) {
                        if (!mvvm.$mapLoaded) {
                            require(["bdmapTool", "ready!"], function (bdmapTool) {
                                mvvm.$map = new bdmapTool({
                                    tmpl: "view",
                                    mapContent: "#dmap",
                                    linepanel: "divline",
                                    left: 0,
                                    right: 820,
                                    height: 520
                                });
                                mvvm.$maploaded = true;
                                if (callback) callback.call(mvvm.$map);
                            });
                        } else {
                            if (callback) {
                                callback.call(mvvm.$map);
                            }
                        }
                    }

                    vm.showMap = function () {
                        var win = art.dialog({
                            width: 300,
                            height: 100,
                            title: "地图加载中……",
                            content: "<img src='/Content/Themes/Base/images/loading2.gif' />"
                        });
                        mvvm.loadMap(function () {
                            var map = mvvm.$map;
                            var point;
                            if (mvvm.entity.Longitude != "" && mvvm.entity.Longitude > 0) {
                                point = new BMap.Point(mvvm.entity.Longitude, mvvm.entity.Latitude);
                            } else {
                                point = null;
                                messageBox.error("抱歉，还未有坐标地址！");
                                return;
                            }
                            map.ops.point = point;
                            map.ops.pointEnd = point;
                            map.openMap(function () {
                                if (win) win.close();
                                if (point) {
                                    //map.addMarker(point, mvvm.entity.Subject);
                                    map.addCustomOverlay(point, {
                                        title:mvvm.entity.Subject
                                    });
                                    map.map.panTo(point);
                                    /*标注上显示地址
                                    var gc = new BMap.Geocoder();
                                    gc.getLocation(point, function (ret) {
                                        var address = ret.address;
                                        var html = "<p>&nbsp;</p><h2>地址：" + address + "</h2>";
                                        var marker = map.addMarker(point, mvvm.entity.Subject);
                                        map.map.panTo(point);
                                        //map.map.setCenter(point);
                                    });
                                    */
                                }
                            });
                        });
                    }

                })
                mvvm.queryData = {
                    pageIndex: '', pageSize: '', customerId: '', ids: '',
                    showdate: '', viewtype: '', timezone: '',
                    vstart: '', vend: ''
                };

                //新增和编辑
                wdCalendarOpen = function (title, start, end, id) {
                    mvvm.Address = "";
                    mvvm.salasList = [];
                    if (id == 0) {
                        if (!mvvm.ADD) {
                            messageBox.error('非常抱歉，您没有此功能的权限！'); return;
                        }
                        mvvm.entity = modelFactory.create('Calendar');
                        mvvm.entity.StartTime = telesa.datetime.cut(start);
                        mvvm.entity.EndTime = telesa.datetime.cut(end);
                        mvvm.entity.Attendees = CBCRM.memberShip.Id
                        mvvm.entity.AttendeeNames = CBCRM.memberShip.FullName
                        mvvm.salasList.unshift({ Id: 0, Title: '无' })

                        if (request.cid && request.cid > 0) {
                            mvvm.entity.CustomId = mvvm.customer.Id;
                            mvvm.entity.CustomName = mvvm.customer.Name;
                            $.get('/Customer/GetConatactByCustomerId/' + mvvm.customer.Id, {}, function (ret) {
                                if (ret.data.length) {
                                    mvvm.contactList = ret.data
                                    mvvm.contactValue = ret.data[0].Id
                                    mvvm.entity.CustomMan = ret.data[0].Name;
                                }
                            });
                        }

                    } else {
                        $.get('/Office/CalendarDetail/' + id, {}, function (ret) {
                            mvvm.entity = ret.data;
                            avalon.vmodels.hotprocessbar.val = parseInt(ret.data.Completion);
                            getLocation();

                            //销售机会
                            mvvm.entity.$watch('SalesId', function (n, o) {
                                mvvm.salasList.forEach(function (item) {
                                    if (item.Id == n) {
                                        mvvm.entity.SalesTitle = item.Title;
                                    }
                                })
                            })

                            if (mvvm.entity.CustomId)
                                initWithSalas(mvvm.entity.CustomId)
                            else {
                                mvvm.salasList.unshift({ Id: 0, Title: '无' })
                            }
                        });
                    }
                    

                    var dialog = messageBox.openHtml(title, '800px', '390px', '', [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            var model = mvvm.entity.$model;
                            //var c = !model.CategoryId ? mvvm.entityCategoryList.$model[0] : getCategory(model.CategoryId);
                            //if (!c || !c.Id) {
                            //    messageBox.warning('请选择日程分类')
                            //    return false;
                            //}
                            if (model.CategoryId) {
                                var c = getCategory(model.CategoryId);
                                if (c && c.Id) {
                                    model.CategoryId = c.Id;
                                    model.Category = c.CategoryName;
                                    model.Color = c.CategoryColor;
                                }
                            }
                            

                            if (model.Subject) {
                                var url = model.Id == 0 ? "/Office/CalendarAdd/" : "/Office/CalendarEdit/" + model.Id;
                                $.post(url, model, function (ret) {
                                    if (ret.result) {
                                        $("#gridcontainer").reload();
                                        initWithPageList(mvvm.queryData.$model);
                                        messageBox.ok(ret.message, function () {
                                            dialog.close();
                                        });
                                    }
                                });
                            }
                            else messageBox.warning('请填写日程主题!');
                            return false;
                        }
                    }],
                    function () {
                        avalon.vmodels.belongToTree.destroy()
                        avalon.vmodels.shareToTree.destroy()
                        avalon.vmodels.setParetCustomer.destroy()
                    });

                    var content = $(dialog.content())
                    content.attr('ms-include', 'formTemplate')
                    avalon.scan(content[0], mvvm)
                    //监控联系人选择项
                    mvvm.$watch('contactValue', function (n, o) {
                        if (mvvm.contactList.length > 0) {
                            mvvm.contactList.forEach(function (item) {
                                if (item.Id == n)
                                    mvvm.entity.CustomMan = item.Name
                            })
                        }
                    })
                }

                function initWithData() {
                    mvvm.entity = modelFactory.create('Calendar');
                    mvvm.entityCategory = modelFactory.create('CalCategory');
                    $.get('/Office/Category/', {}).done(function (ret) {
                        mvvm.entityCategoryList = ret.data
                    });
                    $.get('/Office/Calendar/', {}).done(function (ret) { mvvm.showOnly = ret.data.only });
                    mvvm.youxian = ["最高", "高", "中", "无", "低", "最低"];
                }
                initWithData();

                function getCategory(id) {
                    var res = modelFactory.create('CalCategory');
                    mvvm.entityCategoryList.forEach(function (item) {
                        if (item.Id == id)
                            res = item;
                    });
                    return res;
                }

                function doView(id) {
                    $.get('/Office/CalendarDetail/' + id, {}, function (ret) {
                        mvvm.entity = ret.data;
                        mvvm.Address = "";
                        var dialog = messageBox.openHtml('查看日程', '800px', '340px', '');
                        var content = $(dialog.content())
                        content.attr('ms-include', 'viewTemplate')
                        avalon.scan(content[0], mvvm);
                        getLocation();
                    })
                }
                //地址解析
                function getLocation() {
                    mvvm.Address = "地址解析中……";
                    mvvm.loadMap(function () {
                        var map = mvvm.$map;
                        var point;
                        if (mvvm.entity.Longitude != "" && mvvm.entity.Longitude > 0) {
                            point = new BMap.Point(mvvm.entity.Longitude, mvvm.entity.Latitude);
                            var gc = new BMap.Geocoder();
                            gc.getLocation(point, function (ret) {
                                mvvm.Address = ret.address;
                            });
                        } else {
                            mvvm.Address = "暂无地理位置！";
                        }
                    });
                }
                function initWithPageList(data) {
                    var params = $.extend(true, {}, data);
                    if (params.ids) {
                        if (params.ids.length > 0) $.extend(params, jsonToSubmit("ids", params.ids));
                        else {
                            mvvm.pageList = []
                            avalon.vmodels.upaing.total = 0;
                            return;
                        }
                    }
                    delete params.ids;
                    $.post('/Office/CalendarPageList/', params, function (ret) {
                        ret.data.Source.forEach(function (item) {
                            var toDate = new Date()
                            var endDate = new Date(item.EndTime);
                            item.isOver = toDate.getTime() > endDate.getTime();
                        });
                        mvvm.pageList = ret.data.Source
                        mvvm.ADD = ret.data.ADD;
                        mvvm.DELETE = ret.data.DELETE;
                        avalon.vmodels.upaing.total = ret.data.RecordTotal; //分页总数
                    });
                }
                function initWithSalas(id) {
                    $.get('/Office/GetSalasByCustomer/' + id, {}, function (ret) {
                        ret.data.unshift({ Id: 0, Title: '无' });
                        mvvm.salasList = ret.data;
                        if (ret.data && ret.data.length == 0) {
                            mvvm.entity.SalesId = ret.data[0].Id;
                        }
                    })
                }

                mvvm.entity.$watch('IsAllDayEvent', function (n, o) {
                    var patten = /\d{2}:\d{2}/
                    if (n) {
                        mvvm.entity.StartTime = mvvm.entity.StartTime.replace(patten, '00:00');
                        mvvm.entity.EndTime = mvvm.entity.StartTime.replace(patten, '23:59');
                    } else {
                        mvvm.entity.StartTime = mvvm.entity.StartTime.replace(patten, '00:00');
                        mvvm.entity.EndTime = mvvm.entity.StartTime.replace(patten, '00:00');
                    }
                });

                if (request.id && request.id > 0) {
                    doView(request.id);
                }

                if (request.cid && request.cid > 0) {
                    detail = avalon.vmodels.ViewCustomer
                    if (detail) {
                        /*隐藏其它，只显示列表块*/
                        mvvm.showOnlyList = true
                        detail.showCustomerHead = true
                        detail.otherContent = tmpl
                        avalon.scan(document.getElementById('otherContent'), mvvm)
                        $('#calendar').css({ width: '100%', 'margin-top': '0px', });

                        mvvm.customer.Id = request.cid;
                        mvvm.customer.Name = detail.customerEntity.Name;
                        mvvm.showCustomer = false
                    }
                }
                else CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)

                require('commonui', function () { });
                CBCRM.onLoadModuleBefore = function () {
                    //if (avalon.vmodels.belongToTree)
                    //    avalon.vmodels.belongToTree.destroy();
                    //if (avalon.vmodels.shareToTree)
                    //    avalon.vmodels.shareToTree.destroy();
                    //if (avalon.vmodels.setParetCustomer)
                    //    avalon.vmodels.setParetCustomer.destroy();
                    destroyui(["belongToTree", "shareToTree", "setParetCustomer", "downToTree"]);
                    avalon.vmodels.Calendar = null
                }

                //日程控件相关设置
                var view = "month";
                var op = {
                    view: view,
                    theme: 3,
                    showday: new Date(),
                    ViewCmdhandler: View,
                    onWeekOrMonthToDay: wtd,
                    autoload: true,
                    url: "/Office/CalendarList/",
                    onAfterRequestData: function (s) {
                        console.log(s);
                    }
                };
                var $dv = $("#calhead");
                var _MH = document.documentElement.clientHeight;
                var dvH = $dv.height() + 2;
                op.height = 480;//_MH - dvH;
                op.eventItems = [];

                var p = $("#gridcontainer").bcalendar(op).BcalGetOp();
                setTimeout(function () {
                    if (p && p.datestrshow) {
                        $("#txtdatetimeshow").text(p.datestrshow);
                    }
                }, 2000)

                $("#hdtxtshow").datepicker({
                    picker: "#txtdatetimeshow", showtarget: $("#txtdatetimeshow"),
                    onReturn: function (r) {
                        var p = $("#gridcontainer").gotoDate(r).BcalGetOp();
                        if (p && p.datestrshow) {
                            $("#txtdatetimeshow").text(p.datestrshow);
                        }
                    }
                });
                function View(data) {
                    var str = "";
                    $.each(data, function (i, item) {
                        str += "[" + i + "]: " + item + "\n";
                    });
                    alert(str);
                }
                function wtd(p) {
                    if (p && p.datestrshow) {
                        $("#txtdatetimeshow").text(p.datestrshow);
                    }
                    $("#caltoolbar div.fcurrent").each(function () {
                        $(this).removeClass("fcurrent");
                    })
                    $("#showdaybtn").addClass("fcurrent");
                }
                //日视图
                $("#showdaybtn").click(function (e) {
                    $("#caltoolbar div.fcurrent").each(function () {
                        $(this).removeClass("fcurrent");
                    })
                    $(this).addClass("fcurrent");
                    var p = $("#gridcontainer").swtichView("day").BcalGetOp();
                    if (p && p.datestrshow) {
                        $("#txtdatetimeshow").text(p.datestrshow);
                    }
                    $(this).addClass("active").siblings().removeClass("active");
                });
                //周视图
                $("#showweekbtn").click(function (e) {
                    $("#caltoolbar div.fcurrent").each(function () {
                        $(this).removeClass("fcurrent");
                    })
                    $(this).addClass("fcurrent");
                    var p = $("#gridcontainer").swtichView("week").BcalGetOp();
                    if (p && p.datestrshow) {
                        $("#txtdatetimeshow").text(p.datestrshow);
                    }
                    $(this).addClass("active").siblings().removeClass("active");
                });
                //月视图
                $("#showmonthbtn").click(function (e) {
                    $("#caltoolbar div.fcurrent").each(function () {
                        $(this).removeClass("fcurrent");
                    })
                    $(this).addClass("fcurrent");
                    var p = $("#gridcontainer").swtichView("month").BcalGetOp();
                    if (p && p.datestrshow) {
                        $("#txtdatetimeshow").text(p.datestrshow);
                    }
                    $(this).addClass("active").siblings().removeClass("active");
                });
                //刷新
                $("#showreflashbtn").click(function (e) {
                    $("#gridcontainer").reload();
                });
                //新日程
                $("#faddbtn").click(function (e) {

                });
                //今天
                $("#showtodaybtn").click(function (e) {
                    var p = $("#gridcontainer").gotoDate().BcalGetOp();
                    if (p && p.datestrshow)
                        $("#txtdatetimeshow").text(p.datestrshow);
                });
                //上一个数据表
                $("#sfprevbtn").click(function (e) {
                    var p = $("#gridcontainer").previousRange().BcalGetOp();
                    if (p && p.datestrshow) {
                        $("#txtdatetimeshow").text(p.datestrshow);
                    }
                });
                //下一个数据表
                $("#sfnextbtn").click(function (e) {
                    var p = $("#gridcontainer").nextRange().BcalGetOp();
                    if (p && p.datestrshow) {
                        $("#txtdatetimeshow").text(p.datestrshow);
                    }
                });
                //我的日程
                $('#showmy').click(function () {
                    op.url = "/Office/CalendarList/" + CBCRM.memberShip.Id;
                    var p = $("#gridcontainer").bcalendar(op).BcalGetOp();
                })
                //下属员工
                $('#showdown').click(function () {

                })
                //显示或隐藏分类表单和列表
                $('#CategoryManager').live('click', function () {
                    var warpCategory = $('#warpCategory').show();

                    $("body").bind("mousedown", function (event) {
                        var containerId = "warpCategory";
                        var divcolorLayer = "divcolorLayer";
                        if (!(event.target.id == "CategoryManager"
                            || event.target.id == containerId
                            || event.target.id == divcolorLayer
                            || $(event.target).parents("#" + divcolorLayer).length > 0
                            || $(event.target).parents("#" + containerId).length > 0)) {
                            //$("#" + containerId).hide();
                            warpCategory.hide();
                            $("body").unbind("mousedown");
                            mvvm.showAdd = false;
                        }
                    });
                });
            },

            //工作报告
            DailyReport: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, vmid = "DailyReport";
                var kind1, kind2, request = this.params;
                var action = request.action, paramid = request.id, key = "";
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.$jcal = false;
                    vm.lang = lang
                    vm.entity = {}
                    vm.uid = CBCRM.memberShip.Id;
                    vm.destroy = function () {

                    }
                    vm.ADD = false;
                    vm.DELETE = false;
                    vm.entityList = []
                    vm.calarray = []
                    vm.categorys = []
                    vm.entityDetail = {}
                    vm.entityDetailList = []
                    vm.retreatList = {}

                    vm.customerList = []
                    vm.serviceList = []
                    vm.followupList = []
                    vm.salesList = []
                    vm.documentaryList = []
                    vm.contractList = []
                    vm.complaintsList = []
                    vm.callsList = []
                    vm.showlist = true;
                    vm.sumdata = {};
                    vm.tabWidth = 820;
                    vm.tab = 'tab1';
                    vm.tabChange = function () {
                        var tabid = $(this).attr("val")
                        mvvm.tab = tabid
                    }
                    vm.listtab = 1;
                    vm.listtabChange = function (tabid) {
                        if (tabid == mvvm.listtab) return;
                        mvvm.listtab = tabid;
                        mvvm.addQuery("listType", tabid);
                    }
                    vm.reportTypes = {
                        1: "日报", 2: "周报",
                        3: "月报", 4: "季报",
                        5: "年报"
                    }
                    vm.one = "今日"
                    vm.two = "明日"
                    vm.one1 = "日";
                    vm.empname = ''
                    vm.empsearch = function () {
                        var treeObj = $.fn.zTree.getZTreeObj("empTree")
                        treeObj.reAsyncChildNodes(null, "refresh")
                    }
                    vm.showItem = {}
                    vm.search = {}
                    vm.history = []
                    initQuerys(vm, function (data, name, val, type) {
                        mvvm.grid1.loadData(data);
                    });
                    vm.onRemoveQuery = function (name, type) {
                        if (type == "clear" || name=="emps") {
                            mvvm.clearTree();
                        }
                    }
                    vm.queryData = {
                        key: { label: "关键词", val: "", valLabel: "",syncLabel:true },
                        date: { label: "日期", val: "", valLabel: "" },
                        dateStart: { label: "起始日期", val: "", valLabel: "" },
                        dateEnd: { label: "截止日期", val: "", valLabel: "" },
                        emps: { label: "员工", val: "", valLabel: "" },
                        listType:{label: "列表类型", val: 1,noRemove:true},
                        category: {
                            label: "报告分类", val: "", valLabel: "",
                            items: [
                                { label: "不限", val: '', curr: true },
                                { label: "日报", val: '1', curr: false },
                                { label: "周报", val: '2', curr: false },
                                { label: "月报", val: '3', curr: false },
                                { label: "季报", val: '4', curr: false },
                                { label: "年报", val: '5', curr: false }
                            ]
                        }
                    }
                    vm.grid1 = createGrid({
                        url: "/Office/DailyReport/",
                        modelFactory: modelFactory,
                        $lang: lang,
                        entityId: "DailyReport",
                        pageid: vmid + "_grid1_page",
                        createQuery: function () {
                            var data = mvvm.createQuery();
                            return data;
                        },
                        onLoadData: function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            mvvm.ADD = ret.data.ADD
                            mvvm.DELETE = ret.data.DELETE
                        },
                        onRemove: function (deleteIds) {
                            var gvm = this;
                            $.get('/Office/DailyReportDelAll/', deleteIds, function (ret) {
                                CBCRM.showResult(ret);
                                if (ret.result) {
                                    gvm.reloadData();
                                }
                            });
                        }
                    });
                    vm.birthdayOpts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.ReportStartDate = formatDate;
                            if (mvvm.entity.ReportTypeId == "1") {
                                mvvm.entity.ReportEndDate = formatDate;
                                getHistoryData();
                            }
                            if (["1", "2", "3"].indexOf(mvvm.entity.ReportTypeId) != -1) {
                                getValidTime();
                                getRelatedData();
                            } else {
                                getRelatedSumData();
                            }
                    }
                    }
                    vm.birthdayOpts2 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.ReportEndDate = formatDate;
                            if (mvvm.entity.ReportTypeId == "1") {
                                mvvm.entity.ReportStartDate = formatDate;
                                getHistoryData();
                            }
                            if (["1", "2", "3"].indexOf(mvvm.entity.ReportTypeId) != -1) {
                                getValidTime();
                                getRelatedData();
                            } else {
                                getRelatedSumData();
                            }
                    }
                    }
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.showItem.dateStart = formatDate;
                            mvvm.showItem.datespan = "";
                            mvvm.showItem.datespan = formatDate + "至" + mvvm.showItem.dateEnd;
                            if (mvvm.showItem.dateEnd) initWithPageList(mvvm.showItem.$model);
                        }
                    }
                    vm.dateOpts2 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.showItem.dateEnd = formatDate;
                            mvvm.showItem.datespan = "";
                            mvvm.showItem.datespan = mvvm.showItem.dateStart + "至" + formatDate;
                            if (mvvm.showItem.dateStart) initWithPageList(mvvm.showItem.$model);
                        }
                    }
                    vm.selectSendTo = function () {
                        var ids = mvvm.entity.SendTo || [];
                        if (typeof (ids) == "string") ids = ids.split(",");
                        console.log(ids)
                        plugins.selectUser({
                            multiple:true,
                            listData: ids,
                            callback:function(us){
                                var ids = [], names = [];
                                us.forEach(function (u) {
                                    ids.push(u.Id);
                                    names.push(u.FullName);
                                });
                                mvvm.entity.SendTo = ids.join(",");
                                mvvm.entity.SendToDisplay = names.join(",");
                            }
                        })
                    }
                    vm.sendToOpts = {
                        treeopts: {
                            callback: {
                                onCheck: function (e, 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].FullName);
                                    }
                                    mvvm.entity.SendTo = ids.join(",");
                                    mvvm.entity.SendToDisplay = names.join(",");
                                }
                            },
                            async: {
                                url: function (treeId, treeNode) {
                                    var url = "/Settings/GetGroupPostUsersJoin"
                                    vmtree = avalon.vmodels.daliyReportSendToTree
                                    if (vmtree && vmtree.q && vmtree.q !== vmtree.qcopy) {
                                        url += '?empName=' + vmtree.q
                                    }
                                    return url
                                },
                                dataFilter: notPostFilter
                            },
                            check: {
                                enable: true,
                                chkStyle: "checkbox",
                                chkboxType: { "Y": "p", "N": "s" }
                            }
                        }
                    }
                    vm.removeAllCalarray = function () {
                        mvvm.calarray.removeAll();
                    }
                    vm.clearTree = function () {
                        var treeObj = $.fn.zTree.getZTreeObj("empTree");
                        treeObj.checkAllNodes(false);
                    }
                    vm.timeok = "ok";
                    vm.createEntity = function (item) {
                        if (!item) {
                            item = $.extend(true, {}, modelFactory.create('DailyReport'));
                            item.AddBy = $.extend(true, {}, CBCRM.memberShip.$model);
                            item.ReportTypeId += ''
                            item.ReportStartDate = telesa.datetime.ymd()
                            item.ReportEndDate = telesa.datetime.ymd()
                            if (mvvm.config.configs['UseSendTo'] == '1') {
                                item.SendTo = mvvm.LastSendTo;
                                item.SendToDisplay = mvvm.LastSendToDisplay;
                            }
                            item.YesterdayPlan = mvvm.YesterdayPlan;
                            mvvm.calarray = []
                            mvvm.entityDetailList = []
                        }
                        item.ReportStartDate = item.ReportStartDate.substring(0, 10);
                        item.ReportEndDate = item.ReportEndDate.substring(0, 10);
                        mvvm.entity = item;
                        //监控报告类型
                        mvvm.entity.$watch('ReportTypeId', function (n, o) {
                            var now = new Date(), end = new Date(), day;
                            var showlist = true;
                            switch (parseInt(n)) {
                                case 1:
                                    now = new Date()
                                    mvvm.one = "今日"
                                    mvvm.two = "明日"
                                    mvvm.one1 = "日";
                                    break;
                                case 2:
                                    day = now.getDay()
                                    now.setDate(now.getDate() - day);
                                    end.setDate(end.getDate() + 6 - day);
                                    mvvm.one = "本周"
                                    mvvm.two = "下周"
                                    mvvm.one1 = "周"
                                    break;
                                case 3:
                                    now.setDate(1);
                                    end = new Date(now.getFullYear(), now.getMonth() + 1, 0);
                                    mvvm.one = "本月"
                                    mvvm.two = "下月"
                                    mvvm.one1 = "月"
                                    break;
                                case 4:
                                    now.setMonth(now.getMonth() - 3)
                                    now.setDate(1)
                                    end = new Date(end.getFullYear(), end.getMonth() + 1, 0);
                                    mvvm.one = "本季"
                                    mvvm.two = "下季"
                                    mvvm.one1 = "季"
                                    showlist = false;
                                    break;
                                case 5:
                                    now.setMonth(0)
                                    now.setDate(1)
                                    end = new Date(now.getFullYear(), 12, 0);
                                    mvvm.one = "今年"
                                    mvvm.two = "明年"
                                    mvvm.one1 = "年"
                                    showlist = false;
                                    break;
                                default:
                                    return;
                            }
                            mvvm.showlist = showlist;
                            if (mvvm.action == "add") {
                                mvvm.entity.ReportStartDate = telesa.datetime.ymd(now);
                                mvvm.entity.ReportEndDate = telesa.datetime.ymd(end)
                                mvvm.entity.ReportTitle = "工作" + mvvm.reportTypes[n] + "_" + telesa.datetime.ymd().replace(/-/g, "");
                            }
                            if (mvvm.action == "add" || mvvm.action == "edit") getValidTime();
                            if (showlist) {
                                getRelatedData();
                            } else getRelatedSumData();
                        });
                        var _id = mvvm.entity.ReportTypeId;
                        mvvm.entity.ReportTypeId = "";
                        mvvm.entity.ReportTypeId = _id;
                    }
                    vm.doadd = function () {
                        mvvm.action = 'add'
                        mvvm.tab = 'tab1'
                        
                        mvvm.createEntity();
                        getHistoryData();
                        showForm("新增工作报告");
                    }
                    vm.doview = function (id,tab) {
                        tab = tab || "tab1";
                        mvvm.tab = tab;
                        doView(id)
                    }
                    vm.doedit = function (id) {
                        mvvm.action = 'edit'
                        mvvm.tab = "tab1"
                        mvvm.entityDetailList = []
                        getEntity(id, function (ret) {
                            showForm("编辑工作报告");
                        });
                    }
                    vm.calenderAdd = function () {
                        var c = mvvm.categorys.$model
                            , o = {
                            Id: 0,
                            Subject: '',
                                Category: c.length ? c[0].CategoryName : '',
                                CategoryId: c.length ? c[0].Id : '',
                            StartTime: telesa.datetime.cut(),
                            EndTime: telesa.datetime.cut(),
                            check: false,
                            DailyReport: ""
                        }
                        //mvvm.calarray.push(o)
                        mvvm.entity.CalendarsList.push(o);
                    }
                    vm.calenderAllDel = function () {
                        mvvm.entity.CalendarsList.removeAll();
                            }
                    vm.all = false
                    vm.isadd = true;
                    vm.unit = '朵';
                    vm.viewData = function () {
                        mvvm.isshow = mvvm.isshow == false;
                    }
                    vm.isshow = false;
                    
                    vm.commont = function (item) {
                        var item = item || $.extend(true, {}, modelFactory.create('DailReportDetail'));
                        mvvm.tab = "tab3";
                        mvvm.entityDetail = item.$model || item;
                        mvvm.entityDetail.$watch('FlowersEgg', function (n) {
                            mvvm.unit = n == '1' ? '朵' : '个'
                        });
                        var dialog = messageBox.openHtml('点评意见', '500px', null, '', [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var model = mvvm.entityDetail.$model;
                                model.DailyReportId = mvvm.entity.Id;
                                if (model.Comments) {
                                    var url = model.Id ? "/Office/DailyReportDetailUpdate/" + model.Id : "/Office/DailyReportDetailAdd/";
                                    $.post(url, model, function (ret) {
                                        if (ret.result) {
                                            messageBox.ok(ret.message, function () {
                                                if (dialog) dialog.close();
                                                getDetailList(mvvm.entity.Id);
                                                mvvm.grid1.reloadData();
                                            });
                                        } else {
                                            CBCRM.showResult(ret);
                                        }
                                    })
                                }
                                else messageBox.warning('请输入点评意见!');
                                return false;
                            }
                        }]);

                        var content = $(dialog.content())
                        content.attr('ms-include', 'commTemplate');
                        content.css('padding', '10px').css('padding-bottom', '0px');
                        avalon.scan(content[0], mvvm)
                    }
                    vm.showcommont = false

                    vm.uploadFiles = function () {
                        var upwin=CBCRM.upload(true, function (node, data, file) {
                            mvvm.entity.Affix = '/upload/' + file.Path;
                            upwin.close();
                        }, {muitl:false})
                    }

                    vm.action = ''
                    vm.YesterdayPlan = '';
                    vm.LastSendTo = "";
                    vm.LastSendToDisplay = "";
                    vm.config = {
                        cname: "DailyReport",
                        configs: {
                            CurDayDelay: "0",
                            CurDayHour: "18",
                            CurDayMinute: "30",
                            NextDayHour: "9",
                            NextDayMinute: "30",
                            CurWeekDelay: "0",
                            CurWeekDay: "4",
                            CurWeekHour: "18",
                            CurWeekMinute: "30",
                            NextWeekDay: "0",
                            NextWeekHour: "9",
                            NextWeekMinute: "30",
                            CurMonthDelay: "0",
                            CurMonthLastDay: "5",
                            CurMonthHour: "18",
                            CurMonthMinute: "30",
                            NextMonthBeginDay: "5",
                            NextMonthHour: "9",
                            NextMonthMinute: "30",
                            UseSendTo: "1"
                        }
                    }
                });
                mvvm.grid1.init();
                switch (action) {
                    case "view":
                        doView(paramid)
                        break;
                    case "add":
                        mvvm.doadd();
                        mvvm.entity.ReportTypeId = request.id;
                        break;
                    case "key":
                        mvvm.queryData.key.val = paramid;
                        break;
                }

                function initWithEntity() {
                    //加载日程分类
                    $.get('/Office/Category/', {}, function (ret) {
                        mvvm.categorys = ret.data
                    });
                }
                initWithEntity();
                Config.get(mvvm.config);
                function doView(id) {
                    mvvm.action = "view";
                    mvvm.entityDetailList = []
                    getEntity(id, function (ret) {
                        showForm("查看工作报告", false);
                        //mvvm.showcommont = true;
                        if (mvvm.entity.AddBy.Id == CBCRM.memberShip.Id) {
                            mvvm.grid1.list.forEach(function (item) {
                                if (item.Id == mvvm.entity.Id) {
                                    item.ReadedTotal = item.CommentTotal;
                                }
                            });
                        }
                    });
                }
                function createEditor() {
                    //编辑器
                    if (mvvm.action == "view") return;
                    if (kind1) kind1.remove();
                    kind1 = setEditerSimple('TodaySummary', '700px', '150px');
                    kind1.html(mvvm.entity.TodaySummary);
                    if (kind2) kind2.remove();
                    kind2 = setEditerSimple('TommowPlan', '700px', '150px');
                    kind2.html(mvvm.entity.TommowPlan);
                }
                function showForm(title, b) {
                    var btns = [];
                    if (b == false) {
                        var iscommont = false, incommont = false;
                        mvvm.entityDetailList.forEach(function (item) {
                            if (item.AddEmpId == mvvm.uid) incommont = true;
                            if (item.AddEmpId == mvvm.uid && item.Comments) iscommont = true;
                        });
                        if (incommont || mvvm.config.configs['UseSendTo']=='0') {
                            btns = [{
                                name: "我要点评",
                                focus: true,
                                disabled:iscommont,
                                callback: function () {
                                    mvvm.commont();
                                    return false;
                                }
                            }];
                        }

                    } else {
                        btns = [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                if (kind1) mvvm.entity.TodaySummary = kind1.html();
                                if (kind2) mvvm.entity.TommowPlan = kind2.html();
                                var m = $.extend(true, {}, mvvm.entity.$model);
                                if (!m.ReportStartDate || !m.ReportEndDate) {
                                    messageBox.warning('请选择开始与结束时间！');
                                    return false;
                                }
                                if (m.Title == "") {
                                    messageBox.warning('请填写标题！');
                                    return false;
                                }
                                if (mvvm.config.configs['UseSendTo'] == '1') {
                                    if (!m.SendTo) {
                                        messageBox.warning('请选择呈报领导名单！');
                                        return false;
                                    }
                                }
                                //报告超时检测----暂时使用服务端检测
                                //if (m.ReportTypeId == "1" && config.configs.DateReportDelayDay) {
                                //    var tnow = new Date().getTime();
                                //    var t = new Date(m.ReportStartDate).getTime();
                                //    var c = parseInt((tnow - t) / (1000 * 60 * 60 * 24), 10);//天数
                                //    if (c > config.configs.DateReportDelayDay) {
                                //        messageBox.warning('已经超过（' + m.ReportStartDate + '）'+ c +'天！，按照日报的设置，您已经不能提交该天的报告！');
                                //        return false;
                                //    }
                                //}
                                var clist = m.CalendarsList;//mvvm.calarray.$model
                                clist.forEach(function (item, i) {
                                    var c = getCategory(item.CategoryId);
                                    item.Category = c.CategoryName;
                                    item.Color = c.CategoryColor;
                                });
                                $.extend(m, jsonToSubmit("CalendarsList", clist));
                                delete m.CalendarsList;
                                var url = (m.Id == 0 ? "/Office/DailyReportAdd/" : "/Office/DailyReportEdit/" + m.Id);
                                $.post(url, m, function (ret) {
                                    if (ret.result) {
                                        messageBox.ok(ret.message, function () {
                                            if (dialog) dialog.close();
                                            if (!m.Id) {
                                                mvvm.listtab = 1;
                                                mvvm.addQuery("listType", 1);
                                            } else {
                                                mvvm.grid1.reloadData();
                                            }
                                            if (m.SendTo) {
                                                mvvm.LastSendTo = m.SendTo;
                                                mvvm.LastSendToDisplay = m.SendToDisplay;
                                            }
                                        });
                                    }
                                    else {
                                        messageBox.fail(ret.message);
                                    }
                                })
                                return false;
                            }
                        }]
                    }
                    //if (mvvm.action != "add") getRelatedData();
                    var tmplid = 'DailyReport' + ((mvvm.action == "view" || action == "view") ? "view" : "form") + 'Template';
                    //var htmltmpl=$(tmpl).find("#" + tmplid).text();
                    var dialog = openTmpl({
                        vm: mvvm, title: title, w:mvvm.tabWidth,
                        btns: btns, tmpl: tmpl, tmplid: tmplid,
                        extParam:{top:20},
                        onclose: function () {
                            destroyui(["daliyReportSendToTree"]);
                        }
                    })
                    //if (action == "view") {
                    //    var dialog = openTmpl(mvvm, title, htmltmpl, mvvm.tabWidth, null, btns, null, { top: 20 }, true);
                        
                    //} else {
                    //    var dialog = openTmpl(mvvm, title, htmltmpl, mvvm.tabWidth, null, btns, function () {
                    //        destroyui(["daliyReportSendToTree"]);
                    //    }, { top: 20 }, true);
                    //}
                    avalon.nextTick(function () {
                        createEditor();
                    });
                }
                function formSubmit() {
                    var model = mvvm.entity.$model;
                    mvvm.calarray.forEach(function (item, i) {
                        var c = getCategory(item.CategoryId);
                        model['CalendarsList[' + i + '].Id'] = item.Id;
                        model['CalendarsList[' + i + '].Subject'] = item.Subject;
                        model['CalendarsList[' + i + '].CalendarType'] = item.CalendarType;
                        model['CalendarsList[' + i + '].Completion'] = item.Completion;
                        model['CalendarsList[' + i + '].Description'] = item.Description;
                        model['CalendarsList[' + i + '].SalesId'] = item.SalesId;
                        model['CalendarsList[' + i + '].SalesTitle'] = item.SalesTitle;
                        model['CalendarsList[' + i + '].Attendees'] = item.Attendees;
                        model['CalendarsList[' + i + '].AttendeeNames'] = item.AttendeeNames;
                        model['CalendarsList[' + i + '].CustomId'] = item.CustomId;
                        model['CalendarsList[' + i + '].CustomMan'] = item.CustomMan;
                        model['CalendarsList[' + i + '].CustomName'] = item.CustomName;
                        model['CalendarsList[' + i + '].IsAllDayEvent'] = item.IsAllDayEvent;
                        model['CalendarsList[' + i + '].OtherAttendee'] = item.OtherAttendee;
                        model['CalendarsList[' + i + '].OtherAttendeeNames'] = item.OtherAttendeeNames;
                        model['CalendarsList[' + i + '].CategoryId'] = item.CategoryId;
                        model['CalendarsList[' + i + '].Category'] = c.CategoryName;
                        model['CalendarsList[' + i + '].Color'] = c.CategoryColor;
                        model['CalendarsList[' + i + '].StartTime'] = item.StartTime;
                        model['CalendarsList[' + i + '].EndTime'] = item.EndTime;
                        model['CalendarsList[' + i + '].DailyReport'] = item.DailyReport;
                        model['CalendarsList[' + i + '].PriorityType'] = item.PriorityType;
                    });

                    model.TodaySummary = kind1.html()
                    model.TommowPlan = kind2.html()
                    var url = model.Id == 0 ? "/Office/DailyReportAdd/" : "/Office/DailyReportEdit/" + model.Id;
                    if (model.ReportTitle) {
                        $.post(url, model, function (ret) {
                            if (ret.result) {
                                mvvm.tab = 'list'
                                initWithPageList(mvvm.showItem)
                                messageBox.succeed(ret.message)
                            } else messageBox.error(ret.message)
                        });
                    }
                    else messageBox.warning('请填写报告标题!');
                }

                function getCategory(cid) {
                    var category;
                    mvvm.categorys.forEach(function (item) {
                        if (item.Id == cid)
                            category = item;
                    });
                    return category;
                }
                //获取相关数据
                function getRelatedData() {
                    var data = { id: mvvm.entity.Id, startTime: mvvm.entity.ReportStartDate, endTime: mvvm.entity.ReportEndDate };
                    $.get('/Office/DailyReportGetRelatedData/', data, function (ret) {
                        if (!ret.result) return;
                        mvvm.customerList = ret.data.customerList;
                        mvvm.serviceList = ret.data.serviceList;
                        mvvm.followupList = ret.data.followupList;
                        mvvm.salesList = ret.data.salesList;
                        mvvm.documentaryList = ret.data.documentaryList;
                        mvvm.contractList = ret.data.contractList;
                        mvvm.complaintsList = ret.data.complaintsList;
                        mvvm.callsList = ret.data.callsList;
                        //昨日报告
                        if (ret.data.YesterdayPlan != null) mvvm.YesterdayPlan = ret.data.YesterdayPlan;
                        if (ret.data.LastSendTo != null) {
                            mvvm.LastSendTo = ret.data.LastSendTo;
                            mvvm.LastSendToDisplay = ret.data.LastSendToDisplay;
                        }
                    });
                }
                //获取相关统计数据
                function getRelatedSumData() {
                    var m = mvvm.entity.$model;
                    var data = { id: m.Id, startTime: m.ReportStartDate, endTime: m.ReportEndDate, reportTypeId: m.ReportTypeId };
                    for (var key in mvvm.sumdata.$model) {
                        mvvm.sumdata[key] = "";
                    }
                    $.get('/Office/DailyReportGetRelatedSumData/', data, function (ret) {
                        if (!ret.result) return;
                        mvvm.sumdata = ret.data.sumdata;
                        //昨日报告
                    });
                }
                //获取昨日计划、最后呈报名单
                function getHistoryData() {
                    $.get('/Office/DailyReportGetHistoryData/', { startTime: mvvm.entity.ReportStartDate }, function (ret) {
                        //昨日报告
                        if (ret.data.YesterdayPlan != null) {
                            mvvm.entity.YesterdayPlan = ret.data.YesterdayPlan;
                        }
                        if (ret.data.LastSendTo != null && mvvm.config.configs['UseSendTo'] == '1') {
                            mvvm.entity.SendTo = ret.data.LastSendTo;
                            mvvm.entity.SendToDisplay = ret.data.LastSendToDisplay;
                        }
                    });
                }
                function getValidTime() {
                    var m = mvvm.entity.$model;
                    var data = { Id: m.Id, ReportTypeId: m.ReportTypeId, ReportStartDate: m.ReportStartDate, ReportEndDate: m.ReportEndDate };
                    $.post('/Office/DailyReportGetValidTime/',data , function (ret) {
                        if (!ret.result) return;
                        mvvm.timeok = ret.data.ok;
                    });
                }
                function getEntity(id,callback) {
                    $.get('/Office/DailyReportDetail/' + id, {}, function (ret) {
                        if (!ret.result) {
                            CBCRM.showResult(ret);
                            return;
                        }
                        mvvm.createEntity(ret.data.model);
                        mvvm.entityDetailList = ret.data.entityDetailList;
                        if (callback) callback(ret);
                        //getDetailList(id);
                    });

                        }
                function getDetailList() {
                    $.get('/Office/DailyReportDetailView/' + mvvm.entity.Id, {}, function (ret) {
                        if (ret.result && ret.data) {
                            mvvm.entityDetailList = ret.data;
                            }
                    });
                }

                avalon.filters.reptype = function (val) {
                    var res = '';
                    switch (parseInt(val)) {
                        case 1: res = "日报"; break;
                        case 2: res = "周报"; break;
                        case 3: res = "月报"; break;
                        case 4: res = "季报"; break;
                        case 5: res = "年报"; break;
                    }
                    return res
                }

                avalon.filters.repcategorytype = function (val) {
                    var res = '';
                    var id = parseInt(val)
                    mvvm.categorys.forEach(function (item, index) {
                        if (item.Id == id) {
                            res = item.CategoryName
                        }
                    })
                    return res
                }
                if (!action || action == "key") {
                    require('commonui', function () {
                        CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                        //大日历
                        setJCal('#jscalender', function (day, days,dayArr) {
                            var yy = day.getFullYear();
                            var MM = day.getMonth() + 1;
                            var dd = day.getDate();
                            var date = yy + '-' + (MM < 10 ? ('0' + MM) : MM) + '-' + (dd < 10 ? ('0' + dd) : dd);

                            mvvm.tab = 'list';
                            mvvm.addQuery("date", date, date);
                        });
                    });
                } else {
                    $("#" + contentId).append($(tmpl).filter("style"));
                }
                //选取该节点以及其子节点下所有的员工
                function treeCheckNodes(treeObj, treeNode) {
                    treeObj.checkNode(treeNode, true);
                    if (treeNode.children) {
                        for (var i = 0, l = treeNode.children.length; i < l; i++) {
                            treeCheckNodes(treeObj, treeNode.children[i]);
                        }
                    }
                }

                //选择员工
                var setting = {
                    async: {
                        enable: true,
                        url: function (treeId) {
                            var url = '/Settings/GetGroupPostUser/4040001',
                            m = mvvm
                            if (m && m.empname) {
                                if (avalon.vmodels.CBCRM.$debug)
                                    avalon.log('empName : ' + m.empname)
                                url += '?empName=' + m.empname
                            }
                            return url
                        },
                        type: 'get',
                        dataFilter: groupPostFilter2
                    },
                    callback: {
                        onClick: function (e, treeId, treeNode) {
                            if (treeNode.Id == 1) {
                                mvvm.addQuery("emps", "", treeNode.Name);
                                return;
                            }
                            var treeObj = $.fn.zTree.getZTreeObj(treeId);
                            treeObj.checkAllNodes(false);
                            treeCheckNodes(treeObj, treeNode);
                            var ids = getNodeIds(treeNode, "emp");
                            if (ids.length == 0) {
                                mvvm.addQuery("emps", ids.join(","), treeNode.Name,true);
                                mvvm.grid1.initList([], 0, 1);
                            } else {
                                mvvm.addQuery("emps", ids.join(","), treeNode.Name);
                            }
                        },
                        onCheck: function (e, 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].FullName);
                            }
                            var namestr = avalon.filters.truncate2(names.join(","), 15, "…");
                            if (ids.length == 0) {
                                mvvm.removeQuery("emps");
                            }
                            else mvvm.addQuery("emps", ids.join(","), namestr);
                        }
                    },
                    data: {
                        simpleData: {
                            enable: true,
                            idKey: 'Id',
                            pIdKey: 'ParentId'
                        },
                        key: {
                            name: 'Name'
                        }
                    }
                    ,
                    check: {
                        enable: true,
                        chkStyle: "checkbox",
                        chkboxType: { "Y": "ps", "N": "ps" }
                    }
                }
                $.fn.zTree.init($('#empTree'), setting);
            },

            //物品资产
            GoodsAssets: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM;
                var mvvm = avalon.define('GoodsAssets', function (vm) {
                    vm.bookList = [];
                    vm.goodList = [];
                    vm.assetsList = [];
                    vm.carList = [];
                    vm.showType = 0;//0个人，1公司
                    vm.onShowType = function (v) {
                        mvvm.showType = v;
                        mvvm.loadData();
                    }
                    vm.showSubNav = '';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.loadData = function () {
                        $.post('/Office/GoodsAssets/', { showType: mvvm.showType, pageSize: 5 })
                            .done(function (ret) {
                                if (ret.result) {
                                    if (ret.data) {
                                        mvvm.bookList = ret.data.bookList;
                                        mvvm.goodList = ret.data.goodList;
                                        mvvm.assetsList = ret.data.assetsList;
                                        mvvm.carList = ret.data.carList;
                                        createLineChart(ret.data.goodChart || [], "goodChart");
                                    }
                                } else {
                                    messageBox.error(ret.message);
                                }
                            })
                    }
                });
                mvvm.loadData();
                //线性图
                function createLineChart(chartData, chartId) {
                    var charts = {
                        chart: {
                            //bgColor: 'FFFFFF',
                        },
                        data: chartData
                }
                    var myChart = new FusionCharts("/Scripts/Charts/Charts/Column3D.swf", "funnelChart_" + chartId, "100%", "235");;
                    myChart.setJSONData(charts);
                    myChart.render(chartId);
                }
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.GoodsAssets = null
                }
            },
            //书籍管理
            Books: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this
                require('ConditionFactory', function (conditionFactory) {
                    var conditions = conditionFactory.create(conditionKey || 'Books')
                    , mvvm, init = false

                    CBCRM = avalon.vmodels.CBCRM
                    conditions.conditionChanged = function (item, conditions) {
                        var data = avalon.mix({}, conditions);
                        if (conditions.typeId) {
                            delete data.typeId;
                            avalon.mix(data, mvvm.$typeArr);
                        }
                        mvvm.loadData(data);
                    }
                    conditions.keyCol = 'name';
                    conditions.keyDynamic = false;
                    mvvm = avalon.define('Books', function (vm) {
                        avalon.mix(true, vm, conditions)
                        vm.$skipArray = ['lang']
                        vm.lang = lang
                        /*公用按钮权限设置参数 start*/
                        vm.ADD = false
                        vm.DELETE = false
                        vm.BOOKTYPE = false;
                        /*公用按钮权限设置参数 end*/
                        /*客户 start*/
                        vm.listOpts = { //列表分页组件
                            paging: function () {
                                var m = mvvm,
                                data = m.createDyQuery()
                                data.page = (this.currentindex + 1) || 1
                                data.limit = this.pagesize
                                if (!init) {
                                    data.init = true
                                    init = true
                                }
                                m.loadData(data)
                            }
                        }
                        vm.imgtyps = ["jpg", "png", "gif", "jpeg"];
                        vm.previewPath = "";
                        vm.entity = modelFactory.create('Books');
                        vm.list = []
                        vm.tab = "tab1";
                        vm.tabWidth = 650;
                        vm.tabHeight = 300;
                        vm.checkAll = false;
                        vm.showSubNav = 'books';
                        vm.onSubNav = function (v) {
                            mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                        }
                        vm.showAdd = function () {
                            avalon.mix(mvvm.entity, modelFactory.create('Books'));
                            mvvm.previewPath = "";
                            mvvm.entity.AddBy.FullName = CBCRM.memberShip.FullName;
                            if (!mvvm.entity.AddBy.FullName) mvvm.entity.AddBy.FullName = "";
                            mvvm.entity.StorageId = mvvm.storageDict.size() > 0 ? mvvm.storageDict[0].Id : 0;
                            showForm("新增书籍");
                        }
                        vm.showEdit = function (curitem) {
                            avalon.mix(mvvm.entity, curitem.$model);
                            showForm("编辑书籍");
                        }
                        vm.showView = function (curitem) {
                            avalon.mix(mvvm.entity, curitem.$model);
                            showForm("查看书籍", false);
                        }
                        vm.uploadFiles = function () {
                            var uploadModule, dialog
                            CBCRM.fillContentBefore = function (tmpl, lang, contentId, module, vm) {
                                dialog = messageBox.openHtml('上传文件', '1000px', '500px', tmpl, null, function () {
                                    if (avalon.vmodels.upload) avalon.vmodels.upload = null;
                                });
                                avalon.scan(dialog.content(), mvvm);
                                return false;
                            }
                            CBCRM.loadModule('/Upload/Center')
                            CBCRM.onModuleReady = function (data) {
                                avalon.vmodels.upload.itemSelected = function (node, data, file) {
                                    mvvm.entity.PicturePath = '/upload/' + file.Path;
                                    if (dialog) dialog.close();
                                }
                            }
                        }
                        vm.doRemoveAll = function () {
                            var ids = checkAll();
                            if (!ids["deleteIds[0]"]) {
                                messageBox.error("请选择数据！");
                                return;
                            }
                            messageBox.confirm(lang.RemoveConfirm, function () {
                                $.post('/Office/BooksAllDel/', ids).done(function (ret) {
                                    avalon.vmodels.CBCRM.showResult(ret, function () {
                                        var m = mvvm;
                                        m.conditionChanged(null, m.createDyQuery())
                                        messageBox.close()
                                    })
                                });
                            });

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

                        vm.initList = function (ret) {
                            avalon.log('ret is server response data')
                        }
                        vm.loadData = function (param) {
                            $.post(router.path || '/Office/Books/', param)
                            .done(function (ret) {
                                if (ret.result) {
                                    var lst, stages
                                    if (ret.data.Source) {
                                        mvvm.list = ret.data.Source;
                                    }
                                    avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                                    mvvm.ADD = ret.data.ADD;
                                    mvvm.DELETE = ret.data.DELETE;
                                    mvvm.BOOKTYPE = ret.data.BOOKTYPE;
                                } else {
                                    messageBox.error(ret.message);
                                }
                            })
                        }
                        vm.storageDict = [];
                        vm.loadDict = function () {
                            $.get('/Office/BooksGetDict/').done(function (ret) {
                                if (!ret.result) return;
                                for (var k in ret.data) {
                                    if (mvvm[k]) mvvm[k] = ret.data[k];
                                }
                            });
                        }
                        vm.typelist = [];
                        vm.typeentity = modelFactory.create('BookType');
                        vm.getBookTypeList = function () {
                            $.get('/Office/BooksType/').done(function (ret) {
                                if (ret.result) {
                                    mvvm.typelist = ret.data;
                                    avalon.vmodels.booksTypetree.datasource = ret.data;
                                }
                            });
                        }
                        //标签切换
                        vm.tabChange = function () {
                            var val = $(this).attr('val');
                            mvvm.tab = val;
                        }
                        //日期参数
                        vm.dateOpts = {
                            format: '%Y-%m-%d',
                            onSelect: function (date, formatDate, format) {
                                mvvm.entity.PublicationData = formatDate;
                            }
                        }
                        vm.dateOpts2 = {
                            format: '%Y-%m-%d',
                            onSelect: function (date, formatDate, format) {
                                mvvm.entity.BuyTime = formatDate;
                            }
                        }
                        vm.$typeArr = {};
                        vm.booksTypetreeOpts = {
                            events: {
                                add: function ($cur, data) {
                                    if (data.tadd) {
                                        var pid = data.id, pname = data.name
                                        mvvm.typeentity = modelFactory.create('BookType')
                                        mvvm.typeentity.ParentId.Id = pid
                                        mvvm.typeentity.ParentId.Name = pname
                                        mvvm.typeentity.Parent = pid;
                                        showTypeForm("新增书籍分类");
                                    } else {
                                        messageBox.warning("抱歉，您没有此权限！")
                                    }
                                },
                                edit: function ($cur, data) {
                                    if (data.tedit) {
                                        var id = data.id, name = data.name
                                        $.get('/Office/BooksType/', { "id": id }, function (ret) {
                                            mvvm.typeentity = ret.data[0];
                                            showTypeForm("编辑书籍分类");
                                        })
                                    } else {
                                        messageBox.warning("抱歉，您没有此权限！")
                                    }
                                },
                                remove: function ($cur, data) {
                                    if (data.tdelete) {
                                        var id = data.id, name = data.name
                                        messageBox.confirm('确定删除此数据吗？', function () {
                                            $.post('/Office/BooksTypeDelete/' + id, {}, function (ret) {
                                                if (ret.result) mvvm.getBookTypeList();
                                                else messageBox.error(ret.message);
                                            })
                                        })
                                    } else {
                                        messageBox.warning("抱歉，您没有此权限！")
                                    }
                                }
                            },
                            treeopts: {
                                async: {
                                    url: function () {
                                        return '/Office/BooksType/'
                                    }
                                },
                                callback: {
                                    onClick: function (e, treeId, treeNode) {
                                        console.log(treeNode);
                                        mvvm.typeentity.ParentId.Id = treeNode.Id
                                        mvvm.typeentity.ParentId.Name = treeNode.Name
                                        mvvm.typeentity.Parent = treeNode.Id;
                                        mvvm.typeId.items.removeAll();
                                        var ids = getNodeIds(treeNode);
                                        var typeArr = {};
                                        for (var i = 0, l = ids.length; i < l; i++) {
                                            typeArr["typeId[" + i + "]"] = ids[i];
                                        }
                                        mvvm.$typeArr = typeArr;
                                        var item = { label: treeNode.Name, val: "1", curr: false }
                                        mvvm.typeId.items.push(item);
                                        mvvm.hasCondition = true
                                        mvvm.currConditions['typeId'] = ''
                                        mvvm.currConditions['typeId'] = item.label;
                                        mvvm.checkCondition()
                                        mvvm.conditionChanged(null, mvvm.createDyQuery())
                                    }
                                }
                            }
                        }
                        
                        vm.parentTreeOpts = {
                            treeopts: {
                                async: {
                                    url: function () {
                                        return '/Office/BooksType/'
                                    }
                                },
                                callback: {
                                    onClick: function (e, treeId, treeNode) {
                                        mvvm.typeentity.ParentId.Id = treeNode.Id
                                        mvvm.typeentity.ParentId.Name = treeNode.Name
                                        mvvm.typeentity.Parent = treeNode.Id;
                                    }
                                }
                            }
                        }
                        //
                        vm.formTreeOpts = {
                            treeopts: {
                                async: {
                                    url: function () {
                                        return '/Office/BooksType/'
                                    }
                                },
                                callback: {
                                    onClick: function (e, treeId, treeNode) {
                                        mvvm.entity.TypeId = treeNode.Id
                                        mvvm.entity.TypeIdData = treeNode.Name
                                        if (!mvvm.entity.Id) {
                                            $.post("/Office/BooksGetCountByType/", { id: treeNode.Id }).done(function (ret) {
                                                if (ret.result) {
                                                    mvvm.entity.BookNo = treeNode.TypeNo + "-" + (ret.data.count + 1);
                                                }
                                            });
                                        }
                                    }
                                }
                            }
                        }
                        vm.depatrTreeOpts = {
                            treeopts: {
                                async: {
                                    enable: true,
                                    url: function (treeId, treeNode) {
                                        return "/Settings/GetGroupPostUser/8010000"
                                    }
                                },
                                callback: {
                                    onClick: function (e, treeId, treeNode) {
                                        mvvm.entity.DepatrID = treeNode.Id
                                        mvvm.entity.DepatrIDData = treeNode.Name
                                    }
                                },
                                view: {
                                    addHoverDom: false,
                                    removeHoverDom: false
                                } //替换默认
                            }
                        }
                        vm.bookTypeAdd = function () {
                            mvvm.typeentity = modelFactory.create('BookType');
                            showTypeForm("新增书籍分类");
                        }
                    })
                    mvvm.entity.$watch("BuyCount", function (n, o) {
                        mvvm.entity.TotalMoney = (mvvm.entity.BuyPrice && mvvm.entity.BuyCount) ? mvvm.entity.BuyPrice * mvvm.entity.BuyCount : "";
                        mvvm.entity.InventoryQuantity = mvvm.entity.BuyCount ? mvvm.entity.BuyCount - mvvm.entity.BorrowCount : 0;
                    });
                    mvvm.entity.$watch("BuyPrice", function (n, o) {
                        mvvm.entity.TotalMoney = (mvvm.entity.BuyPrice && mvvm.entity.BuyCount) ? mvvm.entity.BuyPrice * mvvm.entity.BuyCount : "";
                    });
                    function showForm(title, b) {
                        mvvm.tab = "tab1";
                        var btn = b == false ? null : [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var m = mvvm.entity.$model;

                                if (m.Name != "") {
                                    var url = (m.Id == 0 ? "/Office/BooksAdd/" : "/Office/BooksUpdate/");
                                    $.post(url + m.Id, m, function (ret) {
                                        if (ret.result) {
                                            messageBox.ok(ret.message, function () {
                                                if (ret.data.Id) {
                                                    mvvm.entity.Id = ret.data.Id;
                                                }
                                                if (dialog) dialog.close();
                                                mvvm.conditionChanged(null, mvvm.createDyQuery());
                                            });
                                        }
                                        else {
                                            messageBox.fail(ret.message, function () { });
                                        }
                                    })
                                }
                                else messageBox.warning('请填写名称！');
                                mvvm.tab = 'tab1';
                                return false;
                            }
                        }];
                        var dialog = messageBox.openHtml(title, mvvm.tabWidth + 'px', mvvm.tabHeight + 'px', '', btn, function () {
                            destroyui(["booksTypeformtree", "depatrtree"]);
                        });

                        var content = $(dialog.content())
                        content.attr('ms-include', b == false ? 'BooksviewTemplate' : 'BooksformTemplate');
                        content.css("padding", "10px").css("padding-bottom", "10px");
                        avalon.scan(content[0], mvvm);
                    }
                    function showTypeForm(title) {
                        mvvm.typeentity.Parent = mvvm.typeentity.ParentId.Id;
                        var btn = [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var m = mvvm.typeentity.$model;
                                if (m.Name != "") {
                                    var url = (m.Id == 0 ? "/Office/BooksTypeAdd/" : "/Office/BooksTypeUpdate/");
                                    $.post(url + m.Id, m, function (ret) {
                                        if (ret.result) {
                                            messageBox.ok(ret.message, function () {
                                                if (ret.data.Id) {
                                                    mvvm.typeentity.Id = ret.data.Id;
                                                }
                                                dialog.close();
                                                mvvm.getBookTypeList();
                                            });
                                        }
                                        else {
                                            messageBox.fail(ret.message, function () { });
                                        }
                                    })
                                }
                                else messageBox.warning('请填写名称！');
                                mvvm.tab = 'tab1';
                                return false;
                            }
                        }];
                        var dialog = messageBox.openHtml(title, 340, 180, '', btn, function () {
                            destroyui(["booksTypeparenttree"]);
                        });

                        var content = $(dialog.content())
                        content.attr('ms-include', 'BooksTypeformTemplate');
                        content.css("padding", "10px").css("padding-bottom", "10px");
                        avalon.scan(content[0], mvvm);
                    }
                    if (router.params.key) {
                        mvvm.key = router.params.key
                        mvvm.execSearch(mvvm)
                    }
                    mvvm.loadDict();

                    avalon.vmodels.CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                    CBCRM.onLoadModuleBefore = function () {
                        delete avalon.vmodels.Books;
                        //destroyui(["booksTypetree"]);
                    }
                })
            },
            //借阅管理
            BooksBorrow: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this
                require('ConditionFactory', function (conditionFactory) {
                    var conditions = conditionFactory.create(conditionKey || 'BooksBorrow')
                    , mvvm, init = false

                    CBCRM = avalon.vmodels.CBCRM
                    conditions.conditionChanged = function (item, conditions) {
                        mvvm.loadData(conditions)
                    }
                    conditions.keyCol = 'name';
                    conditions.keyDynamic = false;
                    mvvm = avalon.define('BooksBorrow', function (vm) {
                        avalon.mix(true, vm, conditions)
                        vm.$skipArray = ['lang']
                        vm.lang = lang
                        /*公用按钮权限设置参数 start*/
                        vm.ADD = false
                        vm.DELETE = false
                        vm.RETURN = false;
                        /*公用按钮权限设置参数 end*/
                        /*客户 start*/
                        vm.listOpts = { //列表分页组件
                            paging: function () {
                                var m = mvvm,
                                data = m.createDyQuery()
                                data.page = (this.currentindex + 1) || 1
                                data.limit = this.pagesize
                                if (!init) {
                                    data.init = true
                                    init = true
                                }
                                m.loadData(data)
                            }
                        }
                        vm.entity = modelFactory.create('BooksBorrow');
                        vm.list = []
                        vm.tab = "tab1";
                        vm.tabWidth = 650;
                        vm.tabHeight = 300;
                        vm.checkAll = false;
                        vm.showSubNav = 'books';
                        vm.onSubNav = function (v) {
                            mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                        }
                        vm.showAdd = function () {
                            avalon.mix(true, mvvm.entity, modelFactory.create('BooksBorrow'));
                            mvvm.entity.AddBy.FullName = CBCRM.memberShip.FullName;
                            if (!mvvm.entity.AddBy.FullName) mvvm.entity.AddBy.FullName = "";
                            mvvm.booksList.removeAll();
                            mvvm.booksListGetTotal();
                            mvvm.returnList.removeAll();
                            showForm("新增书籍借阅");
                        }
                        vm.showEdit = function (curitem) {
                            avalon.mix(true, mvvm.entity, curitem.$model);
                            mvvm.getBooksList();
                            mvvm.getReturnList();
                            showForm("编辑书籍借阅");
                        }
                        vm.showView = function (curitem) {
                            avalon.mix(true, mvvm.entity, curitem.$model);
                            mvvm.getBooksList();
                            mvvm.getReturnList();
                            showForm("查看书籍借阅", false);
                        }
                        vm.doRemoveAll = function () {
                            var ids = checkAll();
                            if (!ids["deleteIds[0]"]) {
                                messageBox.error("请选择数据！");
                                return;
                            }
                            messageBox.confirm(lang.RemoveConfirm, function () {
                                $.post('/Office/BooksBorrowAllDel/', ids).done(function (ret) {
                                    avalon.vmodels.CBCRM.showResult(ret, function () {
                                        var m = mvvm;
                                        m.conditionChanged(null, m.createDyQuery())
                                        messageBox.close()
                                    })
                                });
                            });

                        }
                        vm.doRemove = function (curItem) {
                            var that = this
                            messageBox.confirm(lang.RemoveConfirm, function () {
                                $.post('/Office/BooksBorrowDel/' + curItem.Id)
                                .done(function (ret) {
                                    avalon.vmodels.CBCRM.showResult(ret, function () {
                                        mvvm.conditionChanged(null, mvvm.createDyQuery())
                                        messageBox.close()
                                    })
                                })
                            })
                        }
                        vm.booksList = [];
                        vm.$tabHeight = vm.tabHeight;
                        vm.booksListGetTotal = function () {
                            var total = 0, totalMoney = 0;;
                            mvvm.booksListTotal = 0;
                            mvvm.booksListTotalMoney = 0;
                            mvvm.booksList.forEach(function (item) {
                                if (item.Number) total += parseInt(item.Number, 10);
                                if (item.TotalMoney) totalMoney += parseFloat(item.TotalMoney, 10);
                            });
                            mvvm.entity.BorrowTotalCount = total;
                            mvvm.entity.BorrowTotalMoney = totalMoney;
                        }
                        vm.addBooksList = function () {
                            mvvm.booksList.push(modelFactory.create('BooksList'));
                            var item = mvvm.booksList[mvvm.booksList.length - 1];
                            item.$watch("Number", function () {
                                item.NotReturnNumber = item.Number;
                                item.TotalMoney = (item.Number && !isNaN(item.Number) && item.Price) ? item.Price * item.Number : 0;
                                mvvm.booksListGetTotal();
                            });
                            item.$watch("Price", function () {
                                item.TotalMoney = (item.Number && !isNaN(item.Number) && item.Price) ? item.Price * item.Number : 0;
                                mvvm.booksListGetTotal();
                            });
                            if (mvvm.booksList.size() > 5) {
                                mvvm.tabHeight += 30;
                            }
                        }
                        vm.delBooksList = function (item) {
                            mvvm.booksList.remove(item);
                        }
                        vm.getBooksList = function () {
                            mvvm.booksList.removeAll();
                            $.post('/Office/BooksList/', { direction: 0, belongId: mvvm.entity.Id }).done(function (ret) {
                                if (ret.result) {
                                    mvvm.booksList = ret.data;
                                    mvvm.booksListGetTotal();
                                    if (mvvm.booksList.size() > 5) {
                                        mvvm.tabHeight += (mvvm.booksList.size() - 5) * 30;
                                    }
                                }
                            });
                        }
                        vm.getBookInfo = function (e, item) {
                            if (e.keyCode != 13) return;
                            $.post('/Office/Books/', { bookNo: item.BookNo }).done(function (ret) {
                                if (ret.result) {
                                    if (ret.data.Source.length == 0) {
                                        messageBox.warning("抱歉，找不到此书籍，请检查输入是否正确！");
                                        return;
                                    }
                                    var m = ret.data.Source[0];
                                    item.BooksId = m.Id;
                                    item.BookNo = m.BookNo;
                                    item.BooksName = m.Name;
                                    item.Price = m.BuyPrice;
                                } else CBCRM.showResult(ret);
                            });
                        }
                        vm.returnList = [];
                        vm.getReturnList = function () {
                            mvvm.returnList.removeAll();
                            $.post('/Office/BooksReturn/', { borrowBillNo: mvvm.entity.BillNo, limit: 100 }).done(function (ret) {
                                if (ret.result) {
                                    mvvm.returnList = ret.data.Source;
                                    if (mvvm.booksList.size() <= 5 && mvvm.returnList.size() > 5) {
                                        mvvm.tabHeight += (mvvm.returnList.size() - 5) * 30;
                                    }
                                }
                            });
                        }
                        vm.loadData = function (param) {
                            $.post(router.path || '/Office/BooksBorrow/', param)
                            .done(function (ret) {
                                if (ret.result) {
                                    var lst, stages
                                    if (ret.data.Source) {
                                        mvvm.list = ret.data.Source;
                                    }
                                    avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                                    mvvm.ADD = ret.data.ADD;
                                    mvvm.DELETE = ret.data.DELETE;
                                    mvvm.RETURN = ret.data.RETURN;
                                } else {
                                    messageBox.error(ret.message);
                                }
                            })
                        }
                        //标签切换
                        vm.tabChange = function () {
                            var val = $(this).attr('val');
                            mvvm.tab = val;
                        }
                        //日期参数
                        vm.dateOpts = {
                            format: '%Y-%m-%d',
                            onSelect: function (date, formatDate, format) {
                                mvvm.entity.BorrowTime = formatDate;
                            }
                        }
                        vm.dateOpts2 = {
                            format: '%Y-%m-%d',
                            onSelect: function (date, formatDate, format) {
                                mvvm.entity.PlanReturnTime = formatDate;
                            }
                        }
                        vm.userTreeOpts = {
                            treeopts: {
                                callback: {
                                    onClick: function (e, treeId, treeNode) {
                                        if (treeNode.iconSkin == "emp") {
                                            mvvm.entity.BorrowBy.Id = treeNode.Id
                                            mvvm.entity.BorrowBy.FullName = treeNode.Name
                                        }
                                    }
                                },
                                async: {
                                    //url: function (treeId, treeNode) {
                                    //    return "/Settings/GetGroupPostUser/"
                                    //},
                                    dataFilter: function (treeId, parentNode, responseData) {
                                        var CBCRM = avalon.vmodels.CBCRM
                                        var ret = [], len = 0, curr, hasEmp = false
                                        if (responseData.data && responseData.data.groups.length)
                                            len = responseData.data.groups.length
                                        while (len) {
                                            curr = responseData.data.groups[--len]
                                            curr.nocheck = 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
                                    }
                                },
                                check: {
                                    enable: false
                                }
                            }
                        }
                    })
                    mvvm.booksList.$watch("length", function () {
                        mvvm.booksListGetTotal();
                    });
                    var dialog;
                    function showForm(title, b) {
                        mvvm.tab = "tab1";
                        mvvm.tabHeight = mvvm.$tabHeight;
                        var btn = [];
                        if (b == false) {
                            if (mvvm.entity.State == 0 || mvvm.entity.State == 1) {
                                //btn.push({
                                //    name: "归还",
                                //    focus: true,
                                //    callback: function () {
                                //        var url = "#!/Office/BooksReturn/" + mvvm.entity.BillNo + "/add/";
                                //        goto(utl);
                                //    }
                                //});
                                btn.push({
                                    name: "设置为坏单",
                                    focus: false,
                                    callback: function () {
                                        var url = "/Office/BooksBorrowBad/" + mvvm.entity.Id;
                                        $.post(url, {}, function (ret) {
                                            if (ret.result) {
                                                messageBox.ok(ret.message, function () {
                                                    if (dialog) dialog.close();
                                                    mvvm.conditionChanged(null, mvvm.createDyQuery());
                                                });
                                            }
                                            else {
                                                messageBox.fail(ret.message, function () { });
                                            }
                                        })
                                    }
                                });
                            }
                        } else {
                            btn.push({
                                name: '提交',
                                focus: true,
                                callback: function () {
                                    var m = mvvm.entity.$model;
                                    delete m.AddBy.hasOwnProperty;
                                    delete m.BorrowBy.hasOwnProperty;
                                    if (mvvm.booksList.size() == 0) {
                                        messageBox.warning("书籍清单至少要包含一本书！");
                                        return false;
                                    }
                                    m["BorrowBy.Id"] = m.BorrowBy.Id;
                                    var b = true;
                                    mvvm.booksList.forEach(function (item, i) {
                                        var bm = item.$model;
                                        for (var k in bm) {
                                            m["Bookslist[" + i + "]." + k] = bm[k];
                                        }
                                        if (item.Number <= 0) b = true;
                                    });
                                    if (!b) {
                                        messageBox.warning("书籍清单不能包含数量为0的书籍！");
                                        return false;
                                    }
                                    if (m.BorrowBy.Id) {
                                        var url = (m.Id == 0 ? "/Office/BooksBorrowAdd/" : "/Office/BooksBorrowUpdate/");
                                        $.post(url + m.Id, m, function (ret) {
                                            if (ret.result) {
                                                messageBox.ok(ret.message, function () {
                                                    if (ret.data.Id) {
                                                        mvvm.entity.Id = ret.data.Id;
                                                    }
                                                    if (dialog) dialog.close();
                                                    mvvm.conditionChanged(null, mvvm.createDyQuery());
                                                });
                                            }
                                            else {
                                                messageBox.fail(ret.message, function () { });
                                            }
                                        })
                                    }
                                    else messageBox.warning('请填写借阅人！');
                                    mvvm.tab = 'tab1';
                                    return false;
                                }
                            });
                        }
                        dialog = messageBox.openHtml(title, mvvm.tabWidth + 'px', mvvm.tabHeight + 'px', '', btn, function () {
                            destroyui(["booksBorrowUserTree"]);
                        });

                        var content = $(dialog.content())
                        content.attr('ms-include', b == false ? 'BooksBorrowviewTemplate' : 'BooksBorrowformTemplate');
                        content.css("padding", "10px").css("padding-bottom", "10px");
                        avalon.scan(content[0], mvvm);
                    }
                    
                    if (router.params.key) {
                        mvvm.key = router.params.key
                        mvvm.execSearch(mvvm)
                    }

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

                    CBCRM.onLoadModuleBefore = function () {
                        delete avalon.vmodels.BooksBorrow;
                    }
                })
            },
            //书籍归还管理
            BooksReturn: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this
                require('ConditionFactory', function (conditionFactory) {
                    var conditions = conditionFactory.create(conditionKey || 'BooksReturn')
                    , mvvm, init = false

                    CBCRM = avalon.vmodels.CBCRM
                    conditions.conditionChanged = function (item, conditions) {
                        mvvm.loadData(conditions)
                    }
                    conditions.keyCol = 'name';
                    conditions.keyDynamic = false;
                    mvvm = avalon.define('BooksReturn', function (vm) {
                        avalon.mix(true, vm, conditions)
                        vm.$skipArray = ['lang']
                        vm.lang = lang
                        vm.ADD = true
                        vm.DELETE = true
                        vm.listOpts = { 
                            paging: function () {
                                var m = mvvm,
                                data = m.createDyQuery()
                                data.page = (this.currentindex + 1) || 1
                                data.limit = this.pagesize
                                if (!init) {
                                    data.init = true
                                    init = true
                                }
                                m.loadData(data)
                            }
                        }
                        vm.entity = modelFactory.create('BooksReturn');
                        vm.list = []
                        vm.tab = "tab1";
                        vm.tabWidth = 650;
                        vm.tabHeight = 300;
                        vm.checkAll = false;
                        vm.showSubNav = 'books';
                        vm.onSubNav = function (v) {
                            mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                        }
                        vm.showAdd = function () {
                            avalon.mix(true, mvvm.entity, modelFactory.create('BooksReturn'));
                            mvvm.booksList.removeAll();
                            mvvm.booksListGetTotal();
                            if (router.params.act == "add") {
                                mvvm.entity.BorrowBillNo = router.params.id;
                                mvvm.getBooksList(router.params.id);
                                delete router.params.id;
                                delete router.params.act;
                            }
                            mvvm.entity.AddBy.FullName = CBCRM.memberShip.FullName;
                            if (!mvvm.entity.AddBy.FullName) mvvm.entity.AddBy.FullName = "";
                            showForm("新增书籍归还");
                        }
                        vm.showEdit = function (curitem) {
                            avalon.mix(true, mvvm.entity, curitem.$model);
                            mvvm.getBooksList();
                            showForm("编辑书籍归还");
                        }
                        vm.showView = function (curitem) {
                            avalon.mix(true, mvvm.entity, curitem.$model);
                            mvvm.getBooksList();
                            showForm("查看书籍归还", false);
                        }
                        vm.doRemoveAll = function () {
                            var ids = checkAll();
                            if (!ids["deleteIds[0]"]) {
                                messageBox.error("请选择数据！");
                                return;
                            }
                            messageBox.confirm(lang.RemoveConfirm, function () {
                                $.post('/Office/BooksReturnAllDel/', ids).done(function (ret) {
                                    avalon.vmodels.CBCRM.showResult(ret, function () {
                                        var m = mvvm;
                                        m.conditionChanged(null, m.createDyQuery())
                                        messageBox.close()
                                    })
                                });
                            });

                        }
                        vm.doRemove = function (curItem) {
                            var that = this
                            messageBox.confirm(lang.RemoveConfirm, function () {
                                $.post('/Office/BooksReturnDel/' + curItem.Id)
                                .done(function (ret) {
                                    avalon.vmodels.CBCRM.showResult(ret, function () {
                                        mvvm.conditionChanged(null, mvvm.createDyQuery())
                                        messageBox.close()
                                    })
                                })
                            })
                        }
                        vm.booksList = [];
                        vm.$tabHeight = vm.tabHeight;
                        vm.booksListGetTotal = function () {
                            var total = 0, totalMoney = 0;;
                            mvvm.booksListTotal = 0;
                            mvvm.booksListTotalMoney = 0;
                            mvvm.booksList.forEach(function (item) {
                                if (item.Number) total += parseInt(item.Number, 10);
                                if (item.TotalMoney) totalMoney += parseFloat(item.TotalMoney, 10);
                            });
                            mvvm.entity.ReturnCount = total;
                            mvvm.entity.ReturnMoney = totalMoney;
                        }
                        vm.delBooksList = function (item) {
                            mvvm.booksList.remove(item);
                        }
                        vm.getBooksList = function (borrowBillNo) {
                            mvvm.booksList.removeAll();
                            var data = borrowBillNo ? { direction: 0, belongId: 0, borrowBillNo: borrowBillNo } : { direction: 1, belongId: mvvm.entity.Id };
                            $.post('/Office/BooksList/', data).done(function (ret) {
                                if (ret.result) {
                                    mvvm.booksList = ret.data;
                                    if (!mvvm.entity.Id) {
                                        mvvm.booksList.forEach(function (item) {
                                            item.Direction = 1;
                                            item.ParentId = item.Id;
                                            item.Id = 0;
                                            item.Number = item.NotReturnNumber;
                                        });
                                    }
                                    mvvm.booksListGetTotal();
                                    mvvm.bindBooklistWatch();
                                    if (mvvm.booksList.size() > 5) {
                                        mvvm.tabHeight += (mvvm.booksList.size - 5) * 30;
                                    }
                                }
                            });
                        }
                        vm.bindBooklistWatch = function () {
                            mvvm.booksList.forEach(function (item) {
                                item.$watch("Number", function () {
                                    if (item.Number > item.NotReturnNumber) {
                                        messageBox.fail("数量超过待还数量，将强制修改为待还数量！", function () {
                                            item.Number = item.NotReturnNumber;
                                        });
                                    }
                                    item.TotalMoney = (item.Number && !isNaN(item.Number) && item.Price) ? item.Price * item.Number : 0;
                                    mvvm.booksListGetTotal();
                                });
                            });
                        }
                        
                        vm.loadData = function (param) {
                            $.post('/Office/BooksReturn/', param)
                            .done(function (ret) {
                                if (ret.result) {
                                    var lst, stages
                                    if (ret.data.Source) {
                                        mvvm.list = ret.data.Source;
                                    }
                                    avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                                    mvvm.ADD = ret.data.ADD;
                                    mvvm.DELETE = ret.data.DELETE;
                                } else {
                                    messageBox.error(ret.message);
                                }
                            })
                        }
                        //标签切换
                        vm.tabChange = function () {
                            var val = $(this).attr('val');
                            mvvm.tab = val;
                        }
                        //日期参数
                        vm.dateOpts = {
                            format: '%Y-%m-%d',
                            onSelect: function (date, formatDate, format) {
                                mvvm.entity.ReturnTime = formatDate;
                            }
                        }
                        vm.userTreeOpts = {
                            treeopts: {
                                callback: {
                                    onClick: function (e, treeId, treeNode) {
                                        if (treeNode.iconSkin == "emp") {
                                            mvvm.entity.ReturnBy.Id = treeNode.Id
                                            mvvm.entity.ReturnBy.FullName = treeNode.Name
                                        }
                                    }
                                },
                                async: {
                                    //url: function (treeId, treeNode) {
                                    //    return "/Settings/GetGroupPostUser/"
                                    //},
                                    dataFilter: function (treeId, parentNode, responseData) {
                                        var CBCRM = avalon.vmodels.CBCRM
                                        var ret = [], len = 0, curr, hasEmp = false
                                        if (responseData.data && responseData.data.groups.length)
                                            len = responseData.data.groups.length
                                        while (len) {
                                            curr = responseData.data.groups[--len]
                                            curr.nocheck = 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
                                    }
                                },
                                check: {
                                    enable: false
                                }
                            }
                        }
                    })
                    mvvm.booksList.$watch("length", function () {
                        mvvm.booksListGetTotal();
                    });
                    var dialog;
                    function showForm(title, b) {
                        mvvm.tab = "tab1";
                        mvvm.tabHeight = mvvm.$tabHeight;
                        var btn = b == false ? null : [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var m = mvvm.entity.$model;
                                delete m.AddBy.hasOwnProperty;
                                delete m.ReturnBy.hasOwnProperty;
                                if (mvvm.booksList.size() == 0) {
                                    messageBox.warning("书籍清单至少要包含一本书！");
                                    return false;
                                }
                                m["ReturnBy.Id"] = m.ReturnBy.Id;
                                var b = true;
                                mvvm.booksList.forEach(function (item, i) {
                                    var bm = item.$model;
                                    for (var k in bm) {
                                        m["Bookslist[" + i + "]." + k] = bm[k];
                                    }
                                    if (item.Number <= 0) b = true;
                                });
                                if (!b) {
                                    messageBox.warning("书籍清单不能包含数量为0的书籍！");
                                    return false;
                                }
                                if (m.ReturnBy.Id) {
                                    var url = (m.Id == 0 ? "/Office/BooksReturnAdd/" : "/Office/BooksReturnUpdate/");
                                    $.post(url + m.Id, m, function (ret) {
                                        if (ret.result) {
                                            messageBox.ok(ret.message, function () {
                                                if (ret.data.Id) {
                                                    mvvm.entity.Id = ret.data.Id;
                                                }
                                                if (dialog) dialog.close();
                                                mvvm.conditionChanged(null, mvvm.createDyQuery());
                                            });
                                        }
                                        else {
                                            messageBox.fail(ret.message, function () { });
                                        }
                                    })
                                }
                                else messageBox.warning('请填写归还人！');
                                mvvm.tab = 'tab1';
                                return false;
                            }
                        }];
                        dialog = messageBox.openHtml(title, mvvm.tabWidth + 'px', mvvm.tabHeight + 'px', '', btn, function () {
                            destroyui(["booksReturnUserTree"]);
                        });

                        var content = $(dialog.content())
                        content.attr('ms-include', b == false ? 'BooksReturnviewTemplate' : 'BooksReturnformTemplate');
                        content.css("padding", "10px").css("padding-bottom", "10px");
                        avalon.scan(content[0], mvvm);
                    }

                    if (router.params.key) {
                        mvvm.key = router.params.key
                        mvvm.execSearch(mvvm)
                    }
                    CBCRM.onLoadModuleBefore = function () {
                        delete avalon.vmodels.BooksReturn;
                    }
                    avalon.vmodels.CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
                    switch (router.params.act) {
                        case "read":
                            $.post('/Office/BooksReturn/', { id: router.params.id })
                            .done(function (ret) {
                                delete router.params.id;
                                delete router.params.act;
                                messageBox.close();
                                if (ret.result) {
                                    if (ret.data.Source.length > 0) mvvm.showView({ $model: ret.data.Source[0] });
                                    else messageBox.warning("抱歉，该数据不存在或已经被删除！");
                                } else {
                                    messageBox.error(ret.message);
                                }
                            })
                            break;
                        case "add":
                            //mvvm.loadData({ borrowBillNo: router.params.id });
                            mvvm.showAdd();
                            break;
                    }
                })
            },
            //物品维护
            GoodsList: function (tmpl, lang, contentId, module, conditionKey) {
                var router, mvvm, init = false;
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define('GoodsList', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.ADD = false
                    vm.DELETE = false
                    vm.loading = true;
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = avalon.mix({}, mvvm.queryinfo.$model);
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    vm.queryinfo = { goodsNo: "", name: "", typeId: "" };
                    vm.doSearch = function () {
                        mvvm.loadData(mvvm.queryinfo.$model);
                    }
                    vm.entity = modelFactory.create('Goods');
                    vm.list = [];
                    initGridvm(vm, vm.list);
                    vm.tab = "tab1";
                    vm.tabWidth = 650;
                    vm.tabHeight = 150;
                    //标签切换
                    vm.tabChange = function () {
                        var val = $(this).attr('val');
                        mvvm.tab = val;
                    }

                    vm.checkAll = false;
                    vm.showSubNav = 'goods';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.showAdd = function () {
                        avalon.mix(mvvm.entity, modelFactory.create('Goods'));
                        mvvm.entity.AddBy.FullName = CBCRM.memberShip.FullName;
                        if (!mvvm.entity.AddBy.FullName) mvvm.entity.AddBy.FullName = "";
                        mvvm.entity.TypeId = mvvm.typeDict.size() > 0 ? mvvm.typeDict[0].Id : 0;
                        showForm("新增物品");
                    }
                    vm.showEdit = function (curitem) {
                        avalon.mix(mvvm.entity, curitem.$model);
                        showForm("编辑物品");
                    }
                    vm.showView = function (curitem) {
                        avalon.mix(mvvm.entity, curitem.$model);
                        showForm("查看物品", false);
                    }
                    vm.doRemoveAll = function () {
                        var ids = mvvm.getIds("deleteIds");
                        if (ids.length == 0) {
                            messageBox.error("请选择数据！");
                            return;
                        }
                        messageBox.confirm(lang.RemoveConfirm, function () {
                            $.post('/Office/GoodsAllDel/', ids).done(function (ret) {
                                avalon.vmodels.CBCRM.showResult(ret, function () {
                                    var m = mvvm;
                                    m.conditionChanged(null, m.createDyQuery())
                                    messageBox.close()
                                })
                            });
                        });

                    }
                    vm.doRemove = function (curItem) {
                        var that = this
                        messageBox.confirm(lang.RemoveConfirm, function () {
                            $.post('/Office/GoodsDel/' + curItem.Id)
                            .done(function (ret) {
                                avalon.vmodels.CBCRM.showResult(ret, function () {
                                    mvvm.conditionChanged(null, mvvm.createDyQuery())
                                    messageBox.close()
                                })
                            })
                        })
                    }

                    vm.initList = function (ret) {
                        avalon.log('ret is server response data')
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/GoodsList/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                var lst, stages
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                                mvvm.ADD = ret.data.ADD;
                                mvvm.DELETE = ret.data.DELETE;
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.typeDict = [];
                    vm.loadDict = function () {
                        $.get('/Office/GoodsGetDict/').done(function (ret) {
                            if (!ret.result) return;
                            for (var k in ret.data) {
                                if (mvvm[k]) mvvm[k] = ret.data[k];
                            }
                            mvvm.typeDict.unshift({ Id: "", Data: "不限" });
                        });
                    }

                })

                function showForm(title, b) {
                    mvvm.tab = "tab1";
                    var btn = b == false ? null : [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            var m = mvvm.entity.$model;
                            if (m.Name != "") {
                                var url = (m.Id == 0 ? "/Office/GoodsAdd/" : "/Office/GoodsUpdate/");
                                $.post(url + m.Id, m, function (ret) {
                                    if (ret.result) {
                                        messageBox.ok(ret.message, function () {
                                            if (ret.data.Id) {
                                                mvvm.entity.Id = ret.data.Id;
                                            }
                                            if (dialog) dialog.close();
                                            mvvm.doSearch();
                                        });
                                    }
                                    else {
                                        messageBox.fail(ret.message, function () { });
                                    }
                                })
                            }
                            else messageBox.warning('请填写名称！');
                            mvvm.tab = 'tab1';
                            return false;
                        }
                    }];
                    var dialog = messageBox.openHtml(title, mvvm.tabWidth + 'px', mvvm.tabHeight + 'px', '', btn, function () {

                    });

                    var content = $(dialog.content())
                    content.attr('ms-include', b == false ? 'GoodsviewTemplate' : 'GoodsformTemplate');
                    content.css("padding", "10px").css("padding-bottom", "10px");
                    avalon.scan(content[0], mvvm);
                }
                mvvm.loadDict();

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

                CBCRM.onLoadModuleBefore = function () {
                    delete avalon.vmodels.GoodsList;
                }
            },
            //物品盘点
            GoodsInventory: function (tmpl, lang, contentId, module, conditionKey) {
                var mvvm, init = false;
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define('GoodsInventory', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.EDIT = false;
                    vm.loading = true;
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = avalon.mix({}, mvvm.queryinfo.$model);
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    vm.queryinfo = { name: "", typeId: "", inventory: "" };
                    vm.doSearch = function () {
                        mvvm.loadData(mvvm.queryinfo.$model);
                    }
                    vm.list = [];
                    initGridvm(vm, vm.list);
                    vm.showSubNav = 'goods';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.initList = function (ret) {

                    }
                    vm.doSave = function () {
                        var a = mvvm.getChecked();
                        if (a.length == 0) {
                            //messageBox.warning("请选择要保存盘点的记录！");
                            //return;
                            a = mvvm.list;
                        }
                        var data = jsonToSubmit("list", a);
                        $.post('/Office/GoodsInventorySave/', data)
                        .done(function (ret) {
                            CBCRM.showResult(ret);
                            if (ret.result) {
                                a.forEach(function (item) {
                                    item.InventoryQuantity = item.LastNumber;
                                });
                            }
                        })
                    }
                    vm.viewInventoryLog = function () {
                        openWin("库存盘点日记", "GoodsInventoryLog", "/Office/GoodsInventoryLog", 900, 600, null);
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/GoodsList/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                mvvm.EDIT = ret.data.EDIT;
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.typeDict = [];
                    vm.loadDict = function () {
                        $.get('/Office/GoodsGetDict/').done(function (ret) {
                            if (!ret.result) return;
                            for (var k in ret.data) {
                                if (mvvm[k]) mvvm[k] = ret.data[k];
                            }
                            mvvm.typeDict.unshift({ Id: "", Data: "不限" });
                        });
                    }
                })
                mvvm.loadDict();
                avalon.vmodels.CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)

                CBCRM.onLoadModuleBefore = function () {
                    delete avalon.vmodels.GoodsInventory;
                }
            },
            //盘点日记
            GoodsInventoryLog: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this, mvvm, init = false;

                CBCRM = avalon.vmodels.CBCRM

                mvvm = avalon.define('GoodsInventoryLog', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.EDIT = false;
                    vm.loading = true;
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = {};
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    vm.list = []
                    initGridvm(vm, vm.list);
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/GoodsInventoryLog/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                mvvm.EDIT = ret.data.EDIT;
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                })
                avalon.vmodels.CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            },
            //物品选择
            GoodsSelect: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this, mvvm, init = false;

                CBCRM = avalon.vmodels.CBCRM

                mvvm = avalon.define('GoodsSelect', 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.loadData({ name: mvvm.key });
                    }
                    vm.clearSearchItem = function () {
                        mvvm.key = "";
                        mvvm.toSearch();
                    }
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = {};
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    vm.list = []
                    initGridvm(vm, vm.list);
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/GoodsList/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                })
                avalon.vmodels.CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            },
            //采购单选择
            GoodsPurchaseSelect: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this, mvvm, init = false;

                CBCRM = avalon.vmodels.CBCRM

                mvvm = avalon.define('GoodsPurchaseSelect', 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.loadData({ name: mvvm.key });
                    }
                    vm.clearSearchItem = function () {
                        mvvm.key = "";
                        mvvm.toSearch();
                    }
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = { state: 2 };//审批通过
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    vm.list = []
                    initGridvm(vm, vm.list);
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/GoodsPurchase/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                })
                avalon.vmodels.CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            },
            //采购历史
            GoodsPurchase: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this
                var mvvm, init = false

                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define('GoodsPurchase', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.ADD = false;
                    vm.CONFIG = false;
                    vm.loading = true;
                    vm.states = [{
                        label: '不限',
                        val: '',
                        curr: true
                    }, {
                        label: '审批中',
                        val: '0',
                        curr: false
                    }, {
                        label: '待入库',
                        val: '2',
                        curr: false
                    }
                        , {
                            label: '已入库',
                            val: '3',
                            curr: false
                        }
                    ]
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = avalon.mix({}, mvvm.queryinfo.$model);
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    vm.queryinfo = { name: "", addBy: "", purchaseDate1: "", purchaseDate2: "", state: "" };
                    vm.doSearch = function () {
                        mvvm.loadData(mvvm.queryinfo.$model);
                    }
                    
                    vm.list = [];
                    initGridvm(vm, vm.list);
                    vm.act = "";
                    vm.showSubNav = 'goods';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.tab = "tab1";
                    vm.tabWidth = 900;
                    vm.tabHeight = 300;
                    //标签切换
                    vm.tabChange = function () {
                        var val = $(this).attr('val');
                        mvvm.tab = val;
                    }
                    vm.goodsList = [];
                    vm.initList = function (ret) {

                    }
                    vm.pconfig = {};
                    vm.showConfig = function () {
                        var btns = [{
                            name: "保存配置",
                            focus: true,
                            callback: function () {
                                var data = mvvm.pconfig.$model;
                                $.post('/Office/GoodsPurchaseConfigSave/' + data.Id, data, function (ret) {
                                    CBCRM.showResult(ret);
                                });
                            }
                        }
                        ];
                        var dialog = openTmpl(mvvm, "采购配置", "config_tmpl", 250, null, btns);
                    }
                    vm.getConfig = function () {
                        $.get('/Office/GoodsPurchaseConfigGet/', function (ret) {
                            if (ret.result) mvvm.pconfig = ret.data.model;
                            else {
                                mvvm.pconfig = { UpdatePrice: false, AutoStorage: false };
                                CBCRM.showResult(ret);
                            }
                        });
                    }
                    vm.createEntity = function () {
                        var s = telesa.datetime.cut();
                        return { FullName: CBCRM.memberShip.FullName, AddTime: s, ReMark: "", TotalMoney: 0 };
                    }
                    vm.entity = {};//vm.createEntity();
                    //日期参数
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.purchaseDate1 = formatDate;
                        }
                    }
                    vm.dateOpts2 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.purchaseDate2 = formatDate;
                        }
                    }
                    vm.dateOpts3 = {
                        format: '%Y-%m-%d %H:%M',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.AddTime = formatDate;
                        }
                    }
                    vm.showSave = function () {
                        mvvm.act = "add";
                        mvvm.goodsList.removeAll();
                        mvvm.entity = mvvm.createEntity();
                        var btns = [{
                            name: "提交申请",
                            focus: true,
                            callback: function () {
                                var a = mvvm.goodsList;
                                if (a.length == 0) {
                                    messageBox.warning("物品列表为空！");
                                    return;
                                }

                                var data = avalon.mix(mvvm.entity.$model, jsonToSubmit("list", a));
                                $.post('/Office/GoodsPurchaseAdd/', data, function (ret) {
                                    CBCRM.showResult(ret);
                                    if (ret.result) {
                                        if (dialog) dialog.close();
                                        mvvm.listOpts.paging();
                                    }
                                });
                                return false;
                            }
                        }
                        ];
                        var dialog = openTmpl(mvvm, "新增采购申请", "GoodsPurchaseAdd_tmpl", mvvm.tabWidth, null, btns);
                    }
                    vm.showView = function (item) {
                        mvvm.act = "view";
                        var billNo = item.BillNo;
                        $.post("/Office/GoodsPurchaseView", { billNo: billNo }, function (ret) {
                            if (ret.result) {
                                mvvm.createEntity();
                                mvvm.goodsList = ret.data.Source;
                                var totalMoney = 0;
                                mvvm.goodsList.forEach(function (m, i) {
                                    if (i == 0) {
                                        mvvm.entity.FullName = m.AddBy.FullName;
                                        mvvm.entity.AddTime = m.AddTime;
                                        mvvm.entity.ReMark = m.ReMark;
                                    }
                                    totalMoney += item.TotalMoney;
                                });
                                mvvm.entity.TotalMoney = totalMoney;
                                var dialog = openTmpl(mvvm, "查看采购申请", "GoodsPurchaseAdd_tmpl", mvvm.tabWidth, null, null);
                            } else {
                                CBCRM.showResult(ret);
                            }
                        });
                    }
                    vm.goodsSelect = function () {
                        var vmid = "GoodsSelect";
                        var dialog = openWin("选择物品", vmid, "/Office/GoodsSelect", 900, 400, [{
                            name: "确定选择",
                            focus: true,
                            callback: function () {
                                var pvm = avalon.vmodels[vmid];
                                if (!pvm) {
                                    messageBox.warning("模块正在载入中，请稍候……");
                                    return false;
                                }
                                var list = pvm.getChecked();
                                if (list.length == 0) {
                                    messageBox.warning("请选择数据！");
                                    return false;
                                }
                                list.forEach(function (item) {
                                    var model = avalon.mix(modelFactory.create("GoodsPurchase"), item.$model);
                                    model.Id = 0;
                                    model.Type = model.TypeIdData;
                                    model.Number = 1;
                                    model.Price = model.ReferencePrice;
                                    mvvm.goodsList.push(model);
                                    var m = mvvm.goodsList[mvvm.goodsList.length - 1];
                                    m.$watch("Number", function (n) {
                                        m.TotalMoney = (m.Number && !isNaN(m.Number) && m.Price) ? m.Price * m.Number : 0;
                                        mvvm.goodsListGetTotal();
                                    });
                                    m.$watch("Price", function (n) {
                                        m.TotalMoney = (m.Price && !isNaN(m.Price) && m.Number) ? m.Price * m.Number : 0;
                                        mvvm.goodsListGetTotal();
                                    });
                                });
                            }
                        }]);
                    }
                    vm.goodsListGetTotal = function () {
                        var total = 0, totalMoney = 0;;
                        mvvm.entity.TotalMoney = "";
                        mvvm.goodsList.forEach(function (item) {
                            if (item.TotalMoney) totalMoney += parseFloat(item.TotalMoney, 10);
                        });
                        mvvm.entity.TotalMoney = totalMoney;
                    }
                    vm.goodsPurchaseApproval = function () {
                        var ids = mvvm.getIds("ids");
                        if (ids.length == 0) {
                            messageBox.error("请选择数据！");
                            return;
                        }
                        messageBox.confirm("是否确认审批？", function () {
                            $.post('/Office/GoodsPurchaseApproval/', ids).done(function (ret) {
                                avalon.vmodels.CBCRM.showResult(ret, function () {
                                    mvvm.listOpts.paging();
                                    messageBox.close()
                                })
                            });
                        });
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/GoodsPurchase/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                mvvm.ADD = ret.data.ADD;
                                mvvm.CONFIG = ret.data.CONFIG;
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                            } else {
                                messageBox.error(ret.message);
                            }
                })
            }
                })
                mvvm.goodsList.$watch("length", function () {
                    mvvm.goodsListGetTotal();
                });
                mvvm.getConfig();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.GoodsPurchase = null;
                }
            },
            //采购入库
            GoodsStorage: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this
                var mvvm, init = false

                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define('GoodsStorage', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.ADD = false;
                    vm.loading = true;
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = avalon.mix({}, mvvm.queryinfo.$model);
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    vm.queryinfo = { name: "", addBy: "", addTime1: "", addTime2: "", type: "" };
                    vm.doSearch = function () {
                        mvvm.loadData(mvvm.queryinfo.$model);
                    }
                    vm.list = [];
                    initGridvm(vm, vm.list);
                    vm.act = "";
                    vm.showSubNav = 'goods';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.tab = "tab1";
                    vm.tabWidth = 900;
                    vm.tabHeight = 300;
                    //标签切换
                    vm.tabChange = function () {
                        var val = $(this).attr('val');
                        mvvm.tab = val;
                    }
                    vm.goodsList = [];
                    vm.initList = function (ret) {

                    }
                    vm.entity = {};
                    vm.createEntity = function () {
                        var dt = new Date();
                        var s = dt.getFullYear() + "-" + (dt.getMonth() + 1) + "-" + dt.getDate();
                        mvvm.entity = { FullName: CBCRM.memberShip.FullName, AddTime: s, ReMark: "", TotalMoney: 0, FromType: 1 };
                        mvvm.entity.$watch("FromType", function (n) {
                            mvvm.goodsList.removeAll();
                        });
                    }

                    //日期参数
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.addTime1 = formatDate;
                        }
                    }
                    vm.dateOpts2 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.addTime2 = formatDate;
                        }
                    }
                    vm.showSave = function () {
                        mvvm.act = "add";
                        mvvm.goodsList.removeAll();
                        mvvm.createEntity();
                        var btns = [{
                            name: "确定入库",
                            focus: true,
                            callback: function () {
                                var a = mvvm.goodsList;
                                if (a.length == 0) {
                                    messageBox.warning("物品列表为空！");
                                    return;
                                }

                                var data = avalon.mix(mvvm.entity.$model, jsonToSubmit("list", a));
                                $.post('/Office/GoodsStorageAdd/', data, function (ret) {
                                    CBCRM.showResult(ret);
                                    if (ret.result) {
                                        if (dialog) dialog.close();
                                        mvvm.listOpts.paging();
                                    }
                                });
                                return false;
                            }
                        }
                        ];
                        var dialog = openTmpl(mvvm, "新增采购入库", "GoodsStorageAdd_tmpl", mvvm.tabWidth, null, btns);
                    }
                    vm.showView = function (item) {
                        mvvm.act = "view";
                        var billNo = item.BillNo;
                        $.post("/Office/GoodsStorageView", { billNo: billNo }, function (ret) {
                            if (ret.result) {
                                mvvm.createEntity();
                                if (ret.data.Source.length > 0) {
                                    var m = ret.data.Source[0];
                                    mvvm.entity.FullName = m.AddBy.FullName;
                                    mvvm.entity.AddTime = m.AddTime;
                                    mvvm.entity.ReMark = m.ReMark;
                                    mvvm.entity.FromType = m.PurchaseId ? 1 : 2;
                                }
                                mvvm.goodsList = ret.data.Source;
                                var dialog = openTmpl(mvvm, "查看采购入库单", "GoodsStorageAdd_tmpl", mvvm.tabWidth);
                            } else {
                                CBCRM.showResult(ret);
                            }
                        });
                    }
                    vm.goodsSelect = function () {
                        var vmid = mvvm.entity.FromType == 1 ? "GoodsPurchaseSelect" : "GoodsSelect",
                            url = mvvm.entity.FromType == 1 ? "/Office/GoodsPurchaseSelect" : "/Office/GoodsSelect",
                            dialog = openWin("选择物品", vmid, url, 900, 400, [{
                                name: "确定选择",
                                focus: true,
                                callback: function () {
                                    var pvm = avalon.vmodels[vmid];
                                    if (!pvm) {
                                        messageBox.warning("系统正在载入中，请稍候……");
                                        return false;
                                    }
                                    var list = pvm.getChecked();
                                    if (list.length == 0) {
                                        messageBox.warning("请选择数据！");
                                        return false;
                                    }
                                    if (mvvm.entity.FromType == 1) {
                                        list.forEach(function (item) {
                                            for (var i = 0, l = mvvm.goodsList.length; i < l; i++) {
                                                if (mvvm.goodsList[i].PurchaseId == item.Id) return;
                                            }
                                            var model = avalon.mix(modelFactory.create("GoodsStorage"), item.$model);
                                            model.PurchaseId = model.Id;
                                            model.Id = 0;
                                            mvvm.goodsList.push(model);
                                            var m = mvvm.goodsList[mvvm.goodsList.length - 1];
                                        });
                                    } else {
                                        list.forEach(function (item) {
                                            for (var i = 0, l = mvvm.goodsList.length; i < l; i++) {
                                                if (mvvm.goodsList[i].GoodsNo == item.GoodsNo) return;
                                            }
                                            var model = avalon.mix(modelFactory.create("GoodsStorage"), item.$model);
                                            model.Id = 0;
                                            model.PurchaseId = 0;
                                            model.Type = model.TypeIdData;
                                            model.Number = 1;
                                            model.Price = model.ReferencePrice;
                                            model.AddBy.Id = 0;
                                            model.AddBy.FullName = "";
                                            model.AddTime = "";
                                            mvvm.goodsList.push(model);
                                        });
                                    }
                                }
                            }]);
                    }
                    vm.removeAllGoods = function () {
                        mvvm.goodsList.removeAll();
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/GoodsStorage/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                mvvm.ADD = ret.data.ADD;
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.typeDict = [];
                    vm.loadDict = function () {
                        $.get('/Office/GoodsGetDict/').done(function (ret) {
                            if (!ret.result) return;
                            for (var k in ret.data) {
                                if (mvvm[k]) mvvm[k] = ret.data[k];
                            }
                        });
                    }
                })
                mvvm.loadDict();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.GoodsStorage = null;
                }
            },
            //领用历史
            GoodsUses: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this
                require('ConditionFactory', function (conditionFactory) {
                    var conditions = conditionFactory.create('GoodsUses')
                    , mvvm, init = false

                    CBCRM = avalon.vmodels.CBCRM
                    mvvm = avalon.define('GoodsUses', function (vm) {
                        vm.$skipArray = ['lang']
                        vm.lang = lang
                        vm.ADD = false;
                        vm.loading = true;
                        vm.states = [{
                            label: '不限',
                            val: '',
                            curr: true
                        }, {
                            label: '审批中',
                            val: '0',
                            curr: false
                        }, {
                            label: '通过审批',
                            val: '2',
                            curr: false
                        }
                        ]
                        vm.listOpts = { //列表分页组件
                            paging: function () {
                                var m = mvvm,
                                data = avalon.mix({}, mvvm.queryinfo.$model);
                                data.page = (this.currentindex + 1) || 1
                                data.limit = this.pagesize
                                if (!init) {
                                    data.init = true
                                    init = true
                                }
                                m.loadData(data)
                            }
                        }
                        vm.queryinfo = { name: "", addBy: "", usesTime1: "", usesTime2: "", type: "", state: "" };
                        vm.doSearch = function () {
                            mvvm.loadData(mvvm.queryinfo.$model);
                        }
                        vm.list = [];
                        initGridvm(vm, vm.list);
                        vm.act = "";
                        vm.showSubNav = 'goods';
                        vm.onSubNav = function (v) {
                            mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                        }
                        vm.tab = "tab1";
                        vm.tabWidth = 900;
                        vm.tabHeight = 300;
                        //标签切换
                        vm.tabChange = function () {
                            var val = $(this).attr('val');
                            mvvm.tab = val;
                        }
                        vm.goodsList = [];
                        vm.initList = function (ret) {

                        }
                        vm.entity = {};
                        vm.createEntity = function () {
                            var dt = new Date();
                            var s = telesa.datetime.cut();
                            mvvm.entity = { FullName: CBCRM.memberShip.FullName, Group: CBCRM.memberShip.Group, AddTime: s, ReMark: "" };
                            console.log(CBCRM.memberShip);
                        }

                        //日期参数
                        vm.dateOpts1 = {
                            format: '%Y-%m-%d',
                            onSelect: function (date, formatDate, format) {
                                mvvm.queryinfo.usesTime1 = formatDate;
                            }
                        }
                        vm.dateOpts2 = {
                            format: '%Y-%m-%d',
                            onSelect: function (date, formatDate, format) {
                                mvvm.queryinfo.usesTime2 = formatDate;
                            }
                        }
                        vm.goodsList = [];
                        vm.showView = function (item) {
                            mvvm.act = "view";
                            var billNo = item.BillNo;
                            $.post("/Office/GoodsUsesView", { billNo: billNo }, function (ret) {
                                if (ret.result) {
                                    mvvm.createEntity();
                                    mvvm.goodsList = ret.data.Source;
                                    if (mvvm.goodsList.size() > 0) {
                                        var m = mvvm.goodsList[0];
                                        mvvm.entity.FullName = m.AddBy.FullName;
                                        mvvm.entity.AddTime = m.AddTime;
                                        mvvm.entity.ReMark = m.ReMark;
                                    }
                                    var dialog = openTmpl(mvvm, "查看领用申请", "GoodsMyUsesAdd_tmpl", mvvm.tabWidth);
                                } else {
                                    CBCRM.showResult(ret);
                                }
                            });
                        }
                        vm
                        vm.goodsUsesApproval = function () {
                            var ids = mvvm.getIds("ids");
                            if (ids.length == 0) {
                                messageBox.error("请选择数据！");
                                return;
                            }
                            messageBox.confirm("是否确认审批？", function () {
                                $.post('/Office/GoodsUsesApproval/', ids).done(function (ret) {
                                    avalon.vmodels.CBCRM.showResult(ret, function () {
                                        mvvm.listOpts.paging();
                                        messageBox.close()
                                    })
                                });
                            });
                        }
                        vm.loadData = function (param) {
                            mvvm.loading = true;
                            $.post('/Office/GoodsUses/', param)
                            .done(function (ret) {
                                mvvm.loading = false;
                                if (ret.result) {
                                    mvvm.ADD = ret.data.ADD;
                                    if (ret.data.Source) {
                                        mvvm.initChecked(ret.data.Source);
                                        mvvm.list = ret.data.Source;
                                    }
                                    avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                                } else {
                                    messageBox.error(ret.message);
                                }
                            })
                        }
                        vm.typeDict = [];
                        vm.loadDict = function () {
                            $.get('/Office/GoodsGetDict/').done(function (ret) {
                                if (!ret.result) return;
                                for (var k in ret.data) {
                                    if (mvvm[k]) mvvm[k] = ret.data[k];
                                }
                            });
                            
                        }
                    })
                    mvvm.loadDict();
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
                    CBCRM.onLoadModuleBefore = function () {
                        avalon.vmodels.GoodsUses = null;
                    }
                })
            },
            //我的领用
            GoodsMyUses: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this
                var mvvm, init = false

                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define('GoodsMyUses', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.ADD = false;
                    vm.loading = true;
                    vm.states = [{
                        label: '不限',
                        val: '',
                        curr: true
                    }, {
                        label: '审批中',
                        val: '0',
                        curr: false
                    }, {
                        label: '通过审批',
                        val: '2',
                        curr: false
                    }
                    ]
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = avalon.mix({}, mvvm.queryinfo.$model);
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    vm.queryinfo = { name: "", addBy: "", usesTime1: "", usesTime2: "", type: "", state: "" };
                    vm.doSearch = function () {
                        mvvm.loadData(mvvm.queryinfo.$model);
                    }
                    vm.list = [];
                    initGridvm(vm, vm.list);
                    vm.act = "";
                    vm.showSubNav = 'goods';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.tab = "tab1";
                    vm.tabWidth = 900;
                    vm.tabHeight = 300;
                    //标签切换
                    vm.tabChange = function () {
                        var val = $(this).attr('val');
                        mvvm.tab = val;
                    }
                    vm.goodsList = [];
                    vm.initList = function (ret) {

                    }
                    vm.entity = {};
                    vm.createEntity = function () {
                        var dt = new Date();
                        var s = telesa.datetime.cut();
                        mvvm.entity = { FullName: CBCRM.memberShip.FullName, Group: CBCRM.memberShip.Group, AddTime: s, ReMark: "" };
                        console.log(CBCRM.memberShip);
                    }

                    //日期参数
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.usesTime1 = formatDate;
                        }
                    }
                    vm.dateOpts2 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.usesTime2 = formatDate;
                        }
                    }
                    vm.dateOpts3 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.AddTime = formatDate;
                        }
                    }
                    vm.showSave = function () {
                        mvvm.act = "add"
                        mvvm.goodsList.removeAll();
                        mvvm.createEntity();
                        var btns = [{
                            name: "发送申请",
                            focus: true,
                            callback: function () {
                                var a = mvvm.goodsList;
                                if (a.length == 0) {
                                    messageBox.warning("物品列表为空！");
                                    return;
                                }

                                var data = avalon.mix(mvvm.entity.$model, jsonToSubmit("list", a));
                                $.post('/Office/GoodsUsesAdd/', data, function (ret) {
                                    CBCRM.showResult(ret);
                                    if (ret.result) {
                                        if (dialog) dialog.close();
                                        mvvm.listOpts.paging();
                                    }
                                });
                                return false;
                            }
                        }
                        ];
                        var dialog = openTmpl(mvvm, "新增领用申请", "GoodsMyUsesAdd_tmpl", mvvm.tabWidth, null, btns);
                    }
                    vm.showView = function (item) {
                        mvvm.act = "view";
                        var billNo = item.BillNo;
                        $.post("/Office/GoodsUsesView", { billNo: billNo }, function (ret) {
                            if (ret.result) {
                                mvvm.createEntity();
                                mvvm.goodsList = ret.data.Source;
                                if (mvvm.goodsList.size() > 0) {
                                    var m = mvvm.goodsList[0];
                                    mvvm.entity.FullName = m.AddBy.FullName;
                                    mvvm.entity.AddTime = m.AddTime;
                                    mvvm.entity.ReMark = m.ReMark;
                                }
                                var dialog = openTmpl(mvvm, "查看领用申请", "GoodsMyUsesAdd_tmpl", mvvm.tabWidth);
                            } else {
                                CBCRM.showResult(ret);
                            }
                        });
                    }
                    vm.goodsSelect = function () {
                        var vmid = "GoodsSelect",
                            url = "/Office/GoodsSelect",
                            dialog = openWin("选择物品", vmid, url, 900, 400, [{
                                name: "确定选择",
                                focus: true,
                                callback: function () {
                                    var pvm = avalon.vmodels[vmid];
                                    if (!pvm) {
                                        messageBox.warning("系统正在载入中，请稍候……");
                                        return false;
                                    }
                                    var list = pvm.getChecked();
                                    if (list.length == 0) {
                                        messageBox.warning("请选择数据！");
                                        return false;
                                    }
                                    list.forEach(function (item) {
                                        for (var i = 0, l = mvvm.goodsList.length; i < l; i++) {
                                            if (mvvm.goodsList[i].GoodsNo == item.GoodsNo) return;
                                        }
                                        var model = avalon.mix(modelFactory.create("GoodsMyUses"), item.$model);
                                        model.Id = 0;
                                        model.Type = model.TypeIdData;
                                        model.Number = 1;
                                        model.AddBy.Id = 0;
                                        model.AddBy.FullName = "";
                                        model.AddTime = "";
                                        mvvm.goodsList.push(model);
                                    });
                                }
                            }]);
                    }
                    vm.removeAllGoods = function () {
                        mvvm.goodsList.removeAll();
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/GoodsMyUses/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                mvvm.ADD = ret.data.ADD;
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.typeDict = [];
                    vm.loadDict = function () {
                        $.get('/Office/GoodsGetDict/').done(function (ret) {
                            if (!ret.result) return;
                            for (var k in ret.data) {
                                if (mvvm[k]) mvvm[k] = ret.data[k];
                            }
                        });
                    }
                })
                mvvm.loadDict();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.GoodsMyUses = null;
                }
            },
            //我的资产
            FixedAssetsMy: function (tmpl, lang, contentId, module, conditionKey) {
                var router, mvvm, init = false;
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define('FixedAssetsMy', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.ADD = false
                    vm.loading = true;
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = avalon.mix({}, mvvm.queryinfo.$model);
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    //日期参数
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.billDate1 = formatDate;
                        }
                    }
                    vm.dateOpts2 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.billDate2 = formatDate;
                        }
                    }

                    vm.queryinfo = { assetsNo: "", name: "", typeId: "", bigtypeId: "", billDate1: "", billDate2: "" };
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.loadData(mvvm.queryinfo.$model);
                    }
                    vm.entity = {};
                    vm.list = [];
                    vm.configList = [];
                    vm.flowList = [];
                    vm.depList = [];
                    vm.allTypes = [];
                    vm.querytypes = [{ Id: "", Name: "请选择" }];
                    vm.types = [{ Id: "", Name: "请选择" }];
                    vm.bigtypes = [{ Id: "", Name: "请选择" }];

                    initGridvm(vm, vm.list);
                    vm.tab = "tab1";
                    vm.tabWidth = 700;
                    vm.tabHeight = 500;
                    //标签切换
                    vm.tabChange = function () {
                        var val = $(this).attr('val');
                        mvvm.tab = val;
                    }

                    vm.showSubNav = 'assets';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.createEntity = function (item) {
                        mvvm.entity = item || modelFactory.create('FixedAssets');
                        bindWatch();
                        watchType(mvvm.entity.Type.Parent.Id, mvvm.types);
                    }
                    
                    vm.showView = function (curitem) {
                        mvvm.createEntity(curitem.$model);
                        mvvm.getFixedAssetsViewList();
                        showForm("查看固定资产", false);
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/FixedAssets/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                var lst, stages
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                                mvvm.ADD = ret.data.ADD;
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.getFixedAssetsViewList = function () {
                        $.post('/Office/FixedAssetsViewList/', { assetsId: mvvm.entity.Id }).done(function (ret) {
                            if (!ret.result) return;
                            mvvm.configList = ret.data.configList;
                            mvvm.flowList = ret.data.flowList;
                            mvvm.depList = ret.data.depList;
                        });
                    }
                    vm.getFixedAssetsConfigList = function () {
                        $.post('/Office/FixedAssetsConfigList/', { assetsId: mvvm.entity.Id }).done(function (ret) {
                            if (!ret.result) return;
                            mvvm.configList = ret.data.configList;
                        });
                    }
                    vm.loadTypes = function () {
                        $.get('/Office/FixedAssetsType/').done(function (ret) {
                            if (!ret.result) return;
                            mvvm.allTypes = ret.data;
                            mvvm.allTypes.forEach(function (item) {
                                if (!item.pId) mvvm.bigtypes.push(item.$model);
                            });

                        });
                    }

                })
                mvvm.createEntity();
                function watchType(n, types) {
                    types.removeAll();
                    types.push({ Id: "", Name: "请选择" });
                    if (!n) return;
                    mvvm.allTypes.forEach(function (item) {
                        if (item.pId == n) types.push(item.$model);
                    });
                }
                function bindWatch() {
                    mvvm.queryinfo.$watch("bigtypeId", function (n) {
                        watchType(n, mvvm.querytypes);
                        mvvm.queryinfo.typeId = "";
                    });
                }
                function showForm(title, b) {
                    mvvm.tab = "tab1";
                    var btns = b == false ? null : [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            var m = mvvm.entity.$model;
                            if (m.Name == "") {
                                messageBox.warning('请填写名称！');
                                return false;
                            }
                            if (!m.Type.Id) {
                                messageBox.warning('请选择类别！');
                                return false;
                            }
                            var url = (m.Id == 0 ? "/Office/FixedAssetsAdd/" : "/Office/FixedAssetsUpdate/" + m.Id);
                            var data = $.extend({}, m, jsonToSubmit("clist", mvvm.configList));
                            $.extend(data, jsonToSubmit("Type", mvvm.entity.Type));
                            delete data.Type.Parent;
                            delete data.Type;
                            $.post(url, data, function (ret) {
                                if (ret.result) {
                                    messageBox.ok(ret.message, function () {
                                        if (ret.data.Id) {
                                            mvvm.entity.Id = ret.data.Id;
                                        }
                                        if (dialog) dialog.close();
                                        mvvm.doSearch();
                                    });
                                }
                                else {
                                    messageBox.fail(ret.message);
                                }
                            })
                            return false;
                        }
                    }];
                    var tmplid = b == false ? 'FixedAssetsviewTemplate' : 'FixedAssetsformTemplate';
                    var dialog = openTmpl(mvvm, title, tmplid, mvvm.tabWidth, null, btns);

                }
                mvvm.loadTypes();
                avalon.vmodels.CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)

                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.FixedAssets = null;
                }
            },
            //资产登记
            FixedAssets: function (tmpl, lang, contentId, module, conditionKey) {
                var router, mvvm, init = false;
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define('FixedAssets', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.ADD = false
                    vm.DELETE = false
                    vm.loading = true;
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = avalon.mix({}, mvvm.queryinfo.$model);
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    //日期参数
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.billDate1 = formatDate;
                        }
                    }
                    vm.dateOpts2 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.billDate2 = formatDate;
                        }
                    }
                    vm.dateOpts3 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.BillDate = formatDate;
                        }
                    }
                    vm.dateOpts4 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.DepreciationStart = formatDate;
                        }
                    }

                    vm.queryinfo = { assetsNo: "", name: "", typeId: "", bigtypeId: "", billDate1: "", billDate2: "" };
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.loadData(mvvm.queryinfo.$model);
                    }
                    vm.entity = {};
                    vm.list = [];
                    vm.configList = [];
                    vm.flowList = [];
                    vm.depList = [];
                    vm.allTypes = [];
                    vm.querytypes = [{ Id: "", Name: "请选择" }];
                    vm.types = [{ Id: "", Name: "请选择" }];
                    vm.bigtypes = [{ Id: "", Name: "请选择" }];

                    initGridvm(vm, vm.list);
                    vm.tab = "tab1";
                    vm.tabWidth = 700;
                    vm.tabHeight = 500;
                    //标签切换
                    vm.tabChange = function () {
                        var val = $(this).attr('val');
                        mvvm.tab = val;
                    }

                    vm.showSubNav = 'assets';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.createEntity = function (item) {
                        mvvm.entity = item || modelFactory.create('FixedAssets');
                        bindWatch();
                        watchType(mvvm.entity.Type.Parent.Id, mvvm.types);
                    }
                    vm.showAdd = function () {
                        vm.createEntity();
                        mvvm.configList.removeAll();
                        showForm("新增固定资产");
                    }
                    vm.showEdit = function (curitem) {
                        mvvm.createEntity(curitem.$model);
                        mvvm.getFixedAssetsConfigList();
                        showForm("编辑固定资产");
                    }
                    vm.showView = function (curitem) {
                        mvvm.createEntity(curitem.$model);
                        mvvm.getFixedAssetsViewList();
                        showForm("查看固定资产", false);
                    }
                    vm.removeAll = function (ids) {
                        console.log(ids);
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/FixedAssets/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                var lst, stages
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                                mvvm.ADD = ret.data.ADD;
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.addConfig = function () {
                        mvvm.configList.push(modelFactory.create('FixedAssetsConfig'));
                    }
                    vm.removeAllConfig = function () {
                        mvvm.configList.removeAll();
                    }
                    vm.getFixedAssetsViewList = function () {
                        $.post('/Office/FixedAssetsViewList/', { assetsId: mvvm.entity.Id }).done(function (ret) {
                            if (!ret.result) return;
                            mvvm.configList = ret.data.configList;
                            mvvm.flowList = ret.data.flowList;
                            mvvm.depList = ret.data.depList;
                        });
                    }
                    vm.getFixedAssetsConfigList = function () {
                        $.post('/Office/FixedAssetsConfigList/', { assetsId: mvvm.entity.Id }).done(function (ret) {
                            if (!ret.result) return;
                            mvvm.configList = ret.data.configList;
                        });
                    }
                    vm.loadTypes = function () {
                        $.get('/Office/FixedAssetsType/').done(function (ret) {
                            if (!ret.result) return;
                            mvvm.allTypes = ret.data;
                            mvvm.allTypes.forEach(function (item) {
                                if (!item.pId) mvvm.bigtypes.push(item.$model);
                            });

                        });
                    }

                })
                mvvm.createEntity();
                function watchType(n, types) {
                    types.removeAll();
                    types.push({ Id: "", Name: "请选择" });
                    if (!n) return;
                    mvvm.allTypes.forEach(function (item) {
                        if (item.pId == n) types.push(item.$model);
                    });
                }
                function bindWatch() {
                    mvvm.queryinfo.$watch("bigtypeId", function (n) {
                        watchType(n, mvvm.querytypes);
                        mvvm.queryinfo.typeId = "";
                    });
                    mvvm.entity.Type.Parent.$watch("Id", function (n) {
                        watchType(n, mvvm.types);
                        mvvm.entity.Type.Id = "";
                    });
                    mvvm.entity.Type.$watch("Id", function (n) {
                        if (n == "") return;
                        mvvm.types.forEach(function (item) {
                            if (item.Id == n) {
                                mvvm.entity.ResidualValueRate = item.ResidualValueRate;
                                mvvm.entity.DepreciationPeriod = item.DepYear;
                            }
                        });
                    });
                }
                function showForm(title, b) {
                    mvvm.tab = "tab1";
                    var btns = b == false ? null : [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            var m = mvvm.entity.$model;
                            if (m.Name == "") {
                                messageBox.warning('请填写名称！');
                                return false;
                            }
                            if (!m.Type.Id) {
                                messageBox.warning('请选择类别！');
                                return false;
                            }
                            var url = (m.Id == 0 ? "/Office/FixedAssetsAdd/" : "/Office/FixedAssetsUpdate/" + m.Id);
                            var data = $.extend({}, m, jsonToSubmit("clist", mvvm.configList));
                            $.extend(data, jsonToSubmit("Type", mvvm.entity.Type));
                            delete data.Type.Parent;
                            delete data.Type;
                            $.post(url, data, function (ret) {
                                if (ret.result) {
                                    messageBox.ok(ret.message, function () {
                                        if (ret.data.Id) {
                                            mvvm.entity.Id = ret.data.Id;
                                        }
                                        if (dialog) dialog.close();
                                        mvvm.doSearch();
                                    });
                                }
                                else {
                                    messageBox.fail(ret.message);
                                }
                            })
                            return false;
                        }
                    }];
                    var tmplid = b == false ? 'FixedAssetsviewTemplate' : 'FixedAssetsformTemplate';
                    var dialog = openTmpl(mvvm, title, tmplid, mvvm.tabWidth, null, btns);

                }
                mvvm.loadTypes();
                avalon.vmodels.CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)

                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.FixedAssets = null;
                }
            },
            //资产领用
            FixedAssetsUses: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this
                var mvvm, init = false

                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define('FixedAssetsUses', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.ADD = false;
                    vm.loading = true;
                    
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = avalon.mix({}, mvvm.queryinfo.$model);
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    vm.queryinfo = {
                        name: "", assetsNo: "", addBy: "", addByGroup: "", usesTime1: "", usesTime2: "",
                        typeId: "", bigtypeId: "", state: ""
                    };
                    vm.doSearch = function () {
                        mvvm.loadData(mvvm.queryinfo.$model);
                    }
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.list = [];
                    initGridvm(vm, vm.list);
                    vm.act = "";
                    vm.showSubNav = 'assets';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.tab = "tab1";
                    vm.tabWidth = 900;
                    vm.tabHeight = 300;
                    //标签切换
                    vm.tabChange = function () {
                        var val = $(this).attr('val');
                        mvvm.tab = val;
                    }
                    vm.assetsList = [];
                    vm.initList = function (ret) {

                    }
                    vm.entity = {};
                    vm.createEntity = function () {
                        var s = telesa.datetime.ymd();
                        mvvm.entity = modelFactory.create('FixedAssetsUses');
                        mvvm.entity.UsesTime = s;
                        mvvm.entity.AddBy = { Id: CBCRM.memberShip.Id, FullName: CBCRM.memberShip.FullName, Group: CBCRM.memberShip.Group };
                    }
                    vm.getEntity = function () {
                        return $.extend(true, {}, modelFactory.create('FixedAssetsUses'));
                    }
                    //日期参数
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.usesTime1 = formatDate;
                        }
                    }
                    vm.dateOpts2 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.usesTime2 = formatDate;
                        }
                    }
                    vm.dateOpts3 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.UsesTime = formatDate;
                        }
                    }
                    vm.assignByTreeOpts = {
                        treeopts: {
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    if (treeNode.iconSkin !== 'emp') {
                                        alert('请选择用户名称！')
                                        return
                                    }
                                    mvvm.entity.AssignBy.Id = treeNode.Id;
                                    mvvm.entity.AssignBy.FullName = treeNode.Name;
                                }
                            },
                            async: {
                                dataFilter: groupPostFilter
                            }
                        }
                    }
                    vm.showSave = function () {
                        mvvm.act = "add"
                        mvvm.assetsList.removeAll();
                        mvvm.createEntity();
                        var btns = [{
                            name: "发送申请",
                            focus: true,
                            callback: function () {
                                if (mvvm.assetsList.length == 0) {
                                    messageBox.warning("资产清单为空！");
                                    return;
                                }
                                var a = [];
                                mvvm.assetsList.forEach(function (item) {
                                    var m = $.extend({}, item.$model);
                                    $.extend(m, jsonToSubmit("Assets", { Id: m.Assets.Id }));
                                    delete m.Assets;
                                    delete m.AssignBy;
                                    a.push(m);
                                });
                                var model = mvvm.entity.$model;
                                $.extend(model, jsonToSubmit("AssignBy", { Id: model.AssignBy.Id }));
                                var data = avalon.mix(jsonToSubmit("model", model), jsonToSubmit("list", a));
                                $.post('/Office/FixedAssetsUsesAdd/', data, function (ret) {
                                    CBCRM.showResult(ret);
                                    if (ret.result) {
                                        if (dialog) dialog.close();
                                        mvvm.listOpts.paging();
                                    }
                                });
                                return false;
                            }
                        }
                        ];
                        var dialog = openTmpl(mvvm, "新增领用申请", "FixedAssetsUsesAdd_tmpl", mvvm.tabWidth, null, btns, function () {
                            destroyui(["assignByTree"]);
                        });
                    }
                    vm.showView = function (item) {
                        mvvm.act = "view";
                        var billNo = item.BillNo;
                        $.post("/Office/FixedAssetsUsesView", { billNo: billNo }, function (ret) {
                            if (ret.result) {
                                mvvm.createEntity();
                                mvvm.assetsList = ret.data.Source;
                                if (ret.data.Source.length > 0) {
                                    var m = ret.data.Source[0];
                                    avalon.mix(mvvm.entity, m);
                                    mvvm.entity.AssignBy = m.AssignBy || {};
                                }
                                var dialog = openTmpl(mvvm, "查看领用申请", "FixedAssetsUsesAdd_tmpl", mvvm.tabWidth);
                            } else {
                                CBCRM.showResult(ret);
                            }
                        });
                    }
                    vm.assetsSelect = function () {
                        var vmid = "FixedAssetsSelect",
                            url = "/Office/FixedAssetsSelect";
                        var dialog = openWin("选择资产", vmid, url, 900, 400, [{
                            name: "确定选择",
                            focus: true,
                            callback: function () {
                                var pvm = avalon.vmodels[vmid];
                                if (!pvm) {
                                    messageBox.warning("系统正在载入中，请稍候……");
                                    return false;
                                }
                                var list = pvm.getChecked();
                                if (list.length == 0) {
                                    messageBox.warning("请选择数据！");
                                    return false;
                                }
                                list.forEach(function (item) {
                                    for (var i = 0, l = mvvm.assetsList.length; i < l; i++) {
                                        if (mvvm.assetsList[i].Assets.Id == item.Id) return;
                                    }
                                    var model = mvvm.getEntity();
                                    model.Assets = item;
                                    mvvm.assetsList.push(model);
                                });
                            }
                        }], function (tmpl, lang, content, module, vmodel) {
                            //查询状态为在库的资产
                            vmodel.$params = { selectType: 'Uses' };
                            vmodel.toSearch();
                        });
                    }
                    vm.removeAllAssets = function () {
                        mvvm.assetsList.removeAll();
                    }
                    vm.approval = function () {
                        var ids = mvvm.getIds("ids");
                        if (ids.length == 0) {
                            messageBox.error("请选择数据！");
                            return;
                        }
                        messageBox.confirm("是否确认审批？", function () {
                            $.post('/Office/AssetsUsesApproval/', ids).done(function (ret) {
                                avalon.vmodels.CBCRM.showResult(ret, function () {
                                    mvvm.listOpts.paging();
                                    messageBox.close()
                                })
                            });
                        });
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/FixedAssetsUses/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                mvvm.ADD = ret.data.ADD;
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.allTypes = [];
                    vm.types = [{ Id: "", Name: "请选择" }];
                    vm.bigtypes = [{ Id: "", Name: "请选择" }];
                    vm.loadTypes = function () {
                        $.get('/Office/FixedAssetsType/').done(function (ret) {
                            if (!ret.result) return;
                            mvvm.allTypes = ret.data;
                            mvvm.allTypes.forEach(function (item) {
                                if (!item.pId) mvvm.bigtypes.push(item.$model);
                            });

                        });
                    }
                })
                function watchType(n, types) {
                    types.removeAll();
                    types.push({ Id: "", Name: "请选择" });
                    if (!n) return;
                    mvvm.allTypes.forEach(function (item) {
                        if (item.pId == n) types.push(item.$model);
                    });
                }
                function bindWatch() {
                    mvvm.queryinfo.$watch("bigtypeId", function (n) {
                        watchType(n, mvvm.types);
                        mvvm.queryinfo.typeId = "";
                    });
                }
                bindWatch();
                mvvm.loadTypes();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.FixedAssetsUses = null;
                }
            },
            //资产归还
            FixedAssetsReturn: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this
                var mvvm, init = false

                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define('FixedAssetsReturn', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.ADD = false;
                    vm.loading = true;

                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = avalon.mix({}, mvvm.queryinfo.$model);
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    vm.queryinfo = {
                        name: "", assetsNo: "", addBy: "", addByGroup: "", returnTime1: "", returnTime2: "",
                        typeId: "", bigtypeId: "", state: ""
                    };
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.loadData(mvvm.queryinfo.$model);
                    }
                    vm.list = [];
                    initGridvm(vm, vm.list);
                    vm.act = "";
                    vm.showSubNav = 'assets';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.tab = "tab1";
                    vm.tabWidth = 900;
                    vm.tabHeight = 300;
                    //标签切换
                    vm.tabChange = function () {
                        var val = $(this).attr('val');
                        mvvm.tab = val;
                    }
                    vm.assetsList = [];
                    vm.initList = function (ret) {

                    }
                    vm.entity = {};
                    vm.createEntity = function () {
                        var s = telesa.datetime.ymd();
                        mvvm.entity = modelFactory.create('FixedAssetsReturn');
                        mvvm.entity.ReturnTime = s;
                        mvvm.entity.AddBy = { Id: CBCRM.memberShip.Id, FullName: CBCRM.memberShip.FullName, Group: CBCRM.memberShip.Group };
                    }
                    vm.getEntity = function () {
                        return $.extend(true, {}, modelFactory.create('FixedAssetsReturn'));
                    }
                    //日期参数
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.returnTime1 = formatDate;
                        }
                    }
                    vm.dateOpts2 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.returnTime2 = formatDate;
                        }
                    }
                    vm.dateOpts3 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.ReturnTime = formatDate;
                        }
                    }
                    vm.showSave = function () {
                        mvvm.act = "add"
                        mvvm.assetsList.removeAll();
                        mvvm.createEntity();
                        var btns = [{
                            name: "发送申请",
                            focus: true,
                            callback: function () {
                                if (mvvm.assetsList.length == 0) {
                                    messageBox.warning("资产清单为空！");
                                    return;
                                }
                                var a = [];
                                mvvm.assetsList.forEach(function (item) {
                                    var m = $.extend({}, item.$model);
                                    $.extend(m, jsonToSubmit("Assets", { Id: m.Assets.Id }));
                                    delete m.Assets;
                                    delete m.AssignBy;
                                    a.push(m);
                                });
                                var model = mvvm.entity.$model;
                                var data = avalon.mix(jsonToSubmit("model", model), jsonToSubmit("list", a));
                                $.post('/Office/FixedAssetsReturnAdd/', data, function (ret) {
                                    CBCRM.showResult(ret);
                                    if (ret.result) {
                                        if (dialog) dialog.close();
                                        mvvm.listOpts.paging();
                                    }
                                });
                                return false;
                            }
                        }
                        ];
                        var dialog = openTmpl(mvvm, "新增归还申请", "FixedAssetsReturnAdd_tmpl", mvvm.tabWidth, null, btns);
                    }
                    vm.showView = function (item) {
                        mvvm.act = "view";
                        var billNo = item.BillNo;
                        $.post("/Office/FixedAssetsReturnView", { billNo: billNo }, function (ret) {
                            if (ret.result) {
                                mvvm.createEntity();
                                mvvm.assetsList = ret.data.Source;
                                if (ret.data.Source.length > 0) {
                                    var m = ret.data.Source[0];
                                    avalon.mix(mvvm.entity, m);
                                }
                                var dialog = openTmpl(mvvm, "查看归还申请", "FixedAssetsReturnAdd_tmpl", mvvm.tabWidth);
                            } else {
                                CBCRM.showResult(ret);
                            }
                        });
                    }
                    vm.assetsSelect = function () {
                        var vmid = "FixedAssetsSelect",
                            url = "/Office/FixedAssetsSelect";
                        var dialog = openWin("选择使用中的资产", vmid, url, 900, 400, [{
                            name: "确定选择",
                            focus: true,
                            callback: function () {
                                var pvm = avalon.vmodels[vmid];
                                if (!pvm) {
                                    messageBox.warning("系统正在载入中，请稍候……");
                                    return false;
                                }
                                var list = pvm.getChecked();
                                if (list.length == 0) {
                                    messageBox.warning("请选择数据！");
                                    return false;
                                }
                                list.forEach(function (item) {
                                    for (var i = 0, l = mvvm.assetsList.length; i < l; i++) {
                                        if (mvvm.assetsList[i].Assets.Id == item.Id) return;
                                    }
                                    var model = mvvm.getEntity();
                                    model.Assets = item;
                                    mvvm.assetsList.push(model);
                                });
                            }
                        }], function (tmpl, lang, content, module, vmodel) {
                            //查询状态为使用中的资产
                            vmodel.$params = { selectType: 'Return' };
                            vmodel.toSearch();
                        });
                    }
                    vm.removeAllAssets = function () {
                        mvvm.assetsList.removeAll();
                    }
                    vm.approval = function () {
                        var ids = mvvm.getIds("ids");
                        if (ids.length == 0) {
                            messageBox.error("请选择数据！");
                            return;
                        }
                        messageBox.confirm("是否确认审批？", function () {
                            $.post('/Office/AssetsReturnApproval/', ids).done(function (ret) {
                                avalon.vmodels.CBCRM.showResult(ret, function () {
                                    mvvm.listOpts.paging();
                                    messageBox.close()
                                })
                            });
                        });
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/FixedAssetsReturn/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                mvvm.ADD = ret.data.ADD;
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.allTypes = [];
                    vm.types = [{ Id: "", Name: "请选择" }];
                    vm.bigtypes = [{ Id: "", Name: "请选择" }];
                    vm.loadTypes = function () {
                        $.get('/Office/FixedAssetsType/').done(function (ret) {
                            if (!ret.result) return;
                            mvvm.allTypes = ret.data;
                            mvvm.allTypes.forEach(function (item) {
                                if (!item.pId) mvvm.bigtypes.push(item.$model);
                            });

                        });
                    }
                })
                function watchType(n, types) {
                    types.removeAll();
                    types.push({ Id: "", Name: "请选择" });
                    if (!n) return;
                    mvvm.allTypes.forEach(function (item) {
                        if (item.pId == n) types.push(item.$model);
                    });
                }
                function bindWatch() {
                    mvvm.queryinfo.$watch("bigtypeId", function (n) {
                        watchType(n, mvvm.types);
                        mvvm.queryinfo.typeId = "";
                    });
                }
                bindWatch();
                mvvm.loadTypes();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.FixedAssetsReturn = null;
                }
            },
            //资产报修
            FixedAssetsRepairs: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this
                var mvvm, init = false

                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define('FixedAssetsRepairs', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.ADD = false;
                    vm.loading = true;

                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = avalon.mix({}, mvvm.queryinfo.$model);
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    vm.queryinfo = {
                        name: "", assetsNo: "", addBy: "", addByGroup: "", addTime1: "", addTime2: "",
                        typeId: "", bigtypeId: "", state: ""
                    };
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.loadData(mvvm.queryinfo.$model);
                    }
                    vm.list = [];
                    initGridvm(vm, vm.list);
                    vm.act = "";
                    vm.showSubNav = 'assets';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.tab = "tab1";
                    vm.tabWidth = 900;
                    vm.tabHeight = 300;
                    //标签切换
                    vm.tabChange = function () {
                        var val = $(this).attr('val');
                        mvvm.tab = val;
                    }
                    vm.assetsList = [];
                    vm.initList = function (ret) {

                    }
                    vm.repairsStates = ["正常", "不正常"];
                    vm.entity = {};
                    vm.createEntity = function () {
                        var s = telesa.datetime.ymd();
                        mvvm.entity = modelFactory.create('FixedAssetsRepairs');
                        mvvm.entity.AddTime = s;
                        mvvm.entity.AddBy = { Id: CBCRM.memberShip.Id, FullName: CBCRM.memberShip.FullName, Group: CBCRM.memberShip.Group };
                    }
                    vm.getEntity = function () {
                        return $.extend(true, {}, modelFactory.create('FixedAssetsRepairs'));
                    }
                    //日期参数
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.addTime1 = formatDate;
                        }
                    }
                    vm.dateOpts2 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.addTime2 = formatDate;
                        }
                    }
                    vm.dateOpts3 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.AddTime = formatDate;
                        }
                    }
                    vm.dateOpts4 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.EndTime = formatDate;
                        }
                    }
                    vm.showSave = function () {
                        mvvm.act = "add"
                        mvvm.assetsList.removeAll();
                        mvvm.createEntity();
                        var btns = [{
                            name: "发送申请",
                            focus: true,
                            callback: function () {
                                if (mvvm.assetsList.length == 0) {
                                    messageBox.warning("资产清单为空！");
                                    return;
                                }
                                var a = [];
                                mvvm.assetsList.forEach(function (item) {
                                    var m = $.extend({}, item.$model);
                                    $.extend(m, jsonToSubmit("Assets", { Id: m.Assets.Id }));
                                    delete m.Assets;
                                    delete m.AssignBy;
                                    a.push(m);
                                });
                                var model = mvvm.entity.$model;
                                var data = avalon.mix(jsonToSubmit("model", model), jsonToSubmit("list", a));
                                $.post('/Office/FixedAssetsRepairsAdd/', data, function (ret) {
                                    CBCRM.showResult(ret);
                                    if (ret.result) {
                                        if (dialog) dialog.close();
                                        mvvm.listOpts.paging();
                                    }
                                });
                                return false;
                            }
                        }
                        ];
                        var dialog = openTmpl(mvvm, "新增报修申请", "FixedAssetsRepairsAdd_tmpl", mvvm.tabWidth, null, btns);
                    }
                    vm.showView = function (item) {
                        mvvm.act = "view";
                        var billNo = item.BillNo;
                        $.post("/Office/FixedAssetsRepairsView", { billNo: billNo }, function (ret) {
                            if (ret.result) {
                                mvvm.createEntity();
                                mvvm.assetsList = ret.data.Source;
                                if (ret.data.Source.length > 0) {
                                    var m = ret.data.Source[0];
                                    avalon.mix(mvvm.entity, m);
                                }
                                var dialog = openTmpl(mvvm, "查看报修申请", "FixedAssetsRepairsAdd_tmpl", mvvm.tabWidth);
                            } else {
                                CBCRM.showResult(ret);
                            }
                        });
                    }
                    vm.assetsSelect = function () {
                        var vmid = "FixedAssetsSelect",
                            url = "/Office/FixedAssetsSelect";
                        var dialog = openWin("选择资产", vmid, url, 900, 400, [{
                            name: "确定选择",
                            focus: true,
                            callback: function () {
                                var pvm = avalon.vmodels[vmid];
                                if (!pvm) {
                                    messageBox.warning("系统正在载入中，请稍候……");
                                    return false;
                                }
                                var list = pvm.getChecked();
                                if (list.length == 0) {
                                    messageBox.warning("请选择数据！");
                                    return false;
                                }
                                list.forEach(function (item) {
                                    for (var i = 0, l = mvvm.assetsList.length; i < l; i++) {
                                        if (mvvm.assetsList[i].Assets.Id == item.Id) return;
                                    }
                                    var model = mvvm.getEntity();
                                    model.Assets = item;
                                    mvvm.assetsList.push(model);
                                });
                            }
                        }], function (tmpl, lang, content, module, vmodel) {
                            //查询未报修、未报废的记录
                            vmodel.$params = { selectType: 'Repairs' };
                            vmodel.toSearch();
                        });
                    }
                    vm.removeAllAssets = function () {
                        mvvm.assetsList.removeAll();
                    }
                    vm.approval = function () {
                        var ids = mvvm.getIds("ids");
                        if (ids.length == 0) {
                            messageBox.error("请选择数据！");
                            return;
                        }
                        messageBox.confirm("是否确认维修？", function () {
                            $.post('/Office/AssetsRepairsApproval/', ids).done(function (ret) {
                                avalon.vmodels.CBCRM.showResult(ret, function () {
                                    mvvm.listOpts.paging();
                                    messageBox.close()
                                })
                            });
                        });
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/FixedAssetsRepairs/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                mvvm.ADD = ret.data.ADD;
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.allTypes = [];
                    vm.types = [{ Id: "", Name: "请选择" }];
                    vm.bigtypes = [{ Id: "", Name: "请选择" }];
                    vm.loadTypes = function () {
                        $.get('/Office/FixedAssetsType/').done(function (ret) {
                            if (!ret.result) return;
                            mvvm.allTypes = ret.data;
                            mvvm.allTypes.forEach(function (item) {
                                if (!item.pId) mvvm.bigtypes.push(item.$model);
                            });

                        });
                    }
                })
                function watchType(n, types) {
                    types.removeAll();
                    types.push({ Id: "", Name: "请选择" });
                    if (!n) return;
                    mvvm.allTypes.forEach(function (item) {
                        if (item.pId == n) types.push(item.$model);
                    });
                }
                function bindWatch() {
                    mvvm.queryinfo.$watch("bigtypeId", function (n) {
                        watchType(n, mvvm.types);
                        mvvm.queryinfo.typeId = "";
                    });
                }
                bindWatch();
                mvvm.loadTypes();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.FixedAssetsRepairs = null;
                }
            },
            //维修确认
            FixedAssetsRepairsConfirm: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this
                var mvvm, init = false

                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define('FixedAssetsRepairsConfirm', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.ADD = false;
                    vm.loading = true;

                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = avalon.mix({}, mvvm.queryinfo.$model);
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    vm.queryinfo = {
                        name: "", assetsNo: "", addBy: "", addByGroup: "", addTime1: "", addTime2: "",
                        typeId: "", bigtypeId: "", state: ""
                    };
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.loadData(mvvm.queryinfo.$model);
                    }
                    vm.list = [];
                    initGridvm(vm, vm.list);
                    vm.act = "";
                    vm.showSubNav = 'assets';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.tab = "tab1";
                    vm.tabWidth = 900;
                    vm.tabHeight = 300;
                    //标签切换
                    vm.tabChange = function () {
                        var val = $(this).attr('val');
                        mvvm.tab = val;
                    }
                    vm.assetsList = [];
                    vm.initList = function (ret) {

                    }
                    vm.repairsStates = ["正常", "不正常"];
                    vm.entity = {};
                    vm.createEntity = function () {
                        var s = telesa.datetime.ymd();
                        mvvm.entity = modelFactory.create('FixedAssetsRepairs');
                        mvvm.entity.AddTime = s;
                        mvvm.entity.AddBy = { Id: CBCRM.memberShip.Id, FullName: CBCRM.memberShip.FullName, Group: CBCRM.memberShip.Group };
                    }
                    vm.getEntity = function () {
                        return $.extend(true, {}, modelFactory.create('FixedAssetsRepairs'));
                    }
                    //日期参数
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.addTime1 = formatDate;
                        }
                    }
                    vm.dateOpts2 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.addTime2 = formatDate;
                        }
                    }
                    vm.showView = function (item) {
                        mvvm.act = "view";
                        var billNo = item.BillNo;
                        $.post("/Office/FixedAssetsRepairsView", { billNo: billNo }, function (ret) {
                            if (ret.result) {
                                mvvm.createEntity();
                                mvvm.assetsList = ret.data.Source;
                                if (ret.data.Source.length > 0) {
                                    var m = ret.data.Source[0];
                                    avalon.mix(mvvm.entity, m);
                                }
                                var dialog = openTmpl(mvvm, "查看报修申请", "FixedAssetsRepairsAdd_tmpl", mvvm.tabWidth);
                            } else {
                                CBCRM.showResult(ret);
                            }
                        });
                    }
                    vm.approval = function () {
                        var ids = mvvm.getIds("ids");
                        if (ids.length == 0) {
                            messageBox.error("请选择数据！");
                            return;
                        }
                        messageBox.confirm("是否确认维修？", function () {
                            $.post('/Office/AssetsRepairsApproval/', ids).done(function (ret) {
                                avalon.vmodels.CBCRM.showResult(ret, function () {
                                    mvvm.listOpts.paging();
                                    messageBox.close()
                                })
                            });
                        });
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/FixedAssetsRepairsConfirm/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                mvvm.ADD = ret.data.ADD;
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.allTypes = [];
                    vm.types = [{ Id: "", Name: "请选择" }];
                    vm.bigtypes = [{ Id: "", Name: "请选择" }];
                    vm.loadTypes = function () {
                        $.get('/Office/FixedAssetsType/').done(function (ret) {
                            if (!ret.result) return;
                            mvvm.allTypes = ret.data;
                            mvvm.allTypes.forEach(function (item) {
                                if (!item.pId) mvvm.bigtypes.push(item.$model);
                            });

                        });
                    }
                })
                function watchType(n, types) {
                    types.removeAll();
                    types.push({ Id: "", Name: "请选择" });
                    if (!n) return;
                    mvvm.allTypes.forEach(function (item) {
                        if (item.pId == n) types.push(item.$model);
                    });
                }
                function bindWatch() {
                    mvvm.queryinfo.$watch("bigtypeId", function (n) {
                        watchType(n, mvvm.types);
                        mvvm.queryinfo.typeId = "";
                    });
                }
                bindWatch();
                mvvm.loadTypes();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.FixedAssetsRepairsConfirm = null;
                }
            },
            //资产报废
            FixedAssetsScrap: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this
                var mvvm, init = false

                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define('FixedAssetsScrap', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.ADD = false;
                    vm.loading = true;

                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = avalon.mix({}, mvvm.queryinfo.$model);
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    vm.queryinfo = {
                        name: "", assetsNo: "", addTime1: "", addTime2: "",
                        typeId: "", bigtypeId: "", state: ""
                    };
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.loadData(mvvm.queryinfo.$model);
                    }
                    vm.list = [];
                    initGridvm(vm, vm.list);
                    vm.act = "";
                    vm.showSubNav = 'assets';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.tab = "tab1";
                    vm.tabWidth = 900;
                    vm.tabHeight = 300;
                    //标签切换
                    vm.tabChange = function () {
                        var val = $(this).attr('val');
                        mvvm.tab = val;
                    }
                    vm.assetsList = [];
                    vm.initList = function (ret) {

                    }
                    vm.entity = {};
                    vm.createEntity = function () {
                        var s = telesa.datetime.ymd();
                        mvvm.entity = modelFactory.create('FixedAssetsScrap');
                        mvvm.entity.AddTime = s;
                        mvvm.entity.AddBy = { Id: CBCRM.memberShip.Id, FullName: CBCRM.memberShip.FullName, Group: CBCRM.memberShip.Group };
                    }
                    vm.getEntity = function () {
                        return $.extend(true, {}, modelFactory.create('FixedAssetsScrap'));
                    }
                    //日期参数
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.addTime1 = formatDate;
                        }
                    }
                    vm.dateOpts2 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.addTime2 = formatDate;
                        }
                    }
                    vm.dateOpts3 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.AddTime = formatDate;
                        }
                    }
                    vm.showSave = function () {
                        mvvm.act = "add"
                        mvvm.assetsList.removeAll();
                        mvvm.createEntity();
                        var btns = [{
                            name: "发送申请",
                            focus: true,
                            callback: function () {
                                if (mvvm.assetsList.length == 0) {
                                    messageBox.warning("资产清单为空！");
                                    return;
                                }
                                var a = [];
                                mvvm.assetsList.forEach(function (item) {
                                    var m = $.extend({}, item.$model);
                                    $.extend(m, jsonToSubmit("Assets", { Id: m.Assets.Id }));
                                    delete m.Assets;
                                    a.push(m);
                                });
                                var model = mvvm.entity.$model;
                                var data = avalon.mix(jsonToSubmit("model", model), jsonToSubmit("list", a));
                                $.post('/Office/FixedAssetsScrapAdd/', data, function (ret) {
                                    CBCRM.showResult(ret);
                                    if (ret.result) {
                                        if (dialog) dialog.close();
                                        mvvm.listOpts.paging();
                                    }
                                });
                                return false;
                            }
                        }
                        ];
                        var dialog = openTmpl(mvvm, "新增报废申请", "FixedAssetsScrapAdd_tmpl", mvvm.tabWidth, null, btns);
                    }
                    vm.showView = function (item) {
                        mvvm.act = "view";
                        var billNo = item.BillNo;
                        $.post("/Office/FixedAssetsScrapView", { billNo: billNo }, function (ret) {
                            if (ret.result) {
                                mvvm.createEntity();
                                mvvm.assetsList = ret.data.Source;
                                if (ret.data.Source.length > 0) {
                                    var m = ret.data.Source[0];
                                    avalon.mix(mvvm.entity, m);
                                }
                                var dialog = openTmpl(mvvm, "查看报废申请", "FixedAssetsScrapAdd_tmpl", mvvm.tabWidth);
                            } else {
                                CBCRM.showResult(ret);
                            }
                        });
                    }
                    vm.assetsSelect = function () {
                        var vmid = "FixedAssetsSelect",
                            url = "/Office/FixedAssetsSelect";
                        var dialog = openWin("选择资产", vmid, url, 900, 400, [{
                            name: "确定选择",
                            focus: true,
                            callback: function () {
                                var pvm = avalon.vmodels[vmid];
                                if (!pvm) {
                                    messageBox.warning("系统正在载入中，请稍候……");
                                    return false;
                                }
                                var list = pvm.getChecked();
                                if (list.length == 0) {
                                    messageBox.warning("请选择数据！");
                                    return false;
                                }
                                list.forEach(function (item) {
                                    for (var i = 0, l = mvvm.assetsList.length; i < l; i++) {
                                        if (mvvm.assetsList[i].Assets.Id == item.Id) return;
                                    }
                                    var model = mvvm.getEntity();
                                    model.Assets = item;
                                    mvvm.assetsList.push(model);
                                });
                            }
                        }], function (tmpl, lang, content, module, vmodel) {
                            //查询状态为未报废的资产
                            vmodel.$params = { selectType: 'Scrap' };
                            vmodel.toSearch();
                        });
                    }
                    vm.removeAllAssets = function () {
                        mvvm.assetsList.removeAll();
                    }
                    vm.approval = function () {
                        var ids = mvvm.getIds("ids");
                        if (ids.length == 0) {
                            messageBox.error("请选择数据！");
                            return;
                        }
                        messageBox.confirm("是否确认审批？", function () {
                            $.post('/Office/FixedAssetsScrapApproval/', ids).done(function (ret) {
                                avalon.vmodels.CBCRM.showResult(ret, function () {
                                    mvvm.listOpts.paging();
                                    messageBox.close()
                                })
                            });
                        });
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/FixedAssetsScrap/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                mvvm.ADD = ret.data.ADD;
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.allTypes = [];
                    vm.types = [{ Id: "", Name: "请选择" }];
                    vm.bigtypes = [{ Id: "", Name: "请选择" }];
                    vm.loadTypes = function () {
                        $.get('/Office/FixedAssetsType/').done(function (ret) {
                            if (!ret.result) return;
                            mvvm.allTypes = ret.data;
                            mvvm.allTypes.forEach(function (item) {
                                if (!item.pId) mvvm.bigtypes.push(item.$model);
                            });

                        });
                    }
                })
                function watchType(n, types) {
                    types.removeAll();
                    types.push({ Id: "", Name: "请选择" });
                    if (!n) return;
                    mvvm.allTypes.forEach(function (item) {
                        if (item.pId == n) types.push(item.$model);
                    });
                }
                function bindWatch() {
                    mvvm.queryinfo.$watch("bigtypeId", function (n) {
                        watchType(n, mvvm.types);
                        mvvm.queryinfo.typeId = "";
                    });
                }
                bindWatch();
                mvvm.loadTypes();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.FixedAssetsScrap = null;
                }
            },
            //资产报表
            FixedAssetsReport: function (tmpl, lang, contentId, module, conditionKey) {
                var mvvm;
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define('FixedAssetsReport', function (vm) {
                    vm.showSubNav = 'assets';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                });
                avalon.vmodels.CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)

                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.FixedAssetsReport = null;
                }
            },
            //资产台账
            FixedAssetsAccount: function (tmpl, lang, contentId, module, conditionKey) {
                module.FixedAssetsVm.call(this, "FixedAssetsAccount", tmpl, lang, contentId, module, conditionKey);
            },
            //资产财务
            FixedAssetsFinance: function (tmpl, lang, contentId, module, conditionKey) {
                module.FixedAssetsVm.call(this, "FixedAssetsFinance", tmpl, lang, contentId, module, conditionKey);
            },
            //资产当前流向
            FixedAssetsFlowNow: function (tmpl, lang, contentId, module, conditionKey) {
                module.FixedAssetsVm.call(this, "FixedAssetsFlowNow", tmpl, lang, contentId, module, conditionKey);
            },
            //资产当前流向
            FixedAssetsFlow: function (tmpl, lang, contentId, module, conditionKey) {
                module.FixedAssetsVm.call(this, "FixedAssetsFlow", tmpl, lang, contentId, module, conditionKey);
            },
            //资产历史折旧
            FixedAssetsDepreciation: function (tmpl, lang, contentId, module, conditionKey) {
                module.FixedAssetsVm.call(this, "FixedAssetsDepreciation", tmpl, lang, contentId, module, conditionKey);
            },
            //资产报表VM
            FixedAssetsVm: function (vmid, tmpl, lang, contentId, module, conditionKey) {
                var router, mvvm, init = false;
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define(vmid, function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.loading = true;
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = avalon.mix({}, mvvm.queryinfo.$model);
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    //日期参数
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.billDate1 = formatDate;
                        }
                    }
                    vm.dateOpts2 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.billDate2 = formatDate;
                        }
                    }
                    vm.queryinfo = { assetsNo: "", name: "", typeId: "", bigtypeId: "", billDate1: "", billDate2: "" };
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.loadData(mvvm.queryinfo.$model);
                    }
                    vm.entity = {};
                    vm.list = [];
                    vm.configList = [];
                    vm.flowList = [];
                    vm.depList = [];
                    vm.allTypes = [];
                    vm.querytypes = [{ Id: "", Name: "请选择" }];
                    vm.types = [{ Id: "", Name: "请选择" }];
                    vm.bigtypes = [{ Id: "", Name: "请选择" }];

                    initGridvm(vm, vm.list);
                    vm.tab = "tab1";
                    vm.tabWidth = 700;
                    vm.tabHeight = 500;
                    //标签切换
                    vm.tabChange = function () {
                        var val = $(this).attr('val');
                        mvvm.tab = val;
                    }

                    vm.showSubNav = 'assets';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.createEntity = function (item) {
                        mvvm.entity = item || modelFactory.create('FixedAssets');
                    }
                    vm.showView = function (curitem) {
                        mvvm.createEntity(curitem.$model);
                        mvvm.getFixedAssetsViewList();
                        showForm("查看固定资产", false);
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/' + vmid + '/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                var lst, stages
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                                mvvm.ADD = ret.data.ADD;
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.getFixedAssetsViewList = function () {
                        $.post('/Office/FixedAssetsViewList/', { assetsId: mvvm.entity.Id }).done(function (ret) {
                            if (!ret.result) return;
                            mvvm.configList = ret.data.configList;
                            mvvm.flowList = ret.data.flowList;
                            mvvm.depList = ret.data.depList;
                        });
                    }
                    vm.getFixedAssetsConfigList = function () {
                        $.post('/Office/FixedAssetsConfigList/', { assetsId: mvvm.entity.Id }).done(function (ret) {
                            if (!ret.result) return;
                            mvvm.configList = ret.data.configList;
                        });
                    }
                    vm.loadTypes = function () {
                        $.get('/Office/FixedAssetsType/').done(function (ret) {
                            if (!ret.result) return;
                            mvvm.allTypes = ret.data;
                            mvvm.allTypes.forEach(function (item) {
                                if (!item.pId) mvvm.bigtypes.push(item.$model);
                            });

                        });
                    }

                })
                mvvm.createEntity();
                bindWatch();
                function watchType(n, types) {
                    types.removeAll();
                    types.push({ Id: "", Name: "请选择" });
                    if (!n) return;
                    mvvm.allTypes.forEach(function (item) {
                        if (item.pId == n) types.push(item.$model);
                    });
                }
                function bindWatch() {
                    mvvm.queryinfo.$watch("bigtypeId", function (n) {
                        watchType(n, mvvm.querytypes);
                        mvvm.queryinfo.typeId = "";
                    });
                }
                function showForm(title, b) {
                    mvvm.tab = "tab1";
                    var tmplid = 'FixedAssetsviewTemplate';
                    var dialog = openTmpl(mvvm, title, tmplid, mvvm.tabWidth);

                }
                mvvm.loadTypes();
                avalon.vmodels.CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)

                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels[vmid] = null;
                }
            },   
            //资产初始化
            FixedAssetsInit: function (tmpl, lang, contentId, module, conditionKey) {
                var router, mvvm, init = false;
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define('FixedAssetsInit', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.ADD = false
                    vm.DEPRECIATION = false
                    vm.loading = true;
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = avalon.mix({}, mvvm.queryinfo.$model);
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    //日期参数
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.billDate1 = formatDate;
                        }
                    }
                    vm.dateOpts2 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.billDate2 = formatDate;
                        }
                    }
                    vm.dateOpts3 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.BillDate = formatDate;
                        }
                    }
                    vm.dateOpts4 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.DepreciationStart = formatDate;
                        }
                    }

                    vm.queryinfo = { assetsNo: "", name: "", typeId: "", bigtypeId: "", billDate1: "", billDate2: "" };
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.loadData(mvvm.queryinfo.$model);
                    }
                    vm.entity = {};
                    vm.list = [];
                    vm.configList = [];
                    vm.flowList = [];
                    vm.depList = [];
                    vm.allTypes = [];
                    vm.querytypes = [{ Id: "", Name: "请选择" }];
                    vm.types = [{ Id: "", Name: "请选择" }];
                    vm.bigtypes = [{ Id: "", Name: "请选择" }];

                    initGridvm(vm, vm.list);
                    vm.tab = "tab1";
                    vm.tabWidth = 700;
                    vm.tabHeight = 500;
                    //标签切换
                    vm.tabChange = function () {
                        var val = $(this).attr('val');
                        mvvm.tab = val;
                    }

                    vm.showSubNav = 'assets';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.createEntity = function (item) {
                        mvvm.entity = item || modelFactory.create('FixedAssets');
                        bindWatch();
                        watchType(mvvm.entity.Type.Parent.Id, mvvm.types);
                    }
                    vm.showAdd = function () {
                        vm.createEntity();
                        mvvm.configList.removeAll();
                        showForm("新增固定资产");
                    }
                    vm.showEdit = function (curitem) {
                        mvvm.createEntity(curitem.$model);
                        mvvm.getFixedAssetsConfigList();
                        showForm("编辑固定资产");
                    }
                    vm.showView = function (curitem) {
                        mvvm.createEntity(curitem.$model);
                        mvvm.getFixedAssetsViewList();
                        showForm("查看固定资产", false);
                    }
                    vm.removeAll = function (ids) {
                        console.log(ids);
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/FixedAssetsInit/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                var lst, stages
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                                mvvm.ADD = ret.data.ADD;
                                mvvm.EDIT = ret.data.EDIT;
                                mvvm.DEPRECIATION = ret.data.DEPRECIATION;
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.addConfig = function () {
                        mvvm.configList.push(modelFactory.create('FixedAssetsConfig'));
                    }
                    vm.removeAllConfig = function () {
                        mvvm.configList.removeAll();
                    }
                    vm.getFixedAssetsViewList = function () {
                        $.post('/Office/FixedAssetsViewList/', { assetsId: mvvm.entity.Id }).done(function (ret) {
                            if (!ret.result) return;
                            mvvm.configList = ret.data.configList;
                            mvvm.flowList = ret.data.flowList;
                            mvvm.depList = ret.data.depList;
                        });
                    }
                    vm.getFixedAssetsConfigList = function () {
                        $.post('/Office/FixedAssetsConfigList/', { assetsId: mvvm.entity.Id }).done(function (ret) {
                            if (!ret.result) return;
                            mvvm.configList = ret.data.configList;
                        });
                    }
                    vm.loadTypes = function () {
                        $.get('/Office/FixedAssetsType/').done(function (ret) {
                            if (!ret.result) return;
                            mvvm.allTypes = ret.data;
                            mvvm.allTypes.forEach(function (item) {
                                if (!item.pId) mvvm.bigtypes.push(item.$model);
                            });

                        });
                    }
                    vm.fixedAssetsDepreciation = function () {
                        var ids = mvvm.getIds("ids");
                        $.post('/Office/FixedAssetsDepreciationAdd/', ids)
                            .done(function (ret) {
                                CBCRM.showResult(ret);
                                if (ret.result) mvvm.doSearch();
                            });
                    }

                })
                mvvm.createEntity();
                function watchType(n, types) {
                    types.removeAll();
                    types.push({ Id: "", Name: "请选择" });
                    if (!n) return;
                    mvvm.allTypes.forEach(function (item) {
                        if (item.pId == n) types.push(item.$model);
                    });
                }
                function bindWatch() {
                    mvvm.queryinfo.$watch("bigtypeId", function (n) {
                        watchType(n, mvvm.querytypes);
                        mvvm.queryinfo.typeId = "";
                    });
                    mvvm.entity.Type.Parent.$watch("Id", function (n) {
                        watchType(n, mvvm.types);
                        mvvm.entity.Type.Id = "";
                    });
                    mvvm.entity.Type.$watch("Id", function (n) {
                        if (n == "") return;
                        mvvm.types.forEach(function (item) {
                            if (item.Id == n) {
                                mvvm.entity.ResidualValueRate = item.ResidualValueRate;
                                mvvm.entity.DepreciationPeriod = item.DepYear;
                            }
                        });
                    });
                }
                function showForm(title, b) {
                    mvvm.tab = "tab1";
                    var btns = b == false ? null : [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            var m = mvvm.entity.$model;
                            if (m.Name == "") {
                                messageBox.warning('请填写名称！');
                                return false;
                            }
                            if (!m.Type.Id) {
                                messageBox.warning('请选择类别！');
                                return false;
                            }
                            var url = (m.Id == 0 ? "/Office/FixedAssetsAdd/" : "/Office/FixedAssetsUpdate/" + m.Id);
                            var data = $.extend({}, m, jsonToSubmit("clist", mvvm.configList));
                            $.extend(data, jsonToSubmit("Type", mvvm.entity.Type));
                            delete data.Type.Parent;
                            delete data.Type;
                            $.post(url, data, function (ret) {
                                if (ret.result) {
                                    messageBox.ok(ret.message, function () {
                                        if (ret.data.Id) {
                                            mvvm.entity.Id = ret.data.Id;
                                        }
                                        if (dialog) dialog.close();
                                        mvvm.doSearch();
                                    });
                                }
                                else {
                                    messageBox.fail(ret.message);
                                }
                            })
                            return false;
                        }
                    }];
                    var tmplid = b == false ? 'FixedAssetsviewTemplate' : 'FixedAssetsformTemplate';
                    var dialog = openTmpl(mvvm, title, tmplid, mvvm.tabWidth, null, btns);

                }
                mvvm.loadTypes();
                avalon.vmodels.CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)

                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.FixedAssets = null;
                }
            },
            //资产类别维护
            FixedAssetsType: function (tmpl, lang, contentId, module, conditionKey) {
                var router, mvvm, init = false;
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define('FixedAssetsType', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.ADD = false
                    vm.DELETE = false
                    vm.loading = true;
                    vm.entity = modelFactory.create('FixedAssetsType');
                    vm.allTypes = [];
                    vm.types = [];
                    vm.bigtypes = [];
                    vm.saveType = "big";
                    vm.saveTypeDsc = "新增资产大类";
                    vm.showSubNav = 'assets';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.showAdd = function (type, data) {
                        avalon.mix(mvvm.entity, modelFactory.create('FixedAssetsType'));
                        mvvm.saveType = type;
                        mvvm.saveTypeDsc = "新增资产" + (mvvm.saveType == "small" ? "小类" : "大类");
                        if (mvvm.saveType == "big") mvvm.entity.Parent.Id = "";
                        if (data) {
                            mvvm.entity.Parent.Id = data.id;
                            mvvm.entity.Parent.Name = data.name;
                        }
                    }
                    vm.showEdit = function (item) {
                        avalon.mix(mvvm.entity, item.$model);
                        mvvm.saveType = mvvm.entity.Parent.Id ? "small" : "big";
                        mvvm.saveTypeDsc = "编辑资产" + (mvvm.saveType == "small" ? "小类" : "大类");
                    }
                    vm.doSave = function () {
                        var m = mvvm.entity.$model;
                        if (m.Name == "") {
                            messageBox.warning('请填写名称！');
                            return;
                        }
                        m["Parent.Id"] = m.Parent.Id;
                        m.ParentId = m.Parent.Id;
                        var url = (m.Id == 0 ? "/Office/FixedAssetsTypeAdd/" : "/Office/FixedAssetsTypeUpdate/" + m.Id);
                        var data = m;
                        $.post(url, data, function (ret) {
                            if (ret.result) {
                                messageBox.ok(ret.message, function () {
                                    if (ret.data.Id) {
                                        mvvm.entity.Id = ret.data.Id;
                                    }
                                    mvvm.loadTypes();
                                });
                            }
                            else {
                                messageBox.fail(ret.message);
                            }
                        })
                        return false;
                    }
                    vm.assetsTypetreeOpts = {
                        treeopts: {
                            async: {
                                url: function () {
                                    return '/Office/FixedAssetsType/'
                                }
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    var id = treeNode.Id;
                                    for (var i = 0, l = mvvm.allTypes.length; i < l; i++) {
                                        var item = mvvm.allTypes[i];
                                        if (item.Id == id) {
                                            mvvm.showEdit(item);
                                            break;
                                        }
                                    }
                                }
                            },
                            view: {
                                addHoverDom: null,
                                removeHoverDom: null,
                                selectedMulti: false
                            }
                        }
                    }
                    vm.isLoad = false;
                    vm.loadTypes = function () {
                        $.get('/Office/FixedAssetsType/').done(function (ret) {
                            if (!ret.result) return;
                            mvvm.allTypes = ret.data;
                            if (avalon.vmodels.assetsTypetree && mvvm.isLoad) avalon.vmodels.assetsTypetree.datasource = ret.data;
                            mvvm.bigtypes.removeAll();
                            mvvm.bigtypes.push({ Id: "", Name: "请选择" });
                            mvvm.allTypes.forEach(function (item) {
                                if (!item.pId) mvvm.bigtypes.push(item.$model);
                            });
                            mvvm.isLoad = true;
                        });
                    }

                })
                mvvm.loadTypes();
                avalon.vmodels.CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)

                CBCRM.onLoadModuleBefore = function () {
                    destroyui(["assetsTypetree"]);
                    avalon.vmodels.FixedAssetsType = null;
                }
            },
            //资产选择
            FixedAssetsSelect: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this, mvvm, init = false;

                CBCRM = avalon.vmodels.CBCRM

                mvvm = avalon.define('FixedAssetsSelect', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.loading = true;
                    vm.key = "";
                    vm.$params = {};
                    vm.toEnter = function (e) {
                        if (e.keyCode == 13) mvvm.toSearch();
                    }
                    vm.toSearch = function () {
                        mvvm.loadData({ name: mvvm.key });
                    }
                    vm.clearSearchItem = function () {
                        mvvm.key = "";
                        mvvm.toSearch();
                    }
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = {};
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            } else {
                                m.loadData(data);
                            }
                        }
                    }
                    vm.list = []
                    initGridvm(vm, vm.list);
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        var data = $.extend({}, param, mvvm.$params);
                        $.post('/Office/FixedAssets/', data)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels["listPage" + mvvm.$id].total = ret.data.RecordTotal || 0
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                })
                avalon.vmodels.CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            },
            //资产后台设置
            FixedAssetsSet: function (tmpl, lang, contentId, module, conditionKey) {
                var mvvm, now = new Date(), year = now.getFullYear(), month = now.getMonth() + 1;
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define('FixedAssetsSet', function (vm) {
                    
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.DPCONFIG = false;
                    vm.loading = true;
                    
                    vm.dpconfig = modelFactory.create('FixedAssetsDepConfig');
                    vm.tabWidth = 450;
                    vm.dpYear = year;
                    vm.dpMonth = formatNum(month);
                    vm.dpYears = [];
                    vm.dpMonths = [];
                    vm.showSubNav = 'assets';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.showDpConfig = function () {
                        avalon.mix(mvvm.entity, modelFactory.create('FixedAssets'));
                        showForm("折旧方案设置");
                    }
                    vm.loadDpConfig = function () {
                        $.get('/Office/FixedAssetsDepConfigGet/').done(function (ret) {
                            if (!ret.result && ret.data.model) return;
                            mvvm.dpconfig = ret.data.model;
                        });
                    }
                    vm.fixedAssetsDepreciation = function () {
                        $.post('/Office/FixedAssetsDepreciationAdd/', { year: mvvm.dpYear, month: mvvm.dpMonth })
                            .done(function (ret) {
                                CBCRM.showResult(ret);
                            });
                    }

                })
                function showForm(title, b) {
                    mvvm.tab = "tab1";
                    var btns = b == false ? null : [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            var m = mvvm.dpconfig.$model;
                            if (m.Type == 1 && !m.ActionDayType == 1 && m.ActionDay == "") {
                                messageBox.warning('请填写一个固定日！');
                                return;
                            }
                            var url = "/Office/FixedAssetsDepConfigSave/" + m.Id;
                            $.post(url, m, function (ret) {
                                CBCRM.showResult(ret);
                            })
                            return false;
                        }
                    }];
                    var tmplid = b == false ? 'FixedAssetsviewTemplate' : 'FixedAssetsformTemplate';
                    var dialog = openTmpl(mvvm, title, tmplid, mvvm.tabWidth, null, btns);

                }
                initData();
                function initData() {
                    for (var i = year, l = year - 10; i > l; i--) {
                        mvvm.dpYears.push(i);
                    }
                    for (var i = month; i > 0 ; i--) {
                        mvvm.dpMonths.push(formatNum(i));
                    }
                    mvvm.$watch("dpYear", function (n) {
                        mvvm.dpMonths.removeAll();
                        if (n == year) {
                            for (var i = month; i > 0 ; i--) {
                                mvvm.dpMonths.push(formatNum(i));
                            }
                        } else {
                            for (var i = 12; i > 0 ; i--) {
                                mvvm.dpMonths.push(formatNum(i));
                            }
                        }
                        mvvm.dpMonth = mvvm.dpMonths[0];
                    })
                    mvvm.loadDpConfig();
                }
                function formatNum(n) {
                    return n < 10 ? "0" + n : n;
                }
                avalon.vmodels.CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)

                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.FixedAssetsSet = null;
                }
            },
            Car: function (tmpl, lang, contentId, module, conditionKey) {
                var router, mvvm, init = false;
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define('Car', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.ADD = false
                    vm.DELETE = false
                    vm.loading = true;
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = avalon.mix({}, mvvm.queryinfo.$model);
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    //日期参数
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.BuyDate = formatDate;
                        }
                    }
                    vm.dateOpts2 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.InsureStartDate = formatDate;
                        }
                    }
                    vm.dateOpts3 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.InsureEndDate = formatDate;
                        }
                    }
                    vm.authMemberTreeOpts = {
                        treeopts: {
                            callback: {
                                onCheck: function (e, treeId, treeNode) {
                                    var treeObj = $.fn.zTree.getZTreeObj(treeId);
                                    var nodes = treeObj.getCheckedNodes(true);
                                    var ids = [];
                                    var names = [];
                                    nodes.forEach(function (n) {
                                        if (n.iconSkin === 'emp') {
                                            ids.push(n.Id);
                                            names.push(n.Name);
                                        }
                                    });
                                    mvvm.entity.AuthMember = ids.join(";");
                                    mvvm.entity.AuthMemberData = names.join(";");
                                }
                            },
                            async: {
                                dataFilter: notMemberFilter
                            },
                            check: {
                                enable: true,
                                chkboxType: { "Y": "s", "N": "ps" }
                            }
                        }
                    }
                    vm.queryinfo = { carState: "" };
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.loadData(mvvm.queryinfo.$model);
                    }
                    vm.entity = {};
                    vm.list = [];
                    vm.insureWarnWays = ["短信", "系统消息"];
                    vm.carStates = [{ val: "", text: "请选择" }, { val: 0, text: "正常" }, { val: 1, text: "已报废" }];

                    initGridvm(vm, vm.list);
                    vm.tab = "tab1";
                    vm.tabWidth = 700;
                    //标签切换
                    vm.tabChange = function () {
                        var val = $(this).attr('val');
                        mvvm.tab = val;
                    }

                    vm.showSubNav = 'cars';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.createEntity = function (item) {
                        mvvm.entity = item || modelFactory.create('Car');
                    }
                    vm.showAdd = function () {
                        vm.createEntity();
                        showForm("新增车辆资料");
                    }
                    vm.showEdit = function (curitem) {
                        mvvm.getModel(curitem.Id, function (model) {
                            mvvm.createEntity(model);
                            showForm("编辑车辆资料");
                        }); 
                    }
                    vm.showView = function (curitem) {
                        mvvm.getModel(curitem.Id, function (model) {
                            mvvm.createEntity(model);
                            showForm("查看车辆资料", false);
                        });
                    }
                    vm.getModel = function (id, callBack) {
                        $.post("/Office/CarView/", { id: id }, function (ret) {
                            if (ret.result) {
                                var m = ret.data.model;
                                if (m.Insure) m.Insure = m.Insure.split(";");
                                if (m.InsureWarnWay) m.InsureWarnWay = m.InsureWarnWay.split(";");
                                if (callBack) callBack(m);
                            } else messageBox.warning(ret.message);
                        });
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/Car/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                var lst, stages
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                                mvvm.ADD = ret.data.ADD;
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.insures = [];
                    vm.getDicts = function () {
                        var dicts = {
                            "100105": "insures"//险种
                        };
                        getDicts(dicts, mvvm);
                    }
                })
                mvvm.createEntity();
                mvvm.getDicts();
                function showForm(title, b) {
                    mvvm.tab = "tab1";
                    var btns = b == false ? null : [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            var m = $.extend(true, {}, mvvm.entity.$model);
                            if (m.CarNo == "") {
                                messageBox.warning('请填写车牌号码！');
                                return false;
                            }
                            if (m.Insure) m.Insure = m.Insure.join(";");
                            if (m.InsureWarnWay) m.InsureWarnWay = m.InsureWarnWay.join(";");
                            var url = (m.Id == 0 ? "/Office/CarAdd/" : "/Office/CarUpdate/" + m.Id);
                            $.post(url, jsonToSubmit("model", m), function (ret) {
                                if (ret.result) {
                                    messageBox.ok(ret.message, function () {
                                        if (ret.data.Id) {
                                            mvvm.entity.Id = ret.data.Id;
                                        }
                                        if (dialog) dialog.close();
                                        mvvm.doSearch();
                                    });
                                }
                                else {
                                    messageBox.fail(ret.message);
                                }
                            })
                            return false;
                        }
                    }];
                    var tmplid = b == false ? 'CarviewTemplate' : 'CarformTemplate';
                    var dialog = openTmpl(mvvm, title, tmplid, mvvm.tabWidth, null, btns, function () {
                        destroyui(["authMemberTree"]);
                    });

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

                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.Car = null;
                }
            },
            CarApply: function (tmpl, lang, contentId, module, conditionKey) {
                var router, mvvm, init = false;
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define('CarApply', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.ADD = false
                    vm.EDIT = false
                    vm.loading = true;
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = avalon.mix({}, mvvm.queryinfo.$model);
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    //日期参数
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d %H:%M',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.BeginTime = formatDate;
                        }
                    }
                    vm.dateOpts2 = {
                        format: '%Y-%m-%d %H:%M',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.EndTime = formatDate;
                        }
                    }
                    vm.carUseByTreeOpts = {
                        treeopts: {
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    if (treeNode.iconSkin !== 'emp') {
                                        alert('请选择用户名称！')
                                        return
                                    }
                                    mvvm.entity.UseBy.Id = treeNode.Id;
                                    mvvm.entity.UseBy.FullName = treeNode.Name;
                                }
                            },
                            async: {
                                dataFilter: groupPostFilter
                            }
                        }
                    }
                    vm.queryinfo = { state: "" };
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.loadData(mvvm.queryinfo.$model);
                    }
                    vm.entity = {};
                    vm.list = [];
                    vm.useTypes = ["公用", "私用"];
                    vm.states = [{ val: "", text: "请选择" }, { val: 0, text: "待审批" }, { val: 1, text: "未通过审批" }
                        , { val: 2, text: "待派车" }, { val: 3, text: "已派车" }, { val: 4, text: "拒绝派车" }, { val: 5, text: "派车结束" }
                    ];

                    initGridvm(vm, vm.list);
                    vm.tab = "tab1";
                    vm.tabWidth = 550;
                    //标签切换
                    vm.tabChange = function () {
                        var val = $(this).attr('val');
                        mvvm.tab = val;
                    }

                    vm.showSubNav = 'cars';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.createEntity = function (item) {
                        mvvm.entity = item || modelFactory.create('CarApply');
                    }
                    vm.showAdd = function () {
                        vm.createEntity();
                        mvvm.entity.UseBy = { Id: CBCRM.memberShip.Id, FullName: CBCRM.memberShip.FullName };
                        showForm("新增用车申请");
                    }
                    vm.showView = function (curitem) {
                        mvvm.createEntity(curitem.$model);
                        showForm("查看用车申请", false);
                    }
                    vm.approval = function () {
                        var ids = mvvm.getIds("ids");
                        if (ids.length == 0) {
                            messageBox.error("请选择数据！");
                            return;
                        }
                        messageBox.confirm("是否确认审批？", function () {
                            $.post('/Office/CarApplyApproval/', ids).done(function (ret) {
                                avalon.vmodels.CBCRM.showResult(ret, function () {
                                    mvvm.listOpts.paging();
                                    messageBox.close()
                                })
                            });
                        });
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/CarApply/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                                mvvm.ADD = ret.data.ADD;
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.carSelect = function () {
                        var vmid = "CarSelect",
                            url = "/Office/CarSelect";
                        var dialog = openWin("选择车辆", vmid, url, 900, 400, [{
                            name: "确定选择",
                            focus: true,
                            callback: function () {
                                var pvm = avalon.vmodels[vmid];
                                if (!pvm) {
                                    messageBox.warning("系统正在载入中，请稍候……");
                                    return false;
                                }
                                var list = pvm.getChecked();
                                if (list.length == 0) {
                                    messageBox.warning("请选择数据！");
                                    return false;
                                }
                                var m = list[0].$model;
                                mvvm.entity.Car = m;
                                mvvm.entity.Driver = m.Driver;
                                mvvm.entity.DriverMobile = m.DriverMobile;
                            }
                        }]);
                    }
                })
                mvvm.createEntity();
                function showForm(title, b) {
                    mvvm.tab = "tab1";
                    var btns = b == false ? null : [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            var m = $.extend(true, {}, mvvm.entity.$model);
                            if (!m.UseBy.Id) {
                                messageBox.warning('请选择用车人！');
                                return false;
                            }
                            if (!m.BeginTime || !m.EndTime) {
                                messageBox.warning('请选择开始与预计结束时间！');
                                return false;
                            }
                            $.extend(m, jsonToSubmit("UseBy", m.UseBy));
                            delete m.UseBy;
                            if (m.Car.Id) $.extend(m, jsonToSubmit("Car", m.Car));
                            delete m.Car;
                            var url = (m.Id == 0 ? "/Office/CarApplyAdd/" : "/Office/CarApplyUpdate/" + m.Id);
                            $.post(url, jsonToSubmit("model", m), function (ret) {
                                if (ret.result) {
                                    messageBox.ok(ret.message, function () {
                                        if (ret.data.Id) {
                                            mvvm.entity.Id = ret.data.Id;
                                        }
                                        if (dialog) dialog.close();
                                        mvvm.doSearch();
                                    });
                                }
                                else {
                                    messageBox.fail(ret.message);
                                }
                            })
                            return false;
                        }
                    }];
                    var tmplid = b == false ? 'CarApplyviewTemplate' : 'CarApplyformTemplate';
                    var dialog = openTmpl(mvvm, title, tmplid, mvvm.tabWidth, null, btns, function () {
                        destroyui(["carUseByTree"]);
                    });

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

                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.CarApply = null;
                }
            },
            CarAppoint: function (tmpl, lang, contentId, module, conditionKey) {
                var router, mvvm, init = false;
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define('CarAppoint', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.ADD = false
                    vm.EDIT = false
                    vm.loading = true;
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = avalon.mix({}, mvvm.queryinfo.$model);
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    //日期参数
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d %H:%M',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.BeginTime = formatDate;
                        }
                    }
                    vm.dateOpts2 = {
                        format: '%Y-%m-%d %H:%M',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.EndTime = formatDate;
                        }
                    }
                    vm.queryinfo = { state: "2" };
                    vm.doSearch = function () {
                        mvvm.loadData(mvvm.queryinfo.$model);
                    }
                    vm.entity = {};
                    vm.list = [];
                    vm.states = [{ val: "", text: "显示全部" }, { val: 0, text: "待审批" }, { val: 1, text: "未通过审批" }
                        , { val: 2, text: "待派车" }, { val: 3, text: "已派车" }, { val: 4, text: "拒绝派车" }, { val: 5, text: "派车结束" }
                    ];

                    initGridvm(vm, vm.list);
                    vm.tab = "tab1";
                    vm.tabWidth = 550;
                    //标签切换
                    vm.tabChange = function () {
                        var val = $(this).attr('val');
                        mvvm.tab = val;
                    }

                    vm.showSubNav = 'cars';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.createEntity = function (item) {
                        mvvm.entity = item || modelFactory.create('CarApply');
                    }
                    vm.appoint = function () {
                        var items = mvvm.getChecked();
                        if (items.length != 1) {
                            messageBox.error("请选择一条申请来派车！");
                            return;
                        }
                        var item = items[0];
                        mvvm.createEntity(item.$model);
                        showForm("派车");
                    }
                    vm.showView = function (curitem) {
                        mvvm.createEntity(curitem.$model);
                        showForm("查看用车申请", false);
                    }
                    vm.appointEnd = function () {
                        var ids = mvvm.getIds("ids");
                        if (ids.length == 0) {
                            messageBox.error("请选择数据！");
                            return;
                        }
                        messageBox.confirm("是否确认结束用车？", function () {
                            $.post('/Office/CarAppointEnd/', ids).done(function (ret) {
                                avalon.vmodels.CBCRM.showResult(ret, function () {
                                    mvvm.listOpts.paging();
                                    messageBox.close()
                                })
                            });
                        });
                    }
                    vm.appointReject = function () {
                        var ids = mvvm.getIds("ids");
                        if (ids.length == 0) {
                            messageBox.error("请选择数据！");
                            return;
                        }
                        messageBox.confirm("是否确认拒绝派车？", function () {
                            $.post('/Office/CarAppointReject/', ids).done(function (ret) {
                                avalon.vmodels.CBCRM.showResult(ret, function () {
                                    mvvm.listOpts.paging();
                                    messageBox.close()
                                })
                            });
                        });
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/CarApply/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                                mvvm.ADD = ret.data.ADD;
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.carSelect = function () {
                        var vmid = "CarSelect",
                            url = "/Office/CarSelect";
                        var dialog = openWin("选择车辆", vmid, url, 900, 400, [{
                            name: "确定选择",
                            focus: true,
                            callback: function () {
                                var pvm = avalon.vmodels[vmid];
                                if (!pvm) {
                                    messageBox.warning("系统正在载入中，请稍候……");
                                    return false;
                                }
                                var list = pvm.getChecked();
                                if (list.length == 0) {
                                    messageBox.warning("请选择数据！");
                                    return false;
                                }
                                var m = list[0].$model;
                                mvvm.entity.Car = m;
                                mvvm.entity.Driver = m.Driver;
                                mvvm.entity.DriverMobile = m.DriverMobile;
                            }
                        }]);
                    }
                })
                mvvm.createEntity();
                function showForm(title, b) {
                    mvvm.tab = "tab1";
                    var btns = b == false ? null : [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            var m = $.extend(true, {}, mvvm.entity.$model);
                            if (!m.UseBy.Id) {
                                messageBox.warning('请选择用车人！');
                                return false;
                            }
                            if (!m.BeginTime || !m.EndTime) {
                                messageBox.warning('请选择开始与预计结束时间！');
                                return false;
                            }
                            if (m.State != 2) {
                                messageBox.warning('请选择状态为待派车的数据！');
                                return false;
                            }
                            $.extend(m, jsonToSubmit("UseBy", m.UseBy));
                            delete m.UseBy;
                            if (m.Car.Id) $.extend(m, jsonToSubmit("Car", m.Car));
                            delete m.Car;
                            var url = (m.Id == 0 ? "/Office/CarApplyAdd/" : "/Office/CarAppointAdd/" + m.Id);
                            $.post(url, jsonToSubmit("model", m), function (ret) {
                                if (ret.result) {
                                    messageBox.ok(ret.message, function () {
                                        if (ret.data.Id) {
                                            mvvm.entity.Id = ret.data.Id;
                                        }
                                        if (dialog) dialog.close();
                                        mvvm.doSearch();
                                    });
                                }
                                else {
                                    messageBox.fail(ret.message);
                                }
                            })
                            return false;
                        }
                    }];
                    var tmplid = b == false ? 'CarApplyviewTemplate' : 'CarApplyformTemplate';
                    var dialog = openTmpl(mvvm, title, tmplid, mvvm.tabWidth, null, btns, function () {
                        destroyui(["carUseByTree"]);
                    });

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

                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.CarApply = null;
                }
            },
            CarUsesInfo: function (tmpl, lang, contentId, module, conditionKey) {
                var router, mvvm, init = false;
                var tarr = { "7": ["0:00", "7:59"] };
                for (var i = 8; i < 20; i++) {
                    tarr[i] = [i + ":00", i + ":59"];
                }
                tarr["21"] = ["21:00", "23:59"];
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define('CarUsesInfo', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.ADD = false
                    vm.EDIT = false
                    vm.loading = true;
                    
                    //日期参数
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d %H:%M',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.useTime = formatDate;
                        }
                    }
                    
                    vm.queryinfo = { useTime: telesa.datetime.ymd(), carNo: '' };
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.loadData(mvvm.queryinfo.$model);
                    }
                    vm.entity = {};
                    vm.list = [];
                    vm.appointList = [];

                    initGridvm(vm, vm.list);

                    vm.showSubNav = 'cars';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.getAppointList = function (carid) {
                        var param = $.extend({ carid: carid }, mvvm.queryinfo.$model);
                        param.state = 3;//已派车状态
                        mvvm.loading = true;
                        $.post('/Office/CarAppointList/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result && ret.data.Source) {
                                mvvm.initChecked(ret.data.Source);
                                mvvm.appointList = ret.data.Source;
                            }
                        })
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/CarUsesInfo/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result && ret.data) {
                                if (ret.data) {
                                    mvvm.initChecked(ret.data);
                                    mvvm.initBusy(ret.data);
                                    mvvm.list = ret.data;
                                }
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.initBusy = function (list) {
                        list.forEach(function (item) {
                            item.busy = getCarBusy(tarr, mvvm.queryinfo.useTime, item);
                        });
                    }
                    vm.entity = {};
                    vm.createEntity = function (item) {
                        mvvm.entity = item || modelFactory.create("Car");
                    }
                    vm.carClick = function (item) {
                        mvvm.list.forEach(function (n) {
                            n.checked = false;
                        })
                        //这里的赋值，checkbox会得到相反的值....
                        //item.checked = true;
                        mvvm.getAppointList(item.Id);
                    }
                })
                mvvm.createEntity();
                mvvm.doSearch();
                avalon.vmodels.CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)

                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.CarUseInfo = null;
                }
            },
            CarUseSearch: function (tmpl, lang, contentId, module, conditionKey) {
                var router, mvvm, init = false;
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define('CarUseSearch', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.loading = true;
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = avalon.mix({}, mvvm.queryinfo.$model);
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    //日期参数
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d %H:%M',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.beginTime = formatDate;
                        }
                    }
                    vm.dateOpts2 = {
                        format: '%Y-%m-%d %H:%M',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.endTime = formatDate;
                        }
                    }
                    vm.queryinfo = { beginTime: '', endTime: '', carNo: '', useBy: '', driver: '' };
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.loadData(mvvm.queryinfo.$model);
                    }
                    vm.entity = {};
                    vm.list = [];
                    initGridvm(vm, vm.list);
                    vm.showSubNav = 'cars';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/CarUseSearch/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                                mvvm.ADD = ret.data.ADD;
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    
                })
                avalon.vmodels.CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)

                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.CarUseSearch = null;
                }
            },
            CarInsure: function (tmpl, lang, contentId, module, conditionKey) {
                var router, mvvm, init = false;
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define('CarInsure', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.ADD = false
                    vm.EDIT = false
                    vm.loading = true;
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = avalon.mix({}, mvvm.queryinfo.$model);
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    //日期参数
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.InsureStartDate = formatDate;
                        }
                    }
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.InsureEndDate = formatDate;
                        }
                    }
                    vm.queryinfo = { carid: "" };
                    vm.doSearch = function () {
                        mvvm.loadData(mvvm.queryinfo.$model);
                    }
                    vm.entity = {};
                    vm.list = [];
                    vm.historyList = [];
                    vm.carList = [];
                    vm.insureWarnWays = ["短信", "系统消息"];

                    initGridvm(vm, vm.list);
                    vm.tab = "tab1";
                    vm.tabWidth = 700;
                    //标签切换
                    vm.tabChange = function () {
                        var val = $(this).attr('val');
                        mvvm.tab = val;
                    }

                    vm.showSubNav = 'cars';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.createEntity = function (item) {
                        if (!item) {
                            item = modelFactory.create('CarInsure');
                            item.InsureBy = CBCRM.memberShip.FullName;
                            if (mvvm.carList.length > 0) item.Car = mvvm.carList[0].$model;
                        }
                        mvvm.entity = item;
                    }
                    vm.showAdd = function () {
                        vm.createEntity();
                        showForm("新增车辆保险");
                    }
                    vm.showEdit = function (curitem) {
                        mvvm.getModel(curitem.Id, function (model) {
                            mvvm.createEntity(model);
                            showForm("编辑车辆保险");
                        });
                    }
                    vm.showView = function (curitem) {
                        mvvm.getModel(curitem.Id, function (model) {
                            mvvm.createEntity(model);
                            showForm("查看车辆资料", false);
                        });
                    }
                    vm.showInsure = function (item) {
                        var s = [], a = item.Insure ? item.Insure.split(";") : [];
                        $.each(a, function (i, id) {
                            $.each(mvvm.insures.$model, function (i, item) {
                                if (item.Id == id) {
                                    s.push(item.Data);
                                    return false;
                                }
                            });
                        });
                        var html = "<p>险种列表：<span style='color:#f00;'>" + s.join(";") + "</span></p>";
                        messageBox.openHtml("险种列表", 300, 100, html);
                    }
                    vm.getModel = function (id, callBack) {
                        $.post("/Office/CarInsureView/", { id: id }, function (ret) {
                            if (ret.result) {
                                var m = ret.data.model;
                                mvvm.historyList = ret.data.historyList;
                                if (m.Insure) m.Insure = m.Insure.split(";");
                                if (m.InsureWarnWay) m.InsureWarnWay = m.InsureWarnWay.split(";");
                                if (callBack) callBack(m);
                            } else messageBox.warning(ret.message);
                        });
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/CarInsure/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                var lst, stages
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                                mvvm.ADD = ret.data.ADD;
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.getCarList = function () {
                        $.post("/Office/CarList/", {}, function (ret) {
                            if (ret.result) {
                                mvvm.carList = ret.data;
                            }
                        });
                    }
                    vm.insures = [];
                    vm.getDicts = function () {
                        var dicts = {
                            "100105": "insures"//险种
                        };
                        getDicts(dicts, mvvm);
                    }
                })
                mvvm.createEntity();
                mvvm.getDicts();
                mvvm.getCarList();
                function showForm(title, b) {
                    mvvm.tab = "tab1";
                    var btns = b == false ? null : [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            var m = $.extend(true, {}, mvvm.entity.$model);
                            if (!m.Car.Id) {
                                messageBox.warning('请选择车牌号码！');
                                return false;
                            }
                            if (m.Insure) m.Insure = m.Insure.join(";");
                            else m.Insure = "";
                            if (m.Insure == "") {
                                messageBox.warning('请选择险种！');
                                return false;
                            }
                            if (m.InsureWarnWay) m.InsureWarnWay = m.InsureWarnWay.join(";");
                            $.extend(m, jsonToSubmit("Car", m.Car));
                            delete m.Car;
                            var url = (m.Id == 0 ? "/Office/CarInsureAdd/" : "/Office/CarInsureUpdate/" + m.Id);
                            $.post(url, jsonToSubmit("model", m), function (ret) {
                                if (ret.result) {
                                    messageBox.ok(ret.message, function () {
                                        if (ret.data.Id) {
                                            mvvm.entity.Id = ret.data.Id;
                                        }
                                        if (dialog) dialog.close();
                                        mvvm.doSearch();
                                    });
                                }
                                else {
                                    messageBox.fail(ret.message);
                                }
                            })
                            return false;
                        }
                    }];
                    var tmplid = b == false ? 'CarInsureviewTemplate' : 'CarInsureformTemplate';
                    var dialog = openTmpl(mvvm, title, tmplid, mvvm.tabWidth, null, btns);

                }
                mvvm.queryinfo.$watch("carid", function () {
                    mvvm.doSearch();
                });
                avalon.vmodels.CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)

                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.CarInsure = null;
                }
            },
            CarService: function (tmpl, lang, contentId, module, conditionKey) {
                var router, mvvm, init = false;
                CBCRM = avalon.vmodels.CBCRM
                mvvm = avalon.define('CarService', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.ADD = false
                    vm.EDIT = false
                    vm.loading = true;
                    vm.listOpts = { //列表分页组件
                        paging: function () {
                            var m = mvvm,
                            data = avalon.mix({}, mvvm.queryinfo.$model);
                            data.page = (this.currentindex + 1) || 1
                            data.limit = this.pagesize
                            if (!init) {
                                data.init = true
                                init = true
                            }
                            m.loadData(data)
                        }
                    }
                    //日期参数
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.ServerTime = formatDate;
                        }
                    }
                    vm.serverTypes = ["维修", "保养"];
                    vm.queryinfo = { carid: "", year: "", serverType: "维修" };
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.loadData(mvvm.queryinfo.$model);
                    }
                    vm.entity = {};
                    vm.list = [];
                    vm.carList = [];

                    initGridvm(vm, vm.list);

                    vm.tabWidth = 600;
                    vm.tabHeight = 400;
                    vm.showSubNav = 'cars';
                    vm.onSubNav = function (v) {
                        mvvm.showSubNav = (mvvm.showSubNav != '' && mvvm.showSubNav == v) ? '' : v;
                    }
                    vm.createEntity = function (item) {
                        if (!item) {
                            item = modelFactory.create('CarService');
                            item.ActionBy = CBCRM.memberShip.FullName;
                            mvvm.serverType = mvvm.queryinfo.serverType;
                        }
                        item.CanUseType = item.CanUse ? "1" : "0";
                        mvvm.entity = item;
                        if (mvvm.carList.length > 0) mvvm.entity.Car = mvvm.carList[0].$model;
                        mvvm.entity.$watch("CanUseType", function (n) {
                            item.CanUse = item.CanUseType == "1" ? true : false;
                        });
                    }
                    vm.showAdd = function () {
                        mvvm.createEntity();
                        showForm("新增车辆" + mvvm.entity.ServerType);
                    }
                    vm.showEdit = function (curitem) {
                        mvvm.createEntity(curitem.$model);
                        showForm("编辑车辆" + mvvm.entity.ServerType);
                    }
                    vm.showView = function (curitem) {
                        mvvm.createEntity(curitem.$model);
                        showForm("查看车辆" + mvvm.entity.ServerType, false);
                    }
                    vm.loadData = function (param) {
                        mvvm.loading = true;
                        $.post('/Office/CarService/', param)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                var lst, stages
                                if (ret.data.Source) {
                                    mvvm.initChecked(ret.data.Source);
                                    mvvm.list = ret.data.Source;
                                }
                                avalon.vmodels.listPage.total = ret.data.RecordTotal || 0
                                mvvm.ADD = ret.data.ADD;
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    }
                    vm.getCarList = function () {
                        $.post("/Office/CarList/", {}, function (ret) {
                            if (ret.result) {
                                mvvm.carList = ret.data;
                            }
                        });
                    }
                })
                mvvm.getCarList();
                mvvm.queryinfo.$watch("serverType", function () {
                    mvvm.doSearch();
                });
                mvvm.queryinfo.$watch("carid", function () {
                    mvvm.doSearch();
                });
                function showForm(title, b) {
                    mvvm.tab = "tab1";
                    var btns = b == false ? null : [{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            var m = $.extend(true, {}, mvvm.entity.$model);
                            if (!m.Car.Id) {
                                messageBox.warning('请选择车牌号码！');
                                return false;
                            }
                            $.extend(m, jsonToSubmit("Car", m.Car));
                            delete m.Car;
                            var url = (m.Id == 0 ? "/Office/CarServiceAdd/" : "/Office/CarServiceUpdate/" + m.Id);
                            $.post(url, jsonToSubmit("model", m), function (ret) {
                                if (ret.result) {
                                    messageBox.ok(ret.message, function () {
                                        if (ret.data.Id) {
                                            mvvm.entity.Id = ret.data.Id;
                                        }
                                        if (dialog) dialog.close();
                                        mvvm.doSearch();
                                    });
                                }
                                else {
                                    messageBox.fail(ret.message);
                                }
                            })
                            return false;
                        }
                    }];
                    var tmplid = b == false ? 'CarServiceviewTemplate' : 'CarServiceformTemplate';
                    var dialog = openTmpl(mvvm, title, tmplid, mvvm.tabWidth, null, btns);

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

                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.CarService = null;
                }
            },
            CarSelect: function (tmpl, lang, contentId, module, conditionKey) {
                var router = this, mvvm, init = false;
                var tarr = { "7": ["0:00", "7:59"] };
                for (var i = 8; i < 20; i++) {
                    tarr[i] = [i + ":00", i + ":59"];
                }
                tarr["21"] = ["21:00", "23:59"];
                CBCRM = avalon.vmodels.CBCRM

                mvvm = avalon.define('CarSelect', function (vm) {
                    vm.$skipArray = ['lang']
                    vm.lang = lang
                    vm.loading = true;
                    vm.queryinfo = { useTime: telesa.datetime.ymd() }
                    vm.$params = {};
                    vm.toEnter = function (e) {
                        if (e.keyCode == 13) mvvm.toSearch();
                    }
                    vm.toSearch = function () {
                        mvvm.loadData(mvvm.queryinfo.$model);
                    }
                    //日期参数
                    vm.dateOpts1 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.queryinfo.useTime = formatDate;
                        }
                    }
                    vm.list = []
                    initGridvm(vm, vm.list);
                    vm.loadData = function (param, callBack) {
                        mvvm.loading = true;
                        var data = $.extend({}, param, mvvm.$params);
                        $.post('/Office/CarSelect/', data)
                        .done(function (ret) {
                            mvvm.loading = false;
                            if (ret.result) {
                                if (ret.data) {
                                    mvvm.initChecked(ret.data);
                                    mvvm.initBusy(ret.data);
                                    mvvm.list = ret.data;
                                }
                            } else {
                                messageBox.error(ret.message);
                            }
                            if (callBack) callBack();
                        })
                    }
                    vm.initBusy = function (list) {
                        list.forEach(function (item) {
                            item.busy = getCarBusy(tarr, mvvm.queryinfo.useTime, item);
                        });
                    }
                    vm.entity = {};
                    vm.createEntity = function (item) {
                        mvvm.entity = item || modelFactory.create("Car");
                    }
                    vm.carClick = function (item) {
                        mvvm.list.forEach(function (n) {
                            n.checked = false;
                        })
                        //这里的赋值，checkbox会得到相反的值....
                        //item.checked = true;
                        mvvm.createEntity(item.$model);
                    }
                })
                
                mvvm.createEntity();
                mvvm.toSearch();
                avalon.vmodels.CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
            },

            //新版日程任务
            CbCalendar: function (tmpl, lang, contentId, module,paramData) {
                var CBCRM = avalon.vmodels.CBCRM;
                var request = this.params;
                var action = request.action, paramid = request.id;
                var mvvm = CBCRM.define('CbCalendar', function (vm) {
                    vm.lang = lang
                    vm.tmpl = tmpl;
                    vm.modelFactory = modelFactory;
                    vm.destroy = function () {

                    }
                    vm.action = action;
                    vm.title = 'calender'
                    vm.tab = 'cal'
                    vm.changeTab = function () {
                        mvvm.tab = $(this).attr('tab')
                    }

                    vm.entity = {}
                    vm.entityList = []
                    vm.pageList = []
                    vm.entityCategory = {}
                    vm.entityCategoryList = []
                    vm.salasList = []
                    vm.queryData = {}
                    vm.contactList = []
                    vm.customer = { Id: '', Name: '' }
                    vm.contactValue = ''
                    vm.showAdd = false
                    vm.youxian = []
                    vm.ADD = true              //!!!!!!!回头记得修改权限
                    vm.DELETE = true           //!!!!!!!回头记得修改权限
                    vm.CATEGORY = false
                    vm.showOnlyList = false
                    vm.showOnly = true
                    vm.showCustomer = true
                    vm.showMobile = false

                    //热度
                    vm.hotOpts = {
                        val: 10,
                        valChanged: function (val) {
                            mvvm.entity.Completion = val
                        }
                    }
                    vm.grid1 = { gridmsg: "" };
                    //分页
                    vm.userpaing = {
                        paging: function (pageIndex,pageSize) {
                            var that = this
                            mvvm.queryData.pageSize = pageSize
                            mvvm.queryData.pageIndex = pageIndex;
                            if (action=="customer")
                                mvvm.queryData.customerId = paramid;
                            initWithPageList(mvvm.queryData.$model);
                        }
                    }

                    //选客户/联系人
                    vm.selectCustomer = function () {
                        plugins.selectCustomer({
                            type: "contacts",
                            required: { cu: false, con: false },
                            callback: function (cus,cons) {
                                var cu = cus.length ? cus[0] : { Id: 0, Name: "" };
                                var con = cons.length ? cons[0] : { Id: 0, Name: "" };
                                mvvm.entity.CustomId = cu.Id;
                                mvvm.entity.CustomName = cu.Name;
                                mvvm.entity.CustomMan = con.Name;
                                initWithSalas(cu.Id)
                            }
                        });
                    }
                    //执行人
                    vm.selectBelongTo = function () {
                        plugins.selectUser({
                            isJoin: true,
                            callback: function (us) {
                                var u = us[0];
                                mvvm.entity.Attendees = u.Id;
                                mvvm.entity.AttendeeNames = u.FullName;
                            }
                        });
                    }
                    //执行伙伴
                    vm.selectPartner = function () {
                        var ids = mvvm.entity.OtherAttendee || [];
                        ids = ids.$model || ids;
                        if (typeof (ids) == "string") ids = ids.split(",");
                        plugins.selectUser({
                            multiple: true,
                            isJoin: true,
                            listData:ids,
                            callback: function (us) {
                                var names = [];
                                var ids = [];
                                us.forEach(function (u) {
                                    names.push(u.FullName)
                                    ids.push(u.Id)
                                })
                                mvvm.entity.OtherAttendee = ids;
                                mvvm.entity.OtherAttendeeNames = names.join(',')
                            }
                        });
                    }
                    //下属员工
                    vm.selectEmp=function () {
                        var ids = mvvm.queryData.ids || [], EMPTYPE = 2;
                        plugins.selectUser({
                            multiple: true,
                            required:false,
                            dataAuth: 4030000,
                            listData:ids,
                            callback: function (us) {
                                var sIds = where(us, true, "Id");
                                empIds = jsonToSubmit("ids", sIds);
                                var name = us.length > 0 ? us[0].FullName : "下属员工";
                                var title = name;
                                if (us.length > 1) {
                                    name += "...";
                                    title = where(us, true, "FullName");
                                }
                                $('#empName').html(name).attr("title",title);
                                mvvm.queryData.ids = sIds;
                                mvvm.queryData.listType = EMPTYPE;
                                empIds.listType = EMPTYPE;
                                initWithPageList(mvvm.queryData.$model);
                                //刷新日程视图
                                calendar.fullCalendar('refetchEvents')
                            }
                        });
                    }
                    //查看
                    vm.doviews = function () {
                        var path = $(this).attr('path')
                        goto(path)
                    }

                    vm.birthdayOpts = {
                        format: '%Y-%m-%d %H:%M',
                        onSelect: function (date, formatDate, format) { }
                    }
                    vm.birthdayOpts2 = {
                        format: '%Y-%m-%d %H:%M',
                        onSelect: function (date, formatDate, format) { }
                    }
                    

                    vm.categoryChange = function () {
                        mvvm.entityCategory = modelFactory.create('CalCategory');
                        var color = mvvm.entityCategory.$model.CategoryColor;
                        //设置颜色
                        if ($('#colorLayer').html() == '') {
                            $('#colorLayer').colorselect({ title: '选择颜色', index: color, hiddenid: "colorValue" });
                        } else {
                            $('.leftdiv').css('background', colorWithIndex(color));
                        }
                        mvvm.showAdd = true;
                    }
                    vm.categoryBack = function () {
                        mvvm.showAdd = false;
                    }
                    vm.categorySubmit = function () {
                        var model = mvvm.entityCategory.$model;
                        if (model.CategoryName) {
                            model.CategoryColor = $('#colorValue').val();
                            var url = model.Id == 0 ? "/Office/CategoryAdd/" : ("/Office/CategoryEdit/" + model.Id);
                            $.post(url, model, function (ret) {
                                if (ret.result) {
                                    mvvm.entityCategoryList = ret.data;
                                    mvvm.showAdd = false;
                                }
                            })
                        }
                        else alert('请填写分类名称');
                    }
                    vm.categoryDetail = function () {
                        mvvm.showAdd = true;
                        var val = $(this).val();
                        $.get('/Office/CategoryDetail/' + val, {}, function (ret) {
                            mvvm.entityCategory = ret.data;
                            var color = mvvm.entityCategory.$model.CategoryColor;
                            //设置颜色
                            if ($('#colorLayer').html() == '') {
                                $('#colorLayer').colorselect({ title: '选择颜色', index: color, hiddenid: "colorValue" });
                            } else {
                                $('.leftdiv').css('background', colorWithIndex(color));
                            }
                        });
                    }
                    vm.categoryDel = function () {
                        if (confirm('确定删除日程分类吗？')) {
                            var i = parseInt($(this).attr('index'));
                            var id = $(this).val();
                            mvvm.entityCategoryList.removeAt(i);
                            $.get('/Office/CategoryDelete/' + id, {}, function (ret) { });
                        }
                    }
                    vm.categorySelect = function () {
                        var val = $(this).val();
                        mvvm.entity.CategoryId = parseInt(val);
                    }
                    //新增
                    vm.doadd = function () {
                        mvvm.showMobile = false
                        mvvm.entity = modelFactory.create('Calendar')
                        mvvm.entity.AddTime = GetDateTime();
                        if (action == "salesopp") {
                            var pvm = avalon.vmodels["marketingsalesopportunities"];
                            if (pvm != null) {
                                var sentity = pvm.entity;
                                mvvm.entity.CustomId = sentity.Customer;
                                mvvm.entity.CustomName = sentity.CustomerDisplay;
                                mvvm.entity.CustomMan = '';
                                if(sentity.Customer)initWithSalas(sentity.Customer)
                            }
                        }
                        initWithForm('新增日程', null, null, 0)
                    }
                    //查看
                    vm.doview = function () {
                        mvvm.showMobile = true;
                        var id = $(this).val();
                        doView(id);

                        $('.fancybox').fancybox();
                    }
                    //编辑
                    vm.doedit = function () {
                        mvvm.showMobile = true;
                        var id = $(this).val();
                        initWithForm('编辑日程', null, null, id)
                    }
                    //删除
                    vm.dodel = function () {
                        var id = $(this).val();
                        var i = parseInt($(this).attr('index'));
                        messageBox.confirm('确定删除此数据吗？', function () {
                            mvvm.pageList.removeAt(i);
                            avalon.vmodels.upaing.total = avalon.vmodels.upaing.total - 1;
                            $.get('/Office/CalendarDelete/' + id, {}, function (ret) { $("#gridcontainer").reload(); });
                        });
                    }
                    //批量删除
                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.get('/Office/CalendarDelAll/', deleteIds, function (ret) {
                                if (ret.result) {
                                    $("#gridcontainer").reload();
                                    initWithPageList(mvvm.queryData.$model);
                                }
                            });
                        });
                    }
                    
                    vm.openimage = function () {
                        var path = $(this).attr('path');
                        art.dialog({ content: '<img src="' + path + '" />', title: '行动图片' });
                    }

                    //查看地图
                    vm.$mapLoaded = false;
                    vm.$map = null;
                    vm.Address = "";
                    vm.loadMap = function (callback) {
                        if (!mvvm.$mapLoaded) {
                            require(["bdmapTool", "ready!"], function (bdmapTool) {
                                var cmyInfo = CBCRM.cmyInfo || {};
                                var pointStart = null;
                                if (cmyInfo.Lng) {
                                    pointStart = new BMap.Point(cmyInfo.Lng, cmyInfo.Lat);
                                }
                                mvvm.$map = new bdmapTool({
                                    tmpl: "line",
                                    mapContent: "#dmap",
                                    linepanel: "divline",
                                    left: 0,
                                    right: 820,
                                    height: 520,
                                    pointStart:pointStart,
                                    pstart: cmyInfo.Address,
                                    pend: mvvm.entity.Location
                                });
                                mvvm.$maploaded = true;
                                if (callback) callback.call(mvvm.$map);
                            });
                        } else {
                            if (callback) {
                                callback.call(mvvm.$map);
                            }
                        }
                    }
                    vm.showMap = function () {
                        var win = art.dialog({
                            width: 300,
                            height: 100,
                            title: "地图加载中……",
                            content: "<img src='/Content/Themes/Base/images/loading2.gif' />"
                        });
                        mvvm.loadMap(function () {
                            var map = mvvm.$map;
                            var point;
                            if (mvvm.entity.Longitude != "" && mvvm.entity.Longitude > 0) {
                                point = new BMap.Point(mvvm.entity.Longitude, mvvm.entity.Latitude);
                            } else {
                                point = null;
                                messageBox.error("抱歉，还未有坐标地址！");
                                return;
                            }
                            map.ops.point = point;
                            map.ops.pointEnd = point;
                            map.ops.pend = mvvm.entity.Location;
                            map.openMap(function () {
                                if (win) win.close();
                                if (point) {
                                    map.addMarker(point, mvvm.entity.Subject);
                                    map.map.panTo(point);
                                }
                            });
                        });
                    }
                    //我的日程
                    vm.mycal = function () {
                        var ids = [], name = "下属员工", METYPE = 1;
                        empIds = jsonToSubmit("ids", ids);
                        $('#empName').html(name).attr("title", name);
                        mvvm.queryData.ids = ids;
                        mvvm.queryData.listType = METYPE;
                        empIds.listType = METYPE;
                        calendar.fullCalendar('refetchEvents')
                        initWithPageList(mvvm.queryData.$model)
                    }
                });

                mvvm.queryData = {
                    pageIndex: '', pageSize: '', customerId: '', ids: [],
                    showdate: '', viewtype: '', timezone: '',
                    vstart: '', vend: '',listType:0
                };

                var calendar, empIds = {};
                avalon.nextTick(function ()
                {
                    var date = new Date();
                    var d = date.getDate();
                    var m = date.getMonth();
                    var y = date.getFullYear();
                    //日程控件
                    calendar = $('#calendar').fullCalendar({
                        header: {
                            left: '',
                            center: 'prev title next',
                            right: 'today,month,agendaWeek,agendaDay'
                        },
                        selectable: true,
                        selectHelper: true,
                        editable: true,
                        firstDay: 1,
                        weekends: true,
                        aspectRatio: 1.8,         //缩放比例
                        timeFormat: 'HH:mm',
                        axisFormat: 'HH:mm',
                        //点击日程项时触发的事件(编辑)
                        eventClick: function (calEvent, jsEvent, view) {
                            var id = calEvent.id;
                            if (id) {
                                mvvm.showMobile = true;
                                initWithForm('编辑日程', null, null, id);
                            }
                            else messageBox.error('发生错误!')
                        },
                        //选择日程项时触发的事件(新增)
                        select: function (start, end) {
                            calendar.fullCalendar('unselect') //取消选择阴影
                            mvvm.showMobile = false                 //不显示移动端的属性
                            mvvm.entity = modelFactory.create('Calendar')
                            initWithForm('新增日程', start, end, 0)
                        },
                        //拖动日程项时触发的事件
                        eventDrop: function (event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view) {
                            $.post('/Office/CalendarChange/' + event.id, { dayDelta: dayDelta, minuteDelta: minuteDelta }, function (ret) { })
                        },
                        //日程数据源
                        events: initWithGrid
                    });

                    //显示或隐藏分类表单和列表
                    $('#CategoryManager').live('click', function () {
                        if (!mvvm.CATEGORY) {
                            messageBox.warning("抱歉，您无此操作权限！");
                            return;
                        }
                        var warpCategory = $('#warpCategory').show();
                        $("body").bind("mousedown", function (event) {
                            var containerId = "warpCategory";
                            var divcolorLayer = "divcolorLayer";
                            if (!(event.target.id == "CategoryManager"
                                || event.target.id == containerId
                                || event.target.id == divcolorLayer
                                || $(event.target).parents("#" + divcolorLayer).length > 0
                                || $(event.target).parents("#" + containerId).length > 0)) {
                                //$("#" + containerId).hide();
                                warpCategory.hide();
                                $("body").unbind("mousedown");
                                mvvm.showAdd = false;
                            }
                        });
                    });

                    

                    //左边两个按钮
                    var leftLayout = $('.fc-header-left')
                    leftLayout.find('span').live({
                        mouseover: function () { $(this).addClass('fc-state-hover') },
                        mouseout: function () { $(this).removeClass('fc-state-hover') }
                    })
                    leftLayout.attr('ms-include', 'buttonTemplate')
                    avalon.scan(leftLayout[0], mvvm)
                })
                
                function initWithData() {
                    mvvm.entity = modelFactory.create('Calendar');
                    mvvm.entityCategory = modelFactory.create('CalCategory');
                    $.get('/Office/Category/', {}).done(function (ret) {
                        mvvm.entityCategoryList = ret.data
                    });
                    $.get('/Office/Calendar/', {}).done(function (ret) { mvvm.showOnly = ret.data.only });
                    mvvm.youxian = ["最高", "高", "中", "无", "低", "最低"];
                }
                initWithData();

                function getCategory(id) {
                    var res = modelFactory.create('CalCategory');
                    mvvm.entityCategoryList.forEach(function (item) {
                        if (item.Id == id)
                            res = item;
                    });
                    return res;
                }
                function doView(id) {
                    $.get('/Office/CalendarDetail/' + id, {}, function (ret) {
                        mvvm.entity = ret.data;
                        mvvm.Address = "";
                        var dialog = mvvm.openTmpl({
                            title:"查看日程",w:800,h:340,
                            tmplid: "viewTemplate"
                        })
                        //getLocation();
                    })
                }
                function getLocation() {
                    mvvm.Address = "地址解析中……";
                    mvvm.loadMap(function () {
                        var map = mvvm.$map;
                        var point;
                        if (mvvm.entity.Longitude != "" && mvvm.entity.Longitude > 0) {
                            point = new BMap.Point(mvvm.entity.Longitude, mvvm.entity.Latitude);
                            var gc = new BMap.Geocoder();
                            gc.getLocation(point, function (ret) {
                                mvvm.Address = ret.address;
                            });
                        } else {
                            mvvm.Address = "暂无地理位置！";
                        }
                    });
                }
                function initWithPageList(data) {
                    var params = $.extend(true, {}, data);
                    if (action == "salesopp") params.salesId = paramid;
                    if (params.ids && params.ids.length > 0) {
                        $.extend(params, jsonToSubmit("ids", params.ids));
                    }
                    delete params.ids;
                    mvvm.grid1.gridmsg = lang.LoadingMsg;
                    $.post('/Office/CalendarPageList/', params, function (ret) {
                        mvvm.grid1.gridmsg = ret.data.RecordTotal > 0 ? "" : lang.NoListData;
                        ret.data.Source.forEach(function (item) {
                            var toDate = new Date()
                            var endDate = new Date(item.EndTime);
                            item.isOver = toDate.getTime() > endDate.getTime();
                        });
                        mvvm.pageList = ret.data.Source
                        mvvm.ADD = ret.data.ADD;
                        mvvm.DELETE = ret.data.DELETE;
                        mvvm.CATEGORY = ret.data.CATEGORY;
                        avalon.vmodels.upaing.total = ret.data.RecordTotal; //分页总数
                    });
                }
                function initWithSalas(id) {
                    mvvm.salasList = [];
                    if (!id) return;
                    $.get('/Office/GetSalasByCustomer/' + id, {}, function (ret) {
                        if (!ret.data) ret.data = [];
                        ret.data.unshift({ Id: 0, Title: '无' });
                        mvvm.salasList = ret.data;
                        if (action == "salesopp") mvvm.entity.SalesId = paramid;
                        if (!mvvm.entity.SalesId) mvvm.entity.SalesId = ret.data[0].Id;
                        else {
                            //列表没有自动选中对应的值，需要重新赋值一次，这是个坑
                            var sid = mvvm.entity.SalesId;
                            mvvm.entity.SalesId = 0;
                            mvvm.entity.SalesId = sid;
                        }
                    })
                }
                function initWithGrid(start, end, callback) {
                    $.get('/Office/CbCalendarView/', empIds ? empIds : {}, function (ret) {
                        var list = ret.data
                        callback(list);
                    })
                }
                function initWithCustomer(cid) {
                    $.get('/Customer/GetConatactByCustomerId/' + cid, {}, function (ret) {
                        if (ret.data.length) {
                            mvvm.contactList = ret.data
                            mvvm.contactValue = ret.data[0].Id
                            mvvm.entity.CustomMan = ret.data[0].Name;
                        }
                    });
                }
                //新增和编辑
                function initWithForm(title, start, end, id) {
                    mvvm.Address = "";
                    mvvm.salasList = [];
                    if (id == 0) {
                        if (!mvvm.ADD) {
                            messageBox.error('非常抱歉，您没有此功能的权限！'); return;
                        }
                        //mvvm.entity = modelFactory.create('Calendar');
                        mvvm.entity.StartTime = telesa.datetime.cut(start);
                        mvvm.entity.EndTime = telesa.datetime.cut(end);
                        mvvm.entity.Attendees = CBCRM.memberShip.Id
                        mvvm.entity.AttendeeNames = CBCRM.memberShip.FullName
                        mvvm.salasList.unshift({ Id: 0, Title: '无' })

                        if (action == "customer") {
                            mvvm.entity.CustomId = paramid;
                            mvvm.entity.CustomName = mvvm.customer.Name;
                            initWithCustomer(paramid);
                            initWithSalas(mvvm.customer.Id);
                        } else if (mvvm.entity.CustomId) {
                            initWithCustomer(mvvm.entity.CustomId);
                        }
                    } else {
                        $.get('/Office/CalendarDetail/' + id, {}, function (ret) {
                            mvvm.entity = ret.data;
                            avalon.vmodels.hotprocessbar.val = parseInt(ret.data.Completion);
                            getLocation();

                            //销售机会
                            mvvm.entity.$watch('SalesId', function (n, o) {
                                mvvm.salasList.forEach(function (item) {
                                    if (item.Id == n) {
                                        mvvm.entity.SalesTitle = item.Title;
                                    }
                                })
                            })

                            if (mvvm.entity.CustomId)
                                initWithSalas(mvvm.entity.CustomId)
                            else {
                                mvvm.salasList.unshift({ Id: 0, Title: '无' })
                            }
                        });
                    }
                    var btns=[{
                        name: '提交',
                        focus: true,
                        callback: function () {
                            var model = $.extend(true, {}, mvvm.entity.$model);
                            var c = model.CategoryId == 0 ? mvvm.entityCategoryList.$model[0] : getCategory(model.CategoryId);
                            if (!c || !c.Id) {
                                messageBox.warning('请选择日程分类')
                                return false;
                            }
                            if (!model.Subject) {
                                messageBox.warning('请填写日程主题!');
                                return false;
                            }
                            model.CategoryId = c.Id;
                            model.Category = c.CategoryName;
                            model.Color = c.CategoryColor;
                            if ($.isArray(model.OtherAttendee)) model.OtherAttendee = model.OtherAttendee.join(",");
                            var url = model.Id == 0 ? "/Office/CalendarAdd/" : "/Office/CalendarEdit/" + model.Id;
                            $.post(url, model, function (ret) {
                                var r=CBCRM.showResult(ret, function () {
                                    dialog.close();
                                    calendar.fullCalendar('refetchEvents')
                                    initWithPageList(mvvm.queryData.$model)
                                })
                            });
                            return false;
                        }
                    }]
                    var dialog=mvvm.openTmpl({
                        title:title,w:760,h:390,
                        tmplid:"formTemplate",btns:btns,
                        onclose:function(){
                            destroyui(["belongToTree", "shareToTree", "setParetCustomer"]);
                        }
                    });
                }
                mvvm.entity.$watch('IsAllDayEvent', function (n, o) {
                    var patten = /\d{2}:\d{2}/
                    if (n) {
                        mvvm.entity.StartTime = mvvm.entity.StartTime.replace(patten, '00:00');
                        mvvm.entity.EndTime = mvvm.entity.StartTime.replace(patten, '23:59');
                    } else {
                        mvvm.entity.StartTime = mvvm.entity.StartTime.replace(patten, '00:00');
                        mvvm.entity.EndTime = mvvm.entity.StartTime.replace(patten, '00:00');
                    }
                });

                switch (action) {
                    case "view":
                        doView(paramid);
                        break;
                    case "customer":
                        
                        //隐藏其它，只显示列表块
                        mvvm.showOnlyList = true
                        mvvm.showCustomer = false
                        mvvm.tab = 'table'
                        if (paramData != null) {
                            paramData.viewOther(tmpl, mvvm);
                            mvvm.customer.Id = paramid;
                            mvvm.customer.Name = paramData.entity.Name;
                        }
                        detail = avalon.vmodels.ViewCustomer
                        break;
                    case "salesopp":
                        if (paramData) {
                            paramData.viewOther(tmpl, mvvm, "#tableList");
                        }
                        break;
                    case "Day":
                        break;
                    case "Week":
                        break;
                    case "Month":
                        break;
                    default:
                        fill();
                        break;
                }
                function fill() {
                    avalon.vmodels.CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
                }       
            }
        }
        return Office;
    });