/// <reference path="../../Content/Themes/Base/Template/HR/Recruitment.html" />
define('HR', ['modelFactory','plugins',
    'json',
    'dialog',
    'jscal2',
    'common',
    'jcal',
    'jqselect',
    'leftMenu',
    'kindedit',
    'upload',
    'swfobject',
    'cookie'
],
    function (modelFactory,plugins) {
        var groupPostFilter = function (treeId, parentNode, responseData) {
            var groups = [];
            if (responseData.data && responseData.data.groups.length) {
                responseData.data.groups.forEach(function (item) {
                    var m = {
                        Id: item.Id, Name: item.Name, ParentId: item.ParentId, iconSkin: item.iconSkin, open: true
                    }
                    groups.push(m);
                    item.Posts.forEach(function (item2) {
                        var mm = {
                            Id: item2.Id, Name: item2.Name, ParentId: item2.Group, iconSkin: item2.iconSkin, open: true
                        }
                        groups = groups.concat(mm);
                        item2.Users.forEach(function (item3) {
                            var mmm = {
                                Id: item3.Id, Name: item3.FullName + "(" + item3.Name + ")", FullName: item3.FullName, UserName: item3.Name, ParentId: item3.PositionId, iconSkin: item3.iconSkin, open: true
                            }
                            groups = groups.concat(mmm);
                        });
                    });
                });
            }
            return groups;
        }
        var notMemberFilter = 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
                    curPostId = curr.Posts[i].Id
                    curPostName = curr.Posts[i].Name
                    p.Users.forEach(function (u, i) {
                        var u = p.Users[i]
                        if (u.Id === CBCRM.memberShip.Id) return true
                        u.ParentId = u.PositionId
                        u.groupId = curr.Id
                        u.groupName = curr.Name
                        u.postId = curPostId
                        u.postName = curPostName
                        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 onlyPostFilter = function (treeId, parentNode, responseData) {
            var CBCRM = avalon.vmodels.CBCRM
            var ret = [], len = 0, curr, hasPsot = false
            if (responseData.data && responseData.data.groups.length)
                len = responseData.data.groups.length
            while (len) {
                curr = responseData.data.groups[--len]
                curr.nocheck = true
                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)
                })
                ret.push(curr)
            }
            return ret
        }
        function viewHr(id) {
            goto('/HR/Archive/' + id + "/view", true);
        }


        var HR = {
            //人事工作台
            Index: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM
                var mvvm = avalon.define('HRController', function (vm) {
                    vm.lang = lang
                    vm.$skipArray = ['lang']



                    vm.reward = false
                    vm.integral = false
                    vm.planning = false
                    vm.hrorganization = false
                    vm.hrpost = false
                    vm.recruitment = false

                    vm.trainPlan = false
                    vm.trainRecord = false

                    vm.archive = false
                    vm.labourContract = false
                    vm.postChange = false
                    vm.communication = false

                    vm.getAuthForView = function () {
                        mvvm.hrpost = CBCRM.hasAuth(6020300)
                        mvvm.planning = CBCRM.hasAuth(6020100)
                        mvvm.hrorganization = CBCRM.hasAuth(6020200)

                        mvvm.reward = CBCRM.hasAuth(6060100)
                        mvvm.integral = CBCRM.hasAuth(6060200)

                        mvvm.recruitment = CBCRM.hasAuth(6030100)

                        mvvm.trainPlan = CBCRM.hasAuth(6040100)
                        mvvm.trainRecord = CBCRM.hasAuth(6040200)

                        mvvm.archive = CBCRM.hasAuth(6050100)
                        mvvm.labourContract = CBCRM.hasAuth(6050200)
                        mvvm.postChange = CBCRM.hasAuth(6050300)
                        mvvm.communication = CBCRM.hasAuth(6050400)

                    }




                    //搜索
                    vm.qkey = ''
                    vm.path = '#/HR/Archive/'
                    vm.toSearch = function () {
                        mvvm.path = '#/HR/Archive/' + encodeURI(mvvm.qkey) + '/key'
                    }
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) {
                            mvvm.path = '#/HR/Archive/' + encodeURI(mvvm.qkey) + '/key'
                            goto(mvvm.path.substring(1));
                        }
                    }

                })
                mvvm.getAuthForView()
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.Index = null
                }
            },
            //人资规划
            Planning: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM;
                var kind1, kind2;
                var mvvm = avalon.define('PlanningController', function (vm) {
                    vm.lang = lang
                    vm.$skipArray = ['lang']
                    vm.keyword = ''
                    vm.ADD = true
                    vm.DELETE = true
                    vm.history = []
                    vm.entityPlan = {}
                    vm.planList = []
                    vm.showItem = {}
                    vm.category = []

                    //关键字搜索
                    vm.search = function () {
                        if (mvvm.keyword) {
                            mvvm.showItem.keyword = mvvm.keyword
                            initWithPageData(mvvm.showItem.$model)
                            if (mvvm.history.length = 3)
                                mvvm.history.removeAt(2)
                            mvvm.history.unshift(mvvm.keyword)
                        }
                    }
                    //历史搜索
                    vm.historyClick = function () {
                        mvvm.keyword = $(this).val()
                        mvvm.showItem.keyword = mvvm.keyword
                        initWithPageData(mvvm.showItem.$model)
                    }
                    //清除
                    vm.clear = function () {
                        mvvm.keyword = ''
                        mvvm.showItem.keyword = mvvm.keyword
                        initWithPageData(mvvm.showItem.$model)
                    }

                    vm.doadd = function () {
                        mvvm.entityPlan = modelFactory.create('Planning');
                        mvvm.entityPlan.CategoryId = mvvm.category.$model[0].Id;
                        mvvm.formSubmit('新增规划')
                    }
                    vm.doedit = function () {
                        var id = $(this).attr('value');
                        $.get('/HR/PlanningDetial/' + id, {}, function (ret) {
                            mvvm.entityPlan = ret.data;

                            mvvm.formSubmit('编辑规划')
                        })
                    }
                    vm.formSubmit = function (title) {
                        var dialog = messageBox.openHtml(title, '750px', '380px', '', [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var model = mvvm.entityPlan.$model;
                                model.WholePlanningContent = kind1.html();
                                model.BusinessPlanningContent = kind2.html();
                                var msg = ''
                                if (!model.Title) msg = '标题不能为空<br/>'
                                if (!model.Target) msg += '目标不能为空<br/>'
                                if (msg) {
                                    messageBox.error('请填写标题和目标')
                                    return false
                                }
                                var url = model.Id == 0 ? "/HR/PlanningAdd/" : "/HR/PlanningEdit/" + model.Id;
                                $.post(url, model, function (ret) {
                                    if (ret.result) {
                                        messageBox.ok(ret.message, function () { dialog.close(); initWithPageData(mvvm.showItem.$model) });
                                    }
                                    else
                                        messageBox.error(ret.message)
                                })

                                return false
                            }
                        }], function () {

                        })
                        var content = $(dialog.content())
                        var inputTmpl = $(tmpl).find("#formTemplate").text();
                        content.html(inputTmpl);
                        avalon.scan(content[0], mvvm)

                        avalon.nextTick(function () {
                            kind1 = setEditerSimple('WholePlanningContent', '95%', '150px');
                            kind2 = setEditerSimple('BusinessPlanningContent', '95%', '150px');
                            if (mvvm.entityPlan.Id > 0) {
                                kind1.html(mvvm.entityPlan.$model.WholePlanningContent);
                                kind2.html(mvvm.entityPlan.$model.BusinessPlanningContent);
                            } else {
                                kind1.html('');
                                kind2.html('');
                            }
                        })
                    }
                    vm.dodel = function () {
                        var id = $(this).attr('value');

                        messageBox.confirm("确定要删除该数据吗？", function () {
                            $.post('/HR/PlanningDel/' + id, function (ret) {
                                if (ret.result)
                                    messageBox.ok('删除数据成功', function () { initWithPageData(mvvm.showItem.$model); });
                                else
                                    messageBox.error(ret.message);
                            })
                        })
                    }

                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm("确定要批量删除数据吗？", function () {
                            $.post('/HR/PlanningDelAll/', deleteIds, function (ret) {
                                if (ret.result)
                                    messageBox.ok(ret.message, function () { initWithPageData(mvvm.showItem.$model); });
                                else
                                    messageBox.error(ret.message);
                            })
                        })
                    }

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

                    vm.birthdayOpts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.StartDate = formatDate;
                        }
                    }
                    vm.birthdayOpts2 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.EndDate = formatDate;
                        }
                    }

                    vm.doview = function () {
                        var id = $(this).attr('value');
                        mvvm.planList.$model.forEach(function (item) {
                            if (item.Id == id) {
                                mvvm.entityPlan = item
                            }
                        })
                        var dialog = messageBox.openHtml('查看规划', '750px', '300px', '');
                        var content = $(dialog.content())
                        var inputTmpl = $(tmpl).find("#viewTemplate").text();
                        content.html(inputTmpl);
                        avalon.scan(content[0], mvvm)
                    }

                    //附件
                    vm.open = function () {
                        var uploadModule, filldialog
                        CBCRM.fillContentBefore = function (tmpl, lang, contentId, module, vm) {
                            filldialog = 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.entityPlan.Attachment = '/upload/' + file.Path;
                                if (filldialog) filldialog.close();
                            }
                        }
                    }
                });

                var queryData = {
                    keyword: '',
                    pageIndex: 1, pageSize: 20
                }
                mvvm.showItem = avalon.mix({}, queryData);
                mvvm.entityPlan = modelFactory.create('Planning');

                function initWithPageData(data) {
                    $.get('/HR/Planning/', data, function (ret) {
                        mvvm.planList = ret.data.Source;
                        mvvm.ADD = ret.data.ADD
                        mvvm.DELETE = ret.data.DELETE
                        avalon.vmodels.upaing.total = ret.data.RecordTotal //分页总数
                    });
                    $.get('/HR/GetPlanningDictionary/', {}, function (ret) {
                        mvvm.category = ret.data.category
                    });
                }

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

                CBCRM.onLoadModuleBefore = function () { avalon.vmodels.Planning = null }
            },
            //架构设计
            HROrganization: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM
                var mvvm = CBCRM.define('hrorganizationController', function (vm) {
                    vm.lang = lang
                    vm.sublist = []
                    vm.groupEntity = modelFactory.create('Group')
                    vm.doadd = function () {
                        mvvm.groupEntity = modelFactory.create('Group')
                        var pid = $(this).attr('data-id')
                        var pname = $(this).attr('data-name')
                        if (pid && pname) {
                            mvvm.groupEntity.ParentId = pid
                            mvvm.groupEntity.ParentGroupName = pname
                        } else {
                            var submodel = mvvm.sublist[0]
                            mvvm.groupEntity.ParentId = submodel.Id
                            mvvm.groupEntity.ParentGroupName = submodel.Name
                        }
                        mvvm.fromsubmit('新增部门')
                    }
                    vm.doedit = function (id) {
                        if (id) {
                            $.get('/Settings/GetGroup/' + id)
                               .done(function (ret) {
                                   if (ret.result) {
                                       mvvm.groupEntity = avalon.mix(modelFactory.create('Group'), ret.data)
                                       if (ret.data.Parent) {
                                           mvvm.groupEntity.ParentGroupName = ret.data.Parent.Name
                                           mvvm.groupEntity.ParentId = ret.data.Parent.Id
                                       } else {
                                           var submodel = mvvm.sublist[0]
                                           mvvm.groupEntity.ParentId = submodel.Id
                                           mvvm.groupEntity.ParentGroupName = submodel.Name
                                       }
                                       mvvm.fromsubmit('编辑部门')
                                   }
                               })
                        }
                    }
                    vm.dodel = function (id) {
                        if (id) {
                            messageBox.confirm('确定要删除此部门吗？', function () {
                                $.post('/Settings/GroupToRecycleBin/' + id)
                                .done(function (ret) {
                                    CBCRM.showResult(ret, function () {
                                        if (mvvm.groupEntity.ParentId)
                                            mvvm.getData(mvvm.groupEntity.ParentId)
                                        else
                                            mvvm.getData(0)
                                        messageBox.close()
                                        if ($.fn.zTree.getZTreeObj("organizationTree"))
                                            $.fn.zTree.getZTreeObj("organizationTree").reAsyncChildNodes(null, "refresh");
                                    })
                                })
                            })
                        }
                    }
                    vm.doview = function (id) {
                        if (id) {
                            $.get('/Settings/GetGroup/' + id)
                               .done(function (ret) {
                                   if (ret.result) {
                                       mvvm.groupEntity = avalon.mix(modelFactory.create('Group'), ret.data)
                                       if (ret.data.Parent) {
                                           mvvm.groupEntity.ParentGroupName = ret.data.Parent.Name
                                           mvvm.groupEntity.ParentId = ret.data.Parent.Id
                                       } else {
                                           var submodel = mvvm.sublist[0]
                                           mvvm.groupEntity.ParentId = submodel.Id
                                           mvvm.groupEntity.ParentGroupName = submodel.Name
                                       }
                                       var dialog = messageBox.openHtml('查看组织架构', '880px', '300px', '');
                                       $content = $(dialog.content())
                                       var inputTmpl = $(tmpl).find("#viewTemplate").text()
                                       $content.html(inputTmpl)
                                       avalon.scan($content[0], mvvm)
                                   }
                               })
                        }

                    }
                    vm.fromsubmit = function (title) {
                        var d = mvvm.openTmpl({
                            title: title, w: 836, h: 446,padding:"def2",
                            tmplId:"formTemplate",tmpl:tmpl,
                            button: [{
                                name: "提交",
                                focus: true,
                                callback: function () {
                                    var path = mvvm.groupEntity.Id > 0 ? '/Settings/EditGroup/' + mvvm.groupEntity.Id : '/Settings/AddGroup/'
                                    $.post(path, mvvm.groupEntity.$model, function (data) {
                                        CBCRM.showResult(data, function () {
                                            if (mvvm.groupEntity.ParentId)
                                                mvvm.getData(mvvm.groupEntity.ParentId)
                                            else
                                                mvvm.getData(0)
                                            messageBox.close()
                                            if ($.fn.zTree.getZTreeObj("organizationTree"))
                                                $.fn.zTree.getZTreeObj("organizationTree").reAsyncChildNodes(null, "refresh");
                                        })
                                    })
                                    return false
                                },
                            }],
                            onClose: function () {
                                mvvm.destroyui(["inputGroupTree"])
                            }
                        });
                    }
                    //展开、收起
                    vm.isExp = true;
                    vm.expanCategory = function () {
                        mvvm.isExp = !mvvm.isExp;
                        $(this).text(mvvm.isExp ? "- 收起" : "+ 展开");
                        var tree = $.fn.zTree.getZTreeObj("organizationTree");
                        if (tree) {
                            var nodes = tree.getNodes();
                            if (nodes.length > 0) tree.expandNode(nodes[0], mvvm.isExp, true);
                            if (!mvvm.isExp) tree.expandNode(nodes[0], !mvvm.isExp, false);
                        }
                    }
                    //组织架构
                    vm.groupTreeOpts = {
                        dataAuth:9040101,
                        treeopts: {
                            //async: {
                            //    enable: true,
                            //    url: '/Settings/GetGroupPostUser/9060000'
                            //},
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    mvvm.getData(treeNode.Id)
                                }
                            },
                            view: {
                                addHoverDom: false,
                                removeHoverDom: false
                            }
                        }
                    }
                    //上级部门
                    vm.inputGroupTreeOpts = {
                        //drowDownTreeId: '',
                        dataAuth:9040101,
                        treeopts: {
                            callback: {
                                onClick: function (event, treeId, treeNode) {
                                    var m = mvvm.groupEntity
                                    m.ParentGroupName = treeNode.Name
                                    m.ParentId = treeNode.Id
                                }
                            }
                        }
                    }
                    //部门主管
                    vm.selectManager = function () {
                        plugins.selectUser({
                            dataAuth: 9040101,
                            callback: function (us) {
                                var u = us[0];
                                mvvm.groupEntity.ManagerId = u.Id;
                                mvvm.groupEntity.ManagerDisplay = u.FullName;
                            }
                        });
                    }
                    //分管领导
                    vm.selectDeputyManager = function () {
                        plugins.selectUser({
                            dataAuth: 9040101,
                            callback: function (us) {
                                var u = us[0];
                                mvvm.groupEntity.DeputyManagerId = u.Id;
                                mvvm.groupEntity.DeputyManagerDisplay = u.FullName;
                            }
                        });
                    }
                    vm.getData = function (groupId) {
                        $.get('/HR/HROrganization', { "groupId": groupId }, function (ret) {
                            mvvm.sublist = ret.data
                        })
                    }
                })
                mvvm.getData(0)
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            },
            //职位拟编
            HRPost: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this
                var DATAAUTH=6020301;//职位拟编查看权限id
                var mvvm = CBCRM.define('hrpostController', function (vm) {
                    vm.lang = lang
                    vm.keyword = ''
                    vm.postlist = []
                    vm.grid1 = { gridmsg: "" };
                    vm.postEntity = modelFactory.create('Post')
                    vm.doadd = function () {
                        mvvm.tab = 'tab1'
                        mvvm.postEntity = modelFactory.create('Post')
                        mvvm.postEntity.GroupName = mvvm.currGroupName
                        mvvm.postEntity.Group = mvvm.currGroup
                        var currUser = CBCRM.memberShip
                        mvvm.postEntity.AddBy.Id = currUser.Id
                        mvvm.postEntity.AddBy.FullName = currUser.FullName
                        mvvm.postEntity.AddTime = GetDateTime()
                        mvvm.fromsubmit('新增职位')
                    }
                    vm.doedit = function () {
                        var id = $(this).attr('val')
                        if (id) {
                            $.get('/Settings/GetPost/' + id)
                               .done(function (ret) {
                                   if (ret.result) {
                                       mvvm.tab = 'tab1'
                                       mvvm.postEntity = avalon.mix(modelFactory.create('Post'), ret.data.length > 0 ? ret.data[0] : {})
                                       mvvm.fromsubmit('编辑职位')
                                   }
                               })
                        }
                    }
                    vm.dodel = function () {
                        var id = $(this).attr('val')
                        if (id) {
                            messageBox.confirm('确定要删除此职位吗？', function () {
                                $.post('/Settings/PostToRecycleBin/' + id)
                                .done(function (ret) {
                                    CBCRM.showResult(ret, function () {

                                        messageBox.close()
                                    })
                                })
                            })
                        }
                    }
                    vm.doview = function () {
                        var id = $(this).attr('val')
                        if (id) {
                            $.get('/Settings/GetPost/' + id)
                               .done(function (ret) {
                                   if (ret.result) {
                                       mvvm.tab = 'tab1'
                                       mvvm.postEntity = avalon.mix(modelFactory.create('Post'), ret.data.length > 0 ? ret.data[0] : {})
                                       var dialog = messageBox.openHtml('查看职位', '832px', '300px', '');
                                       $content = $(dialog.content())
                                       var inputTmpl = $(tmpl).find("#viewTemplate").text()
                                       $content.html(inputTmpl)
                                       avalon.scan($content[0], mvvm)
                                   }
                               })
                        }

                    }
                    vm.fromsubmit = function (title) {
                        var d=mvvm.openTmpl({
                            title: title, w: 836, h: 300,
                            tmplId: "formTemplate", tmpl: tmpl,
                            button: [{
                                name: "提交",
                                focus: true,
                                callback: function () {
                                    var path = mvvm.postEntity.Id > 0 ? '/Settings/EditPost/' + mvvm.postEntity.Id : '/Settings/AddPost/'
                                    $.post(path, mvvm.postEntity.$model, function (ret) {
                                        CBCRM.showResult(ret, function () {
                                            mvvm.getData(mvvm.currGroup)
                                            if (d) d.close();
                                        })
                                    })
                                    return false
                                }
                            }],
                            onClose: function () {
                                mvvm.destroyui(["setGroup", "postBossTreeId"])
                            }
                        });
                    }
                    vm.doSearch = function () {
                        vm.getData(mvvm.currGroup)
                    }
                    //展开、收起
                    vm.isExp = true;
                    vm.expanCategory = function () {
                        mvvm.isExp = !mvvm.isExp;
                        $(this).text(mvvm.isExp ? "- 收起" : "+ 展开");
                        var tree = $.fn.zTree.getZTreeObj("organizationTree");
                        if (tree) {
                            var nodes = tree.getNodes();
                            if (nodes.length > 0) tree.expandNode(nodes[0], mvvm.isExp, true);
                            if (!mvvm.isExp) tree.expandNode(nodes[0], !mvvm.isExp, false);
                        }
                    }
                    //组织架构
                    vm.currGroupName = ''
                    vm.currGroup = ''
                    vm.groupTreeOpts = {
                        dataAuth:DATAAUTH,
                        treeopts: {
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    if (treeNode.Id > 1) {
                                        mvvm.currGroupName = treeNode.Name
                                        mvvm.currGroup = treeNode.Id
                                    }
                                    else {
                                        mvvm.currGroupName = ''
                                        mvvm.currGroup = ''
                                    }
                                    mvvm.getData(treeNode.Id)
                                }
                            },
                            view: {
                                addHoverDom: false,
                                removeHoverDom: false
                            }
                        }
                    }
                    //归属部门
                    vm.postGroupTreeOpts = {
                        dataAuth:DATAAUTH,
                        treeopts: {
                            callback: {
                                onClick: function (event, treeId, treeNode) {
                                    if (treeNode.Id == 1) {
                                        var m = mvvm.postEntity
                                        m.GroupName = ""
                                        m.Group = ""
                                    } else {
                                        var m = mvvm.postEntity
                                        m.GroupName = treeNode.Name
                                        m.Group = treeNode.Id
                                    }
                                }
                            }
                        }
                    }
                    //直接上级
                    vm.postBossTreeOpts = {
                        dataAuth: DATAAUTH,
                        checkType:"post",
                        treeopts: {
                            callback: {
                                onCheck: function (event, treeId, treeNode) {
                                    var m = mvvm.postEntity
                                    m.bossId = treeNode.Id
                                    m.bossName = treeNode.Name
                                }
                            }
                        }
                    }
                    vm.tab = 'tab1'
                    vm.tabChange = function () {
                        vm.tab = $(this).attr('val')
                    }
                    vm.getData = function (groupId) {
                        mvvm.grid1.gridmsg = lang.LoadingMsg;
                        $.get('/HR/HRPost', { "groupId": groupId, "keyword": mvvm.keyword }, function (ret) {
                            if (!ret || !ret.result) {
                                return CBCRM.showResult(ret);
                            }
                            mvvm.grid1.gridmsg = ret.data.length ? "" : lang.NoListData;
                            mvvm.postlist = ret.data
                        })
                    }

                })

                if (that.params.key) {
                    mvvm.getData(that.params.key)
                }
                else
                    mvvm.getData(0)
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            },
            //招聘管理
            RecruitmentManage: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM;
                var mvvm = CBCRM.define('defaultController', function (vm) {
                    vm.lang = lang
                    vm.$skipArray = ['lang']
                });
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
            },
            //招聘计划
            Recruitment: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM;
                var kind1;
                var mvvm = CBCRM.define('RecruitmentController', function (vm) {
                    vm.lang = lang
                    vm.$skipArray = ['lang']

                    vm.ADD = true;
                    vm.DELETE = true
                    vm.entity = {}
                    vm.RecruitmentList = []
                    vm.showItem = {}
                    vm.depart = []
                    vm.Dictionary = []
                    vm.qudaoList = []

                    vm.keyword = ''
                    vm.history = []
                    //关键字搜索
                    vm.search = function () {
                        if (mvvm.keyword) {
                            mvvm.showItem.keyword = mvvm.keyword
                            initWithPageData(mvvm.showItem.$model)
                            if (mvvm.history.length = 3)
                                mvvm.history.removeAt(2)
                            mvvm.history.unshift(mvvm.keyword)
                        }
                    }
                    //历史搜索
                    vm.historyClick = function () {
                        mvvm.keyword = $(this).val()
                        mvvm.showItem.keyword = mvvm.keyword
                        initWithPageData(mvvm.showItem.$model)
                    }
                    //清除
                    vm.clear = function () {
                        mvvm.keyword = ''
                        mvvm.showItem.keyword = mvvm.keyword
                        initWithPageData(mvvm.showItem.$model)
                    }

                    vm.formSubmit = function (title) {
                        var dialog = mvvm.openTmpl({
                            title: title, w: 920, h: 347,padding:"def2",
                            tmplId: "formTemplate", tmpl: tmpl,
                            button: [{
                                name: '提交',
                                focus: true,
                                callback: function () {
                                    var model = mvvm.entity.$model;
                                    model.AuditComment = model.AuditComment.toString();
                                    model.Remark = kind1.html();
                                    var msg = ''
                                    if (!model.Title) msg = '标题不能为空<br/>'
                                    if (msg) {
                                        messageBox.error(msg)
                                        return false
                                    }
                                    var url = model.Id == 0 ? "/HR/RecruitmentAdd/" : "/HR/RecruitmentEdit/" + model.Id;
                                    $.post(url, model, function (ret) {
                                        if (ret.result) {
                                            messageBox.ok(ret.message, function () { dialog.close(); initWithPageData(mvvm.showItem.$model) });
                                        }
                                        else
                                            messageBox.error(ret.message);
                                    });

                                    return false
                                }
                            }],
                            onScan: function () {
                                kind1 = ketool.simple('txtRemark', '792px', '200px');
                                if (kind1) kind1.html(mvvm.entity.Remark);
                            }
                        });
                    }

                    //新增
                    vm.doadd = function () {
                        mvvm.entity = modelFactory.create('Recruitment')
                        var curr = CBCRM.memberShip
                        mvvm.entity.AddBy.Id = curr.Id
                        mvvm.entity.AddBy.FullName = curr.FullName
                        mvvm.entity.ApplyByDisplay = curr.FullName

                        mvvm.entity.ApplyTime = GetDateTime()
                        mvvm.entity.AddTime = GetDateTime()
                        mvvm.formSubmit('新增招聘计划')
                    }

                    vm.doedit = function () {
                        var id = $(this).attr('val');
                        $.get('/HR/RecruitmentDetial/' + id, {}, function (ret) {
                            if (ret.data.model.AuditComment)
                                ret.data.model.AuditComment = ret.data.model.AuditComment.split(',')
                            mvvm.entity = ret.data.model;
                            mvvm.formSubmit('编辑招聘计划')
                        })
                    }

                    vm.dodel = function () {
                        var id = $(this).attr('val');
                        messageBox.confirm("确定要删除数据吗？", function () {
                            $.post('/HR/RecruitmentDel/' + id, function (ret) {
                                if (ret.result)
                                    messageBox.ok(ret.message, function () { initWithPageData(mvvm.showItem.$model); });
                                else
                                    messageBox.error(ret.message);
                            })
                        })
                    }

                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm("确定要删除数据吗？", function () {
                            $.post('/HR/RecruitmentDelAll/', deleteIds, function (ret) {
                                if (ret.result)
                                    messageBox.ok(ret.message, function () { initWithPageData(mvvm.showItem.$model); });
                                else
                                    messageBox.error(ret.message);
                            })
                        })
                    }

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

                    vm.birthdayOpts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.StartDate = formatDate;
                        }
                    }
                    vm.birthdayOpts2 = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.EndDate = formatDate;
                        }
                    }


                    vm.doview = function () {
                        var id = $(this).attr('val')
                        $.get('/HR/RecruitmentDetial/' + id, {}, function (ret) {
                            mvvm.qudaoList = ret.data.qudao;
                            mvvm.entity = ret.data.model;
                            mvvm.openTmpl({
                                title: "查看招聘计划", w: 920, h: 347,
                                tmplId: "viewTemplate", tmpl: tmpl,padding:"def2"
                            });
                        })
                    }

                    //选择申请人   
                    vm.selectUser = function () {
                        plugins.selectUser({
                            dataAuth: 6030101,
                            callback: function (us) {
                                var u = us[0];
                                mvvm.entity.ApplyBy = u.Id
                                mvvm.entity.ApplyByDisplay = u.FullName
                                mvvm.entity.DepartmentId = u.GroupId
                                mvvm.entity.DepartmentIdDisplay = u.GroupName
                            }
                        });
                    }
                    vm.postGroupTreeOpts = {
                        treeopts: {
                            callback: {
                                onCheck: function (e, treeId, treeNode) {
                                    mvvm.entity.ApplyBy = treeNode.Id
                                    mvvm.entity.ApplyByDisplay = treeNode.Name
                                    mvvm.entity.DepartmentId = treeNode.groupId
                                    mvvm.entity.DepartmentIdDisplay = treeNode.groupName
                                }
                            },
                            check: {
                                enable: true,
                                chkStyle: 'radio',
                                radioType: "all"
                            },
                            async: {
                                url: function (treeId, treeNode) {
                                    return "/Settings/GetGroupPostUser"
                                },
                                dataFilter: notMemberFilter
                            }
                        }
                    }

                    vm.selectAllAudit = function () {
                        var chk = parseInt($(this).attr('val'))
                        $('input[name="qudao"]').each(function (i, item) {
                            item.checked = chk ? true : false
                        })
                        $(this).attr('val', chk ? 0 : 1)
                        $(this).html(chk ? '全清' : '全选')
                    }
                })

                var queryData = {
                    keyword: '',
                    pageIndex: 1, pageSize: 20
                }
                mvvm.showItem = avalon.mix({}, queryData);
                mvvm.entity = modelFactory.create('Recruitment');

                function initWithPageData(data) {
                    $.get('/HR/Recruitment/', data, function (ret) {
                        mvvm.RecruitmentList = ret.data.Source;
                        mvvm.ADD = ret.data.ADD
                        mvvm.DELETE = ret.data.DELETE
                        avalon.vmodels.upaing.total = ret.data.RecordTotal //分页总数
                    })
                }

                function initDict() {
                    $.get('/HR/GetRecruitmentDictionary/', {}, function (ret) {
                        mvvm.Dictionary = ret.data.category
                    })
                }
                initDict()
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            },
            //招聘职位
            RecruitPost: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM
                var txtRemark
                var mvvm = CBCRM.define('RecruitPostController', function (vm) {
                    vm.lang = lang
                    vm.$skipArray = ['lang']

                    vm.ADD = true;
                    vm.DELETE = true
                    vm.postList = []
                    vm.showItem = {}
                    vm.searchItem = {}
                    vm.postEntity = {}

                    vm.postpaing = {
                        paging: function () {
                            var that = this
                            mvvm.showItem.pageSize = that.pagesize
                            mvvm.showItem.pageIndex = that.currentindex + 1
                            initWithPageData(mvvm.showItem.$model)
                        }
                    }

                    vm.keyword = ''
                    vm.history = []
                    //关键字搜索
                    vm.search = function () {
                        if (mvvm.keyword) {
                            mvvm.showItem.keyword = mvvm.keyword
                            initWithPageData(mvvm.showItem.$model)
                            if (mvvm.history.length = 3)
                                mvvm.history.removeAt(2)
                            mvvm.history.unshift(mvvm.keyword)
                        }
                    }
                    //历史搜索
                    vm.historyClick = function () {
                        mvvm.keyword = $(this).val()
                        mvvm.showItem.keyword = mvvm.keyword
                        initWithPageData(mvvm.showItem.$model)
                    }
                    //清除
                    vm.clear = function () {
                        mvvm.keyword = ''
                        mvvm.showItem.keyword = mvvm.keyword
                        mvvm.clearAllItem()
                    }
                    vm.clearAllItem = function () {
                        mvvm.showItem.categoryid = mvvm.showItem.categoryidname = ''
                        mvvm.showItem.recruitprop = mvvm.showItem.recruitpropname = ''
                        mvvm.showItem.postprop = mvvm.showItem.postpropname = ''
                        $('.quickword a[value=""]').addClass('selected').siblings().removeClass('selected')
                        initWithPageData(mvvm.showItem.$model)
                    }
                    vm.removeItem = function () {
                        var key = $(this).attr('key')
                        mvvm.showItem[key] = mvvm.showItem[key + 'name'] = ''
                        $('.quickword a[key="' + key + '"]').eq(0).addClass('selected').siblings().removeClass('selected')
                        initWithPageData(mvvm.showItem.$model)
                    }
                    vm.itemClick = function () {
                        var key = $(this).attr('key')
                        var value = $(this).val()
                        var name = $(this).text()
                        if (value) {
                            mvvm.showItem[key] = value
                            mvvm.showItem[key + 'name'] = ''
                            mvvm.showItem[key + 'name'] = name
                        } else {
                            mvvm.showItem[key] = ''
                            mvvm.showItem[key + 'name'] = ''
                        }
                        $(this).addClass('selected').siblings().removeClass('selected')
                        initWithPageData(mvvm.showItem.$model)
                    }
                    //新增
                    vm.doadd = function () {
                        mvvm.postEntity = modelFactory.create('RecruitPost')
                        var curr = CBCRM.memberShip
                        mvvm.postEntity.AddBy.Id = curr.Id
                        mvvm.postEntity.AddBy.FullName = curr.FullName
                        mvvm.postEntity.AddTime = GetDateTime()
                        mvvm.formSubmit('新增招聘职位')
                    }

                    vm.doedit = function () {
                        var id = $(this).attr('val');
                        mvvm.postList.$model.forEach(function (item, i) {
                            if (item.Id == id) {
                                mvvm.postEntity = item
                                mvvm.formSubmit('编辑招聘职位')
                            }
                        })
                    }

                    vm.dodel = function () {
                        var id = $(this).attr('val');
                        messageBox.confirm("确定要删除数据吗？", function () {
                            $.post('/HR/RecruitPostDel/' + id, function (ret) {
                                if (ret.result)
                                    messageBox.ok(ret.message, function () { initWithPageData(mvvm.showItem.$model); });
                                else
                                    messageBox.error(ret.message);
                            })
                        })
                    }

                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm("确定要删除数据吗？", function () {
                            $.post('/HR/RecruitPostDelAll/', deleteIds, function (ret) {
                                if (ret.result)
                                    messageBox.ok(ret.message, function () { initWithPageData(mvvm.showItem.$model); });
                                else
                                    messageBox.error(ret.message);
                            })
                        })
                    }

                    vm.doview = function () {
                        var id = $(this).attr('val')
                        mvvm.postList.$model.forEach(function (item, i) {
                            if (item.Id == id) {
                                mvvm.postEntity = item
                                var dialog = messageBox.openHtml('查看招聘职位', '850px', '347px', '')
                                var content = $(dialog.content())
                                var inputTmpl = $(tmpl).find("#viewTemplate").text();
                                content.html(inputTmpl);
                                avalon.scan(content[0], mvvm)
                            }
                        })
                    }

                    vm.formSubmit = function (title) {
                        var dialog = mvvm.openTmpl({
                            title: title, w: 800, h: 347, padding: "def2",
                            tmplId:"formTemplate",tmpl:tmpl,
                            button: [{
                                name: '提交',
                                focus: true,
                                callback: function () {
                                    var model = mvvm.postEntity.$model;
                                    model.Remark = txtRemark.html();
                                    var msg = ''
                                    if (!model.Name) msg = '职位名称不能为空<br/>'
                                    if (!model.CategoryId) msg += '请选择职位分类'
                                    if (msg) {
                                        messageBox.warning(msg)
                                        return false
                                    }
                                    var url = model.Id == 0 ? "/HR/RecruitPostAdd/" : "/HR/RecruitPostEdit/" + model.Id;
                                    $.post(url, model, function (ret) {
                                        if (ret.result) {
                                            messageBox.ok(ret.message, function () { dialog.close(); initWithPageData(mvvm.showItem.$model) });
                                        }
                                        else
                                            messageBox.error(ret.message);
                                    });

                                    return false
                                }
                            }],
                            onClose: function () {
                                mvvm.destroyui(["inputGroupTree","postcategoryTree"])
                            },
                            onScan: function () {
                                txtRemark = ketool.simple('txtRemark', '600px', '200px');
                                if (txtRemark) {
                                    txtRemark.html(mvvm.postEntity.Remark)
                                }
                            }
                        });
                    }

                    //部门下拉树
                    vm.inputGroupTreeOpts = {
                        dataAuth:9040100,
                        treeopts: {
                            callback: {
                                onClick: function (event, treeId, treeNode) {
                                    var m = mvvm.postEntity
                                    m.GroupDisplay = treeNode.Name
                                    m.GroupId = treeNode.Id
                                }
                            }
                        }
                    }
                    //分类下拉树
                    vm.postcategoryOpts = {
                        treeopts: {
                            async: {
                                url: function (treeId, treeNode) {
                                    var url = '/HR/RecruitCategory?recruitId=' + mvvm.showItem.recruitid
                                    return url
                                }
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    if (treeNode.Id > 1) {
                                        mvvm.postEntity.CategoryId = treeNode.Id
                                        mvvm.postEntity.CategoryDisplay = treeNode.Name
                                    }
                                }
                            }
                        }
                    }
                    /***职位分类管理****/
                    vm.recruitCategroyList = []
                    vm.doCategroy = function () {
                        var dialog = messageBox.openHtml('职位分类管理', '700px', '347px', '', null, function () { mvvm.recruitmentRefresh() })
                        var content = $(dialog.content())
                        var inputTmpl = $(tmpl).find("#formTemplateCategory").text();
                        content.html(inputTmpl);
                        avalon.scan(content[0], mvvm)
                        avalon.nextTick(function () {
                            if (!mvvm.showItem.recruitid && mvvm.recruitmentData.length > 0) {
                                mvvm.showItem.recruitid = mvvm.recruitmentData[0].Id
                            }
                            $('#selectRecruitment').val(mvvm.showItem.recruitid)
                            mvvm.getRecruitCategroyData(mvvm.showItem.recruitid)
                        })
                    }
                    vm.doaddCategory = function () {
                        if (mvvm.recruitmentData.length == 0) {
                            messageBox.warning('必须有招聘计划，然后才能新增职位分类')
                        } else {
                            mvvm.recruitmentData.$model.forEach(function (item) {
                                var currId = $('#selectRecruitment').find('option:selected').val()
                                if (item.Id == currId) {
                                    recruitcategoryData.RecruitmentId = item.Id
                                    recruitcategoryData.RecruitmentDisplay = item.Title
                                }
                            })
                            mvvm.recruitCategroyList.push(avalon.mix({}, recruitcategoryData))
                        }
                    }
                    vm.dodelCategory = function () {
                        var id = $(this).attr('val')
                        var index = $(this).attr('index')
                        if (id) {
                            messageBox.confirm("确定要删除数据吗？", function () {
                                $.post('/HR/RecruitCategoryDel/', { "id": id }, function (ret) {
                                    if (ret.result) {
                                        messageBox.ok(ret.message);
                                        mvvm.recruitCategroyList.removeAt(parseInt(index))
                                    }
                                    else
                                        messageBox.error(ret.message);
                                })
                            })
                        } else {
                            mvvm.recruitCategroyList.removeAt(parseInt(index))
                        }
                    }
                    vm.dosaveCategory = function () {
                        var list = mvvm.recruitCategroyList.$model
                        var model = {}
                        var msg = ''
                        list.forEach(function (item, i) {
                            if (!item.Name) {
                                msg = '职位分类名称不能为空<br/>'
                            }
                            model['list[' + i + '].Id'] = item.Id
                            model['list[' + i + '].Name'] = item.Name
                            model['list[' + i + '].RecruitmentId'] = item.RecruitmentId
                        })
                        if (list.length == 0) {
                            msg += '没有要保存的数据'
                        }
                        if (msg) {
                            messageBox.warning(msg)
                        } else {
                            $.post('/HR/RecruitCategoryAdd', model, function (ret) {
                                if (ret.result)
                                    messageBox.ok(ret.message);
                                else
                                    messageBox.error(ret.message);
                            })
                        }
                    }
                    vm.getRecruitCategroyData = function (recruitId) {
                        $.get('/HR/RecruitCategoryList', { 'recruitId': recruitId }, function (ret) {
                            mvvm.recruitCategroyList = ret.data
                        })
                    }
                    vm.recruitmentchange = function () {
                        var currId = $('#selectRecruitment').find('option:selected').val()
                        mvvm.getRecruitCategroyData(currId)
                    }
                    /***end 职位分类***/

                    //招聘计划下拉数据
                    vm.recruitmentData = []
                    vm.getRecruitmentData = function () {
                        $.get('/HR/Recruitment', {}, function (ret) {
                            mvvm.recruitmentData = ret.data.Source
                            if (mvvm.recruitmentData.length > 0) {
                                mvvm.recruitcurrchange()
                            }
                        })
                    }
                    vm.recruitcurrchange = function () {
                        var curr = $('#selectCurrRecruitment').find('option:selected')
                        mvvm.showItem.recruitid = curr.val()
                        mvvm.showItem.recruitidname = curr.text()
                        mvvm.recruitmentRefresh()
                        initWithPageData(mvvm.showItem.$model)
                    }
                    vm.recruitmentRefresh = function () {
                        var categoryTree = $.fn.zTree.getZTreeObj("postCategroyTree")
                        if (categoryTree)
                            categoryTree.reAsyncChildNodes(null, "refresh");
                    }
                    //数据字典
                    vm.EducationData = []
                    vm.RPropertiesData = []
                    vm.PPropertiesData = []

                    //分类树
                    vm.postCategroyOpts = {
                        treeopts: {
                            async: {
                                url: function () {
                                    var currId = $('#selectCurrRecruitment').find('option:selected').val()
                                    if (!currId) currId = 1
                                    return '/HR/RecruitCategory?recruitId=' + currId
                                }
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    if (treeNode.Id > 1) {
                                        mvvm.showItem.categoryid = treeNode.Id
                                        mvvm.showItem.categoryidname = treeNode.Name
                                    } else if (treeNode.Id == 0) {
                                        //进入分类管理
                                        mvvm.doCategroy()
                                    }
                                    else {
                                        mvvm.showItem.categoryid = ''
                                        mvvm.showItem.categoryidname = ''
                                    }
                                    initWithPageData(mvvm.showItem.$model)
                                }
                            },
                            view: {
                                addHoverDom: false,
                                removeHoverDom: false
                            }
                        }
                    }
                })

                var queryData = {
                    keyword: '', recruitprop: '', postprop: '', categoryid: '', recruitid: '0',
                    recruitpropname: '', postpropname: '', categoryidname: '', recruitidname: '',
                    pageIndex: 1, pageSize: 20
                }

                mvvm.showItem = avalon.mix({}, queryData);
                mvvm.entity = modelFactory.create('RecruitPost');
                var recruitcategoryData = modelFactory.create('RecruitCategory')

                function initWithPageData(data) {
                    $.get('/HR/RecruitPost/', data, function (ret) {
                        mvvm.postList = ret.data.Source
                        mvvm.ADD = ret.data.ADD
                        mvvm.DELETE = ret.data.DELETE
                        avalon.vmodels.upaing.total = ret.data.RecordTotal
                    })
                }
                function GetRecruitPostDictionary() {
                    $.get('/HR/GetRecruitPostDictionary', {}, function (ret) {
                        mvvm.EducationData = ret.data.EducationData
                        mvvm.RPropertiesData = ret.data.RPropertiesData
                        mvvm.PPropertiesData = ret.data.PPropertiesData
                    })
                }
                mvvm.getRecruitmentData()
                GetRecruitPostDictionary()

                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            },
            //简历管理
            Resume: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, txtSkill, txtEducations, txtWorks, txtIntroduce, that = this
                , action = this.params.action, paramid = this.params.id;
                var mvvm = avalon.define('ResumeController', function (vm) {
                    vm.lang = lang
                    vm.$skipArray = ['lang']

                    vm.ADD = true;
                    vm.DELETE = true
                    vm.entity = {}
                    vm.ResumeList = []
                    vm.userpaing = {
                        paging: function () {
                            var that = this
                            mvvm.showItem.pageSize = that.pagesize
                            mvvm.showItem.pageIndex = that.currentindex + 1
                            initWithPageData(mvvm.showItem.$model);
                        }
                    }
                    vm.viewHr = viewHr;
                    vm.keyword = ''
                    vm.history = []
                    vm.showItem = {}
                    vm.has = false
                    vm.stateList = [
                        { Id: 0, Data: "人库备选" }, { Id: 1, Data: "不予考虑" }, { Id: 2, Data: "备用人才" }, { Id: 3, Data: "拟面试" },
                        { Id: 4, Data: "通知面试" }, { Id: 5, Data: "面试报到" }, { Id: 6, Data: "面试中" }, { Id: 7, Data: "通知复试" },
                        { Id: 8, Data: "复试报到" }, { Id: 9, Data: "复试中" }, { Id: 10, Data: "面试通过拟录用" }, { Id: 11, Data: "面试不合格未录用" },
                        { Id: 12, Data: "已录用未入职" }, { Id: 13, Data: "成功入职" }
                    ];

                    vm.closeNotify = function () {
                        messageBox.close();
                    }

                    //关键字搜索
                    vm.search = function () {
                        if (mvvm.keyword) {
                            queryData.key = mvvm.keyword
                            initWithPageData(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
                        initWithPageData(queryData)
                    }
                    //移除单个快速筛选
                    vm.remove = function () {
                        var searchKey = this.$vmodel.$key
                        mvvm.showItem[searchKey] = ''
                        $(".quickword a[key='" + searchKey + "']").eq(0).addClass('selected').siblings().removeClass('selected');
                        mvvm.has = false;
                        for (var item in mvvm.showItem.$model) {
                            if (mvvm.showItem.$model[item]) {
                                mvvm.has = true
                                break
                            }
                        }
                        queryData[searchKey] = ''
                        initWithPageData(queryData)
                    }
                    //清空
                    vm.clear = function () {
                        mvvm.keyword = ''
                        mvvm.showItem = avalon.mix({}, searchItem)
                        mvvm.has = false
                        $(".quickword a[value='']").each(function (item) {
                            $(this).addClass('selected').siblings().removeClass('selected')
                        })
                        queryData.keyword = queryData.sex = queryData.degree = queryData.graduate = queryData.ismarry = ''
                        queryData.driving = queryData.vehicle = queryData.sourceId = queryData.addtime = queryData.skilllevel = queryData.isback = ''
                        initWithPageData(queryData)
                    }
                    //快速筛选 
                    vm.itemClick = function () {
                        $(this).attr('class', 'selected').siblings().removeClass('selected');
                        var key = $(this).attr("key")
                        var value = $(this).attr("value")
                        var display = $(this).text()
                        queryData[key] = value
                        if (value != "") {
                            mvvm.showItem[key] = ''
                            mvvm.showItem[key] = display
                            mvvm.has = true
                        } else {
                            mvvm.showItem[key] = ''
                            mvvm.has = false
                            for (var item in mvvm.showItem.$model) {
                                if (mvvm.showItem.$model[item]) {
                                    mvvm.has = true
                                    break
                                }
                            }
                        }
                        initWithPageData(queryData)
                    }

                    vm.doadd = function () {
                        mvvm.tab = 'tab1'
                        mvvm.entity = modelFactory.create('Resume')
                        mvvm.entity.Degree = mvvm.DegreeList.length > 0 ? mvvm.DegreeList[0].Id : ''
                        mvvm.entity.DrivingLicenseId = mvvm.DrivingList.length > 0 ? mvvm.DrivingList[0].Id : ''
                        mvvm.entity.VehicleId = mvvm.VehicleList.length > 0 ? mvvm.VehicleList[0].Id : ''
                        mvvm.entity.JobState = mvvm.JobStateList.length > 0 ? mvvm.JobStateList[0].Id : ''
                        mvvm.entity.Language = mvvm.LanguageList.length > 0 ? mvvm.LanguageList[0].Id : ''
                        mvvm.entity.IsMarry = mvvm.MarryList.length > 0 ? mvvm.MarryList[0].Id : ''
                        mvvm.entity.SkillLevel = mvvm.SkilllevelList.length > 0 ? mvvm.SkilllevelList[0].Id : ''
                        mvvm.entity.Computer = mvvm.ComputerList.length > 0 ? mvvm.ComputerList[0].Id : ''
                        mvvm.entity.State = mvvm.state
                        var curr = CBCRM.memberShip
                        mvvm.entity.AddBy.Id = curr.Id
                        mvvm.entity.AddTime = GetDateTime()
                        mvvm.formSubmit('新增简历')
                    }
                    vm.doedit = function () {
                        mvvm.tab = 'tab1'
                        var id = $(this).val()
                        mvvm.ResumeList.$model.forEach(function (item) {
                            if (item.Id == id) {
                                mvvm.entity = item
                                if (mvvm.entity.RecruitmentApplyId) {
                                    mvvm.getRecruitPostData(mvvm.entity.RecruitmentApplyId)
                                }
                                if (mvvm.entity.Language) mvvm.entity.Language = mvvm.entity.Language.split(',')
                                else mvvm.entity.Language = []
                                mvvm.formSubmit('编辑简历')
                            }
                        })
                    }
                    vm.dodel = function () {
                        var id = $(this).val()
                        messageBox.confirm("确定要删除数据吗？", function () {
                            $.post('/HR/ResumeDel/' + id, function (ret) {
                                if (ret.result)
                                    messageBox.ok(ret.message, function () { initWithPageData(mvvm.showItem.$model); messageBox.close(); });
                                else
                                    messageBox.error(ret.message);
                            })
                        })
                    }

                    vm.addToArchive = function (id) {
                        var url = "/HR/Archive/" + id + "/add";
                        goto(url, true);
                    }

                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm("确定要删除数据吗？", function () {
                            $.post('/HR/ResumeDelAll/', deleteIds, function (ret) {
                                if (ret.result)
                                    messageBox.ok(ret.message, function () { initWithPageData(mvvm.showItem.$model); });
                                else
                                    messageBox.error(ret.message);
                            })
                        })
                    }
                    vm.getRecruitPostData = function (recruitid) {
                        $.get('/HR/RecruitPost/', { 'recruitid': recruitid }, function (ret) {
                            mvvm.recruitPostData = ret.data.Source
                        })
                    }
                    vm.formSubmit = function (title) {
                        CBCRM.loadView('/HR/formResumeTemplate.html', function (tmpl) {
                            var dialog = messageBox.openHtml(title, '870px', '760px', tmpl, [{
                                name: '提交',
                                focus: true,
                                callback: function () {
                                    var model = mvvm.entity.$model;
                                    var msg = ''
                                    if (!model.Name) msg = '请输入姓名<br/>'
                                    if (!model.Mobile) msg += '请输入手机号码<br/>'
                                    if (msg) {
                                        messageBox.warning(msg)
                                        return false
                                    }
                                    mvvm.entity.Language = mvvm.entity.Language.toString()
                                    mvvm.entity.Skill = txtSkill.html()
                                    mvvm.entity.Educations = txtEducations.html()
                                    mvvm.entity.Works = txtWorks.html()
                                    mvvm.entity.Introduce = txtIntroduce.html()
                                    var url = model.Id == 0 ? "/HR/ResumeAdd/" : "/HR/ResumeEdit/" + model.Id;
                                    $.post(url, model, function (ret) {
                                        if (ret.result) {
                                            messageBox.ok(ret.message, function () { dialog.close(); initWithPageData(mvvm.showItem.$model) });
                                        }
                                        else
                                            messageBox.error(ret.message);
                                    });
                                    return false
                                }
                            }], function () {
                            })

                            var content = $(dialog.content())
                            avalon.scan(content[0], mvvm)

                            mvvm.entity.$watch('RecruitmentApplyId', function (n, o) {
                                if (o != n) {
                                    mvvm.getRecruitPostData(n)
                                }
                            })

                            avalon.nextTick(function () {
                                txtSkill = setEditerSimple('txtSkill', '675px', '100px')
                                txtEducations = setEditerSimple('txtEducations', '675px', '100px')
                                txtWorks = setEditerSimple('txtWorks', '675px', '100px')
                                txtIntroduce = setEditerSimple('txtIntroduce', '675px', '100px')
                                if (mvvm.entity.Id > 0) {
                                    var m = mvvm.entity.$model
                                    txtSkill.html(m.Skill)
                                    txtEducations.html(m.Educations)
                                    txtWorks.html(m.Works)
                                    txtIntroduce.html(m.Introduce)
                                } else {
                                    txtSkill.html('')
                                    txtEducations.html('')
                                    txtWorks.html('')
                                    txtIntroduce.html('')
                                }
                            })
                        })
                    }
                    vm.$resumeMap = {
                        Address: "地址",
                        Birthday: "生日",
                        Email: "邮箱",
                        Graduate: "毕业时间",
                        GraduateSchool: "毕业院校",
                        IDCardNumber: "身份证号",
                        JobAddr: "工作地址",
                        Mobile: "手机",
                        Name: "姓名",
                        QQ: "QQ",
                        Salary: "期望月薪",
                        Height: "身高",
                        IsMarry: "婚姻状态",
                        Sex: "性别",
                        Degree: "学历"
                    }
                    vm.personResumeText = "";
                    vm.personResumeTextResult = "";
                    vm.$resumerResult = null;
                    vm.getResumeText = function () {
                        mvvm.personResumeText = "";
                        mvvm.personResumeTextResult = "";
                        mvvm.$resumerResult = null;
                        var dialog = openTmpl({
                            vm: mvvm, tmplid: "resumeTextTmpl", tmpl: tmpl, title: "简历解析", h: 550,
                            btns: [{
                                name: "开始解析",
                                focus: true,
                                callback: function () {
                                    dialog.button({ name: "确定结果", disabled: true })
                                    $.post("/Tools/GetResumeByTextAnalyse/", { personResumeText: mvvm.personResumeText }, function (ret) {
                                        if (ret.result) {
                                            dialog.button({ name: "确定结果", disabled: false, focus: true })
                                            var d = ret.data;
                                            d.IsMarry = findArr(mvvm.MarryList.$model, d.IsMarry, "Data") || "";
                                            d.Degree = findArr(mvvm.DegreeList.$model, d.Degree, "Data") || "";

                                            d.Sex = d.Sex == 1 ? "女" : "男";
                                            mvvm.$resumerResult = ret.data;
                                            var a = [];
                                            for (var key in mvvm.$resumeMap) {
                                                a.push(mvvm.$resumeMap[key] + ":" + ret.data[key]);
                                            }
                                            mvvm.personResumeTextResult = a.join("\n");
                                        } else
                                            CBCRM.showResult(ret);
                                    });
                                    return false;
                                }
                            }, {
                                name: "确定结果",
                                focus: false,
                                disabled: true,
                                callback: function () {
                                    dialog.button({ name: "确定结果", disabled: true, focus: false })
                                    .button({ name: "开始解析", focus: true })
                                    if (!mvvm.$resumerResult) {
                                        messageBox.alert("操作失败</ br>请先执行[开始解析]按钮，等待有解析预览了再点击[确定结果]");
                                        return false;
                                    }
                                    $.extend(true, mvvm.entity, mvvm.$resumerResult);
                                }
                            }]
                        });
                        $(dialog.content()).css("paddingTop", "5px")
                    }
                    vm.tab = 'tab1'
                    vm.tabChange = function () {
                        mvvm.tab = $(this).attr('val')
                    }

                    //字典
                    vm.DegreeList = []
                    vm.SourceList = []
                    vm.DrivingList = []
                    vm.VehicleList = []
                    vm.JobStateList = []
                    vm.LanguageList = []
                    vm.MarryList = []
                    vm.SkilllevelList = []
                    vm.ComputerList = []
                    vm.ResultList = []

                    //招聘计划下拉数据
                    vm.recruitmentData = []
                    vm.getRecruitmentData = function () {
                        $.get('/HR/Recruitment', {}, function (ret) {
                            mvvm.recruitmentData = ret.data.Source
                        })
                    }
                    vm.recruitPostData = []
                    //相片
                    vm.open = function () {
                        var uploadModule, headfrm
                        CBCRM.fillContentBefore = function (tmpl, lang, contentId, module, vm) {
                            headfrm = 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.HeadPortrait = '/upload/' + file.Path;
                                headfrm.close();
                            }
                        }
                    }
                    //附件
                    vm.openAtta = function () {
                        var uploadModule, attafrm
                        CBCRM.fillContentBefore = function (tmpl, lang, contentId, module, mvvm) {
                            attafrm = messageBox.openHtml('上传文件', '1000px', '500px', tmpl);
                            avalon.scan($(".aui_content")[0], mvvm);
                            return false;
                        }
                        CBCRM.loadModule('/Upload/Center')
                        CBCRM.onModuleReady = function (data) {
                            avalon.vmodels.upload.itemSelected = function (node, data, file) {
                                mvvm.entity.Attachment = '/Upload/' + file.Path;
                                attafrm.close();
                            }
                        }
                    }
                    vm.birthdayOpts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.Birthday = formatDate
                        }
                    }
                    vm.graduateOpts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.Graduate = formatDate
                        }
                    }

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

                    //查看部分 
                    vm.doview = function () {
                        var id = $(this).val()
                        mvvm.openView(id);
                    }
                    vm.openView = function (id) {
                        $.get('/HR/ResumeBase/' + id, {}, function (ret) {
                            if (ret.data.Source && ret.data.Source.length > 0) {
                                mvvm.entity = avalon.mix(modelFactory.create('Resume'), ret.data.Source[0])
                                mvvm.hasPrevious = ret.data.hasPrevious;
                                mvvm.previousId = ret.data.previousId;
                                mvvm.previousLabel = ret.data.previousLabel;
                                mvvm.hasNext = ret.data.hasNext;
                                mvvm.nextId = ret.data.nextId;
                                mvvm.nextLabel = ret.data.nextLabel;
                                mvvm.getnotifyList()
                                mvvm.getinterviewList()
                                mvvm.gethistoryList()

                                CBCRM.loadView('/HR/viewResumeTemplate.html', function (tmpl) {
                                    var dialog = art.dialog.list['viewresume']
                                    if (!dialog) {
                                        dialog = messageBox.openHtml('查看招聘简历', '920px', '612px', tmpl, false, function () { }, 'viewresume')

                                    }
                                    var content = $(dialog.content())
                                    avalon.scan(content[0], mvvm)
                                })
                            }
                        })
                    }
                    //取View刷新用
                    vm.getview = function (id) {
                        $.get(that.path + "/" + id, {}, function (ret) {
                            if (ret.data.Source && ret.data.Source.length > 0) {
                                mvvm.entity = avalon.mix(modelFactory.create('Resume'), ret.data.Source[0])
                            }
                        })
                    }

                    vm.currNav = '1'
                    vm.doChangeNav = function (navid) {
                        mvvm.currNav = navid
                    }
                    //打印
                    vm.isPrint = false
                    vm.doPrint = function () {
                        messageBox.confirm('您确定要打印当前简历信息吗？', function () {
                            mvvm.isPrint = true;
                            $("#ResumePanelPrint").printArea()
                            mvvm.isPrint = false;
                        })
                    }
                    vm.isExport = false;
                    vm.extport = function () {
                        mvvm.isExport = true;
                        var html = $("#ResumePanelPrint").html();
                        html = "<table>" + html + "</table>"
                        var filename = mvvm.entity.Name + " _简历(编号：" + mvvm.entity.NO + ")"
                        ExportWord(html, filename)
                        mvvm.isExport = false;
                    }
                    //列黑
                    vm.dobackname = function () {
                        var backdialog = messageBox.openHtml('黑名单设置', '500px', '150px', '', [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var model = mvvm.entity.$model;
                                var url = "/HR/ResumeEditBack/" + model.Id;
                                $.post(url, model, function (ret) {
                                    if (ret.result) {
                                        messageBox.ok("黑名单设置成功", function () { backdialog.close(); mvvm.getview(model.Id); mvvm.gethistoryList(); });
                                    }
                                    else
                                        messageBox.error(ret.message);
                                });
                            }
                        }], function () {
                        })
                        var content = $(backdialog.content())
                        content.attr('ms-include', 'backnameTemplate')
                        avalon.scan(content[0], mvvm)
                    }
                    //状态设置
                    vm.dostate = function () {
                        var btns = [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var model = mvvm.entity.$model;
                                var url = "/HR/ResumeEditState/" + model.Id;
                                $.post(url, model, function (ret) {
                                    if (ret.result) {
                                        messageBox.ok("状态设置成功", function () { statedialog.close(); mvvm.getview(model.Id) });
                                    }
                                    else
                                        messageBox.error(ret.message);
                                });
                            }
                        }];
                        var statedialog = openTmpl({
                            vm: mvvm, title: "状态设置", w: 550, h: 150, btns: btns,
                            tmpl: tmpl, tmplid: "stateTemplate",
                            onclose: function () {

                            }
                        })
                    }

                    //面试通知
                    vm.notifyEntity = {}
                    vm.notifyList = []
                    vm.notifyerOpts = {
                        treeopts: {
                            check: {
                                enable: true,
                                chkStyle: 'radio'
                            },
                            callback: {
                                onCheck: function (e, treeId, n) {
                                    mvvm.notifyEntity.Notifyer = n.Id
                                    mvvm.notifyEntity.NotifyerDisplay = n.Name
                                }
                            },
                            async: {
                                dataFilter: notMemberFilter
                            }
                        }
                    }
                    vm.doaddnotify = function () {
                        var resumeid = mvvm.entity.$model.Id
                        var curr = CBCRM.memberShip
                        var entity = modelFactory.create("Notify");
                        entity.ResumeId = resumeid;
                        entity.Notifyer = curr.Id;
                        entity.NotifyerDisplay = curr.FullName;
                        mvvm.notifyEntity = entity;
                        mvvm.donotifySubmit('新增面试通知')
                    }
                    vm.doeditnotity = function () {
                        var id = $(this).val()
                        mvvm.notifyList.$model.forEach(function (item) {
                            if (item.Id == id) {
                                var ws = item.NotifyWays;
                                if (!$.isArray(ws)) item.NotifyWays = ws ? ws.split(",") : [];
                                item.context = "";
                                mvvm.notifyEntity = item
                                mvvm.donotifySubmit('编辑面试通知')
                            }
                        })
                    }
                    vm.notifyWidth = 570;
                    //面试通知提交数据
                    vm.donotifySubmit = function (title) {
                        mvvm.getSmsTmpl(function () {
                            var notifydialog = openTmpl({
                                vm: mvvm,
                                title: title,
                                tmpl: tmpl,
                                tmplid: "faceTemplate",
                                w: mvvm.notifyWidth,
                                h: 300,
                                onclose: function () { destroyui(["notifyerTree"]) },
                                btns: [{
                                    name: '提交',
                                    focus: true,
                                    callback: function () {
                                        var model = mvvm.notifyEntity.$model;
                                        var msg = ''
                                        if (!model.NotifyInterviewDate)
                                            msg = '面试时间不能为空'
                                        if (msg) {
                                            messageBox.warning(msg)
                                            return false
                                        }
                                        var ws = model.NotifyWays;
                                        model.NotifyWays = ws ? ws.join(",") : "";
                                        var herf = model.Id > 0 ? '/HR/ResumeNotifyEdit/' + model.Id : '/HR/ResumeNotifyAdd'
                                        $.post(herf, model, function (ret) {
                                            if (ret.result) {
                                                if (ws.indexOf('1') != -1 || ws.indexOf(1) != -1) {
                                                    var dialog2 = messageBox.ok("面试通知保存成功，您选择有短信通知，正在发送短信……");
                                                    var pvm = mvvm.$pvm, sms = pvm.sms;
                                                    sms.numbers = mvvm.entity.Mobile;
                                                    sms.ids = CBCRM.memberShip.Id;
                                                    sms.context = model.context;
                                                    sms.preview = model.context;
                                                    pvm.sendSms(function (ret) {
                                                        if (dialog2) dialog2.close();
                                                    });
                                                    var d = new Date();
                                                } else {
                                                    messageBox.ok("面试通知保存成功");
                                                }
                                                notifydialog.close();
                                                mvvm.getnotifyList();
                                                mvvm.entity.State = model.Type ? 7 : 4
                                            }
                                            else {
                                                messageBox.error(ret.message);
                                            }
                                        });
                                        return false;
                                    }
                                }]
                            });
                        });
                    }
                    vm.smsSign = true;
                    vm.sign = "【" + CBCRM.cmyInfo.ShortName + "】";
                    vm.sendSms = CBCRM.sendSms;
                    vm.sendSmsByTmpl = function () {
                        var m = mvvm.entity, n = mvvm.notifyEntity;
                        var mobile = m.Mobile;
                        var model = { "姓名": m.Name, "类型": n.Type ? "复试" : "初试", "面试时间": n.NotifyInterviewDate, "投递时间": m.AddTime };
                        var dialog = CBCRM.sendSmsTmpl("简历", mobile, model);
                    }
                    vm.$pvm = null;
                    vm.$smsTmpl = null;
                    vm.useSms = function () {
                        if (this.checked) mvvm.getSmsTmpl();
                    }
                    vm.selectTmpl = function () {
                        mvvm.getMessageVm(function (pvm) {
                            pvm.selectTmpl();
                        });
                    }
                    //设置使用的模板
                    vm.setSmsTmpl = function (item) {
                        mvvm.$smsTmpl = item.$model || item;
                        var config = mvvm.$tmplConfig;
                        if (item.Id != config.Value) {
                            config.Value = item.Id;
                            Config.setOne(config);
                        }
                        var m = mvvm.entity, n = mvvm.notifyEntity;
                        var mobile = m.Mobile;
                        var model = { "姓名": m.Name, "类型": n.Type, "面试时间": n.NotifyInterviewDate, "投递时间": m.AddTime };
                        var pvm = mvvm.$pvm;
                        mvvm.notifyEntity.context = pvm.replaceTmplData("简历", model);
                        if (mvvm.smsSign) mvvm.notifyEntity.context += mvvm.sign;
                    }
                    vm.$tmplConfig = { Cname: "MessageTmplConfig", Name: "简历", Value: '' };
                    //获取上次选择的模板
                    vm.getSmsTmpl = function (callback) {
                        if (mvvm.$smsTmpl != null) {
                            mvvm.$pvm.selectTmplItem(mvvm.$smsTmpl);
                            if (callback) callback();
                            return;
                        }
                        mvvm.getMessageVm(function (pvm) {
                            var config = mvvm.$tmplConfig;
                            Config.getOne(config, function (configs) {
                                var id = configs ? configs.Value : ''
                                config.Value = id
                                if (id) {
                                    $.get("/Tools/MessageTmpl/", { id: id }, function (ret) {
                                        if (ret.result && ret.data.Source.length > 0) {
                                            mvvm.$smsTmpl = ret.data.Source[0];
                                            pvm.selectTmplItem(mvvm.$smsTmpl);
                                            if (callback) callback();
                                        }
                                    });
                                }
                            });
                        });
                    }
                    //获取MessageVm
                    vm.getMessageVm = function (callback) {
                        if (mvvm.$pvm != null) return callback(mvvm.$pvm);
                        CBCRM.loadModule("/Tools/Message/0/getvm", null, function (pvm) {
                            mvvm.$pvm = pvm = avalon.vmodels[pvm];
                            pvm.onTmplSelect = mvvm.setSmsTmpl;
                            callback(pvm);
                        });
                    }
                    vm.dodelnotify = function () {
                        var id = $(this).val()
                        var index = parseInt($(this).attr('index'))
                        $.post('/HR/ResumeNotifyDel/' + id, {}, function (ret) {
                            if (ret.result) {
                                messageBox.ok(ret.message, function () { mvvm.notifyList.removeAt(index) })
                            } else {
                                messageBox.error(ret.message)
                            }
                        })
                    }
                    vm.getnotifyList = function () {
                        $.get('/HR/ResumeNotify', { "resumeid": mvvm.entity.Id }, function (ret) {
                            mvvm.notifyList = ret.data
                        })
                    }

                    //面试点评
                    vm.interview = {}
                    vm.interviewList = []
                    vm.doaddinterview = function () {
                        var curr = CBCRM.memberShip
                        mvvm.interview = {
                            Id: '',
                            ResumeId: '',
                            Time: GetDateTime(),
                            Interviewer: curr.Id,
                            InterviewerDisplay: curr.FullName,
                            Extrinsic: '',
                            Skill: '',
                            Matching: '',
                            Practice: '',
                            Score: '',
                            Evaluate: '',
                            ResultId: ''
                        }
                        mvvm.interview.ResumeId = mvvm.entity.$model.Id
                        mvvm.interview.ResultId = mvvm.ResultList.length > 4 ? mvvm.ResultList[3].Id : ''
                        mvvm.dointerviewSubmit("新增面试点评")
                    }
                    vm.interviewerOpts = {
                        treeopts: {
                            check: {
                                enable: true,
                                chkStyle: 'radio'
                            },
                            callback: {
                                onCheck: function (e, treeId, n) {
                                    mvvm.interview.Interviewer = n.Id
                                    mvvm.interview.InterviewerDisplay = n.Name
                                }
                            },
                            async: {
                                dataFilter: notMemberFilter
                            }
                        }
                    }
                    vm.doeditinterview = function () {
                        var id = $(this).attr('value');
                        mvvm.interviewList.$model.forEach(function (item) {
                            if (item.Id == id) {
                                mvvm.interview = item
                                mvvm.dointerviewSubmit("编辑面试点评")
                            }
                        })
                    }
                    vm.dodelinterview = function () {
                        var id = $(this).val()
                        var index = parseInt($(this).attr('index'))
                        messageBox.confirm("确定要删除面试点评吗？", function () {
                            $.post('/HR/ResumeInterviewDel/' + id, {}, function (ret) {
                                if (ret.result)
                                    messageBox.ok(ret.message, function () { mvvm.interviewList.removeAt(index); });
                                else
                                    messageBox.error(ret.message);
                            })
                        })
                    }
                    vm.dointerviewSubmit = function (title) {
                        var dialog = messageBox.openHtml(title, '780px', '300px', '', [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var model = mvvm.interview.$model;
                                var url = model.Id == 0 ? '/HR/ResumeInterviewAdd/' : '/HR/ResumeInterviewEdit/' + model.Id
                                $.post(url, model, function (ret) {
                                    if (ret.result) {
                                        messageBox.ok(ret.message, function () {
                                            mvvm.getinterviewList()
                                            mvvm.getview(mvvm.entity.Id)
                                            dialog.close()
                                        });
                                    }
                                    else {
                                        messageBox.fail(ret.message, function () { dialog.close(); })
                                    }
                                })
                            }
                        }], function () {
                            avalon.vmodels.interviewerTree.destroy()
                        })
                        var content = $(dialog.content())
                        content.attr('ms-include', 'interviewTemplate')
                        avalon.scan(content[0], mvvm)
                    }
                    vm.getinterviewList = function () {
                        $.get('/HR/ResumeInterview', { "resumeid": mvvm.entity.Id }, function (ret) {
                            mvvm.interviewList = ret.data
                        })
                    }

                    //面试报到
                    vm.doarrive = function () {
                        mvvm.entity.ReportDay = GetDateTime()
                        $.get('/HR/GetResumeSort', { "state": mvvm.entity.State > 5 ? 8 : 5 }, function (ret) {
                            mvvm.entity.Sort = ret.data.sort
                        })
                        var arrivedialog = messageBox.openHtml('面试报到', '400px', '100px', '', [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var model = mvvm.entity.$model
                                var msg = ''
                                if (!model.ReportDay)
                                    msg = '报到时间不能为空'
                                if (msg) {
                                    messageBox.warning(msg)
                                    return false
                                }
                                model.State = model.State > 5 ? 8 : 5
                                var url = "/HR/ResumeEdit/" + model.Id;
                                $.post(url, model, function (ret) {
                                    if (ret.result) {
                                        messageBox.ok("操作成功", function () { arrivedialog.close(); mvvm.getview(model.Id) });
                                    }
                                    else
                                        messageBox.error(ret.message);
                                });
                            }
                        }])
                        var content = $(arrivedialog.content())
                        content.attr('ms-include', 'arriveTemplate')
                        avalon.scan(content[0], mvvm)
                    }

                    //历史事件
                    vm.historyList = []
                    vm.gethistoryList = function () {
                        $.get('/HR/GetResumeHistory', { "resumeid": mvvm.entity.Id }, function (ret) {
                            mvvm.historyList = ret.data
                        })
                    }
                    //上一条下一条
                    vm.hasPrevious = false
                    vm.previousLabel = ''
                    vm.previousId = ''
                    vm.hasNext = false
                    vm.nextLabel = ''
                    vm.nextId = ''

                    //浮动窗
                    vm.state = 0
                    vm.floatlistshow = false
                    vm.firstshow = false;
                    vm.setfloatlist = function () {
                        mvvm.floatlistshow = !mvvm.floatlistshow
                        mvvm.firstshow = true;
                        fixtop()
                    }
                    vm.resumeTemp = []
                    vm.addResumeTemp = function (item, index) {
                        var i = findArr(mvvm.resumeTemp, item.Id);
                        if (i != null) return;
                        mvvm.resumeTemp.push(item.$model)
                        //mvvm.ResumeList.removeAt(index)
                        if (!vm.firstshow) {
                            mvvm.floatlistshow = true
                            mvvm.firstshow = true;
                        }
                        fixtop()
                    }


                    vm.removeResumeTemp = function (item, index) {
                        mvvm.resumeTemp.removeAt(index)
                        mvvm.listtag = 'up'
                        fixtop()
                    }
                    vm.clearResumeTemp = function () {
                        mvvm.resumeTemp = []
                        mvvm.listtag = 'up'
                        fixtop()
                    }

                    vm.dosaveTemp = function () {
                        if (mvvm.resumeTemp.length == 0) {
                            messageBox.warning('没有要加入的简历，请筛选简历')
                            return false
                        }
                        var tempids = {}
                        mvvm.resumeTemp.$model.forEach(function (item, i) {
                            tempids['resumeids[' + i + ']'] = item.Id
                        })
                        var joinstate = 0
                        var remark = ''
                        switch (mvvm.state) {
                            case 2:
                                joinstate = 3
                                remark = '从【备用人才】转入【拟面试】'
                                break
                            case 3:
                                joinstate = 0
                                remark = '从【拟面试】放回【简历库】'
                                break
                            case 4:
                                joinstate = 7
                                remark = '从【面试库】转入【复试库】'
                                break
                            case 5:
                                joinstate = 7
                                remark = '从【面试库】转入【复试库】'
                                break
                            case 6:
                                remark = '从【面试库】转入【复试库】'
                                joinstate = 7
                                break
                            case 7:
                                joinstate = 10
                                remark = '从【复试库】转入【拟录用】'
                                break
                            case 8:
                                joinstate = 10
                                remark = '从【复试库】转入【拟录用】'
                                break
                            case 9:
                                joinstate = 10
                                remark = '从【复试库】转入【拟录用】'
                                break
                            case 10:
                                joinstate = 0
                                remark = '从【拟录用】放回【简历库】'
                                break
                            default:
                                joinstate = 3
                                break
                        }
                        tempids['state'] = joinstate
                        tempids['remark'] = remark
                        $.post('/HR/SetAllResumeState', tempids, function (ret) {
                            if (ret.result) {
                                messageBox.ok('操作成功', function () {
                                    initWithPageData(mvvm.showItem.$model)
                                    mvvm.clearResumeTemp();
                                })
                            }
                        })
                    }
                })

                function bindWatch() {
                    mvvm.$watch("sign", function (n, o) {
                        var context = mvvm.notifyEntity.context;
                        mvvm.notifyEntity.context = context.replace(o, n);
                    });
                    mvvm.$watch("smsSign", function (n) {
                        var context = mvvm.notifyEntity.context;
                        mvvm.notifyEntity.context = n ? context + mvvm.sign : context.replace(mvvm.sign, "")
                    });
                }
                bindWatch();
                var queryData = {
                    keyword: '', sex: '', degree: '', graduate: '', ismarry: '', state: '',
                    driving: '', vehicle: '', sourceId: '', addtime: '', skilllevel: '', isback: '',
                    pageIndex: 1, pageSize: 20
                }
                var searchItem = {
                    sex: '', degree: '', graduate: '', ismarry: '', state: '',
                    driving: '', vehicle: '', sourceId: '', addtime: '', skilllevel: '', isback: ''
                }
                mvvm.showItem = avalon.mix({}, searchItem)
                mvvm.entity = modelFactory.create('Resume');

                function initWithPageData(data) {
                    $.get(that.path, data, function (ret) {
                        mvvm.ResumeList = ret.data.Source;
                        mvvm.ADD = ret.data.ADD
                        mvvm.DELETE = ret.data.DELETE
                        avalon.vmodels.upaing.total = ret.data.RecordTotal
                    })
                }

                function getDictionaryData() {
                    $.get('/HR/GetDictionaryList', {}, function (ret) {
                        mvvm.DegreeList = ret.data.DegreeList;
                        mvvm.SourceList = ret.data.SourceList;
                        mvvm.DrivingList = ret.data.DrivingList;
                        mvvm.VehicleList = ret.data.VehicleList;
                        mvvm.JobStateList = ret.data.JobStateList;
                        mvvm.LanguageList = ret.data.LanguageList;
                        mvvm.MarryList = ret.data.MarryList;
                        mvvm.SkilllevelList = ret.data.SkilllevelList;
                        mvvm.ComputerList = ret.data.ComputerList;
                        mvvm.ResultList = ret.data.ResultList;
                    })
                }
                getDictionaryData()
                mvvm.getRecruitmentData()
                var lowIe = $.browser.msie && (parseInt($.browser.version, 10) < 10);
                if (lowIe) {
                    window.onscroll = fixtop
                    window.onresize = fixtop
                }
                function fixtop() {
                    if (!lowIe) return;
                    var tbheight = $('#tableinterview').height()
                    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop
                    var top = document.documentElement.clientHeight || document.body.clientHeight
                    top = top + scrollTop - tbheight
                    $('#tableinterview').css({ 'top': top + 'px', "position": "absolute" })
                }

                //自定义过滤器
                avalon.filters.wayname = function (val) {
                    switch (val) {
                        case 0:
                            return '电话'
                        case 1:
                            return '短信'
                        case 2:
                            return '邮件'
                        case 3:
                            return 'QQ'
                        default: ''
                    }
                }
                avalon.filters.statedisplay = function (val) {
                    switch (val) {
                        case 1:
                            return "不予考虑"
                        case 2:
                            return "备用人才"
                        case 3:
                            return "拟面试"
                        case 4:
                            return "通知面试"
                        case 5:
                            return "面试报到"
                        case 6:
                            return "面试中"
                        case 7:
                            return "通知复试"
                        case 8:
                            return "复试报到"
                        case 9:
                            return "复试中"
                        case 10:
                            return "面试通过拟录用"
                        case 11:
                            return "面试不合格未录用"
                        case 12:
                            return "已录用未入职"
                        case 13:
                            return "成功入职"
                        default:
                            return "入库备选"
                    }
                }
                avalon.filters.resultDisplay = function (val) {
                    var resultdisplay = ''
                    mvvm.ResultList.$model.forEach(function (item) {
                        if (item.Id == val) {
                            resultdisplay = item.Data
                        }
                    })
                    return resultdisplay
                }
                avalon.filters.resumeState = function (val) {
                    var state = findArr(mvvm.stateList, val, "Data");
                    return state;
                }
                var path = that.path.split('/')[2]
                switch (path) {
                    case 'ResumeWithout':
                        mvvm.state = 1
                        break
                    case 'ResumeStore':
                        mvvm.state = 2
                        break
                    case 'ResumePlan':
                        mvvm.state = 3
                        break
                    case 'ResumeAudition':
                        mvvm.state = 4
                        break
                    case 'ResumeReexamine':
                        mvvm.state = 7
                        break
                    case 'ResumeHire':
                        mvvm.state = 10
                        break
                    case 'ResumeNoHire':
                        mvvm.state = 11
                        break
                    case 'ResumeJoin':
                        mvvm.state = 13
                    default:
                        mvvm.state = 0
                        break

                }
                switch (action) {
                    case "view":
                        mvvm.openView(paramid);
                        break;
                    default:
                        fill();
                        break;
                }
                function fill() {
                    require('commonui', function () {
                        CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                    })
                }

                CBCRM.onLoadModuleBefore = function () {
                    if (mvvm.$pvm) mvvm.$pvm.destroy();
                    avalon.vmodels.Resume = null
                }
            },
            ResumePlan: function (tmpl, lang, contentId, module) {
                module.Resume.call(this, tmpl, lang, contentId, module)
            },
            ResumeStore: function (tmpl, lang, contentId, module) {
                module.Resume.call(this, tmpl, lang, contentId, module)
            },
            ResumeWithout: function (tmpl, lang, contentId, module) {
                module.Resume.call(this, tmpl, lang, contentId, module)
            },
            ResumeAudition: function (tmpl, lang, contentId, module) {
                module.Resume.call(this, tmpl, lang, contentId, module)
            },
            ResumeReexamine: function (tmpl, lang, contentId, module) {
                module.Resume.call(this, tmpl, lang, contentId, module)
            },
            ResumeHire: function (tmpl, lang, contentId, module) {
                module.Resume.call(this, tmpl, lang, contentId, module)
            },
            ResumeJoin: function (tmpl, lang, contentId, module) {
                module.Resume.call(this, tmpl, lang, contentId, module)
            },
            ResumeNoHire: function (tmpl, lang, contentId, module) {
                module.Resume.call(this, tmpl, lang, contentId, module)
            },

            //培训管理
            Training: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM;
                var mvvm = CBCRM.define('training', function (vm) {
                    vm.lang = lang
                })
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            },

            //培训计划
            TrainPlan: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, txtContent
                var userFilter = 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('trainplan', function (vm) {
                    vm.lang = lang
                    vm.$skipArray = ['lang']
                    vm.entity = {}
                    vm.trainplanList = []
                    vm.trainplanpaing = {
                        paging: function () {
                            var that = this
                            GetTrainPlanList({
                                pageSize: that.pagesize,
                                pageIndex: that.currentindex + 1
                            });
                        }
                    }

                    vm.classData = []
                    vm.categoryData = []
                    vm.layData = []
                    vm.objectData = []
                    vm.methodData = []
                    vm.checkMethodData = []
                    vm.ADD = true
                    vm.DELETE = true

                    vm.showItem = {}
                    vm.keyword = ''
                    vm.history = []
                    //关键字搜索
                    vm.search = function () {
                        if (mvvm.keyword) {
                            mvvm.showItem.keyword = mvvm.keyword
                            GetTrainPlanList(mvvm.showItem.$model)
                            if (mvvm.history.length = 3)
                                mvvm.history.removeAt(2)
                            mvvm.history.unshift(mvvm.keyword)
                        }
                    }
                    //历史搜索
                    vm.historyClick = function () {
                        mvvm.keyword = $(this).val()
                        mvvm.showItem.keyword = mvvm.keyword
                        GetTrainPlanList(mvvm.showItem.$model)
                    }
                    //清除
                    vm.clear = function () {
                        mvvm.keyword = ''
                        mvvm.showItem.keyword = mvvm.keyword
                        GetTrainPlanList(mvvm.showItem.$model)
                    }

                    //新增
                    vm.doadd = function () {
                        mvvm.action = 'add'
                        mvvm.entity = modelFactory.create('TrainPlan')
                        mvvm.entity.ClassId = mvvm.classData[0].Id
                        mvvm.entity.LayId = mvvm.layData[0].Id
                        mvvm.entity.MethodId = mvvm.methodData[0].Id
                        mvvm.entity.CategoryId = mvvm.categoryData[0].Id
                        mvvm.entity.Object = mvvm.objectData[0].Id
                        mvvm.entity.CheckMethodId = mvvm.checkMethodData[0].Id
                        mvvm.entity.PlanningBy = CBCRM.memberShip.Id
                        mvvm.entity.PlanningByDisplay = CBCRM.memberShip.FullName
                        mvvm.entity.PlanningTime = GetDateTime()
                        mvvm.planempList = []
                        mvvm.formSubmit('新增培训计划')
                    }
                    //编辑
                    vm.doedit = function () {
                        var id = $(this).val()
                        mvvm.trainplanList.$model.forEach(function (item) {
                            if (item.Id == id) {
                                mvvm.entity = avalon.mix(modelFactory.create('TrainPlan'), item)
                                if (mvvm.entity.PlanEmployeeIds.length)
                                    mvvm.getUsersData(mvvm.entity.PlanEmployeeIds.$model)
                                else
                                    mvvm.planempList = []
                                mvvm.formSubmit('编辑培训计划')
                            }
                        })
                    }
                    //查看 
                    vm.doview = function () {
                        mvvm.action = 'view'
                        var id = $(this).val()
                        mvvm.trainplanList.$model.forEach(function (item) {
                            if (item.Id == id) {
                                mvvm.entity = avalon.mix(modelFactory.create('TrainPlan'), item)
                                if (mvvm.entity.PlanEmployeeIds.length)
                                    mvvm.getUsersData(mvvm.entity.PlanEmployeeIds.$model)
                                else
                                    mvvm.planempList = []
                                var dialog = mvvm.openTmpl({
                                    title: "查看培训计划", w: 920, h: 347,
                                    tmplId: "viewTemplate", tmpl: tmpl
                                });
                            }
                        })
                    }

                    //删除
                    vm.dodel = function () {
                        var index = parseInt($(this).attr('index'))
                        var id = $(this).val()
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/HR/TrainPlanDel/' + id, {}, function (ret) {
                                if (ret.result)
                                    mvvm.trainplanList.removeAt(index)
                                messageBox.succeed(ret.message)
                            })
                        });
                    }

                    //批量删除
                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.post('/HR/TrainPlanAllDel/', deleteIds, function (ret) {
                                if (ret.result) {
                                    GetTrainPlanList()
                                    messageBox.succeed(ret.message)
                                }
                            });
                        });
                    }

                    //保存 
                    vm.formSubmit = function (title) {
                        var dialog = mvvm.openTmpl({
                            title: title, w: 862, h: 624,
                            tmplId: "formTemplate", tmpl: tmpl,
                            button: [{
                                name: '提交',
                                focus: true,
                                callback: function () {
                                    var model = mvvm.entity.$model
                                    mvvm.entity.$model.PlanEmployeeIds.forEach(function (item, index) {
                                        model['PlanEmployeeIds[' + index + ']'] = item
                                    })
                                    mvvm.entity.$model.TrainedRecord.forEach(function (item, index) {
                                        model['TrainedRecord[' + index + '].EmployeeId'] = item.EmployeeId
                                    })
                                    model.Content = txtContent.html()
                                    var herf = model.Id == 0 ? "/HR/TrainPlanAdd/" : "/HR/TrainPlanUpdate/" + model.Id
                                    $.post(herf, model, function (ret) {
                                        CBCRM.showResult(ret, function () {
                                            if (ret.result) {
                                                dialog.close()
                                                GetTrainPlanList()
                                            }
                                        })
                                    });
                                    return false
                                }
                            }],
                            onScan: function () {
                                txtContent = ketool.simple('txtContent', '97%', '60px');
                                if (txtContent) {
                                    txtContent.html(mvvm.entity.Content)
                                }
                            }
                        });
                    }

                    //培训时间
                    vm.timeOpts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.Time = formatDate
                        }
                    }

                    //培训运行评估时间
                    vm.pinguOpts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.EmployeeEvaluateDayAfter = formatDate
                        }
                    }

                    //培训转化评估时间
                    vm.trunpinguOpts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.HREvaluateDayAfter = formatDate
                        }
                    }

                    //选择拟培训人员名单
                    vm.planempList = []
                    vm.selectPlanemp = function () {
                        var ids = mvvm.entity.PlanEmployeeIds || [];
                        ids = ids.$model || ids;
                        plugins.selectUser({
                            dataAuth: 6050100,
                            multiple: true,
                            listData:ids,
                            callback: function (us) {
                                mvvm.planempList = us;
                                mvvm.entity.PlanEmployeeIds = where(us, true, "Id");
                                mvvm.entity.PlanEmployeeDisplay = where(us, true, "FullName").join(',')
                            }
                        })
                    }
                    vm.planempOpts = {
                        treeopts: {
                            callback: {
                                onCheck: function (e, treeId, treeNode) {
                                    var treeObj = $.fn.zTree.getZTreeObj(treeId);
                                    var nodes = treeObj.getCheckedNodes(true);
                                    var data = [], names = []
                                    mvvm.planempList = []
                                    nodes.forEach(function (n, i) {
                                        data.push(n.Id)
                                        names.push(n.Name)
                                        mvvm.planempList.push(n)
                                    })
                                    mvvm.entity.PlanEmployeeIds = data
                                    mvvm.entity.PlanEmployeeDisplay = names.join(',')
                                }
                            },
                            async: {
                                url: function (treeId, treeNode) {
                                    return "/Settings/GetGroupPostUser/6050100"
                                },
                                dataFilter: function (treeId, parentNode, responseData) {
                                    var ret = [], len = 0, curr, hasEmp = false, chkids = mvvm.entity.PlanEmployeeIds.join(',')
                                    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
                                                if (chkids.indexOf(u.Id) > -1)
                                                    u.checked = true
                                                else
                                                    u.checked = false
                                                ret.push(u)
                                            })
                                            if (!hasEmp) {
                                                hasEmp = p.Users.length > 0
                                            }
                                            if (hasEmp) {
                                                ret.push(p)
                                            }
                                        })
                                        if (hasEmp) ret.push(curr)
                                    }
                                    return ret
                                }
                            },
                            check: {
                                enable: true,
                                chkStyle: 'checkbox'
                            }
                        }
                    }

                    //上传文件
                    vm.uploadFiles = function () {
                        var uploadModule
                        CBCRM.fillContentBefore = function (tmpl, lang, contentId, module, vm) {
                            var dialog = messageBox.openHtml('上传文件', '1000px', '500px', tmpl);
                            avalon.scan(dialog.content(), vm);
                            return false;
                        }
                        CBCRM.loadModule('/Upload/Center')
                        CBCRM.onModuleReady = function (data) {
                            avalon.vmodels.upload.itemSelected = function (node, data, file) {
                                mvvm.entity.Attachment = '/upload/' + file.Path;
                                messageBox.close();
                            }
                        }
                    }

                    vm.tab = 'tab1'
                    vm.tabChange = function () {
                        vm.tab = $(this).attr('val')
                    }

                    vm.GroupData = []
                    vm.PostData = []

                    vm.getUsersData = function (ids) {
                        var model = {}
                        ids.forEach(function (item, i) {
                            model['ids[' + i + ']'] = item
                        })
                        model.planid = mvvm.entity.Id
                        $.get('/HR/GetUserByIds', model, function (ret) {
                            mvvm.planempList = ret.data
                        })
                    }

                    vm.doallarrive = function () {
                        var chkval = $(this).attr('checked')
                        $('input.chkarrive').each(function (i, item) {
                            item.checked = chkval
                        })
                        mvvm.planempList.$model.forEach(function (item, index) {
                            item.IsArrary = chkval == 'checked' ? true : false
                        })
                    }

                    vm.dosavearrive = function () {
                        var model = {}
                        var inochk = 0
                        mvvm.planempList.$model.forEach(function (item, index) {
                            if (item.IsArrary) {
                                index = index - inochk
                                model['TrainRecord[' + index + '].EmployeeId'] = item.Id
                                model['TrainRecord[' + index + '].TrainingProgram.Id'] = mvvm.entity.Id
                                model['TrainRecord[' + index + '].Id'] = item.RecordId
                            } else {
                                inochk++
                            }
                        })
                        $.post('/HR/TrainRecordAdd', model, function (ret) {
                            if (ret.result)
                                messageBox.ok('保存成功')
                        })
                    }
                    vm.destroy = function () {
                        if (avalon.vmodels.planempId)
                            avalon.vmodels.planempId.destroy()
                        if (avalon.vmodels.empId)
                            avalon.vmodels.empId.destroy()
                        if (avalon.vmodels.TrainPlan)
                            avalon.vmodels.TrainPlan = null
                    }
                })

                var queryData = {
                    keyword: '',
                    pageIndex: 1, pageSize: 20
                }
                mvvm.showItem = avalon.mix({}, queryData);
                function GetTrainPlanList(data) {
                    $.get('/HR/TrainPlan', data || {}, function (ret) {
                        mvvm.trainplanList = ret.data.Source
                        avalon.vmodels.upaing.total = ret.data.RecordTotal

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

                    })
                }
                function InitDictData() {
                    $.get('/HR/TrainPlanDictData', {}, function (ret) {
                        mvvm.classData = ret.data.ClassData
                        mvvm.categoryData = ret.data.CategoryData
                        mvvm.layData = ret.data.LayData
                        mvvm.objectData = ret.data.ObjectData
                        mvvm.methodData = ret.data.MethodData
                        mvvm.checkMethodData = ret.data.CheckMethodData
                        mvvm.GroupData = ret.data.GroupData
                        mvvm.PostData = ret.data.PostData
                    })


                }


                mvvm.entity = modelFactory.create('TrainPlan')
                InitDictData()

                avalon.filters.groupname = function (val) {
                    var name = ''
                    mvvm.GroupData.forEach(function (item) {
                        if (val == item.Id) {
                            name = item.Name
                        }
                    })
                    return name
                }
                avalon.filters.postname = function (val) {
                    var name = ''
                    mvvm.PostData.forEach(function (item) {
                        if (val == item.Id) {
                            name = item.Name
                        }
                    })
                    return name
                }

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

            //培训记录
            TrainRecord: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this
                var notMemberFilter = 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('trainrecord', function (vm) {
                    vm.lang = lang
                    vm.action = 'list'
                    vm.entity = {}
                    vm.trainrecordList = []
                    vm.trainrecordpaing = {
                        paging: function () {
                            var that = this
                            GetTrainRecordList({
                                pageSize: that.pagesize,
                                pageIndex: that.currentindex + 1
                            });
                        }
                    }

                    vm.ADD = false
                    vm.DELETE = false

                    vm.showItem = {}
                    vm.keyword = ''
                    vm.history = []
                    //关键字搜索
                    vm.search = function () {
                        if (mvvm.keyword) {
                            mvvm.showItem.keyword = mvvm.keyword
                            GetTrainRecordList(mvvm.showItem.$model)
                            if (mvvm.history.length = 3)
                                mvvm.history.removeAt(2)
                            mvvm.history.unshift(mvvm.keyword)
                        }
                    }
                    //历史搜索
                    vm.historyClick = function () {
                        mvvm.keyword = $(this).val()
                        mvvm.showItem.keyword = mvvm.keyword
                        GetTrainRecordList(mvvm.showItem.$model)
                    }
                    //清除
                    vm.clear = function () {
                        mvvm.keyword = ''
                        mvvm.showItem.keyword = mvvm.keyword
                        mvvm.showItem.tId = ''
                        GetTrainRecordList(mvvm.showItem.$model)
                    }

                    //评估
                    vm.doview = function (obj) {
                        var id = that.params.id ? that.params.id : $(this).val()
                        that.params.id = null
                        mvvm.trainrecordList.$model.forEach(function (item) {
                            if (item.Id == id) {
                                mvvm.entity = avalon.mix(modelFactory.create('TrainedRecord'), item)
                                GetTrainRecord(item.TrainingProgram.Id)
                                mvvm.action = 'view' + obj
                                vm.tab = 'tab1'
                                if (obj == 2) {
                                    var curr = CBCRM.memberShip
                                    mvvm.entity.EffectEvaluateBy = curr.Id
                                    mvvm.entity.EffectEvaluateByDisplay = curr.FullName
                                    mvvm.entity.EffectEvaluateTime = GetDateTime()
                                } else if (obj == 1) {
                                    if (!mvvm.entity.Satisfied) {
                                        mvvm.entity.Satisfied = 3
                                    }
                                }
                                mvvm.formSubmit('评估')
                            }
                        })
                    }

                    //删除
                    vm.dodel = function () {
                        var index = parseInt($(this).attr('index'))
                        var id = $(this).val()
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/HR/TrainRecordDel/' + id, {}, function (ret) {
                                if (ret.result)
                                    mvvm.trainrecordList.removeAt(index)
                                messageBox.succeed(ret.message)
                            })
                        });
                    }

                    //批量删除
                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.post('/HR/TrainRecordAllDel/', deleteIds, function (ret) {
                                if (ret.result) {
                                    GetTrainRecordList();
                                    messageBox.succeed(ret.message);
                                }
                            });
                        });
                    }

                    vm.formSubmit = function (title) {
                        var dialog = mvvm.openTmpl({
                            title: title, w: 950, h: 700,
                            tmplId: "formTemplate", tmpl: tmpl,
                            button: [{
                                name: '提交',
                                focus: true,
                                callback: function () {
                                    var model = mvvm.entity.$model
                                    model.IsEstimate = true
                                    model['TrainingProgram.Id'] = model.TrainingProgram.Id
                                    $.post('/HR/TrainRecordUpdate/' + model.Id, model, function (ret) {
                                        CBCRM.showResult(ret, function () {
                                            if (ret.result) {
                                                GetTrainRecordList(mvvm.showItem.$model)
                                                dialog.close()
                                            }
                                        })

                                    });
                                    return false
                                }
                            }]
                        });
                    }
                    //评估时间
                    vm.expressionEvaluateTimeOpts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.ExpressionEvaluateTime = formatDate
                        }
                    }

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

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

                    vm.tab = 'tab1'
                    vm.tabChange = function () {
                        vm.tab = $(this).attr('val')
                    }

                    vm.trainplanlist = []
                    vm.getTrainPlan = function () {
                        $.get('/HR/TrainPlan', {}, function (ret) {
                            mvvm.trainplanlist = ret.data.Source
                        })
                    }

                    vm.selectplan = function () {
                        var tid = $(this).val()
                        mvvm.showItem.tId = tid
                        GetTrainRecordList(mvvm.showItem.$model)
                    }
                })
                var queryData = {
                    keyword: '',
                    tId: '',
                    pageIndex: 1, pageSize: 20
                }
                mvvm.showItem = avalon.mix({}, queryData);
                function GetTrainRecordList(data) {
                    $.get('/HR/TrainRecord', data || {}, function (ret) {
                        mvvm.trainrecordList = ret.data.Source
                        avalon.vmodels.upaing.total = ret.data.RecordTotal

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

                        //查看评估
                        if (that.params.id) {
                            mvvm.doview('1')
                        }
                    })
                }
                function GetTrainRecord(id) {
                    $.get('/HR/TrainRecord/', { 'tId': id, 'pageSize': 2000 }, function (ret) {
                        var list = ret.data.Source
                        var data = [], names = []
                        list.forEach(function (n, i) {
                            names.push(n.EmployeeDisplay)
                        })
                        mvvm.entity.TrainingProgram.TrainedRecordDisplay = names.join(',')
                    })
                }
                mvvm.getTrainPlan()

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

            //员工关系
            Labor: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM
                var mvvm = CBCRM.define('Labor', function (vm) {
                    vm.lang = lang
                })
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            },

            //员工档案
            Archive: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM,
                    that = this,
                    OtherSkill,
                    Jiaoyu,
                    Gongzuo,
                    resumeDialog,avatarKey;
                function updateavatar() {
                    $.get("/Upload/GetCameraUrl", { akey: avatarKey }, function (ret) {
                        if (ret && ret.result) {
                            mvvm.entity.Picture = ret.data.url;
                            mvvm.closeCamera();
                        } else {
                            CBCRM.showResult(ret);
                        }
                    });
                }
                var mvvm = CBCRM.define('Archive', function (vm) {
                    vm.lang = lang
                    vm.$skipArray = ['lang']
                    vm.tab = 1
                    vm.tabChange = function () {
                        var val = parseInt($(this).attr('val'));
                        mvvm.tab = val
                    }
                    vm.viewTab = 1
                    vm.viewTabChange = function (val) {
                        mvvm.viewTab = val
                    }
                    vm.viewMenu = 1
                    vm.viewMenuChange = function (val) {
                        mvvm.tabs = 1;
                        mvvm.show = false;
                        mvvm.showNumder = 0;
                        mvvm.viewMenu = val
                        var url = "";
                        switch (val) {
                            case 5:
                                url = "/HR/Reward/" + mvvm.entity.Id + "/Archive";
                                break;
                            case 6:
                                url = "/HR/Integral/" + mvvm.entity.Id + "/Archive";
                                break;
                            case 7:
                                getDataList(mvvm.UserId);
                                getArchiveDataList(mvvm.UserId);
                                break;
                        }
                        if (url != "") {
                            goto(url, true);
                        }
                    }
                    vm.entity = {}
                    vm.list = []
                    vm.resumeList = []
                    vm.postlist = []
                    vm.postion = []
                    vm.ADD = true
                    vm.DELETE = true
                    vm.sendSms = CBCRM.sendSms;
                    //上下条
                    vm.hasPrevious = true;
                    vm.hasNext = true;
                    vm.previousId = '';
                    vm.nextId = '';
                    vm.previousLabel = '';
                    vm.nextLabel = '';
                    //搜索相关
                    vm.showItem = {}
                    vm.keyword = ''
                    vm.doSearch = function () {
                        mvvm.showItem.keyword = ''
                        mvvm.showItem.keyword = mvvm.showItem.keywordName = mvvm.keyword
                        initWithPageList(mvvm.showItem.$model)
                    }
                    vm.clear = function () {
                        mvvm.keyword = mvvm.showItem.keyword = mvvm.showItem.keywordName = ''
                        mvvm.showItem.edu = mvvm.showItem.eduName = ''
                        mvvm.showItem.marry = mvvm.showItem.marryName = ''
                        mvvm.showItem.status = mvvm.showItem.statusName = ''
                        mvvm.showItem.sex = mvvm.showItem.sexName = ''
                        mvvm.showItem.ru = mvvm.showItem.ruName = ''
                        mvvm.showItem.sheng = mvvm.showItem.shengName = ''
                        initWithPageList(mvvm.showItem.$model)
                    }
                    vm.remove = function () {
                        var val = $(this).attr('val');
                        switch (val) {
                            case "keyword": mvvm.showItem.keyword = mvvm.showItem.keywordName = ''; break;
                            case 'edu': mvvm.showItem.edu = mvvm.showItem.eduName = ''; break;
                            case 'marry': mvvm.showItem.marry = mvvm.showItem.marryName = ''; break;
                            case 'status': mvvm.showItem.status = mvvm.showItem.statusName = ''; break;
                            case 'sex': mvvm.showItem.sex = mvvm.showItem.sexName = ''; break;
                            case 'ru': mvvm.showItem.ru = mvvm.showItem.ruName = ''; break;
                            case 'sheng': mvvm.showItem.sheng = mvvm.showItem.shengName = ''; break;
                        }
                        initWithPageList(mvvm.showItem.$model)
                    }
                    vm.itemClick = function () {
                        var cate = $(this).attr('cate');
                        var index = $(this).attr('index');
                        switch (cate) {
                            case 'edu':
                                mvvm.showItem.edu = mvvm.showItem.eduName = '';
                                mvvm.showItem.edu = mvvm.degreeX[index].Id;
                                mvvm.showItem.eduName = mvvm.degreeX[index].Data;
                                mvvm.degreeX.forEach(function (item) { item.selected = false; })
                                mvvm.degreeX[index].selected = true;
                                break;
                            case 'marry':
                                mvvm.showItem.marry = mvvm.showItem.marryName = '';
                                mvvm.showItem.marry = mvvm.marryX[index].Id;
                                mvvm.showItem.marryName = mvvm.marryX[index].Data;
                                mvvm.marryX.forEach(function (item) { item.selected = false; })
                                mvvm.marryX[index].selected = true;
                                break;
                            case 'status':
                                mvvm.showItem.status = mvvm.showItem.statusName = '';
                                mvvm.showItem.status = mvvm.statusX[index].Id;
                                mvvm.showItem.statusName = mvvm.statusX[index].Data;
                                mvvm.statusX.forEach(function (item) { item.selected = false; })
                                mvvm.statusX[index].selected = true;
                                break;
                            case 'sex':
                                mvvm.showItem.sex = mvvm.showItem.sexName = '';
                                mvvm.showItem.sex = mvvm.sexX[index].Id;
                                mvvm.showItem.sexName = mvvm.sexX[index].Data;
                                mvvm.sexX.forEach(function (item) { item.selected = false; })
                                mvvm.sexX[index].selected = true;
                                break;
                            case 'ru':
                                mvvm.showItem.ru = mvvm.showItem.ruName = '';
                                mvvm.showItem.ru = mvvm.ruX[index].Id;
                                mvvm.showItem.ruName = mvvm.ruX[index].Data;
                                mvvm.ruX.forEach(function (item) { item.selected = false; })
                                mvvm.ruX[index].selected = true;
                                break;
                            case 'sheng':
                                mvvm.showItem.sheng = mvvm.showItem.shengName = '';
                                mvvm.showItem.sheng = mvvm.shengX[index].Id;
                                mvvm.showItem.shengName = mvvm.shengX[index].Data;
                                mvvm.shengX.forEach(function (item) { item.selected = false; })
                                mvvm.shengX[index].selected = true;
                                break;
                        }
                        initWithPageList(mvvm.showItem.$model)
                    }
                    vm.clearAllItem = function () {
                        mvvm.showItem.edu = mvvm.showItem.eduName = '';
                        mvvm.showItem.marry = mvvm.showItem.marryName = '';
                        mvvm.showItem.status = mvvm.showItem.statusName = '';
                        mvvm.showItem.ru = mvvm.showItem.ruName = '';
                        mvvm.showItem.sex = mvvm.showItem.sexName = '';
                        mvvm.showItem.sheng = mvvm.showItem.shengName = '';
                        $('.quickword a[value=""]').addClass('selected').siblings().removeClass('selected')
                        initWithPageList(mvvm.showItem.$model)
                    }

                    vm.viewResume = function (ResumeId) {
                        var url = '/HR/Resume/' + ResumeId + '/view';
                        goto(url, true);
                    }

                    vm.ethnic = [] //民族
                    vm.political = [] //政治面貌
                    vm.empCertificate = [] //职业资格证书
                    vm.degree = [] //学历
                    vm.degreeX = []
                    vm.marryX = [
                        { Id: '', Data: '不限', selected: true },
                        { Id: '0', Data: '未婚', selected: false },
                        { Id: '1', Data: '已婚', selected: false },
                        { Id: '2', Data: '离异', selected: false }
                    ]
                    vm.statusX = [
                        { Id: '', Data: '不限', selected: true },
                        { Id: '0', Data: '在职试用', selected: false },
                        { Id: '1', Data: '在职正式', selected: false },
                        { Id: '2', Data: '离职', selected: false },
                        { Id: '3', Data: '退休', selected: false },
                        { Id: '-1', Data: '只显在职', selected: false }
                    ]
                    vm.sexX = [
                        { Id: '', Data: '不限', selected: true },
                        { Id: '0', Data: '男', selected: false },
                        { Id: '1', Data: '女', selected: false },
                    ]
                    vm.typeX = [
                        { Id: '', Data: '不限', selected: true },
                        { Id: '0', Data: '正式工', selected: false },
                        { Id: '1', Data: '合同工', selected: false },
                        { Id: '2', Data: '临时工', selected: false },
                        { Id: '3', Data: '试用工', selected: false },
                        { Id: '4', Data: '兼职工', selected: false },
                    ]
                    vm.ruX = [
                        { Id: '', Data: '不限', selected: true },
                        { Id: '0', Data: '<1年', selected: false },
                        { Id: '1', Data: '>1年', selected: false },
                        { Id: '2', Data: '>2年', selected: false },
                        { Id: '3', Data: '>3年', selected: false },
                        { Id: '4', Data: '>4年', selected: false },
                    ]
                    vm.shengX = [
                        { Id: '', Data: '不限', selected: true },
                        { Id: '0', Data: '今天', selected: false },
                        { Id: '1', Data: '明天', selected: false },
                        { Id: '2', Data: '后天', selected: false },
                        { Id: '3', Data: '本月', selected: false },
                        { Id: '4', Data: '下月', selected: false },
                    ]
                    vm.title = [] //职称
                    vm.language = [] //语言
                    vm.langguageLv = [] //外语水平
                    vm.computerLv = [] //计算机水平
                    vm.driving = [] //驾照
                    vm.vehicle = [] //交通工具

                    //家庭关系
                    vm.family = []
                    vm.familyCheck = false;
                    vm.familyAdd = function () {
                        var model = modelFactory.create('EmployeeFamily');
                        model.Face = mvvm.political[0].Id;
                        mvvm.family.push(model);
                    }
                    vm.familyDel = function () {
                        var index = parseInt($(this).attr('index'));
                        mvvm.family.removeAt(index);
                    }
                    vm.familyDelAll = function () {
                        var arr = []
                        mvvm.family.forEach(function (item) { if (!item.Check) arr.push(item) })
                        mvvm.family = arr;
                        mvvm.familyCheck = false;
                    }
                    vm.$watch('familyCheck', function (n) {
                        mvvm.family.forEach(function (item) { item.Check = n; })
                    })
                    //培训经历
                    vm.train = []
                    vm.trainCheck = false;
                    vm.trainAdd = function () {
                        var model = modelFactory.create('EmployeeEducationHistory'),
                            sd, ed, index, container
                        model.Degree = mvvm.degree[0].Id
                        mvvm.train.push(model)
                        index = mvvm.train.size() - 1
                        container = $('#row' + index)
                        sd = $("#setStartDate" + index)
                        ed = $("#setEndDate" + index)
                        if (!avalon.vmodels['startDay' + index]) {
                            avalon.ui.date(sd, {
                                dateId: 'startDay' + index,
                                dateOptions: {
                                    $skipArray: ['icon', 'format'],
                                    format: '%Y-%m-%d',
                                    onSelect: function (date, formatDate, format) { },
                                    icon: '<img src="/Content/Themes/Base/Images/ico/day.gif" alt="点击选择日期" title="点击选择日期" style="cursor:pointer;position: relative;left: -18px;top: 5px;" />'
                                }
                            }, [mvvm, CBCRM])
                        }
                        if (!avalon.vmodels['endDay' + index]) {
                            avalon.ui.date(ed, {
                                dateId: 'endDay' + index,
                                dateOptions: {
                                    $skipArray: ['icon', 'format'],
                                    format: '%Y-%m-%d',
                                    onSelect: function (date, formatDate, format) { },
                                    icon: '<img src="/Content/Themes/Base/Images/ico/day.gif" alt="点击选择日期" title="点击选择日期" style="cursor:pointer;position: relative;left: -18px;top: 5px;" />'
                                }
                            }, [mvvm, CBCRM])
                        }
                    }
                    vm.trainDel = function () {
                        var index = parseInt($(this).attr('index'));
                        mvvm.train.removeAt(index);
                    }
                    vm.trainDelAll = function () {
                        var arr = []
                        mvvm.train.forEach(function (item) { if (!item.Check) arr.push(item) })
                        mvvm.train = arr;
                        mvvm.trainCheck = false;
                    }
                    vm.$watch('trainCheck', function (n) {
                        mvvm.train.forEach(function (item) { item.Check = n; })
                    })
                    //工作经历
                    vm.history = []
                    vm.historyCheck = false;
                    vm.historyAdd = function () {
                        var model = modelFactory.create('EmployeeWorkHistory');
                        mvvm.history.push(model);

                        var sd, ed, index, container;
                        index = mvvm.history.size() - 1
                        container = $('#his' + index)
                        sd = $("#hisStartDate" + index)
                        ed = $("#hisEndDate" + index)
                        if (!avalon.vmodels['startHisDay' + index]) {
                            avalon.ui.date(sd, {
                                dateId: 'startHisDay' + index,
                                dateOptions: {
                                    $skipArray: ['icon', 'format'],
                                    format: '%Y-%m-%d',
                                    onSelect: function (date, formatDate, format) { },
                                    icon: '<img src="/Content/Themes/Base/Images/ico/day.gif" alt="点击选择日期" title="点击选择日期" style="cursor:pointer;position: relative;left: -18px;top: 5px;" />'
                                }
                            }, [mvvm, CBCRM])
                        }
                        if (!avalon.vmodels['endHisDay' + index]) {
                            avalon.ui.date(ed, {
                                dateId: 'endHisDay' + index,
                                dateOptions: {
                                    $skipArray: ['icon', 'format'],
                                    format: '%Y-%m-%d',
                                    onSelect: function (date, formatDate, format) { },
                                    icon: '<img src="/Content/Themes/Base/Images/ico/day.gif" alt="点击选择日期" title="点击选择日期" style="cursor:pointer;position: relative;left: -18px;top: 5px;" />'
                                }
                            }, [mvvm, CBCRM])
                        }
                    }
                    vm.historyDel = function () {
                        var index = parseInt($(this).attr('index'));
                        mvvm.history.removeAt(index);
                    }
                    vm.historyDelAll = function () {
                        var arr = []
                        mvvm.history.forEach(function (item) { if (!item.Check) arr.push(item) })
                        mvvm.history = arr;
                        mvvm.historyCheck = false;
                    }
                    vm.$watch('historyCheck', function (n) {
                        mvvm.history.forEach(function (item) { item.Check = n; })
                    })
                    //亲属
                    vm.contract = []
                    vm.contractCheck = false
                    vm.contractAdd = function () {
                        var model = modelFactory.create('EmployeeKinsfolk');
                        mvvm.contract.push(model);
                    }
                    vm.contractDel = function () {
                        var index = parseInt($(this).attr('index'));
                        mvvm.contract.removeAt(index);
                    }
                    vm.contractDelAll = function () {
                        var arr = []
                        mvvm.contract.forEach(function (item) { if (!item.Check) arr.push(item) })
                        mvvm.contract = arr;
                        mvvm.contractCheck = false;
                    }
                    vm.$watch('contractCheck', function (n) {
                        mvvm.contract.forEach(function (item) { item.Check = n; })
                    })

                    //关联账号
                    vm.selectBelongTo = function () {
                        plugins.selectUser({
                            dataAuth: 6050100,
                            callback: function (us) {
                                var u = us[0];
                                mvvm.entity.DepartmentId = u.Id;
                                mvvm.entity.DepartmentName = u.UserName;
                                mvvm.entity.Name = u.FullName;
                                mvvm.entity.GroupId = u.GroupId
                                mvvm.entity.GroupName = u.GroupName
                                mvvm.entity.PostionId = u.PositionId
                                mvvm.entity.PostName = u.PositionName
                                mvvm.entity.MobileNumber = u.Phone
                                mvvm.entity.QQ = u.QQ
                                mvvm.entity.Email = u.Email
                                mvvm.entity.HomeTel = u.Tel
                            }
                        })
                    }
                    
                    //上级领导
                    vm.parentPostOpt = {
                        treeopts: {
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    if (treeNode.iconSkin !== 'emp') {
                                        alert('请选择直属上级领导'); return;
                                    }
                                    mvvm.entity.BossId = treeNode.Id;
                                    mvvm.entity.BossName = treeNode.Name;
                                }
                            },
                            async: {
                                url: "/Settings/GetGroupPostUser/6050100",
                                dataFilter: groupPostFilter
                            }
                        }
                    }
                    vm.currEmpIndex = 0
                    vm.setCons = function () {
                        var curItem = this.$vmodel,
                            index = curItem.$index,
                            panel = avalon.vmodels.conscientiousPersonTreepanel,
                            tree = avalon.vmodels.conscientiousPersonTree
                        mvvm.currEmpIndex = index
                        if (!panel) {
                            //具体战斗任务和相关采购计划-下拉负责人
                            avalon.ui.dropDownGroupPostUserTree(this, {
                                dropDownGroupPostUserTreeId: 'conscientiousPersonTree',
                                dropDownGroupPostUserTreeOptions: {
                                    treeopts: {
                                        callback: {
                                            onCheck: function (e, treeId, treeNode) {
                                                var currcombat = mvvm.contract[mvvm.currEmpIndex];
                                                currcombat.KinsfolkId = treeNode.Id;
                                                currcombat.KinsfolkName = treeNode.Name;
                                                currcombat.PostId = treeNode.Pid;
                                                currcombat.PostName = treeNode.PName;
                                                currcombat.DepartmentId = treeNode.Gid;
                                                currcombat.DepartmentName = treeNode.GName;
                                            }
                                        },
                                        async: {
                                            url: function (treeId, treeNode) {
                                                return "/Settings/GetGroupPostUser/2020000"
                                            },
                                            dataFilter: notMemberFilter
                                        },
                                        check: {
                                            enable: true,
                                            chkStyle: 'radio',
                                            radioType: "all"
                                        }
                                    }
                                },
                                initevent: false
                            }, this.$vmodels)
                            panel = avalon.vmodels.conscientiousPersonTreepanel
                            tree = avalon.vmodels.conscientiousPersonTree
                        } else {
                            panel.target = this
                        }
                        panel.toggle(true)
                    }
                    //日期控件
                    vm.dateOpts = {
                        format: '%Y-%m-%d  %H:%M',
                        onSelect: function (date, formatDate, format) { }
                    }
                    //生日
                    vm.bDateOpts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) { }
                    }
                    vm.userpaing = {
                        paging: function () {
                            var thatpage = this
                            mvvm.showItem.pageSize = thatpage.pagesize
                            mvvm.showItem.pageIndex = thatpage.currentindex + 1
                            if (that.params.key && that.params.key != 'groupid')
                                mvvm.showItem.keywordName = mvvm.showItem.keyword = mvvm.keyword = decodeURI(that.params.key)
                            else if (that.params.key == 'groupid') {
                                mvvm.showItem.groupid = that.params.id
                            }
                            initWithPageList(mvvm.showItem.$model);
                        }
                    }
                    //关联简历的分页
                    vm.resumeOpt = {
                        pagesize: 10,
                        pagesizeopts: [10, 20, 50, 100],
                        paging: function () {
                            var thatpage = this
                            var pageSize = thatpage.pagesize;
                            var pageIndex = thatpage.currentindex + 1
                            getResumeList({ pageIndex: pageIndex, pageSize: pageSize })
                        }
                    }
                    //选择部门
                    vm.postGroupTreeOpts = {
                        treeopts: {
                            async: {
                                enable: true,
                                url: '/Settings/GetGroupPostUser/9060000'
                            },
                            callback: {
                                onClick: function (event, treeId, treeNode) {
                                    mvvm.entity.GroupId = treeNode.Id
                                    mvvm.entity.GroupName = treeNode.Name
                                    mvvm.postion = treeNode.Posts
                                    if (treeNode.Posts.length) {
                                        mvvm.entity.PostionId = treeNode.Posts[0].Id
                                        mvvm.entity.PostionName = treeNode.Posts[0].Name
                                    }
                                    else {
                                        mvvm.entity.PostionId = ''
                                        mvvm.entity.PostionName = ''
                                    }
                                }
                            }
                        }
                    }
                    vm.gongzuoTmpl = "";
                    vm.jiaoyuTmpl = "";
                    vm.addUser = function () {
                        var url = "/Settings/Users/HR/add";
                        var p = {
                            callback: function (u,ret) {
                                var treeVm = avalon.vmodels["belongToTree"];
                                if (treeVm) treeVm.reload();
                            }
                        }
                        goto(url, true, p);
                    }
                    vm.doadd = function (cb) {
                        mvvm.tab = 1
                        mvvm.entity = modelFactory.create('Archive');
                        mvvm.entity.IsMarry += '';
                        mvvm.entity.Status += '';
                        mvvm.entity.Language = [];
                        mvvm.entity.EmployeeCertificate = [];
                        mvvm.entity.TitleOfarr = [];

                        mvvm.family = []
                        mvvm.train = []
                        mvvm.history = []
                        mvvm.contract = []
                        if (typeof (cb) == "function") formTemplate('新增档案', cb)
                        else formTemplate('新增员工档案')
                        var num = 'HR' + GetDateNumber() + '-' + (avalon.vmodels.upaing.total + 1)
                        mvvm.entity.FileNumber = num
                    }
                    vm.doedit = function () {
                        mvvm.tab = 1
                        var id = $(this).attr('val');
                        $.get('/HR/ArchiveDetail/' + id, {}, function (ret) {
                            if (!ret.result) return false;
                            var model = ret.data;
                            for (var key in model) {
                                var v = model[key];
                                if (typeof (v) == "string") {
                                    v = v.replace("00:00", "")
                                    model[key] = v
                                }
                            }
                            model.EmployeeCertificate = model.EmployeeCertificate.split(',');
                            model.TitleOfarr = model.TitleOfs.split(",");
                            mvvm.entity = model;
                            mvvm.entity.IsMarry += '';
                            mvvm.entity.Status += '';
                            mvvm.entity.Language = mvvm.entity.Language.split(',');
                            //mvvm.entity.EmployeeCertificate = mvvm.entity.EmployeeCertificate.split(',');
                            if (mvvm.entity.EmployeeFamily.length) {
                                mvvm.family = mvvm.entity.EmployeeFamily;
                            } else mvvm.family = []
                            mvvm.entity.EmployeeFamily = [];
                            if (mvvm.entity.EmployeeKinsfolk.length) {
                                mvvm.contract = mvvm.entity.EmployeeKinsfolk
                            } else mvvm.contract
                            mvvm.entity.EmployeeKinsfolk = []
                            if (mvvm.entity.GroupId) {
                                $.get('/Settings/GetPostToGroup/' + mvvm.entity.GroupId, {}, function (callback) {
                                    if (callback && callback.result) {
                                        mvvm.postion = callback.data
                                    }
                                })
                            }
                            formTemplate('编辑员工档案')
                        });
                    }
                    vm.dodel = function () {
                        var index = parseInt($(this).attr('index'))
                        var id = $(this).attr('val');
                        messageBox.confirm('确定删除此数据吗？', function () {
                            mvvm.list.removeAt(index);
                            $.get('/HR/ArchiveDelete/' + id, {}, function () { })
                        })
                    }
                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.post('/HR/ArchiveAllDelete/', deleteIds, function (ret) {
                                if (ret.result) {
                                    initWithPageList();
                                    messageBox.succeed(ret.message);
                                }
                            });
                        });
                    }
                    vm.UserId = 0


                    vm.doview = function (id) {
                        mvvm.UserId = id
                        mvvm.viewTab = 1
                        mvvm.viewMenu = 1
                        var url = '/HR/ArchiveDetail/' + id
                        $.get(url, function (ret) {
                            var model = ret.data;
                            model.TitleOfarr = model.TitleOfs.split(",");
                            model.Language = model.Language.split(',');
                            model.EmployeeCertificate = model.EmployeeCertificate.split(',');
                            mvvm.entity = model;

                            mvvm.hasPrevious = ret.data.hasPrevious;
                            mvvm.previousId = ret.data.previousId;
                            mvvm.previousLabel = ret.data.previousLabel;
                            mvvm.hasNext = ret.data.hasNext;
                            mvvm.nextId = ret.data.nextId;
                            mvvm.nextLabel = ret.data.nextLabel;
                            mvvm.entity.IsMarry += '';
                            mvvm.entity.Status += '';
                            //mvvm.entity.Language = mvvm.entity.Language.split(',');
                            //mvvm.entity.EmployeeCertificate = mvvm.entity.EmployeeCertificate.split(',');
                            if (mvvm.entity.EmployeeFamily.length) {
                                mvvm.family = mvvm.entity.EmployeeFamily;
                            } else mvvm.family = []
                            mvvm.entity.EmployeeFamily = [];
                            if (mvvm.entity.EmployeeKinsfolk.length) {
                                mvvm.contract = mvvm.entity.EmployeeKinsfolk
                            } else mvvm.contract
                            mvvm.entity.EmployeeKinsfolk = []
                            if (mvvm.entity.GroupId) {
                                $.get('/Settings/GetPostToGroup/' + mvvm.entity.GroupId, {}, function (callback) {
                                    if (callback && callback.result) {
                                        mvvm.postion = callback.data
                                    }
                                })
                            }

                            if (mvvm.entity.DepartmentId) {
                                mvvm.getOtherList(mvvm.entity.Id)
                            }
                            viewTemplate('查看档案');
                        })
                        
                    }
                    vm.getOtherList = function (archiveId) {
                        $.get('/HR/LabourContract', { 'empid': archiveId }, function (ret) {
                            mvvm.laborList = ret.data.Source
                        })
                        $.get('/HR/PostChange', { 'empid': archiveId }, function (ret) {
                            mvvm.postchangeList = ret.data.Source
                        })
                        $.get('/HR/Communication', { 'empid': archiveId }, function (ret) {
                            mvvm.communicationList = ret.data.Source
                        })
                    }
                    vm.uploadPic = function () {
                        var updialog = CBCRM.upload(true, function (node, data, file) {
                            mvvm.entity.Picture = '/upload/' + file.Path;
                            updialog.close();
                        });
                    }
                    vm.$cameraDialog = null;
                    vm.openCamera = function () {
                        avatarKey = "a" + Math.random();
                        window.updateavatar = updateavatar;
                        var html = "<div id='dCamera' style='width:480,height:260'></div>"
                        mvvm.$cameraDialog = openTmpl({
                            vm: mvvm, title: "拍照", w: 480, h: 260,
                            tmplid:html,iscontent:true
                        });
                        var swf = "/Content/Themes/Base/Swf/camera.swf";
                        var flashVars = {
                            nt: 1,
                            inajax: 1,
                            appid: 1,
                            input: avatarKey,
                            agent: "",
                            ucapi: document.location.protocol + "//" + document.location.host + "/Upload/Camera" /*?MySession=" + $.cookie('MySession')+"&_t=1"*/,
                            avatartype: "virtual"
                        };
                        var param = {
                            allowScriptAccess: "always",
                            bgcolor:"#ffffff"
                        }
                        var swfobj = swfobject.embedSWF(swf, "dCamera", "470", "250", "10.0.0", swf, flashVars, param);
                    }
                    vm.closeCamera = function () {
                        if (mvvm.$cameraDialog) {
                            mvvm.$cameraDialog.close();
                            mvvm.$cameraDialog = null;
                        }
                    }
                    //状态修改
                    vm.dostate = function () {
                        var statedialog = messageBox.openHtml('在职状态', '400px', '100px', '', [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var model = mvvm.entity.$model
                                var herf = "/HR/ArchiveUpdate/" + model.Id
                                $.post(herf, model, function (ret) {
                                    if (ret.result) {
                                        messageBox.ok('状态设置成功')
                                        statedialog.close()
                                    }
                                });
                                return false
                            }
                        }])
                        var content = $(statedialog.content())
                        var inputTmpl = $(tmpl).find("#stateTemplate").text();
                        content.html(inputTmpl);
                        avalon.scan(content[0], mvvm)
                    }
                    //打印
                    vm.doPrint = function () {
                        messageBox.confirm('您确定要打印当前档案信息吗？', function () {
                            $("#productPanelPrint").printArea()
                        })
                    }
                    //打开关联简历
                    vm.openResume = function () {
                        CBCRM.loadView('/HR/ArchiveResume.html?v=1.0', function (tmpl) {
                            resumeDialog = messageBox.openHtml('关联简历', '700px', '450px', tmpl);
                            avalon.scan(resumeDialog.content(), mvvm)
                            avalon.nextTick(function () {
                                getResumeList({})
                            });
                        })
                    }
                    //选择关联简历
                    vm.selectResume = function (item) {
                        //选中简历后关联一些数据
                        var entity = mvvm.entity;
                        entity.ResumeId = item.Id
                        entity.ResumeName = item.Name
                        entity.Height = item.Height
                        entity.Name = item.Name
                        entity.Sex = item.Sex
                        entity.Picture = item.HeadPortrait ? item.HeadPortrait : ''
                        entity.Birthday = avalon.filters.truncate(item.Birthday, 10, '')
                        entity.IDCardNumber = item.IDCardNumber
                        entity.NativePlace = item.Register
                        entity.GraduatedFrom = item.GraduateSchool
                        entity.GraduatedDay = avalon.filters.truncate(item.Graduate, 10, '')
                        entity.Profession = item.Profession
                        entity.Degree = item.Degree
                        entity.DrivingLicenseId = item.DrivingLicenseId
                        entity.VehicleId = item.VehicleId
                        entity.ComputerLevel = item.Computer
                        entity.Myinfo = item.Introduce
                        entity.QQ = item.QQ
                        entity.Email = item.Email

                        OtherSkill.html(item.Skill)
                        Jiaoyu.html(item.Educations)
                        Gongzuo.html(item.Works)

                        if (resumeDialog) resumeDialog.close()
                    }

                    vm.laborList = []
                    vm.postchangeList = []
                    vm.communicationList = []

                    //人事合同
                    vm.dodelLabor = function () {
                        var index = parseInt($(this).attr('index'))
                        var id = $(this).val()
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/HR/LabourContractDel/' + id, {}, function (ret) {
                                if (ret.result)
                                    mvvm.laborList.removeAt(index)
                                messageBox.succeed(ret.message)
                            })
                        });
                    }
                    vm.doalldelLabor = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.post('/HR/LabourContractAllDel/', deleteIds, function (ret) {
                                if (ret.result) {
                                    $.get('/HR/LabourContract/', { 'empid': mvvm.entity.DepartmentId }, function (ret) {
                                        mvvm.laborList = ret.data.Source
                                    })
                                    messageBox.succeed(ret.message);
                                }
                            });
                        });
                    }

                    vm.doaddLabor = function () {
                        var arcid = $(this).val()
                        goto('/HR/LabourContract/' + arcid + '/add')
                    }
                    vm.doeditLabor = function () {
                        var id = $(this).val()
                        goto('/HR/LabourContract/' + id + '/edit')
                    }
                    vm.doviewLabor = function () {
                        var id = $(this).val()
                        goto('/HR/LabourContract/' + id + '/view')
                    }
                    //人事调动
                    vm.dodelPostChange = function () {
                        var index = parseInt($(this).attr('index'))
                        var id = $(this).val()
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/HR/PostChangeDel/' + id, {}, function (ret) {
                                if (ret.result)
                                    mvvm.postchangeList.removeAt(index)
                                messageBox.succeed(ret.message)
                            })
                        });
                    }
                    vm.doalldelPostChange = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.post('/HR/PostChangeAllDel/', deleteIds, function (ret) {
                                if (ret.result) {
                                    $.get('/HR/LabourContract/', { 'empid': mvvm.entity.DepartmentId }, function (ret) {
                                        mvvm.postchangeList = ret.data.Source
                                    })
                                    messageBox.succeed(ret.message);
                                }
                            });
                        });
                    }

                    vm.doaddPostChange = function () {
                        var arcid = $(this).val()
                        goto('/HR/PostChange/' + arcid + '/add')
                    }
                    vm.doeditPostChange = function () {
                        var id = $(this).val()
                        goto('/HR/PostChange/' + id + '/edit')
                    }
                    vm.doviewPostChange = function () {
                        var id = $(this).val()
                        goto('/HR/PostChange/' + id + '/view')
                    }
                    //员工沟通
                    vm.dodelCommunication = function () {
                        var index = parseInt($(this).attr('index'))
                        var id = $(this).val()
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/HR/CommunicationDel/' + id, {}, function (ret) {
                                if (ret.result)
                                    mvvm.communicationList.removeAt(index)
                                messageBox.succeed(ret.message)
                            })
                        });
                    }
                    vm.doalldelCommunication = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.post('/HR/CommunicationAllDel/', deleteIds, function (ret) {
                                if (ret.result) {
                                    $.get('/HR/Communication/', { 'empid': mvvm.entity.DepartmentId }, function (ret) {
                                        mvvm.communicationList = ret.data.Source
                                    })
                                    messageBox.succeed(ret.message);
                                }
                            });
                        });
                    }

                    vm.doaddCommunication = function () {
                        var arcid = $(this).val()
                        goto('/HR/Communication/' + arcid + '/add')
                    }
                    vm.doeditCommunication = function () {
                        var id = $(this).val()
                        goto('/HR/Communication/' + id + '/edit')
                    }
                    vm.doviewCommunication = function () {
                        var id = $(this).val()
                        goto('/HR/Communication/' + id + '/view')
                    }

                    //展开、收起
                    vm.isExp = true;
                    vm.expanCategory = function () {
                        mvvm.isExp = !mvvm.isExp;
                        $(this).text(mvvm.isExp ? "- 收起" : "+ 展开");
                        var tree = $.fn.zTree.getZTreeObj("organizationTree");
                        if (tree) {
                            var nodes = tree.getNodes();
                            if (nodes.length > 0) tree.expandNode(nodes[0], mvvm.isExp, true);
                            if (!mvvm.isExp) tree.expandNode(nodes[0], !mvvm.isExp, false);
                        }
                    }
                    //组织架构
                    vm.groupTreeOpts = {
                        treeopts: {
                            async: {
                                enable: true,
                                url: '/Settings/GetGroupPostUser/9060000'
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    mvvm.showItem.groupid = treeNode.Id
                                    initWithPageList(mvvm.showItem.$model)
                                }
                            },
                            view: {
                                addHoverDom: false,
                                removeHoverDom: false
                            }
                        }
                    }

                    /*地图标注*/
                    vm.companyEntity = {};
                    vm.$mapLoaded = false;
                    vm.$map = null;
                    vm.loadMap = function (callback) {
                        var _t = null;
                        if (!mvvm.$mapLoaded) {
                            var win = CBCRM.loading("", "地图加载中……");
                            _t = window.setTimeout(function () {
                                if (win) win.close();
                                messageBox.warning("加载地图超时！<br />请确认您是否已经联网。");
                            }, 10 * 1000);
                        }
                        require(["bdmapTool", "ready!"], function (bdmapTool) {
                            mvvm.$mapLoaded = true;
                            if (win) win.close();
                            if (_t) window.clearTimeout(_t);
                            var map = mvvm.$map || new bdmapTool();
                            mvvm.$map = map;
                            if (callback) callback(map, bdmapTool);
                        });
                    }
                    vm.markInMap = function () {
                        mvvm.loadMap(function (map, bdmapTool) {
                            function _callBack(p, box) {
                                mvvm.entity.Address = p.address;
                                mvvm.entity.Lng = p.point.lng;
                                mvvm.entity.Lat = p.point.lat;
                                box.close();
                            }
                            var cmyInfo = CBCRM.cmyInfo;
                            var point, city = cmyInfo.CityDisplay;
                            if (",市辖区,县,".indexOf(city) > -1 || city == "") city = cmyInfo.ProvinceDisplay;
                            if (cmyInfo && cmyInfo.Lng) {
                                point = new BMap.Point(cmyInfo.Lng, cmyInfo.Lat);
                            } else {
                                point = null;
                            }
                            map.setOps({
                                tmpl: "search",
                                left: 285,
                                right: $(window).width() - 385,
                                pointCallBack: _callBack,
                                searchCallBack: _callBack,
                                city: city,
                                point: point
                            });
                            map.openMap(function () {
                                var name = cmyInfo.CompanyName;
                                var address = cmyInfo.Address;
                                if (point) {
                                    map.addMarker(point, name, { html: name, ops: { width: 250 } });
                                } else {
                                    if (address != "") {
                                        map.searchMap(address);
                                    }
                                }
                            });
                        });
                    }
                    //查看地图
                    vm.showMap = function () {
                        var m = mvvm.entity;
                        var point = new BMap.Point(m.Lng, m.Lat);
                        mvvm.loadMap(function (map, bdmapTool) {
                            map.setOps({
                                tmpl: "view",
                                point: point,
                                left: 0,
                                right: $(window).width() - 100
                            })
                            map.openMap(function () {
                                map.addMarker(point, m.Name);
                            });
                        });
                    }
                    vm.getCompany = function () {
                        $.get('/Settings/DetailCompanyInfo/', {}, function (ret) {
                            if (ret.result && ret.data.model) {
                                mvvm.companyEntity = ret.data.model;
                            }
                            else
                                mvvm.companyEntity = factory.create('CompanyInfo');
                        });
                    }


                    vm.show = 0;
                    vm.searchDay = '';
                    vm.searchMonth = '';
                    vm.searchYear = '';
                    vm.starTime = '';
                    vm.endTime = '';
                    vm.dateOpts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.StartDay = formatDate;
                            mvvm.StartDate = formatDate;
                            mvvm.EndDate = formatDate;
                        }
                    }

                    vm.MonthOpts = {
                        format: '%Y-%m',
                        onSelect: function (date, formatDate, format) {
                        }
                    }
                    vm.YearOpts = {
                        format: '%Y',
                        onSelect: function (date, formatDate, format) {
                        }
                    }
                    //查询日期范围
                    vm.rdSelect = function (type) {
                        mvvm.show = type;
                        switch (type) {
                            case 0:
                                mvvm.searchMonth = '';
                                mvvm.searchYear = '';
                                mvvm.starTime = '';
                                mvvm.endTime = '';
                                break;
                            case 1:
                                mvvm.searchDay = '';
                                mvvm.searchYear = '';
                                mvvm.starTime = '';
                                mvvm.endTime = '';
                                break;
                            case 2:
                                mvvm.searchDay = '';
                                mvvm.searchMonth = '';
                                mvvm.starTime = '';
                                mvvm.endTime = '';
                                break;
                            case 3:
                                mvvm.searchDay = '';
                                mvvm.searchMonth = '';
                                mvvm.searchYear = '';
                                break;
                        }
                    }

                    vm.show = false;
                    vm.showTable = false;
                    vm.MonthOpts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                        }
                    }

                    vm.tabs = 1;
                    vm.tabChanges = function () {
                        var val = $(this).attr("val");
                        mvvm.tabs = val;
                    }
                    vm.bTime = GetDateTime(new Date(new Date().getFullYear(), new Date().getMonth(), 1), "yyyy-MM-dd");
                    vm.eTime = GetDateTime(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0), "yyyy-MM-dd");
                    vm.starTime = GetDateTime(new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1), "yyyy-MM-dd");
                    vm.endTime = GetDateTime(new Date(new Date().getFullYear(), new Date().getMonth(), 0), "yyyy-MM-dd");
                    vm.dateVal = 0
                    vm.TimeTypeOne = 0
                    vm.TimeTypeTwo = 0
                    vm.search = function () {
                        getDataList(mvvm.UserId);
                        getArchiveDataList(mvvm.UserId);
                    }



                    vm.showNumder = 0
                    vm.EmployeeId = 0
                    vm.EmployeeName = ""
                    //员工OK
                    vm.employeeTreeOpts = {
                        treeopts: {
                            callback: {
                                onCheck: function (e, treeId, treeNode) {
                                    mvvm.EmployeeId = treeNode.Id
                                    mvvm.EmployeeName = treeNode.Name
                                    var treeobj = $.fn.zTree.getZTreeObj(treeId)
                                    var arr = treeobj.transformToArray(treeobj.getNodes())
                                    arr.forEach(function (item) {
                                    })
                                }
                            },
                            check: {
                                enable: true,
                                chkStyle: 'radio',
                                radioType: "all"
                            },
                            async: {
                                url: function (treeId, treeNode) {
                                    //return "/HR/GetGroupPostArchive/6050100"
                                    var url = '/Settings/GetGroupPostUser/4040000'
                                    vmtree = avalon.vmodels.employeeTreeId
                                    if (vmtree && vmtree.q && vmtree.q !== vmtree.qcopy) {
                                        url += '?empName=' + vmtree.q
                                    }
                                    return url
                                },
                                dataFilter: notMemberFilter
                            }
                        }
                    }


                    vm.ArchiveTagList = []
                    vm.ArchiveList = []
                    vm.ArchiveModelList = []
                    function getDataList(UserId) {
                        mvvm.ArchiveTagList = []
                        mvvm.ArchiveList = []
                        $.post('/HR/ArchiveStat',
                            { userOneId: UserId, userTwoId: mvvm.EmployeeId, type: mvvm.show, bTime: mvvm.bTime, eTime: mvvm.eTime, sTime: mvvm.starTime, dTime: mvvm.endTime },
                            function (ret) {
                                if (ret.result) {
                                    var data = ret.data;
                                    mvvm.ArchiveModelList = data.UserList;
                                    mvvm.ArchiveTagList = data.ArchiveTagList;
                                    mvvm.ArchiveList = data.ArchiveList;
                                }
                            });
                    }

                })

                mvvm.$watch("TimeTypeOne", function (n) {
                    mvvm.dateVal = n;
                    mvvm.TimeTypeTwo = n;
                    var now = new Date();
                    var nows = new Date();
                    var y = now.getFullYear(), m = now.getMonth(), d = now.getDay();
                    var begin;
                    var end
                    switch (n) {
                        case "0":
                            begin = new Date(y, m, 1);
                            end = new Date(y, m + 1, 0);
                            break;
                        case "1":
                            begin = now;
                            end = nows;
                            break;
                        case "2":
                            begin = Getweekstart(now);
                            end = Getweekend(nows);
                            break;
                        case "3":
                            begin = GetQuarterStartDate(now);
                            end = GetQuarterEndDate(nows);
                            break;
                        case "4":

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

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

                function getArchiveDataList(UserId) {
                    mvvm.ArchiveTagList = []
                    mvvm.ArchiveList = []
                    $.post('/HR/ArchiveAnalysis', { userOneId: UserId, userTwoId: mvvm.EmployeeId, dateType: mvvm.TimeTypeOne, dateType2: mvvm.TimeTypeTwo, bTime: mvvm.bTime, eTime: mvvm.eTime, sTime: mvvm.starTime, dTime: mvvm.endTime, compare: mvvm.show, showNumder: mvvm.showNumder }, function (result) {
                        if (result.data) {
                            require(['jqPlot', 'jqBar', 'jqPointLabels', 'jqCategory', 'jqCanvasText', 'jqCanvasAxisLabel', 'jqPointLabel', 'jqEnhancedLegend'], function () {
                                createLineChart(result.data.chartData1, "chart_sign", 700, 250);
                            });
                        }
                    })
                }

                //线性图
                function createLineChart(chartData, chartId, width, height) {
                    var data = [], series = [], cats = [], index;
                    cats = chartData.categories[0].category;
                    chartData.dataset.forEach(function (item) {
                        var arr = [];
                        series.push({
                            color: item.color ? "#" + item.color : null,
                            label: item.seriesname
                        });
                        index = 0;
                        item.data.forEach(function (d) {
                            var a = [cats[index].label, d.value];
                            arr.push(a);
                            index++;
                        });
                        data.push(arr);
                    })
                    var ops = {
                        title: chartData.chart.caption,
                        series: series,
                        seriesDefaults: {
                            rendererOptions: { fillToZero: true },
                            // Rotate the bar shadow as if bar is lit from top right.
                            shadowAngle: 135
                        },
                        legend: {
                            show: true,
                            placement: 'outsideGrid'
                        },
                        axes: {
                            xaxis: {
                                renderer: $.jqplot.CategoryAxisRenderer
                            }
                        }
                    };
                    var dChart = $("#" + chartId).empty();
                    if (width) dChart.width(width);
                    try {
                        dChart.jqplot(data, ops);
                    } catch (ex) {
                        dChart.html("<p class='nodata'>" + ex.message + "</p>")
                    }
                    return;
                    var charts = {
                        chart: {
                            anchorRadius: '5',
                            baseFontSize: '12',
                            numdivlines: '4',
                            numberSuffix: '',
                            lineThickness: '2',
                            showValues: '0',
                            numVDivLines: '12',
                            formatNumberScale: '0',
                            labelDisplay: 'ROTATE',
                            bgColor: 'FFFFFF',
                            slantLabels: '1',
                            anchorRadius: '2',
                            anchorBgAlpha: '50',
                            showAlternateVGridColor: '1',
                            anchorAlpha: '100',
                            showBorder: '0',
                            animation: '1',
                            limitsDecimalPrecision: '0',
                            divLineDecimalPrecision: '1'
                        },
                        categories: chartData.categories,
                        dataset: chartData.dataset
                    }
                    if (chartData.chart) {
                        $.extend(charts.chart, chartData.chart);
                    }
                    //MSLine
                    //Column3D
                    if (width && height) {
                        var myChart = new FusionCharts("/Scripts/Charts/Charts/MSLine.swf", "funnelChart_" + chartId, width, height);
                    } else {
                        var myChart = new FusionCharts("/Scripts/Charts/Charts/MSLine.swf", "funnelChart_" + chartId);
                    }
                    myChart.setJSONData(charts);
                    myChart.render(chartId);
                }
                var action = that.params.action

                var queryData = {
                    pageIndex: '', pageSize: '',
                    edu: '', eduName: '',
                    marry: '', marryName: '',
                    sex: '', sexName: '',
                    ru: '', ruName: '',
                    status: '', statusName: '',
                    sheng: '', shengName: '',
                    keyword: '', keywordName: '',
                    groupid: ''
                }
                mvvm.showItem = avalon.mix({}, queryData);

                //查询部门
                function initWithPageList(data) {
                    $.get('/HR/Archive', data || {}, function (ret) {
                        mvvm.list = ret.data.Source
                        mvvm.ADD = ret.data.ADD
                        mvvm.DELETE = ret.data.DELETE
                        avalon.vmodels.upaing.total = ret.data.RecordTotal //分页总数
                    });
                }
                function getResumeList(data) {
                    $.get('/HR/ArchiveResume', data || {}, function (ret) {
                        if (ret.result) {
                            mvvm.resumeList = ret.data.Source
                            avalon.vmodels.resume.total = ret.data.RecordTotal
                        }
                    })
                }
                function getQueryPost(id) {
                    $.get('/Settings/GetPost/' + id, {}, function (ret) { mvvm.postlist = ret.data; })
                }
                function getDictionary() {
                    $.get('/HR/ArchiveGetDictionary', {}, function (ret) {
                        mvvm.title = ret.data.title
                        mvvm.language = ret.data.language
                        mvvm.empCertificate = ret.data.empCertificate

                        mvvm.ethnic = ret.data.ethnic
                        mvvm.ethnic.unshift({ Id: '', Data: '请选择' })
                        mvvm.political = ret.data.political
                        mvvm.political.unshift({ Id: '', Data: '请选择' })
                        mvvm.degree = ret.data.degree
                        mvvm.degree.unshift({ Id: '', Data: '请选择' })
                        mvvm.langguageLv = ret.data.langguageLv
                        mvvm.langguageLv.unshift({ Id: '', Data: '请选择' })
                        mvvm.computerLv = ret.data.computerLv
                        mvvm.computerLv.unshift({ Id: '', Data: '请选择' })
                        mvvm.driving = ret.data.driving
                        mvvm.driving.unshift({ Id: '', Data: '请选择' })
                        mvvm.vehicle = ret.data.vehicle
                        mvvm.vehicle.unshift({ Id: '', Data: '请选择' })
                        ret.data.degree.unshift({ Id: '', Data: '不限', selected: true });
                        mvvm.degreeX = ret.data.degree;
                    });
                }
                getDictionary();
                //mvvm.getCompany();
                //新增和编辑
                function formTemplate(title, cb) {
                    CBCRM.loadView('/HR/ArchiveForm.html', function (tmpl) {
                        mvvm.gongzuoTmpl = $(tmpl).filter("#GongzuoTmpl").text();
                        mvvm.jiaoyuTmpl = $(tmpl).filter("#JiaoyuTmpl").text();
                        var button=[{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var model = mvvm.entity.$model;
                                if (model.Name) {
                                    model.Language = model.Language.toString()
                                    model.EmployeeCertificate = model.EmployeeCertificate.toString()
                                    model.TitleOfs = model.TitleOfarr.toString();
                                    //家庭成员
                                    if (mvvm.family.length) {
                                        mvvm.family.forEach(function (item, i) {
                                            model["EmployeeFamily[" + i + "].Contract"] = item.Contract;
                                            model["EmployeeFamily[" + i + "].Name"] = item.Name;
                                            model["EmployeeFamily[" + i + "].Age"] = item.Age;
                                            model["EmployeeFamily[" + i + "].Face"] = item.Face;
                                            model["EmployeeFamily[" + i + "].Tel"] = item.Tel;
                                            model["EmployeeFamily[" + i + "].Work"] = item.Work;
                                            model["EmployeeFamily[" + i + "].Post"] = item.Post;
                                        });
                                    }
                                    else delete model.EmployeeFamily;
                                    //亲属关系
                                    if (mvvm.contract.length) {
                                        mvvm.contract.forEach(function (item, i) {
                                            model["EmployeeKinsfolk[" + i + "].KinsfolkId"] = item.KinsfolkId
                                            model["EmployeeKinsfolk[" + i + "].KinsfolkName"] = item.KinsfolkName
                                            model["EmployeeKinsfolk[" + i + "].DepartmentId"] = item.DepartmentId
                                            model["EmployeeKinsfolk[" + i + "].DepartmentName"] = item.DepartmentName
                                            model["EmployeeKinsfolk[" + i + "].PostId"] = item.PostId
                                            model["EmployeeKinsfolk[" + i + "].PostName"] = item.PostName
                                            model["EmployeeKinsfolk[" + i + "].Relation"] = item.Relation
                                        })
                                    }
                                    else delete model.EmployeeKinsfolk;

                                    model.OtherSkill = OtherSkill.html()
                                    model.Jiaoyu = Jiaoyu.html()
                                    model.Gongzuo = Gongzuo.html()

                                    var url = model.Id == 0 ? "/HR/ArchiveAdd/" : "/HR/ArchiveUpdate/" + model.Id;
                                    $.post(url, model, function (ret) {
                                        if (ret.result) {
                                            messageBox.ok(ret.message, function () {
                                                initWithPageList()
                                                dialog.close()
                                            });
                                        } else messageBox.error(ret.message);
                                    });
                                }
                                else messageBox.warning('请填写员工姓名');
                                return false
                            }
                        }];
                        var dialog=openTmpl({
                            vm:mvvm,title:title,w:900,h:630,
                            tmplId:tmpl,isContent:true,button:button,
                            onClose: function () {
                            if (avalon.vmodels.belongToTree)
                                avalon.vmodels.belongToTree.destroy()
                            if (avalon.vmodels.parentPost)
                                avalon.vmodels.parentPost.destroy()
                            if (avalon.vmodels.setGroup)
                                avalon.vmodels.setGroup.destroy()
                            if (avalon.vmodels.employeeTreeId)
                                avalon.vmodels.employeeTreeId.destroy()
                            }, 
                            onScan:function(){
                                OtherSkill = setEditerSimple('OtherSkill', '760px', '60px')
                                OtherSkill.html(mvvm.entity.OtherSkill)
                                Jiaoyu = setEditerSimple('Jiaoyu', '760px', '230px')
                                if (!mvvm.entity.Id) mvvm.entity.Jiaoyu = mvvm.jiaoyuTmpl;
                                Jiaoyu.html(mvvm.entity.Jiaoyu)
                                Gongzuo = setEditerSimple('Gongzuo', '760px', '230px')
                                if (!mvvm.entity.Id) mvvm.entity.Gongzuo = mvvm.gongzuoTmpl;
                                Gongzuo.html(mvvm.entity.Gongzuo)
                                if (typeof (cb) == "function") cb();
                            }
                        })
                    });
                }
                function viewTemplate(title) {
                    CBCRM.loadView('/HR/ArchiveView.html', function (tmpl) {
                        var dialog = art.dialog.list['archiveviewdetails']
                        if (!dialog) {
                            dialog = messageBox.openHtml(title, '900px', '650px', tmpl, null,
                                 function () {
                                     if (avalon.vmodels.employeeTreeId)
                                         avalon.vmodels.employeeTreeId.destroy()
                                 }, function () { }, 'archiveviewdetails')
                        }
                        avalon.scan(dialog.content(), mvvm)
                        avalon.nextTick(function () {
                            $(dialog.content()).css('padding', '0px');
                        })
                    })
                }
                //过滤器
                avalon.filters.status = function (val) {
                    var res = '';
                    switch (parseInt(val)) {
                        case 0: res = "试用"; break;
                        case 1: res = "正式"; break;
                        case 2: res = "离职"; break;
                        case 3: res = "退休"; break;
                    }
                    return res;
                }
                avalon.filters.marrys = function (val) {
                    var res = '';
                    switch (parseInt(val)) {
                        case 0: res = "未婚"; break;
                        case 1: res = "已婚"; break;
                        case 2: res = "离异"; break;
                    }
                    return res;
                }
                avalon.filters.ethnic = function (val) {
                    var res = '';
                    mvvm.ethnic.forEach(function (item) { if (item.Id == parseInt(val)) res = item.Data; })
                    return res;
                }
                avalon.filters.political = function (val) {
                    var res = '';
                    mvvm.political.forEach(function (item) { if (item.Id == parseInt(val)) res = item.Data; })
                    return res;
                }
                avalon.filters.degree = function (val) {
                    var res = '';
                    mvvm.degree.forEach(function (item) { if (item.Id == parseInt(val)) res = item.Data; })
                    return res;
                }
                avalon.filters.certificate = function (array) {
                    var res = '';
                    if (array.length) {
                        array.forEach(function (item) {
                            mvvm.empCertificate.forEach(function (emp) {
                                if (emp.Id == item) res += emp.Data + ','
                            });
                        });
                    }
                    return res;
                }
                avalon.filters.title = function (array) {
                    var res = '';
                    if (array.length) {
                        array.forEach(function (item) {
                            mvvm.title.forEach(function (emp) {
                                if (emp.Id == item) res += emp.Data + ','
                            });
                        });
                    }
                    return res;
                }
                avalon.filters.types = function (val) {
                    var res = '';
                    switch (parseInt(val)) {
                        case 0: res = "正式工"; break;
                        case 1: res = "合同工"; break;
                        case 2: res = "临时工"; break;
                        case 3: res = "试用工"; break;
                        case 4: res = "兼职工"; break;
                    }
                    return res;
                }
                avalon.filters.rencai = function (val) {
                    var res = '';
                    switch (parseInt(val)) {
                        case 0: res = "普通"; break;
                        case 1: res = "中级"; break;
                        case 2: res = "高级"; break;
                        case 3: res = "顶尖"; break;
                    }
                    return res;
                }
                avalon.filters.driving = function (val) {
                    var res = ''
                    mvvm.driving.forEach(function (item) {
                        if (item.Id) {
                            if (item.Id == val)
                                res = item.Data
                        }
                    })
                    return res
                }
                avalon.filters.vehicle = function (val) {
                    var res = ''
                    mvvm.vehicle.forEach(function (item) {
                        if (item.Id) {
                            if (item.Id == val)
                                res = item.Data
                        }
                    })
                    return res
                }
                avalon.filters.language = function (val) {
                    var res = ''
                    mvvm.langguageLv.forEach(function (item) {
                        if (item.Id) {
                            if (item.Id == val)
                                res = item.Data
                        }
                    })
                    return res
                }
                avalon.filters.computer = function (val) {
                    var res = ''
                    mvvm.computerLv.forEach(function (item) {
                        if (item.Id) {
                            if (item.Id == val)
                                res = item.Data
                        }
                    })
                    return res
                }
                avalon.filters.showlang = function (val) {
                    var res = ''
                    if (val && val.length > 0) {
                        for (var i = 0; i < val.length; i++) {
                            mvvm.language.forEach(function (item) {
                                if (val[i] == item.Id)
                                    res += item.Data + '\t'
                            })
                        }
                    }
                    return res;
                }

                //查看详细
                if (action == "view") {
                    var id = that.params.id
                    var tab = 'view'
                    mvvm.doview(id);
                } else if (action == "add") {
                    var id = that.params.id
                    mvvm.doadd(function () {
                        var ld = CBCRM.loading();
                        $.get("/HR/ResumeBase", { id: id }, function (ret) {
                            if (ld) ld.close();
                            if (ret.result) {
                                var resume = ret.data.Source[0];
                                if (resume) {
                                    mvvm.selectResume(resume);
                                }
                            } else {
                                CBCRM.showResult(ret);
                            }
                        });
                    });
                } else {
                    var key = that.params.id;
                    if (key) mvvm.keyword = key;
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                }

            },

            //人事合同
            LabourContract: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, txtremark, that = this

                var mvvm = CBCRM.define('labourcontract', function (vm) {
                    vm.lang = lang
                    vm.entity = {}
                    vm.viewHr = viewHr;
                    vm.labourcontractList = []
                    vm.labourcontractpaing = {
                        paging: function () {
                            var that = this
                            GetLabourContractList({
                                keyword: mvvm.keyword,
                                pageSize: that.pagesize,
                                pageIndex: that.currentindex + 1
                            });
                        }
                    }

                    vm.ADD = false
                    vm.DELETE = false

                    vm.categoryData = []

                    vm.showItem = {}
                    vm.keyword = ''
                    vm.history = []
                    //关键字搜索
                    vm.doSearch = function () {

                        mvvm.showItem.keyword = mvvm.keyword
                        GetLabourContractList(mvvm.showItem.$model)
                        if (mvvm.history.length = 3)
                            mvvm.history.removeAt(2)
                        mvvm.history.unshift(mvvm.keyword)

                    }
                    //历史搜索
                    vm.historyClick = function () {
                        mvvm.keyword = $(this).val()
                        mvvm.showItem.keyword = mvvm.keyword
                        GetLabourContractList(mvvm.showItem.$model)
                    }
                    //清除
                    vm.clear = function () {
                        mvvm.showItem.keyword = mvvm.keyword = ''
                        GetLabourContractList(mvvm.showItem.$model)
                    }
                    //移除单个快速筛选
                    vm.remove = function () {
                        var searchKey = $(this).attr('val');
                        mvvm.showItem[searchKey] = mvvm.showItem[searchKey + 'name'] = ''
                        $(".quickword a[key='" + searchKey + "']").eq(0).addClass('selected').siblings().removeClass('selected');
                        GetLabourContractList(mvvm.showItem.$model)
                    }

                    vm.clearAllItem = function () {
                        mvvm.showItem.category = mvvm.showItem.categoryname = ''
                        mvvm.showItem.state = mvvm.showItem.statename = ''
                        mvvm.showItem.signtime = mvvm.showItem.signtimename = ''
                        mvvm.showItem.endtime = mvvm.showItem.endtimename = ''
                        $('.quickword a[value=""]').addClass('selected').siblings().removeClass('selected')
                        GetLabourContractList(mvvm.showItem.$model)
                    }
                    vm.removeItem = function () {
                        var key = $(this).attr('key')
                        mvvm.showItem[key] = mvvm.showItem[key + 'name'] = ''
                        $('.quickword a[key="' + key + '"]').eq(0).addClass('selected').siblings().removeClass('selected')
                        GetLabourContractList(mvvm.showItem.$model)
                    }
                    vm.itemClick = function () {
                        var key = $(this).attr('key')
                        var value = $(this).val()
                        var name = $(this).text()
                        if (value) {
                            mvvm.showItem[key] = value
                            mvvm.showItem[key + 'name'] = ''
                            mvvm.showItem[key + 'name'] = name
                        } else {
                            mvvm.showItem[key] = ''
                            mvvm.showItem[key + 'name'] = ''
                        }
                        $(this).addClass('selected').siblings().removeClass('selected')
                        GetLabourContractList(mvvm.showItem.$model)
                    }
                    //新增
                    vm.doadd = function () {
                        mvvm.entity = modelFactory.create('LabourContract')
                        mvvm.entity.CategoryId = mvvm.categoryData.length > 0 ? mvvm.categoryData[0].Id : ''
                        var curr = CBCRM.memberShip
                        mvvm.entity.AddBy.Id = curr.Id
                        mvvm.entity.AddBy.FullName = curr.FullName
                        mvvm.entity.ResponsibleId = curr.Id
                        mvvm.entity.ResponsibleDisplay = curr.FullName
                        mvvm.entity.StartDay = GetDateTimeYMD()
                        mvvm.entity.SigningTime = GetDateTime()
                        mvvm.getAutoNum()
                        if (that.params.key == 'add' && that.params.id) {
                            $.get('/HR/Archive/' + that.params.id, {}, function (ret) {
                                var archive = ret.data.Source[0]
                                mvvm.entity.EmployeeId = archive.Id
                                mvvm.entity.GroupId = archive.GroupId
                            })
                        }
                        FormSubmit("新增劳动合同")
                    }


                    //编辑
                    vm.doedit = function () {
                        var id = 0
                        if (that.params.key == 'edit' && that.params.id) {
                            id = that.params.id
                        } else {
                            id = $(this).val()
                        }
                        $.get('/HR/LabourContract', { 'id': id }, function (ret) {
                            mvvm.entity = avalon.mix(modelFactory.create('LabourContract'), ret.data.Source[0])
                        })
                        FormSubmit("编辑劳动合同")
                    }

                    //查看
                    vm.doview = function () {
                        var id = 0
                        if (that.params.key == 'view' && that.params.id) {
                            id = that.params.id
                        } else {
                            id = $(this).val()
                        }
                        $.get('/HR/LabourContract', { 'id': id }, function (ret) {
                            mvvm.entity = avalon.mix(modelFactory.create('LabourContract'), ret.data.Source[0])
                            var dialog = mvvm.openTmpl({
                                title: "劳动合同详细", w: 930, h: 300,padding:"def2",
                                tmplId: "viewTemplate", tmpl: tmpl
                            });
                        })
                    }

                    //删除
                    vm.dodel = function () {
                        var index = parseInt($(this).attr('index'))
                        var id = $(this).val()
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/HR/LabourContractDel/' + id, {}, function (ret) {
                                if (ret.result)
                                    mvvm.labourcontractList.removeAt(index)
                                messageBox.succeed(ret.message)
                            })
                        });
                    }

                    //批量删除
                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.post('/HR/LabourContractAllDel/', deleteIds, function (ret) {
                                if (ret.result) {
                                    GetLabourContractList(mvvm.showItem.$model);
                                    messageBox.succeed(ret.message);
                                }
                            });
                        });
                    }
                    //展开、收起
                    vm.isExp = true;
                    vm.expanCategory = function () {
                        mvvm.isExp = !mvvm.isExp;
                        $(this).text(mvvm.isExp ? "- 收起" : "+ 展开");
                        var tree = $.fn.zTree.getZTreeObj("organizationTree");
                        if (tree) {
                            var nodes = tree.getNodes();
                            if (nodes.length > 0) tree.expandNode(nodes[0], mvvm.isExp, true);
                            if (!mvvm.isExp) tree.expandNode(nodes[0], !mvvm.isExp, false);
                        }
                    }
                    //组织架构
                    vm.groupTreeOpts = {
                        treeopts: {
                            async: {
                                enable: true,
                                url: '/Settings/GetGroupPostUser/9060000'
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    mvvm.showItem.groupId = treeNode.Id
                                    GetLabourContractList(mvvm.showItem.$model)
                                }
                            },
                            view: {
                                addHoverDom: false,
                                removeHoverDom: false
                            }
                        }
                    }
                    //选择员工档案
                    vm.selectEmy = function () {
                        plugins.selectEmy({
                            dataAuth: 6050101,
                            callback: function (us) {
                                var u = us[0];
                                mvvm.entity.EmployeeId = u.Id
                                mvvm.entity.EmployeeDisplay = u.Name
                                mvvm.entity.GroupId = u.GroupId
                                mvvm.entity.GroupDisplay = u.GroupName
                                mvvm.entity.IDNumber = u.IDCardNumber
                            }
                        })
                    }

                    //时间
                    vm.startdateOpts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.StartDay = formatDate
                        }
                    }

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

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

                    //上传文件
                    vm.uploadFiles = function () {
                        var dialogId
                        CBCRM.fillContentBefore = function (tmpl, lang, contentId, module, vm) {
                            var d = messageBox.openHtml('上传文件', '1000px', '500px', tmpl);
                            avalon.scan($(".aui_content")[0], vm);
                            dialogId = d.config.id
                            return false;
                        }
                        CBCRM.loadModule('/Upload/Center')
                        CBCRM.onModuleReady = function (data) {
                            avalon.vmodels.upload.itemSelected = function (node, data, file) {
                                mvvm.entity.Attachment = '/upload/' + file.Path;
                                messageBox.close(dialogId)
                                dialogId = null
                            }
                        }
                    }

                    vm.getAutoNum = function () {
                        $.get('/HR/GetContractAutoCode', { 'prdfix': 'HR' }, function (ret) {
                            mvvm.entity.No = ret.data.autoCode
                        })
                    }

                    vm.haskey = false

                    vm.signtimeData = []
                    vm.endtimeData = []
                })

                var date = new Date()
                var MM = date.getMonth() + 1
                mvvm.signtimeData = []
                mvvm.endtimeData = []
                for (i = 0; i < 5; i++) {
                    var newsigntime = (MM - 4) + i
                    if (newsigntime < 0) {
                        newsigntime = newsigntime + 12
                    } else if (newsigntime > 12) {
                        newsigntime = newsigntime - 12
                    }
                    var signtime = { 'Id': (MM - 4) + i, 'Data': newsigntime + '月' }
                    mvvm.signtimeData.push(signtime)

                    var newendMM = (MM - 1) + i
                    if (newendMM > 12)
                        newendMM = newendMM - 12
                    else if (newendMM == 0)
                        newendMM = 1
                    var endtime = { 'Id': (MM - 1) + i, 'Data': newendMM + '月' }
                    mvvm.endtimeData.push(endtime)
                }

                //保存
                function FormSubmit(title) {
                    var dialog = mvvm.openTmpl({
                        title: title, w: 860, h: 400,padding:"def2",
                        tmplId: "formTemplate", tmpl: tmpl,
                        button: [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var model = mvvm.entity.$model
                                model.Remark = txtremark.html()
                                var url = (model.Id == 0 ? "/HR/LabourContractAdd/" : "/HR/LabourContractUpdate/")
                                $.post(url + model.Id, model, function (ret) {
                                    if (ret.result) {
                                        messageBox.ok(ret.message, function () {
                                            if (that.params.key) {

                                            } else {
                                                GetLabourContractList(mvvm.showItem.$model);
                                            }
                                            if (that.params.key) {
                                                var pvm = avalon.vmodels["Archive"];
                                                if (pvm) pvm.getOtherList(model.EmployeeId);
                                            }
                                            dialog.close();
                                        })
                                    }
                                    else {
                                        messageBox.fail(ret.message, function () { })
                                    }
                                })

                                return false
                            }
                        }],
                        onScan: function () {
                            txtremark = ketool.simple('txtremark', '95%', '150px');
                            if (txtremark) {
                                txtremark.html(mvvm.entity.Remark);
                            }
                        }
                    });
                    mvvm.entity.$watch('DayType', function (n, o) {
                        if (n == 1) {
                            mvvm.entity.EndDay = ''
                        }
                    })
                }

                var queryData = {
                    keyword: '', category: '', state: '', signtime: '', endtime: '',
                    categoryname: '', statename: '', signtimename: '', endtimename: '',
                    pageIndex: 1, pageSize: 20, groupId: ''
                }
                mvvm.showItem = avalon.mix({}, queryData);
                mvvm.entity = modelFactory.create('LabourContract');
                InitDictData()

                function GetLabourContractList(data) {
                    $.get('/HR/LabourContract', data || {}, function (ret) {
                        mvvm.labourcontractList = ret.data.Source
                        avalon.vmodels.upaing.total = ret.data.RecordTotal

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

                    })
                }

                //从字典取数据
                function InitDictData() {
                    $.get('/Settings/Dictionary/', { "id": 100046 }, function (ret) {
                        mvvm.categoryData = ret.data
                        mvvm.entity.CategoryId = mvvm.categoryData.length > 0 ? mvvm.categoryData[0].Id : ''
                    })
                }

                if (that.params.key == 'add') {
                    mvvm.haskey = true
                    mvvm.doadd()
                } else if (that.params.key == 'edit') {
                    mvvm.haskey = true
                    mvvm.doedit()
                }
                else if (that.params.key == 'view') {
                    mvvm.doview()
                } else {
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                }
            },

            //人事调动
            PostChange: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this
                var mvvm = CBCRM.define('postchange', function (vm) {
                    vm.lang = lang
                    vm.entity = {}
                    vm.postchangeList = []
                    vm.postchangepaing = {
                        paging: function () {
                            var that = this
                            GetPostChangeList({
                                pageSize: that.pagesize,
                                pageIndex: that.currentindex + 1
                            });
                        }
                    }

                    vm.ADD = false
                    vm.DELETE = false
                    vm.viewHr = viewHr;
                    vm.showItem = {}
                    vm.keyword = ''
                    vm.history = []
                    //关键字搜索
                    vm.search = function () {
                        if (mvvm.keyword) {
                            mvvm.showItem.keyword = mvvm.keyword
                            GetPostChangeList(mvvm.showItem.$model)
                            if (mvvm.history.length = 3)
                                mvvm.history.removeAt(2)
                            mvvm.history.unshift(mvvm.keyword)
                        }
                    }
                    //历史搜索
                    vm.historyClick = function () {
                        mvvm.keyword = $(this).val()
                        mvvm.showItem.keyword = mvvm.keyword
                        GetPostChangeList(mvvm.showItem.$model)
                    }
                    //清除
                    vm.clear = function () {
                        mvvm.showItem.keyword = mvvm.keyword = ''
                        GetPostChangeList(mvvm.showItem.$model)
                    }
                    //移除单个快速筛选
                    vm.remove = function () {
                        var searchKey = $(this).attr('val');
                        mvvm.showItem[searchKey] = mvvm.showItem[searchKey + 'name'] = ''
                        $(".quickword a[key='" + searchKey + "']").eq(0).addClass('selected').siblings().removeClass('selected');
                        GetPostChangeList(mvvm.showItem.$model)
                    }

                    vm.clearAllItem = function () {
                        mvvm.showItem.signtime = mvvm.showItem.signtimename = ''
                        mvvm.showItem.endtime = mvvm.showItem.endtimename = ''
                        $('.quickword a[value=""]').addClass('selected').siblings().removeClass('selected')
                        GetPostChangeList(mvvm.showItem.$model)
                    }
                    vm.removeItem = function () {
                        var key = $(this).attr('key')
                        mvvm.showItem[key] = mvvm.showItem[key + 'name'] = ''
                        $('.quickword a[key="' + key + '"]').eq(0).addClass('selected').siblings().removeClass('selected')
                        GetPostChangeList(mvvm.showItem.$model)
                    }
                    vm.itemClick = function () {
                        var key = $(this).attr('key')
                        var value = $(this).val()
                        var name = $(this).text()
                        if (value) {
                            mvvm.showItem[key] = value
                            mvvm.showItem[key + 'name'] = ''
                            mvvm.showItem[key + 'name'] = name
                        } else {
                            mvvm.showItem[key] = ''
                            mvvm.showItem[key + 'name'] = ''
                        }
                        $(this).addClass('selected').siblings().removeClass('selected')
                        GetPostChangeList(mvvm.showItem.$model)
                    }
                    //新增
                    vm.doadd = function () {
                        mvvm.entity = modelFactory.create('PostChange')
                        var curr = CBCRM.memberShip
                        mvvm.entity.AddBy.Id = curr.Id
                        mvvm.entity.AddBy.FullName = curr.FullName
                        mvvm.entity.ChangeDay = GetDateTimeYMD()
                        if (that.params.key == 'add' && that.params.id) {
                            $.get('/HR/Archive/' + that.params.id, {}, function (ret) {
                                var emp = ret.data.Source[0]
                                mvvm.entity.EmployeeId = emp.Id
                                mvvm.entity.EmployeeDisplay = emp.Name
                                mvvm.entity.OldDepartmentId = emp.GroupId
                                mvvm.entity.OldDepartmentDisplay = emp.GroupName
                                mvvm.entity.OldSalary = emp.Salary
                                mvvm.entity.OldPostId = emp.PostionId
                                mvvm.entity.OldPostDisplay = emp.PostName
                            })
                        }
                        FormSubmit("新增人事调动")
                    }

                    //编辑
                    vm.doedit = function () {
                        var id = 0
                        if (that.params.key == 'edit' && that.params.id) {
                            id = that.params.id
                        } else {
                            id = $(this).val()
                        }
                        mvvm.postchangeList.$model.forEach(function (item) {
                            if (item.Id == id) {
                                if (item.NewDepartmentId)
                                    getQueryPost(item.NewDepartmentId)
                                mvvm.entity = item
                            }
                        })
                        $.get('/HR/PostChange/' + id, {}, function (ret) {
                            var item = ret.data.Source[0]
                            if (item.NewDepartmentId)
                                getQueryPost(item.NewDepartmentId)
                            mvvm.entity = item
                            FormSubmit("编辑人事调动")
                        })
                    }

                    //查看
                    vm.doview = function () {
                        var id = 0
                        if (that.params.key == 'view' && that.params.id) {
                            id = that.params.id
                        } else {
                            id = $(this).val()
                        }
                        $.get('/HR/PostChange/' + id, {}, function (ret) {
                            var item = ret.data.Source[0]
                            mvvm.entity = avalon.mix(modelFactory.create('PostChange'), item)
                            var dialog = mvvm.openTmpl({
                                title: "人事调动详细", w: 900, h: 300,padding:"def2",
                                tmplId: "viewTemplate", tmpl: tmpl
                            });
                        })
                    }

                    //删除
                    vm.dodel = function () {
                        var index = parseInt($(this).attr('index'))
                        var id = $(this).val()
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/HR/PostChangeDel/' + id, {}, function (ret) {
                                if (ret.result)
                                    mvvm.postchangeList.removeAt(index)
                                messageBox.succeed(ret.message)
                            })
                        });
                    }

                    //批量删除
                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.post('/HR/PostChangeAllDel/', deleteIds, function (ret) {
                                if (ret.result) {
                                    GetPostChangeList();
                                    messageBox.succeed(ret.message);
                                }
                            });
                        });
                    }

                    //选择员工档案
                    vm.selectEmy = function () {
                        plugins.selectEmy({
                            dataAuth: 6050101,
                            callback: function (us) {
                                var u = us[0];
                                mvvm.entity.EmployeeId = u.Id;
                                mvvm.entity.EmployeeDisplay = u.Name;
                                mvvm.entity.OldDepartmentId = u.GroupId
                                mvvm.entity.OldDepartmentDisplay = u.GroupName
                                mvvm.entity.OldPostId = u.PostionId
                                mvvm.entity.OldPostDisplay = u.PostName
                                mvvm.entity.OldSalary = u.Salary;
                            }
                        })
                    }
                    vm.posts = []
                    //选择部门
                    vm.newDepartmentTreeOpts = {
                        dataAuth: 6050100,
                        getPost: true,
                        onlyGroup:true,
                        treeopts: {
                            callback: {
                                onClick: function (event, treeId, treeNode) {
                                    mvvm.entity.NewDepartmentId = treeNode.Id
                                    mvvm.entity.NewDepartmentDisplay = treeNode.Name
                                    mvvm.posts = treeNode.Posts
                                    if (treeNode.Posts.length)
                                        mvvm.entity.NewPostId = treeNode.Posts[0].Id
                                    else
                                        mvvm.entity.NewPostId = 0
                                }
                            }
                        }
                    }

                    // 调动时间
                    vm.changedayOpts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.ChangeDay = formatDate
                        }
                    }
                    vm.haskey = false

                    vm.signtimeData = []
                    vm.endtimeData = []
                })

                var date = new Date()
                var MM = date.getMonth() + 1
                mvvm.signtimeData = []
                mvvm.endtimeData = []
                for (i = 0; i < 5; i++) {
                    var newendMM = (MM - 1) + i
                    if (newendMM > 12)
                        newendMM = newendMM - 12
                    else if (newendMM == 0)
                        newendMM = 1

                    var signtime = { 'Id': (MM - 1) + i, 'Data': newendMM + '月' }
                    mvvm.signtimeData.push(signtime)

                    var newsigntime = (MM - 4) + i
                    if (newsigntime < 0) {
                        newsigntime = newsigntime + 12
                    } else if (newsigntime > 12) {
                        newsigntime = newsigntime - 12
                    }
                    var endtime = { 'Id': (MM - 4) + i, 'Data': newsigntime + '月' }
                    mvvm.endtimeData.push(endtime)
                }

                var queryData = {
                    keyword: '', signtime: '', endtime: '',
                    signtimename: '', endtimename: '',
                    pageIndex: 1, pageSize: 20
                }
                mvvm.showItem = avalon.mix({}, queryData)

                //保存
                function FormSubmit(title) {
                    var dialog = mvvm.openTmpl({
                        title: title, w: 850, h: 500, padding: "def2",
                        tmplId: "formTemplate", tmpl: tmpl,
                        button: [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var model = mvvm.entity.$model
                                var url = (model.Id == 0 ? "/HR/PostChangeAdd/" : "/HR/PostChangeUpdate/")
                                $.post(url + model.Id, model, function (ret) {
                                    if (ret.result) {
                                        messageBox.ok(ret.message, function () {
                                            if (that.params.key) {
                                                var pvm = avalon.vmodels["Archive"];
                                                if (pvm) pvm.getOtherList(model.EmployeeId);
                                            }
                                            GetPostChangeList();
                                            dialog.close();
                                        })
                                    }
                                    else {
                                        messageBox.fail(ret.message, function () { })
                                    }
                                })

                                return false
                            }
                        }],
                        onClose: function () {
                            mvvm.destroyui(["employeeTreeId","newDepartmentTreeId"])
                        }
                    });
                }

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

                function GetPostChangeList(data) {
                    $.get('/HR/PostChange', data || {}, function (ret) {
                        mvvm.postchangeList = ret.data.Source
                        avalon.vmodels.upaing.total = ret.data.RecordTotal

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

                    })
                }

                function getQueryPost(id) {
                    $.get('/Settings/GetPostToGroup/' + id, {}, function (ret) {
                        mvvm.posts = ret.data
                    })
                }

                if (that.params.key == 'add') {
                    mvvm.haskey = true
                    avalon.nextTick(function () {
                        mvvm.doadd()
                    })

                } else if (that.params.key == 'edit') {
                    mvvm.haskey = true
                    avalon.nextTick(function () {
                        mvvm.doedit()
                    })
                }
                else if (that.params.key == 'view') {
                    mvvm.doview()
                } else {
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                }
            },

            //员工沟通
            Communication: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, txtContent, that = this
                var mvvm = CBCRM.define('communication', function (vm) {
                    vm.lang = lang
                    vm.entity = {}
                    vm.communicationList = []
                    vm.communicationpaing = {
                        paging: function () {
                            var that = this
                            GetCommunicationList({
                                pageSize: that.pagesize,
                                pageIndex: that.currentindex + 1
                            });
                        }
                    }
                    vm.ADD = false
                    vm.DELETE = false
                    vm.viewHr = viewHr;
                    vm.categoryData = []
                    vm.methodData = []
                    vm.showItem = {}
                    vm.keyword = ''
                    vm.history = []
                    //关键字搜索
                    vm.search = function () {
                        if (mvvm.keyword) {
                            mvvm.showItem.keyword = mvvm.keyword
                            GetCommunicationList(mvvm.showItem.$model)
                            if (mvvm.history.length = 3)
                                mvvm.history.removeAt(2)
                            mvvm.history.unshift(mvvm.keyword)
                        }
                    }
                    //历史搜索
                    vm.historyClick = function () {
                        mvvm.keyword = $(this).val()
                        mvvm.showItem.keyword = mvvm.keyword
                        GetCommunicationList(mvvm.showItem.$model)
                    }
                    //清除
                    vm.clear = function () {
                        mvvm.showItem.keyword = mvvm.keyword = ''
                        GetCommunicationList(mvvm.showItem.$model)
                    }
                    //移除单个快速筛选
                    vm.remove = function () {
                        var searchKey = $(this).attr('val');
                        mvvm.showItem[searchKey] = mvvm.showItem[searchKey + 'name'] = ''
                        $(".quickword a[key='" + searchKey + "']").eq(0).addClass('selected').siblings().removeClass('selected');
                        GetCommunicationList(mvvm.showItem.$model)
                    }
                    vm.clearAllItem = function () {
                        mvvm.showItem.category = mvvm.showItem.categoryname = ''
                        mvvm.showItem.method = mvvm.showItem.methodname = ''
                        $('.quickword a[value=""]').addClass('selected').siblings().removeClass('selected')
                        GetCommunicationList(mvvm.showItem.$model)
                    }
                    vm.removeItem = function () {
                        var key = $(this).attr('key')
                        mvvm.showItem[key] = mvvm.showItem[key + 'name'] = ''
                        $('.quickword a[key="' + key + '"]').eq(0).addClass('selected').siblings().removeClass('selected')
                        GetCommunicationList(mvvm.showItem.$model)
                    }
                    vm.itemClick = function () {
                        var key = $(this).attr('key')
                        var value = $(this).val()
                        var name = $(this).text()
                        if (value) {
                            mvvm.showItem[key] = value
                            mvvm.showItem[key + 'name'] = ''
                            mvvm.showItem[key + 'name'] = name
                        } else {
                            mvvm.showItem[key] = ''
                            mvvm.showItem[key + 'name'] = ''
                        }
                        $(this).addClass('selected').siblings().removeClass('selected')
                        GetCommunicationList(mvvm.showItem.$model)
                    }
                    //新增
                    vm.doadd = function () {
                        mvvm.entity = modelFactory.create('Communication')
                        var curr = CBCRM.memberShip
                        mvvm.entity.AddBy.Id = curr.Id
                        mvvm.entity.AddBy.FullName = curr.FullName
                        mvvm.entity.Time = GetDateTimeYMD()
                        mvvm.entity.PersonInCharge = curr.Id
                        mvvm.entity.PersonInChargeDisplay = curr.FullName
                        mvvm.entity.CategoryId = mvvm.categoryData.length > 0 ? mvvm.categoryData[0].Id : 0
                        mvvm.entity.MethodId = mvvm.methodData.length > 0 ? mvvm.methodData[0].Id : 0
                        if (that.params.key == 'add' && that.params.id) {
                            mvvm.entity.EmployeeId = that.params.id
                        }
                        FormSubmit("新增员工沟通")
                    }

                    //编辑
                    vm.doedit = function () {
                        var id = 0
                        if (that.params.key == 'edit' && that.params.id) {
                            id = that.params.id
                        } else {
                            id = $(this).val()
                        }
                        $.get('/HR/Communication/' + id, {}, function (ret) {
                            var item = ret.data.Source[0]
                            mvvm.entity = avalon.mix(modelFactory.create('Communication'), item)
                            FormSubmit("编辑员工沟通")
                        })
                    }

                    //查看
                    vm.doview = function () {
                        var id = 0
                        if (that.params.key == 'view' && that.params.id) {
                            id = that.params.id
                        } else {
                            id = $(this).val()
                        }
                        $.get('/HR/Communication/' + id, {}, function (ret) {
                            var item = ret.data.Source[0]
                            mvvm.entity = avalon.mix(modelFactory.create('Communication'), item)
                            var dialog = mvvm.openTmpl({
                                title: "员工沟通详细", w: 920, h: 400, padding: "def2",
                                tmplId: "viewTemplate", tmpl: tmpl
                            });
                        })
                    }

                    //删除
                    vm.dodel = function () {
                        var index = parseInt($(this).attr('index'))
                        var id = $(this).val()
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/HR/CommunicationDel/' + id, {}, function (ret) {
                                if (ret.result)
                                    mvvm.communicationList.removeAt(index)
                                messageBox.succeed(ret.message)
                            })
                        });
                    }

                    //批量删除
                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.post('/HR/CommunicationAllDel/', deleteIds, function (ret) {
                                if (ret.result) {
                                    GetCommunicationList();
                                    messageBox.succeed(ret.message);
                                }
                            })
                        })
                    }

                    //选择员工档案
                    vm.selectEmy = function (type) {
                        plugins.selectEmy({
                            dataAuth: 6050101,
                            callback: function (us) {
                                var u = us[0];
                                if (type == 1) {//沟通负责人
                                    mvvm.entity.PersonInCharge = u.Id
                                    mvvm.entity.PersonInChargeDisplay = u.Name
                                } else {//沟通对象
                                    mvvm.entity.EmployeeId = u.Id
                                    mvvm.entity.EmployeeDisplay = u.Name
                                }
                            }
                        })
                    }

                    //员工
                    vm.employeeTreeOpts = {
                        treeopts: {
                            callback: {
                                onCheck: function (e, treeId, treeNode) {
                                    mvvm.entity.EmployeeId = treeNode.Id
                                    mvvm.entity.EmployeeDisplay = treeNode.Name
                                }
                            },
                            check: {
                                enable: true,
                                chkStyle: 'radio',
                                radioType: "all"
                            },
                            async: {
                                url: function (treeId, treeNode) {
                                    var url = "/HR/GetGroupPostArchive/6050100"
                                    vmtree = avalon.vmodels.employeeTreeId
                                    if (vmtree && vmtree.q && vmtree.q !== vmtree.qcopy) {
                                        url += '?empName=' + vmtree.q
                                    }
                                    return url
                                },
                                dataFilter: notMemberFilter
                            }
                        }
                    }

                    //沟通负责人
                    vm.personInChargeTreeOpts = {
                        treeopts: {
                            callback: {
                                onCheck: function (e, treeId, treeNode) {
                                    mvvm.entity.PersonInCharge = treeNode.Id
                                    mvvm.entity.PersonInChargeDisplay = treeNode.Name
                                }
                            },
                            check: {
                                enable: true,
                                chkStyle: 'radio',
                                radioType: "all"
                            },
                            async: {
                                url: function (treeId, treeNode) {
                                    return "/Settings/GetGroupPostUser/6050100"
                                },
                                dataFilter: notMemberFilter
                            }
                        }
                    }

                    // 沟通日期
                    vm.ctimeOpts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.Time = formatDate
                        }
                    }

                    vm.settarget = function () {
                        mvvm.entity.Target = $('#seltarget').find('option:selected').val()
                    }
                    vm.haskey = false
                })
                var queryData = {
                    keyword: '', category: '', method: '',
                    categoryname: '', methodname: '',
                    pageIndex: 1, pageSize: 20
                }
                mvvm.showItem = avalon.mix({}, queryData)

                //保存
                function FormSubmit(title) {
                    var dialog = mvvm.openTmpl({
                        title: title, w: 870, h: 400, padding: "def2",
                        tmplId: "formTemplate", tmpl: tmpl,
                        button: [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var model = mvvm.entity.$model
                                model.Content = txtContent.html()
                                var url = (model.Id == 0 ? "/HR/CommunicationAdd/" : "/HR/CommunicationUpdate/")
                                $.post(url + model.Id, model, function (ret) {
                                    CBCRM.showResult(ret, function () {
                                        if (that.params.key) {
                                            var pvm = avalon.vmodels["Archive"];
                                            if (pvm) pvm.getOtherList(model.EmployeeId);
                                        }
                                        GetCommunicationList();
                                        dialog.close();
                                    })
                                })

                                return false
                            }
                        }],
                        onClose: function () {
                            
                        },
                        onScan: function () {
                            txtContent =ketool.simple('txtContent', '97%', '150px');
                            if (txtContent) {
                                txtContent.html(mvvm.entity.Content);
                            } 
                        }
                    });
                }

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

                function GetCommunicationList(data) {
                    $.get('/HR/Communication', data || {}, function (ret) {
                        mvvm.communicationList = ret.data.Source
                        avalon.vmodels.upaing.total = ret.data.RecordTotal

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

                    })
                }

                function GetDictData() {
                    $.get('/HR/GetCommunicationDictionaryData', {}, function (ret) {
                        mvvm.categoryData = ret.data.CategoryData
                        mvvm.methodData = ret.data.MethodData
                        mvvm.entity.CategoryId = mvvm.categoryData.length > 0 ? mvvm.categoryData[0].Id : 0
                        mvvm.entity.MethodId = mvvm.methodData.length > 0 ? mvvm.methodData[0].Id : 0
                    })
                }

                GetDictData()

                if (that.params.key == 'add') {
                    mvvm.haskey = true
                    avalon.nextTick(function () {
                        mvvm.doadd()
                    })
                } else if (that.params.key == 'edit') {
                    mvvm.haskey = true
                    avalon.nextTick(function () {
                        mvvm.doedit()
                    })
                }
                else if (that.params.key == 'view') {
                    avalon.nextTick(function () {
                        mvvm.doview()
                    })
                } else {
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                }
            },

            //奖惩记录 颜
            Reward: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, txtremark, that = this
                var mvvm = CBCRM.define('Reward', function (vm) {
                    vm.lang = lang //语言
                    vm.entity = {}//奖惩数据
                    vm.viewHr = viewHr;//弹窗路径
                    vm.RewardList = []//奖惩数据列表
                    //分页数据
                    vm.rewardpaing = {
                        paging: function () {
                            var that = this
                            var data = avalon.mix(true, mvvm.createQuery(), { pageSize: that.pagesize, pageIndex: that.currentindex + 1 })
                            GetRewardList(data);
                        }
                    }
                    vm.action = "";
                    //查询条件
                    initQuerys(vm, function (data, name, val, type) {
                        if (name == "dateTimes") {
                            {
                                if (val == 2) {
                                    mvvm.queryData.dateTimes.valLabel = ""
                                    if (mvvm.hasLength == 1) {
                                        mvvm.hasQuery = false;
                                    }
                                    return;
                                } else {
                                    mvvm.removeQuery("begindate", true);
                                    mvvm.removeQuery("enddate", true);
                                }
                            }
                        }
                        GetRewardList(data);
                    });
                    vm.queryData = {
                        keyword: {
                            label: "关键词", val: "", valLabel: ""
                        },
                        category: {
                            label: "奖惩类型", val: "", valLabel: "",
                            items: [
                                { label: "不限", val: "", curr: true }
                            ]
                        },
                        dateTimes: {
                            label: "时间范围", val: "", valLabel: "",
                            items: [
                                { label: "不限", val: "", curr: true },
                                { label: "本月", val: "0", curr: false },
                                { label: "上月", val: "1", curr: false },
                                { label: "时间段", val: "2", curr: false }
                            ]
                        },
                        begindate: {
                            label: "起始时间", val: "", valLabel: ""
                        },
                        enddate: {
                            label: "结束时间", val: "", valLabel: ""
                        },
                        emid: {
                            label: "档案id", val: ""
                        }
                    }
                    //检索时间范围
                    vm.datespan = false
                    vm.begindateopts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {

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

                    vm.ADD = false
                    vm.DELETE = false
                    vm.RewardData = []//奖励列表
                    vm.PunishData = []//奖励列表
                    vm.showItem = {}//搜索条件 
                    vm.keyword = ''//员工姓名检索
                    vm.history = []//历史索搜
                    //关键字搜索 OK
                    vm.search = function () {
                        if (mvvm.keyword != "") {
                            mvvm.addQuery("keyword", mvvm.keyword, mvvm.keyword);
                        }
                    }
                    //回车事件
                    vm.toEnter = function (e) {
                        if (e.keyCode == 13) {
                            mvvm.search();
                        }
                    }
                    vm.options = {
                        "+": "加",
                        "-": "扣",
                    }
                    vm.optionsReward = {
                        "+": "奖金",
                        "-": "罚款",
                    }
                    vm.dateClick = function (id, data, type) {
                        mvvm.entity.RewardType = id;
                        mvvm.entity.InReward = type == 1 ? true : false;
                        mvvm.entity.InRewardName = type == 1 ? "+" : "-";
                        mvvm.entity.InRewardMoney = type == 1 ? "+" : "-";
                    }
                    //新增
                    vm.doadd = function () {
                        mvvm.entity = modelFactory.create('Reward')
                        var curr = CBCRM.memberShip
                        mvvm.entity.AddBy.Id = curr.Id
                        mvvm.entity.AddBy.FullName = curr.FullName
                        mvvm.entity.AddTime = GetDateTime()
                        if (id && action == "Archive") {
                            var vmodel = avalon.vmodels["Archive"];
                            var hentity = vmodel.entity;
                            mvvm.entity.EmployeeId = hentity.Id;
                            mvvm.entity.Name = hentity.Name
                            mvvm.entity.GroupId = hentity.GroupId;
                            mvvm.entity.GroupName = hentity.GroupName;

                        }
                        FormSubmit("新增奖惩记录")
                    }

                    //选择员工档案
                    vm.selectUser = function () {
                        plugins.selectEmy({
                            dataAuth: 6050101,
                            callback: function (us) {
                                var u = us[0];
                                mvvm.entity.EmployeeId = u.Id
                                mvvm.entity.Name = u.Name
                                mvvm.entity.GroupId = u.GroupId
                                mvvm.entity.GroupName=u.GroupName
                            }
                        })
                    }
                    //编辑
                    vm.doedit = function () {
                        var id = 0
                        if (that.params.key == 'edit' && that.params.id) {
                            id = that.params.id
                        } else {
                            id = $(this).val()
                        }
                        $.get('/HR/GetRewardList', { 'id': id }, function (ret) {
                            mvvm.entity = avalon.mix(modelFactory.create('Reward'), ret.data.Source[0])

                        })
                        FormSubmit("编辑奖惩记录")

                    }

                    //查看
                    vm.doview = function () {
                        var id = 0
                        if (that.params.key == 'view' && that.params.id) {
                            id = that.params.id
                        } else {
                            id = $(this).val()
                        }
                        $.get('/HR/GetRewardListTable', { 'id': id }, function (ret) {
                            mvvm.entity = avalon.mix(modelFactory.create('Reward'), ret.data.Source[0])
                            var dialog = mvvm.openTmpl({
                                title: "奖惩记录详细", w: 720, h:200,padding:"def2",
                                tmplId: "viewTemplate", tmpl: tmpl
                            });
                        })
                    }
                    //删除 移除回收站问题
                    vm.dodel = function () {
                        var index = parseInt($(this).attr('index'))
                        var id = $(this).val()
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/HR/RewardDelete/' + id, {}, function (ret) {
                                if (ret.result)
                                    mvvm.RewardList.removeAt(index)
                                messageBox.succeed(ret.message)
                            })
                        });

                    }
                    //批量删除 移除回收站问题
                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.post('/HR/RewardAllDelete/', deleteIds, function (ret) {
                                if (ret.result) {
                                    GetRewardList(mvvm.createQuery());
                                    messageBox.succeed(ret.message);
                                }
                            });
                        });
                    }
                    vm.haskey = false
                })
                var action = that.params.action, id = that.params.id;
                mvvm.action = action;
                mvvm.entity = modelFactory.create('Reward');
                InitDictData()
                function GetRewardList(data) {
                    if (action == "Archive") {
                        data.emid = id;
                    }
                    $.get('/HR/GetRewardList', data || {}, function (ret) {
                        mvvm.RewardList = ret.data.Source
                        avalon.vmodels.upaing.total = ret.data.RecordTotal
                        mvvm.ADD = ret.data.ADD
                        mvvm.DELETE = ret.data.DELETE
                    })
                }
                avalon.filters.formats = function (val) {
                    if (isNaN(val)) return "";
                    var num = Math.round(val * 100) / 100
                    if (num != 0)
                        return num;
                    else
                        return "";
                }
                //从字典取数据 OK
                function InitDictData() {
                    var dict = { RewardData: 190011, PunishData: 190012 };
                    getDicts(dict, mvvm, function (dicts) {
                        mvvm.RewardData.forEach(function (item) {
                            mvvm.queryData.category.items.push({ label: item.Data, val: item.Id, curr: false });
                        });
                        mvvm.PunishData.forEach(function (item) {
                            mvvm.queryData.category.items.push({ label: item.Data, val: item.Id, curr: false });
                        });
                    });
                }
                //保存
                function FormSubmit(title) {
                    var dialog = mvvm.openTmpl({
                        title: title,
                        tmpl: tmpl,
                        tmplid: "formTemplate",
                        w: 600,
                        padding:"def2",
                        btns: [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var model = mvvm.entity.$model
                                if (model.RewardType == 0) {
                                    messageBox.warning('请选择奖惩类别');
                                    return false
                                }
                                if (model.Name) {
                                    var url = (model.Id == 0 ? "/HR/RewardAdd/" : "/HR/RewardUpdate/")
                                    $.post(url + model.Id, model, function (ret) {
                                        if (ret.result) {
                                            messageBox.ok(ret.message, function () {
                                                if (that.params.key) {
                                                } else {
                                                    GetRewardList(mvvm.createQuery());
                                                }
                                                if (that.params.key) {
                                                    var pvm = avalon.vmodels["Archive"];
                                                    if (pvm) pvm.getOtherList(model.EmployeeId);
                                                }
                                                dialog.close();
                                            })
                                        }
                                        else {
                                            messageBox.fail(ret.message, function () { })
                                        }
                                    })
                                } else
                                    messageBox.warning('请选择员工姓名');
                                return false
                            }
                        }]
                    });
                }

                switch (action) {
                    case "add":
                        break;
                    case "edit":
                        break;
                    case "view":
                        break;
                    case "Archive":
                        mvvm.queryData.emid.val = id;
                        var content = $("#otherRightContent").html($(tmpl).find("#tableList"));
                        avalon.scan(content[0], mvvm);
                        break;
                    default:
                        fill();
                }
                function fill() {
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                }
            },
            //积分明细 颜
            Integral: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this
                var mvvm = CBCRM.define('Integral', function (vm) {
                    vm.lang = lang //语言
                    vm.entity = {}//奖惩数据
                    vm.viewHr = viewHr;//弹窗路径
                    vm.IntergralList = []//奖惩数据列表
                    vm.action = "";
                    vm.sumIntegral = 0;

                    vm.ADD = false
                    //分页数据
                    vm.Integralpaing = {
                        paging: function () {
                            var that = this
                            var data = avalon.mix(true, mvvm.createQuery(), { pageSize: that.pagesize, pageIndex: that.currentindex + 1 })
                            GetIntegralList(data);
                        }
                    }
                    //查询条件
                    initQuerys(vm, function (data, name, val, type) {
                        if (name == "dateTimes") {
                            {
                                if (val == 2) {
                                    mvvm.queryData.dateTimes.valLabel = ""
                                    if (mvvm.hasLength == 1) {
                                        mvvm.hasQuery = false;
                                    }
                                    return;
                                } else {
                                    mvvm.removeQuery("begindate", true);
                                    mvvm.removeQuery("enddate", true);
                                }
                            }
                        }
                        GetIntegralList(data);
                    });
                    vm.queryData = {
                        keyword: {
                            label: "关键词", val: "", valLabel: ""
                        },
                        dateTimes: {
                            label: "时间范围", val: "", valLabel: "",
                            items: [
                                { label: "不限", val: "", curr: true },
                                { label: "本月", val: "0", curr: false },
                                { label: "上月", val: "1", curr: false },
                                { label: "时间段", val: "2", curr: false }
                            ]
                        },
                        score: {
                            label: "积分操作", val: "", valLabel: "",
                            items: [
                                { label: "不限", val: "", curr: true },
                                { label: "加分", val: "+", curr: false },
                                { label: "扣分", val: "-", curr: false },
                            ]
                        },
                        state: {
                            label: "在职状态", val: "", valLabel: "",
                            items: [
                                { label: "不限", val: "", curr: true },
                                { label: "在职试用", val: "0", curr: false },
                                { label: "在职正式", val: "1", curr: false },
                                { label: "离职", val: "2", curr: false },
                                { label: "退休", val: "3", curr: false },
                            ]
                        },
                        begindate: {
                            label: "起始时间", val: "", valLabel: ""
                        },
                        enddate: {
                            label: "结束时间", val: "", valLabel: ""
                        },
                        emid: {
                            label: "档案id", val: ''
                        }
                    }
                    vm.options = {
                        "+": "加",
                        "-": "扣",
                    }
                    //检索时间范围
                    vm.datespan = false
                    vm.begindateopts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {

                            mvvm.addQuery("begindate", formatDate, "起始时间:" + formatDate);
                        }
                    }
                    vm.enddateopts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.addQuery("enddate", formatDate, "结束时间:" + formatDate);
                        }
                    }
                    //选择员工档案
                    vm.selectEmy = function () {
                        plugins.selectEmy({
                            dataAuth: 6050101,
                            callback: function (us) {
                                var u = us[0];
                                mvvm.entity.EmployeeId = u.Id
                                mvvm.entity.Name = u.Name
                                mvvm.entity.GroupId = u.GroupId
                                mvvm.entity.GroupName = u.GroupName
                            }
                        })
                    }
                    vm.ADD = false
                    vm.DELETE = false
                    vm.showItem = {}//搜索条件 
                    vm.keyword = ''//员工姓名检索
                    vm.history = []//历史索搜
                    //关键字搜索 OK
                    vm.search = function () {
                        if (mvvm.keyword != "") {
                            mvvm.addQuery("keyword", mvvm.keyword, mvvm.keyword);
                        }
                    }
                    //回车事件
                    vm.toEnter = function (e) {
                        if (e.keyCode == 13) {
                            mvvm.search();
                        }
                    }
                    //查看
                    vm.doview = function () {
                        var id = 0
                        if (that.params.key == 'view' && that.params.id) {
                            id = that.params.id
                        } else {
                            id = $(this).val()
                        }
                        $.get('/HR/GetIntegralList', { 'id': id }, function (ret) {
                            mvvm.entity = avalon.mix(modelFactory.create('Integral'), ret.data.Source[0])
                            var dialog = mvvm.openTmpl({
                                title: "积分记录详细", w: 800, h: 200,padding:"def2",
                                tmplId: "viewTemplate", tmpl: tmpl
                            });
                        })
                    }
                    //新增
                    vm.doadd = function () {
                        mvvm.entity = modelFactory.create('Integral')
                        var curr = CBCRM.memberShip
                        mvvm.entity.AddBy.Id = curr.Id
                        mvvm.entity.AddBy.FullName = curr.FullName
                        mvvm.entity.AddTime = GetDateTime()
                        if (id && action == "Archive") {
                            var vmodel = avalon.vmodels["Archive"];
                            var hentity = vmodel.entity;
                            mvvm.entity.EmployeeId = hentity.Id;
                            mvvm.entity.Name = hentity.Name
                            mvvm.entity.GroupId = hentity.GroupId;
                            mvvm.entity.GroupName = hentity.GroupName;

                        }
                        FormSubmit("新增积分记录")
                    }

                    vm.haskey = false
                })
                var action = that.params.action, id = that.params.id;
                mvvm.action = action;
                //保存
                function FormSubmit(title) {
                    var dialog = mvvm.openTmpl({
                        title: title,
                        tmpl: tmpl,
                        tmplid: "fTemplate",
                        w: 600,
                        padding:"def2",
                        btns: [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var model = mvvm.entity.$model
                                if (model.Name) {
                                    var url = (model.Id == 0 ? "/HR/IntegralAdd/" : "/HR/RewardUpdate/")
                                    $.post(url + model.Id, model, function (ret) {
                                        if (ret.result) {
                                            messageBox.ok(ret.message, function () {
                                                if (that.params.key) {
                                                } else {
                                                    GetIntegralList(mvvm.createQuery());
                                                }
                                                if (that.params.key) {
                                                    var pvm = avalon.vmodels["Archive"];
                                                    if (pvm) pvm.getOtherList(model.EmployeeId);
                                                }
                                                dialog.close();
                                            })
                                        }
                                        else {
                                            messageBox.fail(ret.message, function () { })
                                        }
                                    })
                                } else
                                    messageBox.warning('请选择员工姓名');
                                return false
                            }
                        }]
                    });
                }

                switch (action) {
                    case "Archive":
                        mvvm.queryData.emid.val = id;
                        var content = $("#otherRightContent").html($(tmpl).find("#tableList"));
                        avalon.scan(content[0], mvvm);
                        break;
                    default:
                        fill();
                }
                mvvm.entity = modelFactory.create('Integral');
                function GetIntegralList(data) {
                    mvvm.sumIntegral = 0;
                    $.get('/HR/GetIntegralList', data || {}, function (ret) {
                        mvvm.IntergralList = ret.data.Source
                        for (var i = 0, tmp; tmp = ret.data.Source[i]; i++) {
                            if (tmp.IntegralType == "+")
                                mvvm.sumIntegral = mvvm.sumIntegral + tmp.IntegralNumber
                            else
                                mvvm.sumIntegral = mvvm.sumIntegral - tmp.IntegralNumber
                        }
                        mvvm.ADD = ret.data.ADD;
                        avalon.vmodels.upaing.total = ret.data.RecordTotal
                    })
                }
                function fill() {
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                }
            },
            //考勤签到列表
            CheckInList: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, vmid = "HR_CheckInList";
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.$skipArray = ['lang'];
                    vm.lang = lang 
                    vm.entity = {}
                    vm.auth = { ADD: false, EDIT: false, DELETE: false };
                    vm.listtab = 0;
                    vm.listTabs = [
                        { label: "全部签到", val: 0 }, { label: "我的签到", val: 1 }, { label: "下属签到", val: 2 }
                    ]
                    vm.listtabChange = function (tabid) {
                        if (tabid == mvvm.listtab) return;
                        mvvm.listtab = tabid;
                        mvvm.addQuery("listType", tabid);
                    }
                    //查询条件
                    initQuerys(vm, function (data, name, val, type) {
                        if (name == "timeScope") {
                            {
                                if (val == "c") {
                                    if (type == "remove") {
                                        mvvm.removeQuery("startTime", true);
                                        mvvm.removeQuery("endTime", true);
                                    } else {
                                        mvvm.queryData.timeScope.valLabel = ""
                                        if (mvvm.hasLength == 1) {
                                            mvvm.hasQuery = false;
                                        }
                                        return false;
                                    }
                                } else {
                                    mvvm.removeQuery("startTime", true);
                                    mvvm.removeQuery("endTime", true);
                                }
                            }
                        }
                        var data = mvvm.createQuery();
                        mvvm.grid1.loadData(data);
                    });
                    vm.queryData = {
                        checkInState: {
                            label: "考勤类型", val: "", valLabel: "",
                            items: [
                                { label: "不限", val: "", curr: true },
                                { label: "正常", val: "正常", curr: false },
                                { label: "迟到", val: "迟到", curr: false },
                                { label: "早退", val: "早退", curr: false }
                            ]
                        },
                        timeScope: {
                            label: "时间范围", val: "", valLabel: "",
                            items: [
                                { label: "不限", val: "", curr: true },
                                { label: "今天", val: "d", curr: false },
                                { label: "昨天", val: "d_-1", curr: false },
                                { label: "本周", val: "w", curr: false },
                                { label: "本月", val: "m", curr: false },
                                { label: "自定义", val: "c", curr: false, type: "date",d1:"startTime",d2:"endTime", format: "%Y-%m-%d" },
                            ]
                        },
                        key: {label: "关键词", val: "", valLabel: ""},
                        startTime: {label: "起始时间", val: ""},
                        endTime: {label: "结束时间", val: ""},
                        ids: { label: "员工id", val: '', valLabel: "" },
                        listType: { label: "列表类型", val: 0, noRemove: true }
                    }
                    vm.grid1 = createGrid({
                        url: "/HR/CheckInList",
                        pageid: vmid + "_page_grid1",
                        modelFactory: modelFactory,
                        $lang: lang,
                        createQuery: function () {
                            var data = mvvm.createQuery();
                            return data;
                        },
                        onLoadData: function (ret,list) {
                            for (var key in mvvm.auth.$model) {
                                if (ret.data[key] != null) mvvm.auth[key] = ret.data[key];
                            }
                            return ret.data;
                        },
                        onRemove: function (deleteIds) {
                            if (!deleteIds.length) {
                                messageBox.warning("请选择数据！");
                                return;
                            }
                            delete deleteIds.length;
                            $.post("/HR/CheckInDelete", deleteIds, function (ret) {
                                var ok=CBCRM.showResult(ret);
                                if (ok) mvvm.grid1.reloadData();
                            })
                        }
                    });
                    //vm.doAdd = function (CheckInType) {
                    //    var entity = mvvm.grid1.getEntity();
                    //    entity.CheckInType = CheckInType;
                    //    $.post("/HR/CheckInAdd", entity, function (ret) {
                    //        var ok=CBCRM.showResult(ret);
                    //        if (ok) mvvm.grid1.reloadData();
                    //    });
                    //}
                    vm.doVerify = function () {
                        var ids = mvvm.grid1.getCheckedIds("ids")
                        if (!ids.length) {
                            messageBox.warning("请选择数据！");
                            return;
                        }
                        delete ids.length;
                        $.post("/HR/CheckInVerify", ids, function (ret) {
                            var ok = CBCRM.showResult(ret);
                            if (ok) mvvm.grid1.reloadData();
                        })
                    }
                })
                mvvm.grid1.init();
                mvvm.queryData.startTime.$watch("val", watchTime);
                mvvm.queryData.endTime.$watch("val", watchTime);
                function watchTime(v1,v2) {
                    if (v1 && v1 != v2) {
                        var data = mvvm.createQuery();
                        mvvm.grid1.loadData(data);
                    }
                }
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
            },
            //考勤签到统计
            CheckInAnalysis: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, vmid = "HR_CheckInAnalysis";
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.$skipArray = ['lang'];
                    vm.lang = lang
                    //查询条件
                    initQuerys(vm, function (data, name, val, type) {
                        if (name == "timeScope") {
                            {
                                if (val == "c") {
                                    if (type == "remove") {
                                        mvvm.removeQuery("startTime", true);
                                        mvvm.removeQuery("endTime", true);
                                    } else {
                                        mvvm.queryData.timeScope.valLabel = ""
                                        if (mvvm.hasLength == 1) {
                                            mvvm.hasQuery = false;
                                        }
                                        return false;
                                    }
                                } else {
                                    mvvm.removeQuery("startTime", true);
                                    mvvm.removeQuery("endTime", true);
                                }
                            }
                        }
                        var data = mvvm.createQuery();
                        mvvm.grid1.loadData(data);
                    });
                    vm.queryData = {
                        timeScope: {
                            label: "时间范围", val: "", valLabel: "",
                            items: [
                                { label: "不限", val: "", curr: true },
                                { label: "今天", val: "d", curr: false },
                                { label: "昨天", val: "d_-1", curr: false },
                                { label: "本周", val: "w", curr: false },
                                { label: "本月", val: "m", curr: false },
                                { label: "自定义", val: "c", curr: false, type: "date", d1: "startTime", d2: "endTime", format: "%Y-%m-%d" },
                            ]
                        },
                        key: {
                            label: "关键词", val: "", valLabel: ""
                        },
                        startTime: {
                            label: "起始时间", val: ""
                        },
                        endTime: {
                            label: "结束时间", val: ""
                        },
                        ids: {
                            label: "员工id", val: '', valLabel: ""
                        }
                    }
                    vm.grid1 = createGrid({
                        url: "/HR/CheckInAnalysis",
                        $lang: lang,
                        listkey:'',
                        createQuery: function () {
                            var data = mvvm.createQuery();
                            return data;
                        }
                    });
                })
                mvvm.grid1.init();
                mvvm.queryData.startTime.$watch("val", watchTime);
                mvvm.queryData.endTime.$watch("val", watchTime);
                function watchTime(v1, v2) {
                    if (v1 && v1 != v2) {
                        var data = mvvm.createQuery();
                        mvvm.grid1.loadData(data);
                    }
                }
                mvvm.grid1.doSearch();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
            },
            UserTrack: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, init = false, maptool = null, vmid = "HrUserTrack";
                var cmyInfo = CBCRM.cmyInfo;
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.destroy = function () {
                        window.map = null;
                    }
                    vm.entity = {};
                    vm.employes = []
                    vm.letters = [];
                    vm.cityLetters = {};
                    vm.cityAreas = [];
                    vm.emyName = ''
                    vm.curCountryId = '';
                    vm.curCountry = '';
                    vm.curProvince = '';
                    vm.curProvinceId = '';
                    vm.curCityId = '';
                    vm.curAreaId = '';
                    vm.curCountry = "请选择";
                    vm.curCity = "请选择";
                    vm.curArea = "请选择";
                    vm.areaId = ''
                    vm.$point1 = null;
                    vm.$point2 = null;
                    vm.mapHrPageOpts = {
                        paging: function () {
                            if (!init) {
                                init = true;
                                return;
                            }
                            var data = mvvm.getQueyData();
                            data.pageIndex = (this.currentindex + 1) || 1
                            data.pageSize = this.pagesize
                            mvvm.loadData(data)
                        },
                        enablesetsize: false,
                        showtotal: false,
                        showpages: 4,
                        initload: false,
                        pagesize: 50

                    }
                    vm.viewEmy = function (entity) {
                        if (!entity || !entity.ArchiveId) {
                            messageBox.warning("此员工还未建立人事档案");
                            return;
                        }
                        mvvm.closeInfoWindow();
                        mvvm.gotoview(entity.ArchiveId, "hr");
                    }
                    vm.mapwidth = 800;
                    vm.mapheight = 600;
                    vm.leftTab = "tab1";
                    vm.showLeftTab = true;
                    vm.changeLeftTab = function (tab) {
                        mvvm.leftTab = tab;
                    }
                    vm.leftTabToggle = function () {
                        mvvm.showLeftTab = !mvvm.showLeftTab;
                        if (!mvvm.showLeftTab) mvvm.mapwidth += 311;
                        else mvvm.mapwidth -= 311;
                    }
                    //加载地图
                    vm.$mapLoaded = false;
                    vm.$map = null;
                    vm.linetype = "bus";
                    vm.pstart = "";
                    vm.pend = "";
                    vm.$pointStart = null;
                    vm.$pointEnd = null;
                    vm.$marker = null;
                    vm.$loadmsg = "地图正在加载中，请稍等...";
                    vm.loadMap = function (callback) {
                        if (!vm.$mapLoaded) {
                            var _t = null;
                            var dialog = CBCRM.loading(mvvm.$loadmsg, null, function () {
                                if (_t) window.clearTimeout(_t);
                            });
                            require(["bdmapTool", "ready!"], function (bdmapTool) {
                                if (_t) window.clearTimeout(_t);
                                maptool = bdmapTool;
                                if (dialog) dialog.close();
                                vm.$map = new bdmapTool({
                                    mapContent: "#dmap",
                                    linepanel: "",/*divline*/
                                    city: cmyInfo.CityDisplay,
                                    onSearchComplete: mvvm.onSearchComplete
                                });
                                if (",市辖区,县,".indexOf(vm.$map.ops.city) > -1 || vm.$map.ops.city == "") mvvm.$map.ops.city = cmyInfo.ProvinceDisplay;
                                if (!mvvm.$map.ops.city) mvvm.$map.ops.city = "南宁市";
                                window.bdmapTool = bdmapTool;
                                mvvm.$mapLoaded = true;
                                if (cmyInfo.Lng != "" && cmyInfo.Lng > 0) {
                                    mvvm.pstart = cmyInfo.Address;
                                    mvvm.$pointStart = new BMap.Point(cmyInfo.Lng, cmyInfo.Lat);
                                }
                                mvvm.$map.initMap(callback);
                                var map = mvvm.$map.map;
                                map.addControl(new BMap.NavigationControl());
                                maptool.Event.bind(map, "dragstart", mvvm.closeInfoWindow);
                                /*暂时不要拖动查询*/
                                //if (!mvvm.$binddrag) {
                                //    mvvm.$binddrag = true
                                //    maptool.Event.bind(map, "dragend", mvvm.getCustomerByBounds);
                                //}
                                //if (!mvvm.isBindZoomEnd) {
                                //    maptool.Event.bind(map, "zoomend", mvvm.getCustomerByBounds);
                                //    mvvm.isBindZoomEnd = true;
                                //}
                                //var map = mvvm.$map.map;
                                //maptool.Event.bind(map, "dragend", mvvm.getCustomerByBounds);
                                //maptool.Event.bind(map, "dragstart", function () {
                                //    mvvm.$map.closeCustomOverlayInfo();
                                //});
                            }, function (error) {
                                if (_t) window.clearTimeout(_t);
                                console.log(error);
                            });
                            _t = window.setTimeout(function () {
                                if (dialog) dialog.close();
                                messageBox.warning("加载地图超时，请检查您是否已经连接网络。")
                            }, 10 * 1000);
                        } else {
                            if (callback) {
                                callback.call(vm.$map, vm.$map);
                            }
                        }
                    }
                    vm.closeInfoWindow = function () {
                        if (mvvm.$map) mvvm.$map.closeCustomOverlayInfo();
                    }
                    vm.plans = [];
                    vm.moreResultsUrl = "";
                    vm.curLineIndex = "";
                    vm.$lineRet = null;
                    /*到这里去/从这里出发*/
                    vm.navType = "start";
                    vm.navTypeChange = function (navType) {
                        mvvm.navType = navType;
                    }
                    /*起点和终点交换*/
                    vm.navTypeExchange = function () {
                        var t = mvvm.pstart;
                        mvvm.pstart = mvvm.pend;
                        mvvm.pend = t;
                        mvvm.navType = mvvm.navType == "start" ? "end" : "start";
                        if (mvvm.$pointStart && mvvm.$pointEnd) mvvm.lineSearch(mvvm.linetype);
                    }
                    vm.setLinetype = function () {
                        var type = avalon(this).data().linetype;
                        vm.linetype = type;
                    }
                    vm.lineSearch = function (linetype, marker) {
                        mvvm.plans = [];
                        mvvm.moreResultsUrl = "";
                        mvvm.curLineIndex = "";
                        mvvm.showLeftTab = true;
                        mvvm.linetype = linetype;
                        if (vm.$map) {
                            if (mvvm.$pointStart == null) {
                                messageBox.error("请先在系统设置里标注本公司地址");
                                return;
                            }
                            if (mvvm.$pointEnd == null) {
                                messageBox.error("请选择一个目的地");
                                return;
                            }
                            if (mvvm.$marker) mvvm.$marker.closeInfoWindow();
                            mvvm.$markers = [];
                            if (mvvm.linetype == "bus") mvvm.$map.ops.linepanel = "";
                            else mvvm.$map.ops.linepanel = "divline";
                            if (mvvm.navType == "start") mvvm.$map.lineMap(mvvm.$pointStart, mvvm.$pointEnd, mvvm.linetype);
                            else mvvm.$map.lineMap(mvvm.$pointEnd, mvvm.$pointStart, mvvm.linetype);
                            mvvm.changeLeftTab("tab3");
                        } else {
                            messageBox.warning(vm.$loadmsg);
                        }
                    }
                    vm.onSearchComplete = function (ret) {
                        mvvm.$lineRet = ret;
                        if (mvvm.linetype == "bus") {
                            var planobj = mvvm.$map.getPlan(ret);
                            mvvm.plans = planobj.plans;
                            mvvm.moreResultsUrl = planobj.moreResultsUrl;
                        }
                        else {
                            mvvm.plans = [];
                            mvvm.moreResultsUrl = "";
                        }
                        //else mvvm.plan = { plans: [], moreResultsUrl: ret.moreResultsUrl };
                    }
                    vm.lineClick = function (index) {
                        mvvm.curLineIndex = mvvm.curLineIndex == index ? "" : index;
                        if (mvvm.curLineIndex) {
                            mvvm.$map.drawLine(index - 1, mvvm.$lineRet);
                        }
                    }

                    /* 鼠标移动显示 */
                    /*客户*/
                    vm.showByEmy = function (c, type) {
                        if (!mvvm.$mapLoaded || mvvm.leftTab == "tab3" || mvvm.$map.isOpenCustomOverlayInfo()) {
                            return;
                        }
                        if (c.Lng) {
                            for (var i = 0, l = mvvm.$markers.length; i < l; i++) {
                                var marker = mvvm.$markers[i];
                                if (marker.Id == c.Id) {
                                    mvvm.showOverMark(marker, type);
                                    break;
                                }
                            }
                        }
                    }
                    /*省份 */
                    vm.showByProvince = function (p, type) {
                        for (var i = 0, l = mvvm.$provinceMarks.length; i < l; i++) {
                            var marker = mvvm.$provinceMarks[i];
                            if (marker.ProvinceId == p.ProvinceId) {
                                mvvm.showOverMark(marker, type);
                                break;
                            }
                        }
                    }
                    /*城市*/
                    vm.showByCity = function (p, type) {
                        for (var i = 0, l = mvvm.$cityMarks.length; i < l; i++) {
                            var marker = mvvm.$cityMarks[i];
                            if (marker.CityId == p.CityId) {
                                mvvm.showOverMark(marker, type);
                                break;
                            }
                        }
                    }
                    vm.showOverMark = function (marker, type) {
                        if (mvvm.$map.isOpenCustomOverlayInfo()) return;
                        if (type == "over") {
                            $(marker.div).addClass("redbt");
                            $(this).addClass("selected");
                            marker.setTop(true);
                        } else {
                            $(marker.div).removeClass("redbt");
                            $(this).removeClass("selected");
                            marker.setTop(false);
                        }
                    }
                    vm.removeRedbtClass = function (markers) {
                        markers.forEach(function (marker) {
                            $(marker.div).removeClass("redbt");
                            marker.setTop(false);
                        })
                    }
                    /*点击客户显示标注*/
                    vm.clickByEmy = function (c) {
                        if (!mvvm.$mapLoaded) {
                            messageBox.warning("地图正在加载中，请稍候……");
                            return;
                        }
                        if (c.Lng) {
                            if (mvvm.$markers.length == 0) {
                                mvvm.showMarkers(_showMark);
                            } else {
                                _showMark();
                            }
                        } else {
                            messageBox.warning("此员工未有坐标！");
                        }
                        function _showMark() {
                            for (var i = 0, l = mvvm.$markers.length; i < l; i++) {
                                var marker = mvvm.$markers[i];
                                if (marker.Id == c.Id) {
                                    mvvm.markerClick.call(marker);
                                    break;
                                }
                            }
                        }
                    }
                    vm.markerClick = function () {
                        var marker = this;
                        mvvm.$marker = marker;
                        $.each(mvvm.employes.$model, function (i, c) {
                            if (c.Id == marker.Id) {
                                mvvm.entity = c;
                                return false;
                            }
                        });
                        if (mvvm.navType == "start") mvvm.pend = marker.address;
                        else mvvm.pstart = marker.address;
                        mvvm.$pointEnd = marker.point;
                        var infohtml = $(tmpl).filter("#mapEmyTmpl").text();
                        var map = mvvm.$map.map;
                        disabledGetEmyList = true;
                        map.centerAndZoom(marker.point, 12);
                        var infow = marker.openInfoWindow(infohtml);
                        mvvm.removeRedbtClass(mvvm.$markers);
                        $(marker.div).addClass("redbt");
                        marker.setTop(true);
                        maptool.Event.bindOnce(map, "zoomend", function () {
                            disabledGetEmyList = false;
                        });
                        avalon.scan(infow[0], mvvm);
                    }
                    /*热门区域*/
                    vm.hotCitys = [
                        { Id: 733635308600004, Data: "北京市" }, { Id: 733647300801606, Data: "上海市" },
                        { Id: 733640084400046, Data: "天津市" }, { Id: 733660012504170, Data: "广州市" },
                        { Id: 733660202304222, Data: "深圳市" }, { Id: 733660828904494, Data: "南宁市" }
                    ];
                    vm.clearCurArea = function () {
                        disabledGetEmyList = true;
                        mvvm.curProvinceId = "";
                        mvvm.curProvince = "";
                        mvvm.curCityId = "";
                        mvvm.curAreaId = "";
                        mvvm.curArea = "";
                        mvvm.curCity = "全部";
                        mvvm.$point1 = "";
                        mvvm.$point2 = "";
                        mvvm.getEmyList();
                        disabledGetEmyList = false;
                        mvvm.closeSelectCity();
                    }
                    vm.selectProvince = function (p) {
                        disabledGetEmyList = true;
                        mvvm.curProvinceId = p.ProvinceId;
                        mvvm.curProvince = p.ProvinceName;
                        mvvm.curCityId = "";
                        mvvm.curAreaId = "";
                        mvvm.curArea = "";
                        mvvm.curCity = p.ProvinceName;
                        if (mvvm.$mapLoaded) {
                            var map = mvvm.$map.map;
                            map.centerAndZoom(p.ProvinceName, 7);
                        }
                        //mvvm.getEmyList();
                        mvvm.getGroupDataCity(p);
                        //disabledGetEmyList = false;
                    }
                    vm.selectCity = function (c, p) {
                        var marker;
                        var cityName = c.Data || c.CityName;
                        var id = c.Id || c.CityId, name = (p && ["市辖区", "县"].indexOf(cityName) != -1) ? (p.Data || p.ProvinceName) : cityName;
                        $.each(mvvm.$cityMarks, function () {
                            if (this.Id == id) {
                                marker = this;
                                return false;
                            }
                        });
                        mvvm.curProvince = p ? p.Data || p.ProvinceName : "";
                        mvvm.curProvinceId = p ? p.ProvinceId || p.Id : "";
                        mvvm.curCity = name;
                        mvvm.curCityId = id;
                        mvvm.closeSelectCity();
                        if (mvvm.$mapLoaded) {
                            //messageBox.warning("操作失败！<br />地图尚未加载，请稍后。");
                            //return;
                            var map = mvvm.$map.map;
                            map.centerAndZoom(mvvm.curCity, 12);
                            map.centerAndZoom(marker ? marker.point : mvvm.curCity, 12);
                        }
                        mvvm.getEmyList();
                    }
                    vm.showSelectCity = false;
                    vm.openSelectCity = function (e) {
                        mvvm.showSelectCity = !mvvm.showSelectCity;
                    }
                    vm.closeSelectCity = function () {
                        mvvm.showSelectCity = false;
                    }
                    vm.openSelectArea = function (e) {

                    }
                    /*查询员工*/
                    vm.getQueyData = function () {
                        var data;
                        if (mvvm.$point1) {
                            data = { pointStart: mvvm.$point1, pointEnd: mvvm.$point2, pageSize: 50 };
                        } else {
                            data = { provinceId: mvvm.curProvinceId, cityId: mvvm.curCityId, areaId: mvvm.curAreaId, emyName: mvvm.emyName, pageSize: 50 };
                        }
                        var page = avalon.vmodels.mapHrPage;
                        if (page) data.pageSize = page.pagesize;
                        return data;
                    }
                    vm.getEmyList = function () {
                        disabledGetEmyList = false;
                        mvvm.isShowGroup = false;
                        var data = mvvm.getQueyData();
                        mvvm.loadData(data);
                    }
                    //拖动地图搜索
                    vm.isBindZoomEnd = false;
                    vm.getCustomerByBounds = function (e) {
                        if (mvvm.emyName || disabledGetEmyList || mvvm.leftTab == "tab3" || mvvm.isShowGroup) return;
                        var map = mvvm.$map.map;
                        var bs = map.getBounds();
                        var p1 = bs.getSouthWest();
                        var p2 = bs.getNorthEast();
                        mvvm.$point1 = p1.lng + "," + p1.lat;
                        mvvm.$point2 = p2.lng + "," + p2.lat;
                        mvvm.getEmyList();
                    }
                    vm.totalEmy = 0;
                    vm.isShowGroup = true;
                    vm.groupDataProvince = [];
                    vm.groupDataCity = [];
                    vm.totalEmyCity = 0;
                    vm.$markers = [];
                    vm.$provinceMarks = [];
                    vm.$cityMarks = [];
                    vm.$binddrag = false;
                    vm.loadData = function (data) {
                        //var dialog = CBCRM.loading("数据加载中……");
                        mvvm.closeInfoWindow();
                        $.post('/Hr/UserTrack', data)
                        .done(function (ret) {
                            //if (dialog) dialog.close();
                            if (ret.result) {
                                //var list = ret.data.employes.Source, totalEmy = ret.data.employes.RecordTotal;
                                var trackList = ret.data.trackList;
                                var totalEmy = trackList.length;
                                //list.forEach(function (c) {
                                //    var track = findArr(trackList, { Uid: c.Id });
                                //    c.Lng = track == null ? '' : track.Lng;
                                //    c.Lat = track == null ? '' : track.Lat;
                                //    c.TrackTime = track == null ? '' : track.TrackTime;
                                //    c.address = "";
                                //});
                                mvvm.employes = trackList;
                                mvvm.totalEmy = totalEmy;
                                var page = avalon.vmodels.mapHrPage;
                                if (page) page.total = totalEmy;
                                mvvm.showMarkers();
                            }
                        })
                    }
                    //省份分布统计
                    vm.getGroupDataProvince = function () {
                        mvvm.closeInfoWindow();
                        mvvm.closeSelectCity();
                        mvvm.isShowGroup = true;
                        mvvm.curCity = "全部";
                        $.get("/Customer/MapGroupProvince", {}, function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            var total = 0;
                            ret.data.forEach(function (item) {
                                item.citys = [];
                                if (item.ProvinceName.indexOf("广西") > -1) item.ProvinceName = "广西";
                                total += item.CustomerCount;
                            });
                            mvvm.groupDataProvince = ret.data;
                            mvvm.totalEmy = total;
                            mvvm.showGroupMarkerProvince();
                        });
                    }
                    /* 省份标注点*/
                    vm.showGroupMarkerProvince = function () {
                        disabledGetEmyList = true;
                        var groupData = mvvm.groupDataProvince, total = mvvm.totalEmy;
                        var overlayHtml = $(tmpl).filter("#mapOverlayTmpl").text();
                        mvvm.loadMap(function () {
                            var map = mvvm.$map.map;
                            map.centerAndZoom(mvvm.curCountry || "中国", 5);
                            map.clearOverlays();
                            var bdary = new BMap.Boundary();
                            var bColors = ["#ff0000", "#ff5400", "#ffd800"];
                            groupData.forEach(function (item) {
                                var op = item.CustomerCount / total;
                                var ProvinceName = item.ProvinceName;
                                mvvm.$provinceMarks = [];
                                function _click(e) {
                                    mvvm.selectProvince(item);
                                }
                                bdary.get(ProvinceName, function (rs) {
                                    var count = rs.boundaries.length; //行政区域的点有多少个
                                    for (var i = 0; i < count; i++) {
                                        var r = parseInt(Math.random() * 0 + 1, 3);
                                        var ply = new BMap.Polygon(rs.boundaries[i], { strokeWeight: 2, strokeColor: bColors[r], strokeOpacity: 0.7, fillColor: "#0000aa", fillOpacity: op }); //建立多边形覆盖物
                                        map.addOverlay(ply);
                                        //map.setViewport(ply.getPath());    //调整视野 
                                        maptool.Event.bindOnce(ply, "click", _click);
                                        if (i == 0) {
                                            var bs = ply.getBounds();
                                            var cpoint = bs.getCenter();
                                            var html = overlayHtml.replace("#name#", ProvinceName + ":" + item.CustomerCount);
                                            var marker = mvvm.$map.addCustomOverlay(cpoint, {
                                                html: html,
                                                domEvents: { click: _click }
                                            });
                                            marker.Id = item.ProvinceId;
                                            mvvm.$provinceMarks.push(marker);
                                        }
                                    }
                                });
                            });
                        });
                    }
                    vm.getGroupDataCity = function (p) {
                        mvvm.groupDataProvince.forEach(function (item) {
                            item.citys = [];
                        });
                        $.get("/Customer/MapGroupCity", { pid: p.ProvinceId }, function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            mvvm.groupDataCity = ret.data;
                            p.citys = ret.data;
                            mvvm.showGroupMarkerCity(p);
                        });
                    }
                    /* 城市标注点*/
                    vm.showGroupMarkerCity = function (p) {
                        var groupData = mvvm.groupDataCity, total = 0;
                        groupData.forEach(function (item) {
                            //if (["市辖区", "县"].indexOf(item.CityName) != -1) item.CityName = p.ProvinceName;
                            item.Parent = p;
                            total += item.CustomerCount;
                        });
                        mvvm.totalEmyCity = total;
                        var overlayHtml = $(tmpl).filter("#mapOverlayTmpl").text();
                        mvvm.loadMap(function () {
                            var map = mvvm.$map.map;
                            //map.centerAndZoom(p.ProvinceName, 10);
                            map.clearOverlays();
                            var bdary = new BMap.Boundary();
                            var bColors = ["#ff0000", "#ff5400", "#ffd800"];
                            mvvm.$cityMarks = [];

                            groupData.forEach(function (item) {
                                var op = item.CustomerCount / total * 0.8;
                                var CityName = item.CityName;
                                if (["市辖区", "县"].indexOf(CityName) != -1) CityName = p.ProvinceName;
                                function _click(e) {
                                    mvvm.selectCity(item, p);
                                }
                                bdary.get(CityName, function (rs) {
                                    var count = rs.boundaries.length; //行政区域的点有多少个
                                    for (var i = 0; i < count; i++) {
                                        var r = getRnd(0, 2);
                                        var ply = new BMap.Polygon(rs.boundaries[i], { strokeWeight: 2, strokeColor: bColors[r], strokeOpacity: 0.7, fillColor: "#0000aa", fillOpacity: op }); //建立多边形覆盖物
                                        map.addOverlay(ply);
                                        var bs = ply.getBounds();
                                        var cpoint = bs.getCenter();
                                        var html = overlayHtml.replace("#name#", item.CityName + ":" + item.CustomerCount);
                                        var mops = {
                                            html: html,
                                            domEvents: { click: _click }
                                        };
                                        if (CityName != item.CityName) {
                                            //var r = getRnd(10, 15);
                                            //mops.offset = { left: r, top: r };
                                        }
                                        var marker = mvvm.$map.addCustomOverlay(cpoint, mops);
                                        marker.Id = item.CityId;
                                        mvvm.$cityMarks.push(marker);
                                        //map.setViewport(ply.getPath());    //调整视野 
                                        maptool.Event.bindOnce(ply, "click", _click);
                                    }
                                });
                            });
                        });
                    }
                    /* 标注点*/
                    vm.showMarkers = function (callback) {
                        vm.loadMap(function () {
                            var map = mvvm.$map;
                            map.clearOverlays();
                            mvvm.$markers = [];
                            var overlayHtml = $(tmpl).filter("#mapOverlayTmpl").text();
                            mvvm.employes.forEach(function (item) {
                                if (item.Lng) {
                                    var point = new BMap.Point(item.Lng, item.Lat);
                                    var html = overlayHtml.replace("#name#", item.FullName + "&nbsp;" + item.TrackTime);
                                    //mvvm.markerClick
                                    var marker = map.addCustomOverlay(point, {
                                        html: html,
                                        domEvents: {
                                            click: mvvm.markerClick,
                                            mouseover: function () {
                                                mvvm.showOverMark(this, "over");
                                            },
                                            mouseout: function () {
                                                mvvm.showOverMark(this, "out");
                                            }
                                        },
                                        onCloseInfoWindow: function () {
                                            $(this.div).removeClass("redbt");
                                            mvvm.$marker = null;
                                        },
                                        debug: true
                                    });
                                    $(marker.div).removeClass("bluebt").addClass("yellowbt")
                                    marker.address = "";
                                    marker.Id = item.Id;
                                    mvvm.$markers.push(marker);
                                }
                            });
                            if (callback) callback();
                        });
                    }
                })
                bindWatch();
                var disabledGetEmyList = false;
                function bindWatch() {
                    mvvm.$watch("curCityId", function (n) {
                        var areas = n ? getChildAreas(n) : [];
                        mvvm.cityAreas = areas;
                        mvvm.curAreaId = "";
                        mvvm.curArea = "";
                    });
                    mvvm.$watch("curAreaId", function (n) {
                        var area, areas = mvvm.cityAreas;
                        var map = mvvm.$map.map;
                        for (var i = 0, l = areas.length; i < l; i++) {
                            if (n == areas[i].Id) {
                                area = areas[i];
                                mvvm.curArea = area.Data;
                                map.centerAndZoom(mvvm.curArea, 13);
                                break;
                            }
                        }
                        if (!disabledGetEmyList) mvvm.getEmyList();
                    });
                }
                function getCompany() {
                    var m = cmyInfo;
                    mvvm.curCountryId = m.CountryId;
                    mvvm.curCountry = m.CountryDisplay;
                    mvvm.curProvinceId = m.ProvinceId;
                    m.curProvince = m.ProvinceDisplay;
                    mvvm.curCityId = m.CityId;
                    //mvvm.curAreaId = m.AreaId;
                    mvvm.curCountry = m.CountryDisplay;
                    mvvm.curCity = m.CityDisplay;
                    //mvvm.curAreaId = "";
                    //mvvm.curArea = "";
                }
                var locations = [];
                function getLocations() {
                    $.get("/Settings/GetLocations", {}, function (d) {
                        if (d.data && d.data.length > 0) {
                            var a = d.data;
                            locations = a;
                            //mvvm.eachCountry.removeAll();
                        }
                        getHotCitys();
                        getCompany();
                        fill();
                    });
                }
                function getHotCitys() {
                    //$.get("/Settings/GetHotCitys", {}, function (ret) {
                    //    if (ret.result) {
                    //        mvvm.hotCitys = ret.data;
                    //    }
                    //});
                }
                function initSelectCity() {
                    var allletters = [];
                    for (var i = 65; i < 91; i++) {
                        var c = String.fromCharCode(i);
                        allletters[c] = [];
                    }
                    var btn = $("#curCity_i"), dcity = $("#citySelectDiv"), offset = btn.offset();
                    dcity.css({ left: offset.left + "px", top: (offset.top + btn.height()) + "px" });
                    for (var i = 0, l = locations.length; i < l; i++) {
                        var a = locations[i];
                        if (a.ParentId == mvvm.curCountryId) {
                            var pro = { Id: a.Id, Data: a.Data, FirstLetter: a.FirstLetter, Letter: a.Letter };
                            pro.citys = getChildAreas(pro.Id);
                            allletters[pro.FirstLetter].push(pro);
                        }
                    }
                    var cityLetters = [], letters = [];
                    for (var key in allletters) {
                        var parr = allletters[key];
                        if (parr.length > 0) {
                            letters.push(key);
                            parr.forEach(function (p, i) {
                                p.L = i == 0 ? p.FirstLetter : "";
                                cityLetters.push(p);
                            })
                        }
                    }
                    mvvm.letters = letters;
                    mvvm.cityLetters = cityLetters;
                }
                function getChildAreas(id) {
                    var areas = [];
                    locations.forEach(function (a) {
                        if (a.ParentId == id) areas.push({ Id: a.Id, Data: a.Data, FirstLetter: a.FirstLetter, Letter: a.Letter });
                    });
                    return areas;
                }
                function getRnd(min, max) {
                    var r = parseInt(Math.random() * (max - min + 1) + min, 10);
                }
                //getLocations();
                getCompany();
                fill();
                function fill() {
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
                    avalon.nextTick(function () {
                        //initSelectCity();
                        mvvm.getEmyList();
                        var w = 0;
                        if ($.browser.msie) w = 20;
                        if ($.browser.mozilla) w = 0;
                        mvvm.mapwidth = $(document).width() - $("#map_client_l").width() - w;
                        mvvm.mapheight = $(window).height() - $("#topBg").height() - $("#gps").height() - 5;
                    });
                }
            }
        }
        return HR;
    });