define('Knowledge', ['modelFactory', 'plugins', 'json', 'dialog', 'common', 'leftMenu', 'jscal2', 'kindedit', 'Jpin', 'upload', 'fusionCharts'], function (modelFactory, plugins) {
    //知识模块
    var Knowledge = {
        ///知识管理
        Index: function (tmpl, lang, contentId, module)
        {
            var CBCRM = avalon.vmodels.CBCRM
            //下拉配置过滤数据 只可选择职位
            var notMemberFilter = function (treeId, parentNode, responseData) {
                var ret = [], len = 0, curr, hasPost=false
                if (responseData.data && responseData.data.groups.length)
                    len = responseData.data.groups.length
                while (len) {
                    curr = responseData.data.groups[--len]
                    curr.nocheck = true
                    hasPost = false
                    curr.Posts.forEach(function (p, i) {
                        curr.Posts[i].ParentId = p.Boss ? p.Boss.Id : p.Group
                        curr.Posts[i].nocheck = false 
                        ret.push(p)
                        hasPost = true
                    })
                    if (hasPost) ret.push(curr)
                }
                return ret
            }
            //下拉配置过滤数据 只可选员工
            var memberFilter = function (treeId, parentNode, responseData) {
                var ret = [], len = 0, curr, hasEmp = false
                if (responseData.data && responseData.data.groups.length)
                    len = responseData.data.groups.length
                while (len) {
                    curr = responseData.data.groups[--len]
                    curr.nocheck = true
                    hasEmp = false
                    curr.Posts.forEach(function (p, i) {
                        curr.Posts[i].ParentId = p.Boss ? p.Boss.Id : p.Group
                        curr.Posts[i].nocheck = true
                        p.Users.forEach(function (u, i) {
                            var u = p.Users[i]
                            if (u.Id === CBCRM.memberShip.Id) return true
                            u.ParentId = u.PositionId
                            u.Name = u.FullName
                            ret.push(u)
                        })
                        if (!hasEmp) {
                            hasEmp = p.Users.length > 0
                        }
                        if (hasEmp) {
                            ret.push(p)
                        }
                    })
                    if (hasEmp) ret.push(curr)
                }
                return ret
            }

            var mvvm = CBCRM.define('knowledgeindex', function (vm) {
                vm.destroy = function () {
                    var uis = ['knowledgecategorytreeid', 'knowledgegroupTreeid', 'pCategoryTree'];
                    mvvm.destroyui(uis);
                }
                vm.lang = lang
                vm.entity = {}
                vm.knowledgeList = []
                vm.knowledgepaing = {
                    paging: function () {
                        var that = this
                        queryData.pageSize = that.pagesize
                        queryData.pageIndex = that.pageindex
                        GetKnowledgeList(queryData)
                    }
                }
                vm.action = "list"
                vm.title = ""
               
                vm.keyword = ''
                vm.history = []
                vm.showItem = {}
                vm.has = false
                vm.ADD = true
                vm.DELETE = true

                vm.menuTab = 1
                vm.doMenuTab = function (tab) {
                    mvvm.menuTab = tab
                    mvvm.has = false
                    mvvm.showItem.categoryid = 0,
                    mvvm.showItem.applytodepartid = 0,
                    mvvm.showItem.applytopostid = 0,
                    mvvm.showItem.applytodictid = 0,
                    mvvm.showItem.key = ''
                    GetKnowledgeList()
                }
                vm.subNav = 1
                vm.doSubNav = function (subid) {
                    mvvm.subNav = subid
                }
                //当前用户部门
                vm.CurrGroupId = 0
                vm.CurrGroupName = ''
                //关键字搜索
                vm.search = function () {
                    if (mvvm.keyword) {
                        queryData.key = mvvm.keyword
                        GetKnowledgeList(queryData)
                        if (mvvm.history.length = 3)
                            mvvm.history.removeAt(2)
                        mvvm.history.unshift(mvvm.keyword)
                    }
                }
                //历史搜索
                vm.historyClick = function () {
                    mvvm.keyword = $(this).val()
                    queryData.key = mvvm.keyword
                    GetKnowledgeList(queryData)
                }
                //移除单个快速筛选
                vm.remove = function () {
                    var searchKey = this.$vmodel.$key
                    mvvm.showItem[searchKey] = ''
                    mvvm.has = false;
                    for (var item in mvvm.showItem.$model) {
                        if (mvvm.showItem.$model[item]) {
                            mvvm.has = true;
                            break;
                        }
                    }
                    queryData[searchKey] = '' 
                    GetKnowledgeList(queryData)
                }
                //清空
                vm.clear = function () {
                    mvvm.keyword = ''
                    mvvm.showItem.categoryid = ''
                    mvvm.showItem.applytodepartid = ''
                    mvvm.showItem.applytopostid = ''
                    mvvm.showItem.applytodictid = '' 

                    mvvm.has = false 
                    queryData.categoryid = 0
                    queryData.applytodepartid = 0
                    queryData.applytopostid = 0
                    queryData.applytodictid = 0
                    queryData.key = ''
                    GetKnowledgeList(queryData)
                }
                //分类配置
                vm.knowledgecategorytreeOpts = {
                    treeopts: {
                        async: {
                            url: function () {
                                return '/Knowledge/Category'
                            }
                        },
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                if (!mvvm.has) mvvm.has = true
                                mvvm.showItem.categoryid = ''
                                mvvm.showItem.categoryid = '分类：' + treeNode.Name
                                queryData.categoryid = treeNode.Id
                                mvvm.action = 'list'
                                GetKnowledgeList(queryData)
                            }
                        },
                        view: {
                            addHoverDom: '',
                            removeHoverDom: ''
                        }
                    }
                }
                //部门检索
                vm.knowledgegroupTreeOpts = {
                    dataAuth:8010000,
                    treeopts: {
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                if (!mvvm.has) mvvm.has = true
                                mvvm.showItem.applytodepartid = ''
                                mvvm.showItem.applytodepartid = '适用于部门：' + treeNode.Name
                                queryData.applytodepartid = treeNode.Id
                                GetKnowledgeList(queryData)
                                mvvm.action = 'list'
                            }
                        },
                        view: {
                            addHoverDom: false,
                            removeHoverDom: false
                        }//替换默认
                    }
                }
                //职位检索
                vm.knowledgepostTreeOpts = {
                    treeopts: {
                        async: {
                            enable: true
                            , url: function (treeId, treeNode) {
                                return "/Settings/GetGroupPostUser/8010000"
                            },
                            dataFilter: notMemberFilter
                        },
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                if (treeNode.level > 0) {
                                    if (!mvvm.has) mvvm.has = true
                                    mvvm.showItem.applytopostid = ''
                                    mvvm.showItem.applytopostid = '适用于职位：' + treeNode.Name
                                    queryData.applytopostid = treeNode.Id
                                    GetKnowledgeList(queryData)
                                    mvvm.action = 'list'
                                }
                            }
                        },
                        view: {
                            addHoverDom: false,
                            removeHoverDom: false
                        } //替换默认
                    }
                }
                vm.pCategoryTreeOpts = {
                    treeopts: {
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                mvvm.action = 'list'
                                if (!mvvm.has) mvvm.has = true
                                mvvm.showItem.categoryid = ''
                                mvvm.showItem.categoryid = '分类：' + treeNode.Name

                                queryData.applytodictid = treeNode.Id
                                GetKnowledgeList(queryData)
                            }
                        },
                        view: {
                            addHoverDom: '',
                            removeHoverDom: ''
                        }
                    }
                }

                //分类下拉树
                vm.knowledgeTreeOpts = {
                    treeopts: {
                        async: {
                            url: function () {
                                return '/Knowledge/Category'
                            }
                        },
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                mvvm.entity.CategoryId = treeNode.Id
                                mvvm.entity.CategoryDisplay = treeNode.Name
                            }
                        }
                    }
                }
                //选择产品业务
                vm.applyToBusinessOpts = {
                    treeopts: {
                        callback: {
                            onCheck: function (e, treeId, treeNode) {
                                var treeObj = $.fn.zTree.getZTreeObj(treeId)
                                var nodes = treeObj.getCheckedNodes(true)
                                var ids = [],names = []
                                for (var i = 0; i < nodes.length; i++) {
                                    ids.push(nodes[i].Id)
                                    names.push(nodes[i].Name)
                                }
                                mvvm.entity.ApplyToBusinessIds = ids.join(',')
                                mvvm.entity.ApplyToBusinessDisplay = names.join(',')
                            }
                        },
                        check: {
                            enable: true,
                            chkStyle: 'checkbox'
                        }
                    }
                }
                //选择部门
                vm.groupTreeOpts = {
                    treeopts: {
                        callback: {
                            onCheck: function (event, treeId, treeNode) {
                                var treeObj = $.fn.zTree.getZTreeObj(treeId);
                                var nodes = treeObj.getCheckedNodes(true);
                                var ids = [], names = []
                                for (var i = 0; i < nodes.length; i++) {
                                    ids.push(nodes[i].Id)
                                    names.push(nodes[i].Name)
                                } 
                                mvvm.entity.ApplyToDeptIds = ids.join(',')
                                mvvm.entity.ApplyToDeptDisplay = names.join(',')
                            }
                        },
                        async: {
                            url: function (treeId, treeNode) {
                                return "/Settings/GetGroupPostUser/8010000"
                            } 
                        },
                        check: {
                            enable: true,
                            chkStyle: 'checkbox'
                        }
                    }
                }
                //指定范围
                vm.shareToDepartTreeOpts = {
                    dataAuth:8010000,
                    treeopts: {
                        callback: {
                            onCheck: function (event, treeId, treeNode) {
                                var treeObj = $.fn.zTree.getZTreeObj(treeId)
                                var nodes = treeObj.getCheckedNodes(true)
                                  
                               var  data = [], names = [],
                               m = model
                                nodes.forEach(function (n, i) {
                                    data.push(n.Id)
                                    names.push(n.Name)
                                })
                                mvvm.entity.ShareIds = data.join(',')
                                mvvm.entity.ShareDisplay = names.join(',')
                            }
                        },
                        check: {
                            enable: true,
                            chkStyle: 'checkbox',
                            chkboxType: { "Y": "s", "N": "s" } 
                        }
                    }
                }
                //新增
                vm.doadd = function () {
                    mvvm.action = 'add'
                    mvvm.entity = modelFactory.create('Knowledge')
                    mvvm.entity.Publisher = CBCRM.memberShip.Id
                    mvvm.entity.PublisherDisplay = CBCRM.memberShip.FullName
                    mvvm.entity.PublishSector = mvvm.CurrGroupId
                    mvvm.entity.PublishSectorDisplay = mvvm.CurrGroupName
                    fromTemplate('新增知识', '')
                }
                //修改
                vm.doedit = function () {
                    var id = $(this).attr("value")
                    mvvm.knowledgeList.$model.forEach(function (item) {
                        if (item.Id == id) {
                            mvvm.action = 'edit'
                            mvvm.entity = avalon.mix(modelFactory.create('Knowledge'), item)
                            mvvm.entity.ShareType += ''
                            mvvm.entity.LastChangeDate = GetDateTime()
                            fromTemplate('编辑知识', item.KContent)
                        }
                    })
                }
                //删除
                vm.dodel = function () {
                    var index = parseInt($(this).attr('index'))
                    var id = $(this).attr("value")
                    messageBox.confirm('确定删除此数据吗？', function () {
                        $.post('/Knowledge/KnowledgeDel/' + id, {}, function (ret) {
                            if (ret.result) {
                                mvvm.knowledgeList.removeAt(index)
                                if (mvvm.action != 'list') mvvm.action == 'list'
                            }
                            messageBox.succeed(ret.message)
                        })
                    });
                }
                //批量删除
                vm.doalldel = function () {
                    var deleteIds = checkAll()
                    messageBox.confirm('确定删除选中的数据吗？', function () {
                        $.post('/Knowledge/KnowledgeAllDel/', deleteIds, function (ret) {
                            if (ret.result) {
                                GetKnowledgeList(queryData)
                                messageBox.succeed(ret.message)
                            }
                        });
                    });
                }
                //查看
                vm.doview = function () {
                    var id = $(this).attr("value")
                    mvvm.knowledgeList.$model.forEach(function (item) {
                        if (item.Id == id) {
                            mvvm.entity = item 
                        }
                    })
                    mvvm.action = 'view'
                    viewTemplate('查看知识')
                }
                //取消
                vm.docancel = function () {
                    mvvm.action = 'list'
                }
                //上传文件
                vm.uploadFiles = function () {
                    var uploadModule
                    CBCRM.fillContentBefore = function (tmpl, lang, contentId, module, vm) {
                        messageBox.openHtml('上传文件', '1000px', '500px', tmpl);
                        avalon.scan($(".aui_content")[0], vm);
                        return false;
                    }
                    CBCRM.loadModule('/Upload/Center')
                    CBCRM.onModuleReady = function (data) {
                        avalon.vmodels.upload.itemSelected = function (node, data, file) {
                            mvvm.entity.AttachFile = '/upload/' + file.Path;
                            messageBox.close();
                        }
                    }
                }
            })
            
            var queryData = avalon.mix({}, {
                categoryid: 0,
                applytodepartid: 0,
                applytopostid: 0,
                applytodictid:0,
                key: '',
                pageSize: 20,
                pageIndex: 1
            })

            mvvm.showItem = avalon.mix({}, {
                categoryid: '',
                applytodepartid: '',
                applytopostid: '',
                applytodictid: '',
            })

            function GetKnowledgeList(data)
            {
                $.get('/Knowledge/Index/', data || {}, function (ret) {
                    mvvm.knowledgeList = ret.data.Source;
                    avalon.vmodels.knowledgepaingid.total = ret.data.RecordTotal
                    mvvm.ADD = ret.data.ADD
                    mvvm.DELETE = ret.data.DELETE
                    //当前用户部门
                    mvvm.CurrGroupId = ret.data.CurrGroupId
                    mvvm.CurrGroupName = ret.data.CurrGroupName
                })
            }
            var txtKContent;
            require('commonui', function () { 
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            })

            //打开知识表单
            function fromTemplate(title,text) {
                CBCRM.loadView('/Knowledge/From.html', function (tmpl) {
                    var dialog = mvvm.openTmpl({
                        title: title, w: 800,h:410, padding: "def2",
                        tmplId: tmpl, isContent: true,
                        button: [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var model = mvvm.entity.$model
                                var shareids = mvvm.entity.$model.ShareIds
                                if (shareids) {
                                    for (var i = 0; i < shareids.length; i++) {
                                        model["ShareIds[" + i + "]"] = shareids[i]
                                    }
                                }
                                mvvm.entity.KContent = txtKContent.html()
                                var url = mvvm.action == "add" ? "/Knowledge/KnowledgeAdd/" : "/Knowledge/KnowledgeUpdate/";
                                $.post(url + model.Id, model, function (ret) {
                                    CBCRM.showResult(ret, function () {
                                        if (ret.result) {
                                            GetKnowledgeList(queryData)
                                            mvvm.action = "list"
                                        }
                                    })
                                });
                            }
                        }],
                        onClose: function () {
                            mvvm.destroyui(["ccknowledgeTreeId","shareToDepartTreeId","applyToBusinessId"])
                        },
                        onScan: function () {
                            txtKContent = ketool.canUpImg('txtKContent', '95%', '200px');//编辑器可上传图片
                            txtKContent.html(text)
                        }
                    });
                });
            }
            //查看知识详情
            function viewTemplate(title)
            {
                CBCRM.loadView('/Knowledge/View.html', function (tmpl) {
                    var dialog = mvvm.openTmpl({
                        title: title, w: 800, padding: "def2",
                        tmplId: tmpl, isContent: true
                    });
                });
            }
        },
        ///分类管理
        Category: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM
            var mvvm = CBCRM.define('knowledgecategory', function (vm) {
                vm.destroy = function () {
                    mvvm.destroyui(["knowledgecategorytreeid"]);
                }
                vm.lang = lang
                vm.entity = {}
                vm.action = "add"
                vm.title = "新增分类"
                vm.sublist = []
                vm.auth = { ADD: true, EDIT: true, DELETE: true }
                vm.moveId = 0
                vm.moveName = ''
                vm.selectId = 0
                vm.selectName = ''
                vm.pCategoryTreeOpts = {
                    treeopts: {
                        async: {
                            url: function () {
                                return '/Knowledge/Category'
                            }
                        },
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                var pid = treeNode.Id;
                                initWithData({ pid: pid }, treeNode);
                                mvvm.selectId = treeNode.Id
                                mvvm.selectName = treeNode.Name
                            }
                        },
                        view: {
                            addHoverDom: '',
                            removeHoverDom: ''
                        }
                    }
                }
                vm.moveTreeOpts = {
                    treeopts: {
                        async: {
                            url: function () {
                                return '/Knowledge/Category'
                            }
                        },
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                mvvm.moveId = treeNode.Id
                                mvvm.moveName = treeNode.Name
                            }
                        },
                        view: {
                            addHoverDom: '',
                            removeHoverDom: ''
                        }
                    }
                }
                //分类下拉树
                vm.parentTreeOpts = {
                    treeopts: {
                        async: {
                            url: function () { return '/Knowledge/Category' }
                        },
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                mvvm.entity.Parent.Id = treeNode.Id
                                mvvm.entity.Parent.Name = treeNode.Name
                            }
                        }
                    }
                }
                //新增
                vm.doadd = function (val) {
                    mvvm.entity = modelFactory.create('KnowledgeCategory')
                    if (val != 0) {
                        mvvm.entity.Parent.Id = val.Id
                        mvvm.entity.Parent.Name = val.Name
                        mvvm.entity.Parent.Sort = val.Sort
                        mvvm.entity.ParentId = val.Id
                    } else {
                        if (mvvm.selectId > 1) {
                            mvvm.entity.ParentId = mvvm.selectId
                            mvvm.entity.Parent.Id = mvvm.selectId
                            mvvm.entity.Parent.Name = mvvm.selectName
                        }
                        else {
                            mvvm.entity.ParentId = ''
                            mvvm.entity.Parent.Id = ''
                            mvvm.entity.Parent.Name = ''
                            mvvm.entity.Parent.Sort = ''
                        }
                    }
                    setMaxSort()
                    fromTemplate('新增分类')
                }
                //编辑
                vm.doedit = function (val) {
                    mvvm.action = "edit"
                    $.get('/Knowledge/KnowledgeCategoryDetail/' + val, {}, function (ret) {
                        mvvm.entity = ret.data;
                    })
                    fromTemplate("编辑分类")
                }
                //删除
                vm.dodel = function (id, i) {
                    messageBox.confirm('确定删除此分类吗?', function () {
                        $.post('/Knowledge/CategoryDel/' + id, {}, function (ret) {
                            if (ret.result) {
                                getCategoryList()
                                mvvm.sublist.removeAt(i)
                            }
                            else messageBox.error(ret.message)
                        })
                    })
                }
                //保存
                vm.doSubmit = function () {
                    var model = mvvm.entity.$model;
                    model["ParentId"] = mvvm.entity.$model.Parent.Id;
                    var herf = mvvm.action == "add" ? "/Knowledge/CategoryAdd/" : "/Knowledge/CategoryUpdate/";
                    $.post(herf + model.Id, model, function (ret) {
                        var name = mvvm.entity.$model.Name
                        if (name == '') {
                            messageBox.error('分类名称不能为空')
                            return
                        }
                        if (ret.result) {
                            messageBox.ok(ret.message)
                            getCategoryList()
                            if (mvvm.action == "add") mvvm.entity = modelFactory.create('Category');
                        }
                    })
                    return false;
                }
                vm.doalldel = function () {
                    var deleteIds = checkAll();
                    messageBox.confirm('确定删除选中的数据吗？', function () {
                        $.post('/Knowledge/CategoryDelAll/', deleteIds, function (ret) {
                            if (ret.result) {
                                getCategoryList()
                                initWithData()
                                messageBox.succeed(ret.message);
                            }
                        });
                    });
                }
                vm.categoryMoreSave = function () {
                    var model = { ids: '', sorts: '' }
                    mvvm.sublist.forEach(function (item, i) {
                        if (item.Id != 1) {
                            model.ids += item.Id + ','
                            model.sorts += item.Sort + ','
                        }
                    })
                    if (model.ids) model.ids = model.ids.substring(0, model.ids.length - 1)
                    if (model.sorts) model.sorts = model.sorts.substring(0, model.sorts.length - 1)
                    $.post('/Knowledge/CategorySorts/', model, function (ret) {
                        if (ret.result) {
                            messageBox.succeed(ret.message)
                            initWithData()
                        }
                    })
                }
                vm.moveCategorys = function () {
                    var deleteIds = checkAll();
                    if (deleteIds.length > 0) {
                        moveTemplate('移动分类')
                    }
                    else messageBox.warning('请选择需要移动的分类')
                }
                //获取列表或子列表
                vm.getSublist = function (model) {
                    initWithData({ pid: model.Id }, model);
                    mvvm.selectId = model.Id
                    mvvm.selectName = model.Name
                }
            })
            mvvm.entity = modelFactory.create('KnowledgeCategory')

            function getCategoryList() {
                $.get('/Knowledge/Category/', {}, function (ret) {
                    avalon.vmodels.knowledgecategorytreeid.datasource = ret.data
                })
            }
            function initWithData(data, model) {
                $.get('/Knowledge/KnowledgeSubList/', data || {}, function (ret) {
                    if (model) {
                        ret.data.unshift(model)
                    } else {
                        var first = modelFactory.create('KnowledgeCategory')
                        first.Id = 1
                        first.Name = '全部分类'
                        ret.data.unshift(first)
                    }
                    mvvm.sublist = ret.data
                })
            }
            initWithData()
            //新增或编辑
            function fromTemplate(title) {
                CBCRM.loadView('/Knowledge/CategoryFrom.html', function (tmpl) {
                    var dialog = mvvm.openTmpl({
                        title: title, w: 450, h: 100, padding: "def2",
                        tmplId: tmpl, isContent: true,
                        button: [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var model = mvvm.entity.$model;
                                model["ParentId"] = model.Parent.Id;

                                var url = !model.Id ? "/Knowledge/CategoryAdd/" : "/Knowledge/CategoryUpdate/" + model.Id;
                                if (model.Name) {
                                    var isint = new RegExp(/^[0-9]+$/)
                                    if (isint.test(model.Sort)) {
                                        $.post(url, model, function (ret) {
                                            if (ret.result) {
                                                getCategoryList()
                                                initWithData({ pid: model.ParentId }, ret.data)
                                                messageBox.ok(ret.message, function () {
                                                    dialog.close()
                                                })
                                            }
                                        })
                                    } else messageBox.error('排序必须为数字')
                                } else messageBox.error('分类名称不能为空')
                                return false
                            }
                        }],
                        onClose: function () {
                            mvvm.destroyui(["knowledgeparentTree"]);
                        }
                    });
                });
            }
            //移动分类
            function moveTemplate(title) {
                CBCRM.loadView('/Knowledge/CategoryMove.html', function (tmpl) {
                    var dialog = mvvm.openTmpl({
                        title: title, w: 400, h: 100, padding: "def2",
                        tmplId: tmpl, isContent: true,
                        button: [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var deleteIds = checkAll();
                                $.post('/Knowledge/CategoryMove/' + mvvm.moveId, deleteIds, function (ret) {
                                    CBCRM.showResult(ret, function () {
                                        getCategoryList()
                                        initWithData()
                                    });
                                })
                            }
                        }],
                        onClose: function () {
                            mvvm.destroyui(["moveTreeId"]);
                        }
                    });
                })
            }
            //获取当前最大的排序并赋给新增项
            function setMaxSort() { 
                var sort = 1
                mvvm.sublist.forEach(function (item) {
                    if (item.Sort > sort)
                        sort = item.Sort
                })
                mvvm.entity.Sort = parseInt(sort) + 1
            }
            require('commonui', function () {
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            })
        },
        ///文档资料
        Documents: function (tmpl, lang, contentId, module) {
            var vmid='Documents'
            var CBCRM = avalon.vmodels.CBCRM, txtKContent
            var mvvm = CBCRM.define(vmid, function (vm) {
                vm.title = ''
                vm.ADD = true
                vm.DELETE = true
                vm.menuTab = 0
                vm.has = false
                vm.action = 'list'
                vm.keyword = ''
                vm.history = []
                vm.showItem = {}
                vm.entity = {}
                vm.entityList = []
                vm.selectId = 0
                vm.selectName = ''
                vm.knowledgepaing = {
                    paging: function () {
                        var that = this
                        queryData.pageSize = that.pagesize
                        queryData.pageIndex = that.pageindex
                        initWithData(queryData)
                    }
                }
                vm.search = function () {
                    if (mvvm.keyword) {
                        queryData.keyword = mvvm.keyword
                        initWithData(queryData)
                        if (mvvm.history.length = 3)
                            mvvm.history.removeAt(2)
                        mvvm.history.unshift(mvvm.keyword)
                    }
                }
                vm.historyClick = function () {
                    mvvm.keyword = $(this).val()
                    queryData.keyword = mvvm.keyword
                    initWithData(queryData);
                }
                vm.clear = function () {
                    mvvm.keyword = ''
                    mvvm.has = false
                    mvvm.showItem = avalon.mix({}, {
                        keywrod: '',
                        category: '',
                        productid: '',
                    })
                    mvvm.title = ''
                    queryData.keywrod = ''
                    queryData.category = ''
                    queryData.productid = ''
                    queryData.privateId = ''
                    initWithData(queryData)
                }
                vm.remove = function () {
                    var searchKey = this.$vmodel.$key
                    mvvm.showItem[searchKey] = ''
                    mvvm.has = false;
                    for (var item in mvvm.showItem.$model) {
                        if (mvvm.showItem.$model[item]) {
                            mvvm.has = true;
                            break;
                        }
                    }
                    queryData[searchKey] = ''
                    initWithData(queryData);
                }
                vm.doMenuTab = function (val) {
                    mvvm.has = false
                    mvvm.menuTab = val
                    mvvm.showItem = avalon.mix({}, {
                        keywrod: '',
                        category: '',
                        productid: '',
                    })
                    initWithData()
                }
                vm.doadds = function () {
                    mvvm.entity = avalon.mix({}, modelFactory.create('Documents'));
                    mvvm.entity.AddBy.FullName = CBCRM.memberShip.FullName
                    if (mvvm.selectId > 1) {
                        mvvm.entity.CategoryId = mvvm.selectId
                        mvvm.entity.CategoryDisplay = mvvm.selectName
                    }
                    fromTemplate('新增文档')
                }
                vm.doedit = function () {
                    var id = parseInt($(this).val())
                    $.get('/Knowledge/DocumentDetail/' + id, {}, function (ret) {
                        mvvm.entity = ret.data
                        messageBox.close()
                        fromTemplate('编辑文档', ret.data.Explain);
                    })
                }
                vm.dodel = function () {
                    var id = parseInt($(this).attr('value'))
                    messageBox.confirm('确定删除此文档吗?', function () {
                        $.get('/Knowledge/DocumentDelete/' + id, {}, function (ret) {
                            if (ret) {
                                initWithData()
                                messageBox.close()
                            } else {
                                messageBox.error(ret.message);
                            }
                        })
                    })
                }
                vm.doalldel = function () {
                    var deleteIds = checkAll()
                    messageBox.confirm('确定删除选中的数据吗？', function () {
                        $.post('/Knowledge/DocumentDeleteAll/', deleteIds, function (ret) {
                            if (ret.result) {
                                initWithData()
                                messageBox.succeed(ret.message)
                            }
                        });
                    });
                }
                vm.doview = function () {
                    var id = parseInt($(this).val())
                    $.get('/Knowledge/DocumentDetail/' + id, {}, function (ret) {
                        mvvm.entity = ret.data
                        viewTemplate('查看文档')
                    })
                }
                vm.doshare = function () {
                    var id = parseInt($(this).val())
                    $.get('/Knowledge/DocumentDetail/' + id, {}, function (ret) {
                        mvvm.entity = ret.data
                        messageBox.close()
                        shareTemplate('共享')
                    })
                }
                vm.domove = function () {
                    var id = parseInt($(this).val())
                    $.get('/Knowledge/DocumentDetail/' + id, {}, function (ret) {
                        mvvm.entity = ret.data
                        messageBox.close()
                        moveTemplate('移动分类')
                    })
                }
                //产品搜索
                vm.pCategoryTreeOpts = {
                    treeopts: {
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                
                                if (!mvvm.has) mvvm.has = true
                                mvvm.showItem.productid = ''
                                mvvm.showItem.productid = '分类：' + treeNode.Name
                                queryData.productid = treeNode.Id
                                initWithData(queryData)
                            }
                        },
                        view: {
                            addHoverDom: '',
                            removeHoverDom: ''
                        }
                    }
                }
                //分类搜索
                vm.knowledgecategorytreeOpts = {
                    treeopts: {
                        async: {
                            url: function () {
                                return '/Knowledge/DocCategory'
                            }
                        },
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                var tObj = $.fn.zTree.getZTreeObj('mytree')
                                tObj.selectNode({})

                                if (!mvvm.has) mvvm.has = true
                                mvvm.showItem.category = ''
                                mvvm.showItem.category = '分类：' + treeNode.Name
                                mvvm.title = treeNode.Name
                                queryData.category = treeNode.Id
                                queryData.privateId = ''
                                initWithData(queryData)
                                mvvm.selectId = treeNode.Id
                                mvvm.selectName = treeNode.Name
                            }
                        },
                        view: {
                            addHoverDom: '',
                            removeHoverDom: ''
                        }
                    }
                }
                vm.mytreeOpts = {
                    treeopts: {
                        async: {
                            url: function () {
                                return '/Knowledge/MyFile'
                            }
                        },
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                var tObj = $.fn.zTree.getZTreeObj('knowledgecategorytreeid')
                                tObj.selectNode({})

                                mvvm.keyword = ''
                                mvvm.has = false
                                mvvm.showItem = avalon.mix({}, {
                                    keywrod: '',
                                    category: '',
                                    productid: '',
                                })
                                mvvm.title = ''
                                queryData.keywrod = ''
                                queryData.category = ''
                                queryData.productid = ''
                                queryData.privateId = treeNode.Id
                                initWithData(queryData)
                            }
                        },
                        view: {
                            addHoverDom: '',
                            removeHoverDom: ''
                        }
                    }
                }
                //文档分类
                vm.documentsTreeOpts = {
                    treeopts: {
                        async: {
                            url: function () {
                                return '/Knowledge/DocCategory'
                            }
                        },
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                mvvm.entity.CategoryId = treeNode.Id
                                mvvm.entity.CategoryDisplay = treeNode.Name
                            }
                        },
                        view: {
                            addHoverDom: '',
                            removeHoverDom: ''
                        }
                    }
                }
                //选择产品业务
                vm.applyToBusinessOpts = {
                    treeopts: {
                        callback: {
                            onCheck: function (e, treeId, treeNode) {
                                var treeObj = $.fn.zTree.getZTreeObj(treeId)
                                var nodes = treeObj.getCheckedNodes(true)
                                var ids = [], names = []
                                for (var i = 0; i < nodes.length; i++) {
                                    ids.push(nodes[i].Id)
                                    names.push(nodes[i].Name)
                                }
                                
                                mvvm.entity.ProductIds = ids.join(',')
                                mvvm.entity.ProductDisplay = names.join(',')
                            }
                        },
                        check: {
                            enable: true,
                            chkStyle: 'checkbox'
                        }
                    }
                }
                //共享给
                vm.selectShareTo = function () {
                    var ids = mvvm.entity.ShareId || "";
                    ids = ids.split(",");
                    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.ShareId = ids.join(',')
                            mvvm.entity.ShareDisplay = names.join(',')
                        }
                    })
                }
                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.ShareId = ids.join(',')
                                mvvm.entity.ShareDisplay = names.join(',')
                            }
                        },
                        async: {
                            url: function (treeId, treeNode) {
                                return "/Settings/GetGroupPostUser/"
                            },
                            dataFilter: 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;
                            }
                        },
                        check: {
                            enable: true,
                            chkboxType: { "Y": "s", "N": "ps" }
                        }
                    }
                }
                
                vm.openUpload = function () {
                    $('#upfile').click()
                }
                vm.change = function () {
                    //带进度条的上传
                    var upsize = 1048576 * 300; //上传限制300M
                    var upfile = document.getElementById('upfile')
                    var file = upfile.files[0];
                    if (file.size > upsize) {
                        messageBox.error('上传的文件大小超过限制');
                        return;
                    }
                    var formData = new FormData();
                    formData.append("upfile", file);
                    var upload = new CBCRMUpload({
                        url: '/Knowledge/Upload/',
                        resultType:'json',
                        formData: formData,
                        onProgress: function (loaded, total) {
                            var complete = (loaded / total * 100 | 0)
                            if(complete<100)
                                $('#pro').html('正在上传文档：' + complete + '%')
                        },
                        //上传完成
                        onComplete: function (ret) {
                            if (ret.result) {
                                var model = ret.data
                                mvvm.entity.FileName = model.name
                                mvvm.entity.FilePath = model.path
                                mvvm.entity.FileType = model.type
                                mvvm.entity.FileSize = model.size
                                $('#pro').html('上传完成')
                                $('#myft').removeClass()
                                $('#myft').addClass('file_img').addClass('file_' + model.type)
                                if (mvvm.entity.Id) {
                                    var vcode = parseInt(mvvm.entity.$model.Vercode)
                                    mvvm.entity.Vercode = vcode + 1
                                }
                            } else {
                                messageBox.error(ret.message);
                            }
                        }
                    });
                    upload.start();
                }
            })
            var queryData = avalon.mix({}, {
                keyword: '',
                category: '',
                productid: '',
                privateId: '',
                pageSize: 20,
                pageIndex: 1
            })
            mvvm.showItem = avalon.mix({}, {
                keywrod: '',
                category: '',
                productid: '',
            })
            function initWithData(data) {
                $.get('/Knowledge/Documents/', data || {}, function (ret) {
                    mvvm.entityList = ret.data.Source
                    mvvm.ADD = ret.data.ADD
                    mvvm.DELETE = ret.data.DELETE
                })
            }
            
            //新增或编辑
            function fromTemplate(title, text) {
                CBCRM.loadView('/Knowledge/Add.html', function (tmpl) {
                    var dialog = mvvm.openTmpl({
                        title: title, w: 800, h: 400, padding: "def2",
                        tmplId: tmpl, isContent: true,
                        button: [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                mvvm.entity.Explain = txtKContent.html()
                                var model = mvvm.entity.$model;
                                var url = !model.Id ? "/Knowledge/DocumentsAdd/" : "/Knowledge/DocumentsUpdate/" + model.Id
                                if (model.Title) {
                                    $.post(url, model, function (ret) {
                                        if (ret.result) {
                                            mvvm.entity.Id = ret.data
                                            initWithData()
                                            messageBox.ok(ret.message, function () { dialog.close() })
                                        }
                                        else messageBox.error(ret.message)
                                    })
                                } else messageBox.warning('请填写文档标题');
                                return false;
                            }
                        }],
                        onClose: function () {
                            mvvm.destroyui(["documentsTreeId","shareToTree","applyToBusinessId"])
                            if (mvvm.entity.Id == '') { //如果不提交则关闭窗口时,删除已上传的文件
                                $.get('/Knowledge/DocumentsRemove/', { path: mvvm.entity.FilePath }, function () { })
                            }
                        },
                        onScan: function () {
                            txtKContent = ketool.canUpImg('txtKContent', '99%', '180px')
                            txtKContent.html(text)
                            $('#myft').addClass('file_' + mvvm.entity.FileType)
                        }
                    });
                })
            }

            //查看文档
            function viewTemplate(title) {
                CBCRM.loadView('/Knowledge/DocumentView.html', function (tmpl) {
                    var dialog = mvvm.openTmpl({
                        title: title, w: 800, h: 400, padding: "def2",
                        tmplId: tmpl, isContent: true,
                        onScan: function () {
                            $('#myft').addClass('file_' + mvvm.entity.FileType)
                        }
                    });
                })
            }

            //共享
            function shareTemplate(title) {
                CBCRM.loadView('/Knowledge/Share.html', function (tmpl) {
                    var dialog = messageBox.openHtml(title, '500px', '100px', tmpl,[{
                        name: '保存',
                        focus: true,
                        callback: function () {
                            var model = mvvm.entity.$model;
                            var url = !model.Id ? "/Knowledge/DocumentsAdd/" : "/Knowledge/DocumentsUpdate/" + model.Id
                            $.post(url, model, function (ret) {
                                if (ret.result) {
                                    mvvm.entity.Id = ret.data
                                    initWithData()
                                    messageBox.ok(ret.message, function () { dialog.close() })
                                }
                                else messageBox.error(ret.message)
                            })
                            return false;
                        }
                    }], function () {
                        if (avalon.vmodels.shareToTree)
                            avalon.vmodels.shareToTree.destroy()
                    });
                    avalon.scan(dialog.content(), mvvm)
                })
            }

            //移动
            function moveTemplate(title) {
                CBCRM.loadView('/Knowledge/DocumentsMove.html', function (tmpl) {
                    var dialog = messageBox.openHtml(title, '500px', '100px', tmpl, [{
                        name: '保存',
                        focus: true,
                        callback: function () {
                            var model = mvvm.entity.$model;
                            var url = !model.Id ? "/Knowledge/DocumentsAdd/" : "/Knowledge/DocumentsUpdate/" + model.Id
                            $.post(url, model, function (ret) {
                                if (ret.result) {
                                    mvvm.entity.Id = ret.data
                                    initWithData()
                                    messageBox.ok(ret.message, function () { dialog.close() })
                                }
                                else messageBox.error(ret.message)
                            })
                            return false;
                        }
                    }], function () {
                        if (avalon.vmodels.documentsTreeId)
                            avalon.vmodels.documentsTreeId.destroy()
                    });
                    avalon.scan(dialog.content(), mvvm)
                })
            }
            
            require('commonui', function () {
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            })
            CBCRM.onLoadModuleBefore = function () {
                var uis = ["knowledgecategorytreeid", "mytree", "pCategoryTree"]
                destroyui(uis)
                avalon.vmodels[vmid] = null;
            }
        },
        ///文档分类
        DocCategory: function (tmpl, lang, contentId, module) {
            var vmid='doccategory'
            var CBCRM = avalon.vmodels.CBCRM
            var mvvm = CBCRM.define(vmid, function (vm) {
                vm.destroy = function () {
                    mvvm.destroyui(["knowledgecategorytreeid"])
                }
                vm.lang = lang
                vm.entity = {}
                vm.action = "add"
                vm.title = "新增分类"
                vm.sublist = []
                vm.moveId = 0
                vm.moveName = ''
                vm.selectId = 0
                vm.selectName = ''
                vm.auth = { ADD: true, EDIT: true, DELETE: true }
                //列表分类配置
                vm.pCategoryTreeOpts = {
                    treeopts: {
                        async: {
                            url: function () {
                                return '/Knowledge/DocCategory'
                            }
                        },
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                var pid = treeNode.Id;
                                initWithData({ pid: pid }, treeNode);
                                mvvm.selectId = treeNode.Id
                                mvvm.selectName = treeNode.Name
                            }
                        },
                        view: {
                            addHoverDom: '',
                            removeHoverDom: ''
                        }
                    }
                }
                vm.documentsTreeOpts = {
                    treeopts: {
                        async: {
                            url: function () {
                                return '/Knowledge/DocCategory/'
                            }
                        },
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                mvvm.moveId = treeNode.Id
                                mvvm.moveName = treeNode.Name
                            }
                        },
                        view: {
                            addHoverDom: '',
                            removeHoverDom: ''
                        }
                    }
                }
                //表单分类配置
                vm.parentTreeOpts = {
                    treeopts: {
                        async: {
                            url: function () {
                                return '/Knowledge/DocCategory/'
                            }
                        },
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                mvvm.entity.Parent.Id = treeNode.Id
                                mvvm.entity.Parent.Name = treeNode.Name
                            }
                        }
                    }
                }
                //新增
                vm.doadd = function (val) {
                    mvvm.action = "add"
                    mvvm.entity = modelFactory.create('DocCategory')
                    if (val != 0) {
                        mvvm.entity.Parent.Id = val.Id
                        mvvm.entity.Parent.Name = val.Name
                        mvvm.entity.Parent.Sort = val.Sort
                        mvvm.entity.ParentId = val.Id
                    } else {
                        if (mvvm.selectId > 1) {
                            mvvm.entity.ParentId = mvvm.selectId
                            mvvm.entity.Parent.Id = mvvm.selectId
                            mvvm.entity.Parent.Name = mvvm.selectName
                            mvvm.entity.Parent.Sort = ''
                        }
                        else {
                            mvvm.entity.Parent.Id = ''
                            mvvm.entity.Parent.Name = '全部分类'
                            mvvm.entity.Parent.Sort = ''
                        }
                    }
                    setMaxSort()
                    fromTemplate("新增分类")
                }
                //编辑
                vm.doedit = function (val) {
                    mvvm.action = "edit"
                    $.get('/Knowledge/DocCategoryDetail/' + val, {}, function (ret) {
                        mvvm.entity = ret.data;
                    })
                    fromTemplate("编辑分类")
                }
                //保存
                vm.categoryMoreSave = function () {
                    var model = { ids: '', sorts: '' }
                    mvvm.sublist.forEach(function (item, i) {
                        if (item.Id != 1) {
                            model.ids += item.Id + ','
                            model.sorts += item.Sort + ','
                        }
                    })
                    if (model.ids) model.ids= model.ids.substring(0, model.ids.length - 1)
                    if (model.sorts) model.sorts= model.sorts.substring(0, model.sorts.length - 1)
                    $.post('/Knowledge/SetSorts/', model, function (ret) {
                        if (ret.result) {
                            messageBox.succeed(ret.message)
                            initWithData()
                        }
                    })
                }
                //移动分类
                vm.moveCategorys = function () {
                    var deleteIds = checkAll();
                    if (deleteIds.length > 0) {
                        moveTemplate('移动分类')
                    }
                    else messageBox.warning('请选择需要移动的分类')
                }
                //删除
                vm.dodel = function (id, i) {
                    messageBox.confirm('确定删除此分类吗?', function () {
                        $.post('/Knowledge/DocCategoryDel/' + id, {}, function (ret) {
                            if (ret.result) {
                                mvvm.sublist.removeAt(i)
                                getCategoryList()
                            }
                            else messageBox.error(ret.message)
                        })
                    })
                }
                //全选删除
                vm.doalldel = function () {
                    var deleteIds = checkAll();
                    messageBox.confirm('确定删除选中的数据吗？', function () {
                        $.post('/Knowledge/DocCategoryDelAll/', deleteIds, function (ret) {
                            if (ret.result) {
                                getCategoryList()
                                initWithData()
                                messageBox.succeed(ret.message);
                            }
                        });
                    });
                }
                //获取列表或子列表
                vm.getSublist = function (model) {
                    mvvm.selectId = model.Id
                    mvvm.selectName = model.Name
                    initWithData({ pid: model.Id }, model);
                }
            })

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

            function getCategoryList() {
                $.get('/Knowledge/DocCategory/', {}, function (ret) {
                    avalon.vmodels.knowledgecategorytreeid.datasource = ret.data
                })
            }
            function initWithData(data, model) {
                $.get('/Knowledge/GetSubList/', data || {}, function (ret) {
                    if (model) {
                        ret.data.unshift(model)
                    } else {
                        var first = modelFactory.create('DocCategory')
                        first.Id = 1
                        first.Name = '全部分类'
                        ret.data.unshift(first)
                    }
                    mvvm.sublist = ret.data
                })
            }
            initWithData()

            function fromTemplate(title)
            {
                CBCRM.loadView('/Knowledge/DocFrom.html', function (tmpl) {
                    var dialog = mvvm.openTmpl({
                        title: title, w: 450, h: 100, padding: "def2",
                        tmplId: tmpl, isContent: true,
                        button: [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var model = mvvm.entity.$model;
                                model["ParentId"] = model.Parent.Id;

                                var url = mvvm.action == "add" ? "/Knowledge/DocCategoryAdd/" : "/Knowledge/DocCategoryUpdate/" + model.Id;
                                if (model.Name) {
                                    var isint = new RegExp(/^[0-9]+$/);
                                    if (isint.test(model.Sort)) {
                                        $.post(url, model, function (ret) {
                                            if (ret.result) {
                                                getCategoryList()
                                                initWithData({ pid: model.ParentId }, ret.data)
                                                messageBox.ok(ret.message, function () {
                                                    dialog.close()
                                                })
                                            }
                                        })
                                    } else messageBox.error('排序必须为数字')
                                } else messageBox.error('分类名称不能为空')
                                return false
                            }
                        }],
                        onClose: function () {
                            mvvm.destroyui(["knowledgeparentTree"]);
                        }
                    });
                });
            }

            function moveTemplate(title) {
                CBCRM.loadView('/Knowledge/Move.html', function (tmpl) {
                    var dialog = mvvm.openTmpl({
                        title: title, w: 450, h: 100, padding: "def2",
                        tmplId: tmpl, isContent: true,
                        button: [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var deleteIds = checkAll();
                                $.post('/Knowledge/MoveCategory/' + mvvm.moveId, deleteIds, function (ret) {
                                    if (ret.result) {
                                        messageBox.succeed(ret.message)
                                        getCategoryList()
                                        initWithData()
                                    }
                                })
                            }
                        }],
                        onClose: function () {
                            mvvm.destroyui(["documentsTreeId"]);
                        }
                    });
                })
            }

            function setMaxSort() { //获取当前最大的排序并赋给新增项
                var sort = 1
                mvvm.sublist.forEach(function (item) {
                    if (item.Sort > sort)
                        sort = item.Sort
                })
                mvvm.entity.Sort = parseInt(sort) + 1
            }

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