define('Tools', [
    'modelFactory',
    'plugins',
    'json',
    'dialog',
    'common',
    'upload',
    'kindedit', 'leftMenu'],
    function (modelFactory,plugins) {
        var Tools = {
            /// <summary>
            /// 工作台
            /// </summary>
            Index: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this, params = this.params,
                    mvvm = avalon.define('Tools', function (vm) {
                        vm.SMS = false;
                        vm.IMPORT = false;
                        vm.EXPORT = false;
                        vm.EMAIL = false;
                    });
                function initIndex() {
                    $.get('/Tools/Index/', {}, function (ret) {
                        if (ret.result) {
                            mvvm.SMS = ret.data.SMS;
                            mvvm.IMPORT = ret.data.IMPORT;
                            mvvm.EXPORT = ret.data.EXPORT;
                            mvvm.EMAIL = ret.data.EMAIL;
                        }
                    });
                }
                initIndex();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                CBCRM.onLoadModuleBefore = function () {
                    avalon.vmodels.Index = null
                }
            },
            //数据导入
            Import: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this, params = this.params
                var mvvm = CBCRM.define('Import', function (vm) {
                    vm.lang = lang;
                    vm.$skipArray = ['lang'];
                    vm.destroy = function () {
                        destroyui(["dropDownAreasTreeImport"])
                    }
                    vm.leftTabs = [
                        { value: '客户导入', key: 'khdr' },
                        { value: '产品导入', key: 'cpdr'  },
                        { value: '联系人导入', key: 'lxrdr'  }
                    ];
                    vm.title = '客户导入'
                    vm.auth = {

                    }
                    vm.importLabel = '开始导入'
                    vm.lockSubmit = false
                    vm.dictory = []
                    vm.areaDisplay = ''
                    vm.dropDownAreasTreeOpts = {
                        treeopts: {
                            callback: {
                                onCheck: function (event, treeId, treeNode) {
                                    var treeObj = $.fn.zTree.getZTreeObj(treeId)
                                    , nodes = treeObj.getCheckedNodes(true)
                                    , display = []
                                    , ids = []
                                    , start = null
                                    if (nodes) {
                                        start = nodes[0]
                                        display.unshift(start.Data)
                                        ids.unshift(start.Id)
                                        while (true) {
                                            start = start.getParentNode()
                                            if (!start)
                                                break
                                            display.unshift(start.Data)
                                            ids.unshift(start.Id)
                                        }
                                    }
                                    if (display.length)
                                        mvvm.areaDisplay = display.join('，')
                                    if (ids.length) {
                                        mvvm.include.companyCountryId = ids[0]
                                        mvvm.include.companyProvinceId = ids.length > 1 ? ids[1] : ''
                                        mvvm.include.companyCityId = ids.length > 2 ? ids[2] : ''
                                        mvvm.include.companyAreaId = ids.length > 3 ? ids[3] : ''
                                    } else {
                                        mvvm.include.companyCountryId = ''
                                        mvvm.include.companyProvinceId = ''
                                        mvvm.include.companyCityId = ''
                                        mvvm.include.companyAreaId = ''
                                    }
                                }
                            }
                            , check: {
                                enable: true,
                                chkStyle: 'radio',
                                radioType: 'all'

                            }
                        }
                    }
                    vm.include = {
                        filepath: '',
                        repeat: true,
                        setArea: false,
                        cate: 'khdr',
                        companyCountryId: '',
                        companyProvinceId: '',
                        companyCityId: '',
                        companyAreaId: ''
                    }
                    vm.leftTabChange = function (key,value) {
                        mvvm.include.cate = key;
                        mvvm.title = value;
                    }
                    vm.importStart = function () {
                        var model = mvvm.include.$model;
                        mvvm.lockSubmit = true
                        mvvm.importLabel = '正在导入，请稍后……'
                        if (model.filepath) {
                            var url;
                            switch (model.cate) {
                                case "cpdr":
                                    url = "/Tools/ImportProdutct";
                                    break;
                                case "lxrdr":
                                    url = "/Tools/ImportContact";
                                    break;
                                default:
                                    url = "/Tools/ImportCustomer";
                                    break;
                            }
                            $.post(url, model, function (ret) {
                                mvvm.lockSubmit = false
                                mvvm.importLabel = '开始导入'
                                if (ret.result)
                                    messageBox.succeed(ret.message);
                                else
                                    messageBox.warning(ret.message);
                            }).error(function () {mvvm.lockSubmit = false });
                        }
                        else messageBox.warning('请先选择需要导入的文件!');
                    }
                    vm.openImport = function () {
                        var upwin=CBCRM.upload(true, function (node, data, file) {
                            var src = '/Upload/' + file.Path;
                            if (isExcle(src)) {
                                upwin.close();
                                mvvm.include.filepath = src;
                            }
                            else messageBox.error("操作失败,选择的文件不是Excel格式!");
                        }, { settings: { multi: false, fileTypeExts: "*.xls;" }});
                    }
                    vm.loading = false

                    vm.country = []
                    vm.province = []
                    vm.city = []
                    vm.area = []
                })
                $.post('/Tools/Import')
                .done(function (ret) {
                    if (ret.result) {
                        var auth=ret.data.auth
                        mvvm.auth = auth;
                    }
                })
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                $('#left_menu_top').html('<h2>数据导入</h2>').show()

            },
            //数据导出
            Export: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this, params = this.params;
                var mvvm = CBCRM.define('Export', function (vm) {
                    vm.lang = lang;
                    vm.destroy = function () {
                        mvvm.destroyui(["dropDownAreasTreeExport", "exportCustomerUserTree"])
                    }
                    vm.leftTabs = [
                        { value: '客户导出', key: 'khdc' }
                        //{ value: '产品导出', key: 'cpdc' },
                        //{ value: '联系人出', key: 'lxrdc' }
                    ];
                    vm.title = '客户导出'
                    vm.auth = {};
                    vm.exportLabel = '开始导出'
                    vm.lockSubmit = false
                    vm.showList = true;
                    vm.grid1 = createGrid({
                        $lang:lang
                    });
                    vm.dictory = []
                    vm.areaDisplay = ''
                    vm.dropDownAreasTreeOpts = {
                        treeopts: {
                            callback: {
                                onCheck: function (event, treeId, treeNode) {
                                    var treeObj = $.fn.zTree.getZTreeObj(treeId)
                                    , nodes = treeObj.getCheckedNodes(true)
                                    var ids = [[], [], [], []], names = [];
                                    nodes.forEach(function (item) {
                                        if (item.level < ids.length) ids[item.level].push(item.Id);
                                        if (names.length < 10) names.push(item.Data);
                                    });
                                    if (nodes.length > 10) names.push("...");
                                    mvvm.customerQuery.ctIds = ids[0].join(",")
                                    mvvm.customerQuery.pIds = ids[1].join(",")
                                    mvvm.customerQuery.cIds = ids[2].join(",")
                                    mvvm.customerQuery.aIds = ids[3].join(",")
                                    mvvm.customerQuery.areas = names.join(",");
                                }
                            }
                            , check: {
                                enable: true,
                                chkStyle: "checkbox",
                                chkboxType: { "Y": "", "N": "" }
                            }
                        }
                    }
                    vm.initQuery = function (exportType) {
                        switch (exportType) {
                            case "customer":
                                mvvm.customerQuery= {
                                    setArea: false,
                                    setBelong: false,
                                    exportExcel: true,
                                    sCat: "",
                                    cat: "",
                                    stage: "",
                                    state: "",
                                    memberGrade: "",
                                    uids: "",
                                    unames: "",
                                    addTime1: "",
                                    addTime2: "",
                                    cAmount1: "",
                                    cAmount2: "",
                                    areas: "",
                                    ctIds: '',
                                    pIds: '',
                                    cIds: '',
                                    aIds: ''
                                }
                                break;
                        }
                    }
                    vm.customerQuery = {};
                    vm.selectUser = function () {
                        var ids = mvvm.customerQuery.uids || "";
                        var ids = ids.split(",");
                        plugins.selectUser({
                            dataAuth: "1020101,1020301,1020401,1020501,1020601,1020701,1020801",
                            multiple: true,
                            listData:ids,
                            callback: function (us) {
                                var a = where(us, true, ["Id", "FullName"]);
                                var l = a[1].length;
                                if (l > 10) {
                                    a[1].splice(10, l - 10);
                                    a[1].push("...");
                                }
                                mvvm.customerQuery.uids = a[0].join(",");
                                mvvm.customerQuery.unames = a[1].join(",")
                            }
                        })
                    }
                    vm.include = {
                        cate: 'khdc'
                    }
                    vm.leftTabChange = function (key, value) {
                        mvvm.include.cate = key;
                        mvvm.title = value;
                    }
                    
                    vm.exportStart = function () {
                        var model = mvvm.include.$model;
                        mvvm.lockSubmit = true
                        mvvm.exportLabel = '正在导出，请稍后……'
                        var url="", data = {};
                        switch (model.cate) {
                            default:
                                url = "/Customer/ExportToExcel";
                                data = mvvm.customerQuery.$model;
                                break;
                        }
                        mvvm.grid1.clear();
                        mvvm.grid1.gridmsg = lang.LoadingMsg;
                        mvvm.$stopExport = false;
                        mvvm.doExport(url,data);
                    }
                    vm.$dialog = null;
                    vm.$stopExport = false;
                    vm.doExport = function (url,data) {
                        if (mvvm.$stopExport) return;
                        var req = $.ajax({
                            type: "post",
                            url: url,
                            data:data,
                            error:function(re,s,ex){
                                mvvm.resetBtnStart();
                                console.log(ex);
                                console.log(re);
                                messageBox.error("导出过程发生意外错误或者被中止，导出已经停止！");
                            },
                            success:function (ret) {
                                if (!ret.result) {
                                    mvvm.resetBtnStart();
                                    if (mvvm.$dialog) mvvm.$dialog.close();
                                    return CBCRM.showResult(ret);
                                }
                                if (mvvm.$stopExport) return;
                                var re = ret.data;
                                mvvm.grid1.addRow(re.file);
                                if (re.pageCount == 1) {
                                    //mvvm.showList = false;
                                    mvvm.resetBtnStart();
                                    mvvm.grid1.gridmsg = "";
                                    //mvvm.downFile(mvvm.grid1.list[0]);
                                } else {
                                    mvvm.showList = true;
                                    if (re.pageCount > re.pageIndex) {
                                        data.pageIndex = re.pageIndex + 1;
                                        data.pageSize = re.pageSize;
                                        var msg = "共有(" + re.total + ")条数据，分成"+  re.pageCount +"个文件，正在导出第" + data.pageIndex + "个（共" + re.pageCount + "个）,请耐心等待。";
                                        if (mvvm.$dialog) {
                                            mvvm.$dialog.noAbort = true;
                                            mvvm.$dialog.close();
                                        }
                                        mvvm.$dialog = CBCRM.loading(msg, null, function () {
                                            if (mvvm.$dialog.noAbort) return;
                                            mvvm.$stopExport = true;
                                            if (req) {
                                                req.abort();
                                            }
                                            mvvm.resetBtnStart();
                                            mvvm.grid1.gridmsg = "";
                                        }, "停止导出");
                                        mvvm.doExport(url, data);
                                    } else if (re.pageCount <= re.pageIndex) {
                                        mvvm.grid1.gridmsg = "";
                                        mvvm.resetBtnStart();
                                        if (mvvm.$dialog) mvvm.$dialog.close();
                                        var msg = "文件导出完成！共有数据(" + re.total + ")条，共导出" + re.pageCount + "个文件";
                                        messageBox.ok(msg);
                                    }
                                }
                            }
                        });
                    }
                    vm.zipDown = function () {
                        var list = mvvm.grid1.getChecked();
                        if (list.length == 0) {
                            messageBox.error("请选择需要打包下载的文件。");
                            return;
                        }
                        var data = { exportType: list[0].exportType };
                        var fileList = where(list, true, "rFileName");
                        $.extend(data, jsonToSubmit("fileList", fileList));
                        var url = "/Tools/ZipExportFile";
                        var dialog = CBCRM.loading("正在进行打包，请稍后。");
                        $.post(url, data, function (ret) {
                            dialog.close();
                            if (!ret || !ret.result) return CBCRM.showResult(ret);
                            dialog=messageBox.ok("已经成功打包文件,开始下载压缩包。")
                            var file = ret.data.file;
                            var url = "/Tools/DownloadExportFile";
                            file.exportExcel = true;
                            frameSubmit(url, "post", file, function () {
                                if (dialog) dialog.close();
                            });
                        });
                    }
                    vm.resetBtnStart = function () {
                        mvvm.exportLabel = "开始导出";
                        mvvm.lockSubmit = false;
                    }
                    
                    vm.downFile = function (file,index) {
                        var data = file.$model;
                        data.exportExcel = true;
                        var url = "/Tools/DownloadExportFile";
                        frameSubmit(url, "post", data);
                        if (index != null) mvvm.grid1.list.removeAt(index);
                    }
                    vm.loading = false
                    vm.bindWatch = function () {
                        mvvm.customerQuery.$watch("sCat", function (n,o) {
                            mvvm.customerQuery.cat = "";
                            mvvm.dicts.cats = [];
                            if (!n) return;
                            mvvm.dicts.allCats.$model.forEach(function (item) {
                                if(item.ParentId==n)mvvm.dicts.cats.push(item)
                            });
                        })
                    }
                    vm.dicts = {
                        sCats: [],
                        cats: [],
                        allCats:[],
                        stages: [],
                        memberGrades:[]
                    };
                    vm.getDicts = function () {
                        getDicts({
                            sCats: 100026,
                            allCats: 100027,
                            stages: 100011
                        }, mvvm.dicts);
                    }
                })
                function init() {
                    mvvm.grid1.init();
                    mvvm.initQuery("customer");
                    $.post('/Tools/Export')
                        .done(function (ret) {
                            if (ret.result) {
                                mvvm.auth = ret.data.auth;
                                mvvm.dicts.memberGrades = ret.data.memberGrades;
                            }
                        })
                    mvvm.getDicts();
                    mvvm.bindWatch();
                }

                init();
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                $('#left_menu_top').html('<h2>数据导出</h2>').show()

            },
            ///手机短信
            Message: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this, params = this.params,vmid="Message",
                    subCategorys = [];
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.lang = lang;
                    vm.title = '客户导入'
                    vm.show = 'index'
                    vm.SMS = false
                    vm.sameData = false
                    vm.showSameData = false
                    vm.lockSubmit = false
                    vm.classChange = function () {
                        var index = parseInt($(this).attr('index'));
                        mvvm.dictory[index].ShowChild = !mvvm.dictory[index].ShowChild;
                    }
                    vm.shortcut = function () {
                        var val = $(this).attr('title');
                        mvvm.sms.context = val;
                        compeContext(mvvm.sign);
                    }
                    vm.dictory = []
                    vm.sms = { numbers: '', context: '', preview: '', ids: '' }
                    vm.smsSend = function () {
                        var that = $(this);
                        that.attr('disabled', 'disabled');
                        mvvm.loading = true;
                        mvvm.sendSms(function (ret) {
                            that.removeAttr('disabled');
                            mvvm.loading = false;
                        });
                    }
                    vm.beforeSend = function () {
                        return true;
                    }
                    vm.sendSms = function (callback) {
                        if (!mvvm.beforeSend(callback)) {
                            return;
                        }
                        var model = mvvm.sms.$model;
                        if (model.numbers && model.context) {
                            $.post('/Tools/SmsSend/', mvvm.sms.$model, function (ret) {
                                if (ret.result) {
                                    messageBox.succeed("短信发送成功！");
                                    mvvm.smsHistory = ret.data.Source;
                                }
                                else
                                    messageBox.error(ret.message);
                                if (callback) callback(ret);
                            });
                        }
                        else {
                            messageBox.warning('请填写手机号码和短信内容');
                            if(callback)callback(false);
                        }
                    }
                    vm.sendSmsMulti = function (listData, callback) {
                        var data = $.extend(true, {}, listData);
                        if (mvvm.sign) {
                            for (var key in data) {
                                data[key] = data[key] + mvvm.fullName;
                            }
                        }
                        var data = jsonToSubmit("listData", data);
                        data.sameData = mvvm.sameData;
                        $.post('/Tools/SmsSendMulti/', data, function (ret) {
                            if (ret.result) {
                                messageBox.succeed("短信发送成功！");
                            }
                            else
                                messageBox.error(ret.message);
                            if (callback) callback(ret);
                        });
                    }
                    vm.dialogWidth = 760;
                    vm.showSend = function () {
                        var htmltmpl = $(tmpl).find("#message_input_tmpl").text();
                        var btns = [
                            {
                                name: "发送",
                                focus: true,
                                callback: function () {
                                    var dialog = loading("短信发送中……");
                                    mvvm.sendSms(function (ret) {
                                        if (dialog) dialog.close();
                                    });
                                    return false;
                                }
                            }
                        ]
                        var dialog = mvvm.openTmpl({
                            title: "发送手机短信", w: mvvm.dialogWidth,
                            tmplId: "message_input_tmpl", tmpl: tmpl,
                            extParam: { top: 50 },
                            button:btns
                        });
                    }
                    vm.smsTag = 'send'
                    vm.smsChange = function () {
                        var tag = $(this).attr('tag');
                        mvvm.smsTag = tag;
                    }
                    //分页
                    vm.userpaing = {
                        paging: function () {
                            var that = this
                            $.get('/Tools/SmsHistory/', {
                                pageSize: that.pagesize,
                                pageIndex: that.currentindex + 1
                            }, function (ret) {
                                mvvm.smsHistory = ret.data.Source;
                                avalon.vmodels.upaing.total = ret.data.RecordTotal;
                            });
                        }
                    }
                    vm.smsHistory = []
                    vm.fullName = ''
                    vm.sign = true
                    vm.loading = false
                    vm.contacts = []
                    vm.users = []
                    vm.smsEntity = {};
                    vm.doViewSms = function (entity) {
                        mvvm.smsEntity = entity;
                        var dialog = mvvm.openTmpl({
                            title: "短信发送详情", w:600,h:300,
                            tmplId: "viewTmpl", tmpl: tmpl
                        });
                    }
                    //选择收信人
                    //查询条件
                    vm.subCategorys = [];
                    vm.showMoreQuery = false;
                    vm.toggleMoreQuery = function () {
                        mvvm.showMoreQuery = !mvvm.showMoreQuery;
                    }
                    initQuerys(vm);
                    var firstQ = { label: "不限", val: "", curr: true };
                    vm.queryData = {
                        categoryId: {
                            label: "客户形态", val: "", valLabel: "",
                            items: [$.extend({}, firstQ)]
                        },
                        subCategoryId: {
                            label: "客户分类", val: "", valLabel: "", showMore: false, length: 0,
                            items: [$.extend({}, firstQ)]
                        },
                        cState: {
                            label: "客户状态", val: "", valLabel: "",
                            items: [$.extend({}, firstQ),
                            { label: "正式", val: "1", curr: false },
                            { label: "潜在", val: "0", curr: false },
                            ]
                        },
                        state: {
                            label: "客户阶段", val: "", valLabel: "",
                            items: [$.extend({}, firstQ)]
                        },
                        businessType: {
                            label: '业务分类', val: "", valLabel: "", showMore: false, length: 0,
                            items: [$.extend({}, firstQ)]
                        },
                        serviceLabel: {
                            label: '服务标签', val: "", valLabel: "", showMore: false, length: 0,
                            items: [$.extend({}, firstQ)]
                        },
                        memberGrade: {
                            label: '会员级别', val: "", valLabel: "", showMore: false, length: 0,
                            items: [$.extend({}, firstQ)]
                        },
                        addTime1: {
                            label: '起始时间', val: "", valLabel: "",
                        },
                        addTime2: {
                            label: '截止时间', val: "", valLabel: "",
                        }
                    }
                    vm.addTime1Opts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.addQuery("addTime1", formatDate, mvvm.queryData.addTime1.label + ":" + formatDate);
                        }
                    }
                    vm.addTime2Opts = {
                        format: '%Y-%m-%d',
                        onSelect: function (date, formatDate, format) {
                            mvvm.addQuery("addTime2", formatDate, mvvm.queryData.addTime2.label + ":" + formatDate);
                        }
                    }
                    vm.clearQueryTime = function () {
                        mvvm.removeQuery("addTime1", true);
                        mvvm.removeQuery("addTime2", false);
                    }
                    vm.onQueryChange = function (data, name, val, type) {
                        data.keyword = mvvm.keyword;
                        GetContactsData(data);
                    }
                    vm.tabWidth = 800;
                    vm.tabHeight = 500;
                    //选择客户联系人
                    vm.openSelect = function () {
                        mvvm.showMoreQuery = false;
                        mvvm.initKey();
                        mvvm.clearQuery(false);
                        mvvm.allc = false;
                        mvvm.allu = false;
                        var btns = [{
                            name: '确定',
                            focus: true,
                            callback: function () {
                                var numbers = [], ids = [], msg = "";
                                var reg = /^\d{11}$/

                                if (mvvm.selectTag == 'contacts') {
                                    mvvm.contacts.forEach(function (item) {
                                        if (!item.Checked) return;
                                        var number = item.MobileNumber1 || item.Customer.CompanyTel1;
                                        if (number && reg.test(number)) {
                                            numbers.push(number)
                                            ids.push(item.Name)
                                        } else {
                                            msg += item.Name + "(" + (number || "") + ")<br/>";
                                        }
                                    });
                                } else {
                                    mvvm.users.forEach(function (item) {
                                        if (!item.Checked) return;
                                        if (item.Phone && reg.test(item.Phone)) {
                                            numbers.push(item.Phone)
                                            ids.push(item.FullName)
                                        } else {
                                            msg += item.FullName + "(" + (item.Phone || "") + ")<br/>";
                                        }

                                    });
                                }
                                mvvm.sms.numbers = numbers.toString();
                                mvvm.sms.ids = ids.toString();
                                if (msg != "")
                                    messageBox.warning(msg + '手机号码为空或者格式错误,已过滤!');
                                return true;
                            }
                        },
                        {
                            name: "选全部结果",
                            callback: function () {
                                var data = mvvm.createQuery();
                                var ldialog = loading("正在获取数据……")
                                $.post("/Tools/GetContactsMobile", data, function (ret) {
                                    if (ldialog) ldialog.close();
                                    if (ret.result) {
                                        var numbers = [], ids = [];
                                        ret.data.forEach(function (item) {
                                            numbers.push(item.mobile);
                                            ids.push(item.name);
                                        })
                                        mvvm.sms.numbers = numbers.toString();
                                        mvvm.sms.ids = ids.toString();
                                        if (dialog) dialog.close();
                                    }
                                })
                                return false
                            }
                        }
                        ];
                        var dialog = mvvm.openTmpl({
                            title: "选择联系人手机号码", w: mvvm.tabWidth, h: mvvm.tabHeight,
                            tmplId: "selectTemplate", tmpl: tmpl,
                            button:btns
                        });
                    }
                    vm.key = { user: "", contact: "" };
                    vm.initKey = function () {
                        mvvm.key = { user: "", contact: "" }
                    }
                    vm.onKeySearch = function (act, type) {
                        if (type == "Contact") {
                            if (act == 1) mvvm.key.contact = "";
                            GetContactsData(mvvm.createQuery());
                        } else {
                            if (act == 1) mvvm.key.user = "";
                            GetUsers();
                        }

                    }
                    vm.onKeyEnter = function (e, type) {
                        if (e.keyCode == 13) {
                            mvvm.onKeySearch(0, type);
                        }
                    }
                    vm.getCheckContact = function (treeObj) {
                        var nodes = treeObj.getCheckedNodes(true);
                        var numbers = [], ids = [];
                        var reg = /^\d{11}$/
                        for (var i = 0; i < nodes.length; i++) {
                            var m = nodes[i].Phone;
                            if (reg.test(m)) {
                                numbers.push(m);
                                ids.push(nodes[i].Name);
                            }
                        }
                        mvvm.sms.numbers = numbers.toString();
                        mvvm.sms.ids = ids.toString();
                    }
                    //选择同事
                    vm.selectUser = function () {
                        plugins.selectUser({
                            multiple: true,
                            callback: function (us) {
                                var reg = /^\d{11}$/
                                var a = where(us, function (m) {
                                    return reg.test(m.Phone);
                                }, ["Phone","FullName"]);
                                mvvm.sms.numbers = a[0].join(",");
                                mvvm.sms.ids = a[1].join(",");
                            }
                        })
                    }
                    //联系人分页
                    vm.contactOpts = {
                        pagesize: 10,
                        pagesizeopts: [10, 20, 50, 100],
                        paging: function () {
                            var pIndex = (this.currentindex + 1) || 1
                            var pSize = this.pagesize
                            var data = mvvm.createQuery();
                            $.extend(data, { pageIndex: pIndex, pageSize: pSize });
                            GetContactsData(data);
                        }
                    }
                    //选项卡
                    vm.selectTag = 'contacts'
                    vm.selectChange = function () {
                        vm.selectTag = $(this).attr('tag');
                    }
                    vm.allc = false;
                    vm.allu = false;
                    //短信模板选择
                    vm.tmplWidth = 800;
                    vm.$sdialog = null;
                    //选择短信模板
                    vm.selectTmpl = function () {
                        mvvm.$sdialog = openTmpl({
                            vm: mvvm,
                            title: "请选择模板",
                            tmpl: tmpl,
                            tmplid: "messageSelectTmpl",
                            w: mvvm.tmplWidth,
                            padding:"10px",
                            btns: [{
                                name: "确定选择",
                                focus: true,
                                callback: function () {
                                    var items = mvvm.grid2.getChecked();
                                    if (items.length == 0) {
                                        messageBox.error("操作失败<br />请选择模板！");
                                        return false;
                                    }
                                    mvvm.selectTmplItem(items[0]);
                                }
                            }],
                            onclose: function () {
                                destroyui(["MessageTmplSelectpage", "MessageTmplSelectTree"]);
                            },
                        });
                    }
                    vm.selectTmplItem = function (item) {
                        mvvm.sms.context = item.Data;
                        if (mvvm.$sdialog) {
                            mvvm.$sdialog.close();
                            mvvm.$sdialog = null;
                        }
                        if (mvvm.onTmplSelect) mvvm.onTmplSelect.call(mvvm.sms, item);
                    }
                    vm.selectChange = function (item) {
                        if (!this.checked) return;
                        mvvm.grid2.list.forEach(function (c) {
                            if (c.Id != item.Id) c.checked = false;
                        });
                    }
                    vm.onTmplSelect = function (tmplItem) {
                        mvvm.replaceTmplData("通用", {});
                    }
                    vm.replaceTmplData = function (tableName,model) {
                        if (tableName != "通用") mvvm._replaceTmplData(tableName, model);
                        var t=new Date(),user=CBCRM.memberShip,cmy=CBCRM.cmyInfo;
                        //通用信息模板数据模型
                        var cModel = {
                            "公司名称": cmy.CompanyName, "公司简称": cmy.ShortName, "公司电话": cmy.OfficeTel1, "公司传真": cmy.Fax,
                            "公司QQ":cmy.QQ,"Email":cmy.Email,"公司地址":cmy.Address,
                            "登陆名": user.UserName, "用户姓名": user.FullName, "用户部门": user.Post, "用户职位": user.Position,
                            "系统时间": telesa.datetime.now(), "年": t.getFullYear(), "月": t.getMonth() + 1, "日": t.getDate(),
                            "时": t.getHours(), "分": t.getMinutes(), "秒": t.getSeconds
                        }
                        var context = mvvm._replaceTmplData("通用", cModel);
                        return context;
                    }
                    vm._replaceTmplData = function (tableName,model) {
                        var context = mvvm.sms.context;
                        for (var key in model) {
                            context = mvvm.replaceAll(context, "#"+tableName + "_" + key+"#", model[key]);
                        }
                        mvvm.sms.context = context;
                        return context;
                    }
                    vm.replaceAll = function (s1, s2,s3) {
                        if (s3 == null) return s1;
                        var reg = new RegExp(s2, "ig");
                        return s1.replace(reg, s3);
                    }
                    vm.doTmplSearch = function () {
                        mvvm.grid2LoadData(mvvm.queryData2.$model);
                    }
                    vm.onTmplEnter = function (e) {
                        if(e.keyCode==13)mvvm.doTmplSearch();
                    }
                    vm.grid2 = createGrid({});
                    vm.queryData2 = {
                        category: "",
                        name: ""
                    }
                    vm.selectlistpaing = {
                        paging: function () {
                            var data = $.extend(true, {}, mvvm.queryData2.$model);
                            data.pageSize = this.pagesize
                            data.pageIndex = this.currentindex + 1
                            mvvm.grid2LoadData(data);
                        }
                    }
                    vm.grid2LoadData = function (data) {
                        $.post("/Tools/MessageTmpl", data, function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            var list = ret.data.Source;
                            mvvm.grid2.initList(list, ret.data.RecordTotal);
                            var page = avalon.vmodels["MessageTmplSelectpage"];
                            if (page) page.total = ret.data.RecordTotal;
                        })
                    }
                    //分类树
                    vm["MessageTmplSelectTreeOpts"] = {
                        treeopts: {
                            async: {
                                url: function (treeId, treeNode) {
                                    var url = "/Tools/MessageTmplCategory"
                                    return url
                                }
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    var category = treeNode.Id;
                                    if (category == 1) category = "";
                                    else {
                                        category = getNodeIds(treeNode).join(",");
                                    }
                                    mvvm.queryData2.category = category;
                                    mvvm.grid2LoadData(mvvm.queryData2.$model);
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            }
                        }
                    }
                    vm.destroy = function () {
                        destroyui(["messageContactTree", "shareToTree"]);
                        avalon.vmodels[vmid] = null;
                    }
                });
                mvvm.grid2.bindWatch();
                mvvm.$watch('allc', function (n, o) {
                    mvvm.contacts.forEach(function (item) { item.Checked = n; })
                })
                mvvm.$watch('allu', function (n, o) {
                    mvvm.users.forEach(function (item) { item.Checked = n; })
                })
                mvvm.$watch('sign', function (n, o) {
                    compeContext(n);
                });
                mvvm.sms.$watch('context', function (n, o) {
                    compeContext(mvvm.sign);
                });
                mvvm.$watch('fullName', function (n, o) {
                    compeContext(mvvm.sign);
                });
                mvvm.queryData.categoryId.$watch("val", function (n) {
                    var q = mvvm.queryData.subCategoryId
                    mvvm.removeQuery("subCategoryId", true);
                    q.items.splice(1, q.items.length);
                    if (!n) return;
                    subCategorys.forEach(function (item) {
                        if (item.ParentId == n) {
                            q.items.push({ label: item.Data, val: item.Id, curr: false });
                        }
                    });
                });
                var action = params.action;
                function loading(msg) {
                    var html = "<p>" + msg + "</p><p><img src='/Content/Themes/Base/Images/loading2.gif' border='0' /></p>";
                    return messageBox.openHtml("系统提示", 300, 100, html);
                }
                //选取该节点以及其子节点下所有的员工
                function treeCheckNodes(treeObj, treeNode) {
                    treeObj.checkNode(treeNode, true);
                    if (treeNode.children) {
                        for (var i = 0, l = treeNode.children.length; i < l; i++) {
                            treeCheckNodes(treeObj, treeNode.children[i]);
                        }
                    }
                }
                function compeContext(chk) {
                    mvvm.sms.preview = chk
                        ? mvvm.sms.context + " " + mvvm.fullName
                        : mvvm.sms.context;
                }
                function initWithData(callback) {
                    $.get('/Tools/GetSmsDictionary/', {}, function (ret) {
                        if (ret.result && ret.data) {
                            var dicts = ret.data.dicts, name = ret.data.name, dictory = ret.data.dictory;
                            mvvm.fullName = name;
                            if (dicts) {
                                subCategorys = dicts.subCategorys;
                                for (var key in dicts) {
                                    if (mvvm.queryData[key]) {
                                        var arr = dicts[key];
                                        arr.forEach(function (d) {
                                            if (key != "subCategory") {
                                                var item = { label: d.Data || d.Name, val: d.Id, curr: false };
                                                mvvm.queryData[key].items.push(item);
                                            }
                                        })
                                    }
                                }
                            }
                        }
                        if (callback) callback();
                    });
                    //$.get('/Tools/GetAuthData/', {}, function (ret) {
                    //    if (ret.result) {
                    //        mvvm.SMS = ret.data.SMS;
                    //    }
                    //});

                }
                function GetContactsData(data) {
                    data = data || {};
                    data.type = "Sms";
                    data.key = mvvm.key.contact;
                    $.get('/Tools/GetSelectData/', data, function (ret) {
                        if (!ret.result) return CBCRM.showResult(ret);
                        mvvm.contacts = ret.data.Source;
                        avalon.vmodels.contactPage.total = ret.data.RecordTotal
                    });
                }
                function GetUsers(data) {
                    data = data || {};
                    data.type = "Sms";
                    data.key = mvvm.key.user;
                    $.get('/Tools/GetUsersData/', data, function (ret) {
                        mvvm.users = ret.data.Source;
                        avalon.vmodels.contactPage2.total = ret.data.RecordTotal
                    });
                }
                if (action == "send") {
                    var no = params.id || "";
                    mvvm.sms.numbers = no;
                    mvvm.showSend();
                    var dialog = loading("数据载入中……");
                    initWithData(function () {
                        if (dialog) dialog.close();
                    });
                }else if(action=="select"){
                    mvvm.selectTmpl();
                } else if (action == "getvm") {

                }else {
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
                    initWithData();
                    $('#left_menu_top').html('<h2>通信工具</h2>').show();
                }
            },
            //邮件信息
            Email: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this, params = this.params,
                    mvvm = CBCRM.define('Email', function (vm) {
                        vm.lang = lang;
                        vm.$skipArray = ['lang'];
                        vm.destroy = function () {
                            destroyui(["emailUserTree"]);
                        }
                        vm.sign = false
                        vm.loading = false
                        vm.contacts = []
                        vm.users = []
                        vm.isLocal = '';
                        vm.EMAIL = false;
                        vm.EMAILSEND = false;
                        vm.EMAILVIEW = false;
                        vm.EMAILDELETE = false;
                        vm.INTERFACESETTINGS = false;
                        vm.EMAILRECIVE = false;
                        vm.emailOnlyMy = true;
                        vm.emailTag = 'toolEmail';
                        vm.emailBoxTag = 'inBox';
                        vm.emailEntity = {};
                        vm.emailinBoxList = [];
                        vm.emailoutBoxList = [];
                        vm.emailgrassBoxList = [];
                        vm.checkemailinBoxAll = false;
                        vm.checkemailoutBoxAll = false;
                        vm.checkemailgrassBoxAll = false;
                        vm.emailCount = { inBox: 0, grassBox: 0, outBox: 0 };
                        vm.emailLocalChange = function (v) {
                            mvvm.isLocal = v;
                            var box = "email" + mvvm.emailBoxTag;
                            mvvm[box + "Opts"].paging();
                        }
                        vm.emailOnlyMyChange = function (v) {
                            mvvm.emailOnlyMy = v;
                            var box = "email" + mvvm.emailBoxTag;
                            mvvm[box + "Opts"].paging();
                        }
                        vm.emailChange = function (tag) {
                            //var tag = $(this).attr('tag');
                            mvvm.emailTag = tag;
                            switch (tag) {
                                case "toolWirte":
                                    mvvm.emailEntity = modelFactory.create('Mails');
                                    mvvm.emailSend();
                                    if (mvvm.emailList.size() == 0) {
                                        $.get('/Tools/GetEmailInterface/', {}, function (ret) {
                                            mvvm.emailList = ret.data;
                                            if (mvvm.emailList.size() > 0) mvvm.emailEntity.MailFrom = ret.data[0].Email;
                                        });
                                    } else {
                                        mvvm.emailEntity.MailFrom = mvvm.emailList[0].Email;
                                    }
                                    break;
                                case "toolEmail":
                                    mvvm.getEmailCount();
                                    vm.emailBoxChange("inBox");
                                    break;
                                case "toolView":

                                    break;
                            }
                        }
                        vm.emailBoxChange = function (tag) {
                            mvvm.emailTag = "toolEmail";
                            mvvm.emailBoxTag = tag;
                            switch (tag) {
                                case "grassBox":

                                    break;
                                case "outBox":

                                    break;
                                case "inBox":

                                    break;
                            }
                            mvvm.getEmailBoxList(tag);
                        }
                        vm.init = false;
                        vm.emailinBoxOpts = {
                            pagesize: 10,
                            pagesizeopts: [10, 20, 50, 100],
                            paging: function () {
                                var data = { page: (this.currentindex + 1) || 1, pageSize: this.pagesize };
                                mvvm.getEmailBoxList('inBox', data);
                            }
                        }
                        vm.emailoutBoxOpts = {
                            pagesize: 10,
                            pagesizeopts: [10, 20, 50, 100],
                            paging: function () {
                                var data = { page: (this.currentindex + 1) || 1, pageSize: this.pagesize };
                                mvvm.getEmailBoxList('outBox', data);
                            }
                        }
                        vm.emailgrassBoxOpts = {
                            pagesize: 10,
                            pagesizeopts: [10, 20, 50, 100],
                            paging: function () {
                                var data = { page: (this.currentindex + 1) || 1, pageSize: this.pagesize };
                                mvvm.getEmailBoxList('grassBox', data);
                            }
                        }
                        vm.getEmailCount = function () {
                            $.get('/Tools/GetEmailCount/').done(function (ret) {
                                if (ret.result) {
                                    mvvm.emailCount = ret.data;
                                    $("#msgTip").html(ret.data.inBox);
                                }
                            });
                        }
                        vm.getEmailBoxList = function (tag, data) {
                            var queryParams = avalon.mix({ tag: tag, isLocal: mvvm.isLocal, onlyMy: mvvm.emailOnlyMy }, data || {});
                            $.post('/Tools/GetEmailBoxList/', queryParams).done(function (ret) {
                                if (ret.result) {
                                    var box = "email" + tag;
                                    mvvm[box + "List"] = ret.data.Source;
                                    avalon.vmodels[box + "Page"].total = ret.data.RecordTotal;
                                    if (tag == "inBox") mvvm.init = true;
                                    //显示
                                    //if (params.id && tag == "inBox") {
                                    //    mvvm[box + "List"].forEach(function (item) {
                                    //        if (item.Id == params.id) {
                                    //            params.id = null;
                                    //            mvvm.emailView(item);
                                    //        }
                                    //    });
                                    //}
                                } else CBCRM.showResult(ret);
                            });
                        }
                        vm.emailReplyList = [];
                        vm.emailAllReply = "";
                        vm.emailViewReplayList = function () {
                            var itemVm = this.$vmodel,
                            curitem = itemVm[itemVm.$itemName];
                            mvvm.emailAllReply = curitem.MailToDisplay;
                            $.post('/Tools/EmailViewReplayList/', { Id: curitem.Id }).done(function (ret) {
                                if (ret.result) {
                                    mvvm.emailReplyList = ret.data;
                                    var dialog = messageBox.openHtml("已读回执列表", 500, 300, "");
                                    var content = $(dialog.content())
                                    content.attr('ms-include', 'demailReplyList')
                                    avalon.scan(content[0], mvvm)
                                }
                            });
                        }
                        vm.getEmailFromNet = function () {
                            var win = loading("邮件收取中……");
                            $.get('/Tools/GetEmailFromNet/').done(function (ret) {
                                if (win) win.close();
                                CBCRM.showResult(ret);
                                if (ret.result) {
                                    mvvm.getEmailCount();
                                    mvvm.emailinBoxOpts.paging();
                                }
                            });
                        }
                        vm.emailSend = function () {
                            if (mvvm.emailList.size() > 0) mvvm.emailEntity.MailFrom = mvvm.emailList.$model[0].Email;
                            bindWatchEmail();
                            mvvm.emailTag = "toolWirte";
                            if (mvvm.emailBoxTag != "") mvvm.emailTempTag = mvvm.emailBoxTag;
                            mvvm.emailBoxTag = "";
                            if (kind1) kind1.remove();
                            kind1 = setEditerSimple('MailContent', '785px', '308px');
                            kind1.html(mvvm.emailEntity.MailContent);
                        }
                        vm.emailSendBack = function () {
                            mvvm.emailTag = "toolEmail";
                            mvvm.emailBoxTag = mvvm.emailTempTag;
                        }
                        vm.emailView = function (id) {
                            //var itemVm = this.$vmodel,
                            //curitem = itemVm[itemVm.$itemName];
                            $.post("/Tools/EmailView/", { Id: id }).done(function (ret) {
                                if (ret.result && ret.data.model) {
                                    var user = CBCRM.memberShip;
                                    //if (user.Id == curitem.MailToUid) curitem.IsRead = true;
                                    mvvm.emailEntity = ret.data.model
                                    mvvm.emailTag = "toolView";
                                    if (mvvm.emailBoxTag != "") mvvm.emailTempTag = mvvm.emailBoxTag;
                                    mvvm.emailBoxTag = "";
                                    mvvm.getEmailCount();
                                    mvvm["email" + mvvm.emailTempTag + "Opts"].paging();
                                    CBCRM.getEmailNoReadList();
                                } else {
                                    CBCRM.showResult(ret);
                                }
                            });
                        }
                        vm.emailgrassView = function () {
                            var itemVm = this.$vmodel,
                            curitem = itemVm[itemVm.$itemName];
                            mvvm.emailEntity = curitem.$model;
                            mvvm.emailSend();
                        }
                        vm.emailTempTag = "";
                        vm.emailViewBack = function () {
                            mvvm.emailTag = "toolEmail";
                            mvvm.emailBoxTag = mvvm.emailTempTag;
                        }
                        vm.emailReply = function () {

                            if (mvvm.emailEntity.MailCreate == 0) {
                                messageBox.warning("抱歉，不能回复系统消息！");
                                return;
                            }
                            mvvm.emailEntity.ParentId = mvvm.emailEntity.Id;
                            mvvm.emailEntity.Id = 0;
                            mvvm.emailEntity.MailTitle = "回复：" + mvvm.emailEntity.MailTitle;
                            mvvm.emailEntity.MailTo = mvvm.emailEntity.MailFrom;
                            mvvm.emailEntity.MailToDisplay = mvvm.emailEntity.MailFromDisplay;
                            var content = "<p></p><p></p>------------------" + mvvm.emailEntity.MailFromDisplay + "在原文中写道：------------------<p></p>" + mvvm.emailEntity.MailContent;
                            mvvm.emailEntity.MailContent = content;
                            mvvm.emailSend();
                        }
                        vm.emailForward = function () {
                            mvvm.emailEntity.ParentId = 0;
                            mvvm.emailEntity.Id = 0;
                            mvvm.emailEntity.MailTitle = "转发：" + mvvm.emailEntity.MailTitle;
                            mvvm.emailEntity.MailTo = "";
                            mvvm.emailEntity.MailToDisplay = "";
                            mvvm.emailSend();
                        }
                        vm.emailDel = function () {
                            var ids = { "deleteIds[0]": mvvm.emailEntity.Id };
                            messageBox.confirm("您确定要删除数据吗？", function () {
                                $.post('/Tools/EmailAllDel/', ids).done(function (ret) {
                                    avalon.vmodels.CBCRM.showResult(ret, function () {
                                        messageBox.close();
                                        var box = "email" + mvvm.emailTempTag;
                                        mvvm[box + "Opts"].paging();
                                        mvvm.getEmailCount();
                                        mvvm.emailViewBack();
                                    });
                                });
                            });

                        }
                        vm.emailAllDel = function () {
                            var ids = checkAll();
                            if (!ids["deleteIds[0]"]) {
                                messageBox.error("请选择邮件！");
                                return;
                            }
                            ids.tag = mvvm.emailBoxTag;
                            messageBox.confirm("您确定要删除数据吗？", function () {
                                $.post('/Tools/EmailAllDel/', ids).done(function (ret) {
                                    avalon.vmodels.CBCRM.showResult(ret, function () {
                                        messageBox.close();
                                        var box = "email" + mvvm.emailBoxTag;
                                        mvvm[box + "Opts"].paging();
                                        mvvm.getEmailCount();
                                    });
                                });
                            });
                        }
                        vm.EmailSend = function () {
                            SandEmail(1);
                        }
                        vm.EmailSave = function () {
                            SandEmail(0);
                        }
                        vm.emailList = []
                        //内部消息》选择收件人
                        vm.selectEmailUser = function () {
                            var ids = mvvm.emailEntity.MailTo || "";
                            ids = ids.split(";");
                            plugins.selectUser({
                                multiple: true,
                                listData:ids,
                                callback: function (us) {
                                    var a = where(us, true, ["Id", "FullName"]);
                                    mvvm.emailEntity.MailTo = a[0].join(";");
                                    mvvm.emailEntity.MailToDisplay = a[1].join(";");
                                }
                            })
                        }
                        vm.emailUserTreeOpts = {
                            treeopts: {
                                callback: {
                                    onCheck: function (e, treeId, treeNode) {
                                        var treeObj = $.fn.zTree.getZTreeObj(treeId);
                                        var nodes = treeObj.getCheckedNodes(true);
                                        var ids = [];
                                        var names = [];
                                        nodes.forEach(function (n) {
                                            if (n.iconSkin === 'emp') {
                                                ids.push(n.Id);
                                                names.push(n.Name);
                                            }
                                        });
                                        mvvm.emailEntity.MailTo = ids.join(";");
                                        mvvm.emailEntity.MailToDisplay = names.join(";");
                                    }
                                },
                                async: {
                                    url: function (treeId, treeNode) {
                                        var url = '/Settings/GetGroupPostUsersJoin',
                                               vm = avalon.vmodels[treeId.replace('zTree', '')]
                                        if (vm && vm.q != vm.qcopy) {
                                            if (avalon.vmodels.CBCRM.$debug)
                                                avalon.log('empName : ' + vm.q)
                                            url += '?empName=' + vm.q
                                        }
                                        return url
                                    },
                                    dataFilter: notMemberFilter
                                },
                                check: {
                                    enable: true,
                                    chkboxType: { "Y": "s", "N": "ps" }
                                }
                            }
                        }
                        //附件
                        vm.open = function () {
                            var type = $(this).attr('val');
                            var uploadModule
                            CBCRM.fillContentBefore = function (tmpl, lang, contentId, module, mvvm) {
                                messageBox.openHtml('上传文件', '1000px', '500px', tmpl, null, function () {
                                    if (avalon.vmodels.upload) avalon.vmodels.upload = null;
                                });
                                avalon.scan($(".aui_content")[0], mvvm);
                                return false;
                            }
                            CBCRM.loadModule('/Upload/Center')
                            CBCRM.onModuleReady = function (data) {
                                avalon.vmodels.upload.itemSelected = function (node, data, file) {
                                    var src = '/Upload/' + file.Path;
                                    mvvm.emailEntity.AttachFile = src;
                                    messageBox.close();
                                }
                            }
                        }
                        //选择收件人
                        vm.openSelect = function () {
                            mvvm.initKey();
                            mvvm.allc = false;
                            mvvm.allu = false;
                            mvvm.selectTag = mvvm.emailEntity.IsLocal == "true" ? "emploee" : "contacts";
                            var btns = [{
                                name: '确定',
                                focus: true,
                                callback: function () {
                                    var address = [], addressDisplay = [], msg = "";
                                    var reg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/

                                    if (mvvm.selectTag == 'contacts') {
                                        mvvm.contacts.forEach(function (item) {
                                            if (!item.Checked) return;
                                            if (item.Email && reg.test(item.Email)) {
                                                address.push(item.Email);
                                                addressDisplay.push(item.Email);
                                            } else {
                                                msg += item.Name + "(" + (item.Email || "") + ")<br/>";
                                            }
                                        });
                                    } else {
                                        mvvm.users.forEach(function (item) {
                                            if (!item.Checked) return;
                                            if (mvvm.emailEntity.IsLocal == "true") {
                                                address.push(item.Id);
                                                addressDisplay.push(item.FullName);
                                            } else {
                                                if (item.Email && reg.test(item.Email)) {
                                                    address.push(item.Email);
                                                    addressDisplay.push(item.Email);
                                                } else {
                                                    msg += item.FullName + "(" + (item.Email || "") + ")<br/>";
                                                }
                                            }

                                        });
                                    }
                                    mvvm.emailEntity.MailTo = address.join(";");
                                    mvvm.emailEntity.MailToDisplay = addressDisplay.join(";");
                                    if (msg != "")
                                        messageBox.warning(msg + '邮箱为空或者格式错误,已过滤!');
                                    return true;
                                }
                            }]
                            var dialog = openTmpl(mvvm, "选择收件人", "selectTemplate", 800, 500, btns);
                        }
                        vm.initKey = function () {
                            mvvm.key = { user: "", contact: "" }
                        }
                        vm.key = { user: "", contact: "" };
                        vm.onKeySearch = function (act, type) {
                            if (type == "Contact") {
                                if (act == 1) mvvm.key.contact = "";
                                GetContactsData();
                            } else {
                                if (act == 1) mvvm.key.user = "";
                                GetUsers();
                            }

                        }
                        vm.onKeyEnter = function (e, type) {
                            if (e.keyCode == 13) {
                                mvvm.onKeySearch(0, type);
                            }
                        }
                        //联系人分页
                        vm.contactOpts = {
                            pagesize: 10,
                            pagesizeopts: [10, 20, 50, 100],
                            paging: function () {
                                var pIndex = (this.currentindex + 1) || 1
                                var pSize = this.pagesize
                                GetContactsData({ pageIndex: pIndex, pageSize: pSize });
                            }
                        }
                        //同事分页
                        vm.contactOpts2 = {
                            pagesize: 10,
                            pagesizeopts: [10, 20, 50, 100],
                            paging: function () {
                                var pIndex = (this.currentindex + 1) || 1
                                var pSize = this.pagesize
                                GetUsers({ pageIndex: pIndex, pageSize: pSize });
                            }
                        }
                        //选项卡
                        vm.selectTag = 'contacts'
                        vm.selectChange = function () {
                            vm.selectTag = $(this).attr('tag');
                        }
                        vm.allc = false;
                        vm.allu = false;
                    })
                var action = params.action, id = params.id;
                mvvm.$watch('allc', function (n, o) {
                    mvvm.contacts.forEach(function (item) { item.Checked = n; })
                })
                mvvm.$watch('allu', function (n, o) {
                    mvvm.users.forEach(function (item) { item.Checked = n; })
                })
                mvvm.$watch("emailOnlyMy", function (n, o) {
                    mvvm.emailinBoxOpts.paging();
                });
                mvvm.emailEntity = modelFactory.create('Mails');
                function loading(msg) {
                    var html = "<p>" + msg + "</p><p><img src='/Content/Themes/Base/Images/loading2.gif' border='0' /></p>";
                    return messageBox.openHtml("系统提示", 300, 100, html);
                }
                function bindWatchEmail() {
                    mvvm.emailEntity.$watch("IsLocal", function (n, o) {
                        if (avalon.vmodels.emailUserTree) {
                            var treeObj = $.fn.zTree.getZTreeObj(avalon.vmodels.emailUserTree.treeId);
                            if (treeObj) treeObj.checkAllNodes(false);
                        }
                        mvvm.emailEntity.MailTo = "";
                        mvvm.emailEntity.MailToDisplay = "";
                        mvvm.emailEntity.NeedReply = false;
                    });
                }
                function initEmailData() {
                    $.get('/Tools/GetAuthData/', {}, function (ret) {
                        if (ret.result) {
                            $.each(ret.data, function (k, v) {
                                mvvm[k] = v;
                            });
                        }
                    });
                }
                initEmailData();
                mvvm.getEmailCount();
                function GetContactsData(data) {
                    data = data || {};
                    data.type = "Email";
                    data.key = mvvm.key.contact;
                    $.get('/Tools/GetSelectData/', data, function (ret) {
                        mvvm.contacts = ret.data.Source;
                        avalon.vmodels.contactPage.total = ret.data.RecordTotal
                    });
                }
                function GetUsers(data) {
                    data = data || {};
                    data.type = "Email";
                    data.key = mvvm.key.user;
                    $.get('/Tools/GetUsersData/', data, function (ret) {
                        mvvm.users = ret.data.Source;
                        avalon.vmodels.contactPage2.total = ret.data.RecordTotal
                    });
                }
                function SandEmail(state) {
                    mvvm.emailEntity.MailContent = kind1.html();
                    var model = mvvm.emailEntity.$model;
                    model.MailState = state;
                    if (state != 0) {
                        if ((model.IsLocal == false || model.IsLocal == "false") && (!mvvm.emailList || !mvvm.emailList.length)) {
                            messageBox.error('没有设置发件人的电子邮件账户,请到接口设置里面完成设置'); return;
                        }
                        if (model.MailTo == "" && model.MailToDisplay != "") {
                            model.MailTo = model.MailToDisplay;
                        }
                        if (!model.MailTo || !model.MailTitle) {
                            messageBox.error('请填写收件人的电子邮箱地址和邮件主题'); return;
                        }
                    }
                    var url = "/Tools/EmailSend/";
                    if (model.Id && model.Id != "") url += model.Id;
                    $.post(url, model, function (ret) {
                        var b = false;
                        if (ret.result) {
                            mvvm.getEmailCount();
                            if (state == 0) {
                                mvvm.emailEntity.Id = ret.data.Id;//存草稿
                                CBCRM.showResult(ret);
                            } else {
                                var btns = [
                                    {
                                        name: "继续",
                                        focus: true,
                                        callback: function () {
                                            b = true;
                                            mvvm.emailEntity.MailTo = "";
                                            mvvm.emailEntity.MailToDisplay = "";
                                            mvvm.emailEntity.MailTitle = "";
                                            mvvm.emailEntity.MailContent = "";
                                            mvvm.emailEntity.AttachFile = "";
                                            mvvm.emailSend();
                                        }
                                    },
                                    {
                                        name: "返回",
                                        focus: false,
                                        callback: function () {
                                            mvvm.emailSendBack();
                                        }
                                    }
                                ];
                                art.dialog({
                                    title: "系统提示",
                                    content: "邮件发送成功，是否继续写邮件？",
                                    icon: "succeed",
                                    button: btns,
                                    close: function () {
                                        if (!b) mvvm.emailSendBack();
                                    }
                                })

                            }
                        } else {
                            CBCRM.showResult(ret);
                        }
                    });
                }
                var kind1;
                switch (action) {
                    case "view":
                        fill();
                        mvvm.emailView(id);
                        break;
                    case "send":
                        fill();
                        var cvm = avalon.vmodels.ViewCustomer;
                        if (cvm && cvm.$viewdialog && cvm.$viewdialog.close) cvm.$viewdialog.close();
                        window.setTimeout(function () {
                            mvvm.emailChange("toolWirte");
                            mvvm.emailEntity.MailTo = id;
                            mvvm.emailEntity.MailToDisplay = id;
                        }, 400);
                        break;
                    default:
                        fill();
                        break;
                }
                function fill(callback) {
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                    $('#left_menu_top').html('<h2>通信工具</h2>').show();
                    if (callback) avalon.nextTick(callback);
                }
            },
            ///信息模板管理
            MessageTmpl: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, that = this, vmid = "MessageTmpl", treeid = vmid + "Tree";
                var mvvm = CBCRM.define(vmid, function (vm) {
                    vm.destroy=function () {
                        mvvm.destroyui([treeid]);
                    }
                    vm.$skipArray = ['lang'];
                    vm.lang = lang
                    vm.entity = {}
                    vm.ADD = true
                    vm.DELETE = true;
                    vm.EDIT = true;
                    vm.tab = "tab1";
                    vm.tabWidth = 650;
                    vm.tabChange = function (tab) {
                        mvvm.tab = tab;
                    }
                    vm.grid1 = createGrid({
                        url: that.path,
                        entityId: vmid,
                        modelFactory: modelFactory,
                        onRemove: function (ids) {
                            $.post('/Tools/' + vmid + 'Del/', ids, function (ret) {
                                CBCRM.showResult(ret);
                                if (ret.result) mvvm.reloadData();
                            })
                        }
                    });
                    initQuerys(vm, function (data, name, val, type) {
                        if (name == "category" && type == "remove") {
                            mvvm.selectFirstTreeNode();
                        }
                        mvvm.loadData(data);
                    });
                    vm.queryData = {
                        name: {
                            label: "模板名称：", val: ""
                        },
                        category: {
                            label: "模板分类", val: ""
                        }
                    }
                    vm.listpaing = {
                        paging: function () {
                            var data = mvvm.createQuery();
                            data.pageSize = this.pagesize
                            data.pageIndex = this.currentindex + 1
                            mvvm.loadData(data);
                        }
                    }
                    //分类树
                    vm[treeid + "Opts"] = {
                        treeopts: {
                            async: {
                                url: function (treeId, treeNode) {
                                    var url = "/Tools/MessageTmplCategory"
                                    vmtree = avalon.vmodels.parentTree
                                    if (vmtree && vmtree.q && vmtree.q !== vmtree.qcopy) {
                                        url += '&name=' + vmtree.q
                                    }
                                    return url
                                }
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    var category = treeNode.Id;
                                    if (category == 1) category = "";
                                    else {
                                        category = getNodeIds(treeNode).join(",");
                                    }
                                    mvvm.addQuery("category", category);
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            }
                        }
                    }
                    //下拉分类树
                    vm[vmid + "SetTreeOpts"] = {
                        treeopts: {
                            async: {
                                url: function (treeId, treeNode) {
                                    var url = "/Tools/MessageTmplCategory"
                                    vmtree = avalon.vmodels.parentTree
                                    if (vmtree && vmtree.q && vmtree.q !== vmtree.qcopy) {
                                        url += '&name=' + vmtree.q
                                    }
                                    return url
                                }
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    var category = treeNode.Id, name = treeNode.Name;
                                    if (category == 1) {
                                        category = "";
                                        name = "";
                                    }
                                    mvvm.entity.Category.Id = category;
                                    mvvm.entity.Category.Name = name;
                                }
                            },
                            view: {
                                addHoverDom: '',
                                removeHoverDom: ''
                            }
                        }
                    }
                    vm.setTreeData = function (id) {
                        id = id || treeid;
                        var atree = avalon.vmodels[id];
                        if (atree) {
                            var rows = [{ Id: 1, Data: "全部分类", open: true, checked: true }];
                            rows = rows.concat(mvvm.categoryList.$model);
                            $.each(rows, function (i) {
                                if (i == 0) return;
                                this.pId = 1;
                            });
                            atree.datasource = rows;
                            if (id == treeid) mvvm.selectFirstTreeNode();
                        }
                    }
                    vm.selectFirstTreeNode = function () {
                        var tree = $.fn.zTree.getZTreeObj(treeid);
                        var nodes = tree.getNodes();
                        if (nodes.length > 0) {
                            tree.selectNode(nodes[0]);
                        }
                    };
                    vm.loadData = function (data) {
                        $.post(that.path, data, function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            mvvm.ADD = ret.data.ADD;
                            mvvm.DELETE = ret.data.DELETE;
                            mvvm.EDIT = ret.data.EDIT;
                            var list = ret.data.Source;
                            mvvm.grid1.initList(list, ret.data.RecordTotal);
                            var page = avalon.vmodels[vmid];
                            if (page) page.total = ret.data.RecordTotal;
                        })
                    }
                    vm.reloadData = function () {
                        var page = avalon.vmodels[vmid + "page"];
                        if (page) {
                            var data = mvvm.createQuery();
                            data.pageSize = page.pagesize
                            data.pageIndex = page.currentindex == 0 ? 1 : page.currentindex
                            mvvm.loadData(data);
                        }
                    }
                    //关键字搜索
                    vm.onEnter = function (e) {
                        if (e.keyCode == 13) mvvm.doSearch();
                    }
                    vm.doSearch = function () {
                        mvvm.addQuery("name", mvvm.queryData.name.val);
                    }

                    //新增
                    vm.doadd = function () {
                        mvvm.grid1.getEntity("", function (entity) {
                            var category = $.fn.zTree.getZTreeObj(treeid).getSelectedNodes();
                            if (category.length > 0 && category[0].Id != 1) {
                                category = category[0];
                                entity.Category.Id = category.Id;
                                entity.Category.Name = category.Name;
                            }
                            mvvm.entity = entity;
                            mvvm.showForm("新增模板");
                        });
                    }
                    //编辑
                    vm.doedit = function (id) {
                        mvvm.grid1.getEntity(id, function (entity) {
                            mvvm.entity = entity;
                            mvvm.showForm("编辑模板");
                        });
                    }
                    vm.showForm = function (title) {
                        var btns = [{
                            name: "提交",
                            focus: true,
                            callback: function () {
                                var m = $.extend(true, {}, mvvm.entity.$model);
                                if (m.Name == "") {
                                    messageBox.error("请填写名称！");
                                    return false;
                                }
                                if (!m.Category.Id) {
                                    messageBox.error("请选择分类！");
                                    return false;
                                }
                                if (m.Data == "") {
                                    messageBox.error("请填写内容！");
                                    return false;
                                }
                                if (!m.Id) $.extend(m, jsonToSubmit("Category", m.Category));
                                else {
                                    m.categoryId = m.Category.Id;
                                }
                                delete m.Category;
                                delete m.AddBy;
                                var url = m.Id ? "/Tools/" + vmid + "Update/" + m.Id : "/Tools/" + vmid + "Add/";
                                $.post(url, m, function (ret) {
                                    CBCRM.showResult(ret);
                                    if (ret.result) {
                                        if (dialog) dialog.close();
                                        mvvm.reloadData();
                                    }
                                });
                                return false;
                            }
                        }
                        ];
                        var dialog = mvvm.openTmpl({
                            title: title, btns: btns, w: mvvm.tabWidth,
                            tmplid: "formTemplate",tmpl:tmpl,
                            onclose: function () {
                                mvvm.destroyui([vmid + "SetTree"])
                            }
                        });
                    }
                    //查看
                    vm.doview = function (id) {
                        mvvm.grid1.getEntity(id, function (entity) {
                            mvvm.entity = entity;
                            mvvm.openTmpl({ title: "查看模板", w: mvvm.tabWidth, tmplid: "viewTemplate", tmpl: tmpl });
                        });

                    }

                    //数据表、字段
                    function _getLables(a) {
                        var arr = [];
                        a.forEach(function (m) {
                            var kv = m.split(":");
                            arr.push({ key: kv[0], value: kv[1], checked: false });
                        })
                    }
                    //vm.lables = _getLables(["public:通用", "customer:客户", "contacts:联系人", "archive:员工", "product:产品", "resume:简历"]);
                    vm.tables = ["通用", "客户","联系人", "员工", "产品", "简历"]
                    vm.fields = {
                        "通用": ['公司名称', '公司简称', '公司电话', '公司传真', '公司QQ', 'Email', '公司地址',
                                    'CRM账号', '用户姓名', '用户部门', '用户职位', '用户角色','系统时间', '年', '月', '日', '时', '分', '秒'],
                        "客户": ['名称', '类型', '会员级别', '分类', '公司电话', '公司地址', 'Email', 'QQ'],
                        "联系人":['姓名','称谓','部门','职位','对应客户','生日','性别'],
                        "员工": ['姓名', 'CRM账号', '姓名', '部门', '职位', '角色', '档案编号', '入职时间', '离职时间'],
                        "产品": ['编号','条码','名称','分类','品牌','供应商','库存','规格型号','重量'],
                        "简历": ['姓名', '面试时间','投递时间','面试类型']
                    };
                    vm.curTable = "";
                    vm.curFields = [];
                    vm.changeCurTable = function (curTable) {
                        mvvm.curTable = curTable;
                    }
                    vm.selectField = function (item) {
                        var m = mvvm.entity;
                        m.Data = m.Data + "#" + item.TableName + "_" + item.FieldName + "#"
                    }
                })
                mvvm.grid1.bindWatch();
                bindWatch();
                function bindWatch() {
                    mvvm.$watch("curTable", function (n) {
                        mvvm.curFields = [];
                        if (!n) return;
                        var fields = mvvm.fields[n];
                        fields.forEach(function (item) {
                            mvvm.curFields.push({ TableName: n, FieldName: item });
                        });
                    });
                }

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

            },
            ///模板分类
            MessageTmplCategory: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM, init = false;
                var mvvm = CBCRM.define('MessageTmplCategory', function (vm) {
                    vm.destroy = function () {
                        var uis = ['pCategoryTree']
                        mvvm.destroyui(uis);
                    }
                    vm.lang = lang
                    vm.auth = { EDIT: true, ADD: true, DELETE: true };
                    vm.entity = {}
                    vm.action = "add"
                    vm.title = "新增分类"
                    vm.sublist = [];
                    vm.curParent = { Id: '', Name: '' };
                    vm.pCategoryTreeOpts = {
                        treeopts: {
                            async: {
                                enable:false,
                                url: ""
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    //mvvm.getSublist(treeNode.Id);
                                    mvvm.getSublist(treeNode);
                                }
                            },
                            view: {
                                addHoverDom: null,
                                removeHoverDom: null,
                                selectedMulti: false
                            }
                        }
                    }
                    vm.getSublist = function (node) {
                        var treeobj = $.fn.zTree.getZTreeObj("tmplCategoryTree");
                        treeobj.selectNode(node);
                        mvvm.curParent = node;
                        mvvm.sublist = [];
                        var a = [];
                        a.push(node);
                        if (node.children) {
                            node.children.forEach(function (item) {
                                a.push(item)
                            });
                        }
                        mvvm.sublist = a;
                    }
                    //分类树展开、收起
                    vm.$expancategory = true;
                    vm.expanCategory = function () {
                        mvvm.$expancategory = !mvvm.$expancategory;
                        $(this).text(mvvm.$expancategory ? "- 收起" : "+ 展开");
                        var tree = $.fn.zTree.getZTreeObj("tmplCategoryTree");
                        if (tree) {
                            var nodes = tree.getNodes();
                            if (nodes.length > 0) tree.expandNode(nodes[0], mvvm.$expancategory, true);
                            //收起的时候让根节点处于展开状态
                            if (!mvvm.$expancategory) tree.expandNode(nodes[0], !mvvm.$expancategory, false);
                        }
                    }
                    //分类下拉树
                    vm.parentTreeOpts = {
                        treeopts: {
                            async: {
                                url: function (treeId, treeNode) {
                                    var url = "/Tools/MessageTmplCategory"
                                    vmtree = avalon.vmodels.parentTree
                                    if (vmtree && vmtree.q && vmtree.q !== vmtree.qcopy) {
                                        url += '&name=' + vmtree.q
                                    }
                                    return url
                                }
                            },
                            callback: {
                                onClick: function (e, treeId, treeNode) {
                                    var id = mvvm.entity.Id;
                                    if (id) {
                                        var nodes = $.fn.zTree.getZTreeObj(treeId).getNodes();
                                        var node = getzTreeNode(nodes, id);
                                        var ids = getNodeIds(node);
                                        if (ids.indexOf(treeNode.Id) != -1) messageBox.error("操作失败！<br />不能选择自己或者自己的子目录为父目录！")
                                        else {
                                            mvvm.entity.Parent.Id = treeNode.Id
                                            mvvm.entity.Parent.Name = treeNode.Name
                                        }
                                    } else {
                                        mvvm.entity.Parent.Id = treeNode.Id
                                        mvvm.entity.Parent.Name = treeNode.Name
                                    }
                                }
                            }
                        }
                    }
                    vm.createEntity = function (item) {
                        if (!item) {
                            item = $.extend(true, {}, modelFactory.create('MessageTmplCategory'));
                        }
                        mvvm.entity = item;
                    }
                    //新增
                    vm.doadd = function (item) {
                        if (item == 0) {
                            item = mvvm.curParent.$model;
                        }
                        mvvm.action = "add"
                        mvvm.title = "新增分类"
                        mvvm.createEntity();
                        mvvm.entity.Parent.Id = item.Id;
                        mvvm.entity.Parent.Name = item.Name;
                        if (item.children && item.children.length > 0) {
                            var m = item.children[item.children.length - 1];
                            mvvm.entity.Sort = m.Sort ? parseInt(m.Sort) + 1 : 0;
                        } else {
                            mvvm.entity.Sort = 1;
                        }
                        mvvm.showForm(mvvm.title);
                    }
                    vm.doedit = function (id) {
                        mvvm.sublist.$model.forEach(function (item) {
                            if (item.Id == id) {
                                mvvm.createEntity(item);
                                mvvm.action = "edit";
                                mvvm.title = "编辑分类";
                                mvvm.showForm(mvvm.title);
                            }
                        });
                    }

                    vm.dodel = function (id) {
                        messageBox.confirm('确定要删除该分类吗？<br />如果该分类下包含有产品，将无法删除，您可以先转移产品到其它分类。', function () {
                            var ids = _getNodeIds(id);
                            var data = jsonToSubmit("deleteIds", ids);
                            ; $.post('/Tools/MessageTmplCategoryDel/', data, function (ret) {
                                CBCRM.showResult(ret);
                                if (ret.result) {
                                    getCategoryList();
                                }
                            })
                        });
                    }
                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        if (!deleteIds["deleteIds[0]"]) {
                            messageBox.warning("未选择任何数据！");
                            return;
                        }
                        var ids = [];
                        for (var key in deleteIds) {
                            ids = ids.concat(_getNodeIds(deleteIds[key]));
                        }
                        console.log(ids);
                        var data = jsonToSubmit("deleteIds", ids);
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/Tools/MessageTmplCategoryDel/', data, function (ret) {
                                CBCRM.showResult(ret);
                                if (ret.result) getCategoryList();
                            })
                        });
                    }
                    vm.showForm = function (title) {
                        var btns = [{
                            name: "提交",
                            callback: function () {
                                var model = $.extend(true, {}, mvvm.entity.$model);
                                model["ParentId"] = mvvm.entity.$model.Parent.Id;
                                //$.extend(model, jsonToSubmit("Parent", model.Parent));
                                delete model.Parent;
                                var name = model.Name;
                                if (name == '') {
                                    messageBox.error('分类名称不能为空')
                                    return false;
                                }
                                var herf = mvvm.action == "add" ? "/Tools/MessageTmplCategoryAdd/" : "/Tools/MessageTmplCategoryUpdate/" + model.Id;
                                $.post(herf, model, function (ret) {
                                    if (ret.result) {
                                        if (dialog) dialog.close();
                                        getCategoryList();
                                    }
                                    CBCRM.showResult(ret);
                                })
                                return false;
                            }
                        }]
                        var dialog = mvvm.openTmpl({
                            tmpl: tmpl,
                            tmplid: "formTmpl",
                            title: title,
                            w: 400,
                            h: 200,
                            padding:"def2",
                            btns: btns,
                            onclose: function () {
                                destroyui(["parentTree"]);
                            }
                        });
                    }
                    vm.categoryMoreSave = function () {
                        var list = [];
                        mvvm.sublist.$model.forEach(function (item) {
                            if (item.Id == 1) return;
                            list.push({ Id: item.Id, Sort: item.Sort });
                        });
                        var data = jsonToSubmit("list", list);
                        $.post('/Tools/MessageTmplCategoryMoreSave/', data, function (ret) {
                            CBCRM.showResult(ret);
                            if (ret.result) {
                                getCategoryList();
                            }
                        })
                    }
                    vm.uploadIcon = function () {
                        var upwin = CBCRM.upload(true, function (node, data, file) {
                            console.log(file);
                            var src = '/Upload/' + file.Path;
                            mvvm.entity.Icon = src;
                            upwin.close();
                        }, { settings: { multi: false, fileTypeExts: "*.png;*.jpg;*.jpeg;*.bmp;*.gif" } });
                    }
                })

                function getCategoryList() {
                    $.get('/Tools/MessageTmplCategory/', {}, function (ret) {
                        if (!ret.result) return;
                        ret.data.forEach(function (item) {
                            item._checked = false;
                        });
                        avalon.vmodels.pCategoryTree.datasource = ret.data;
                        var treeobj = $.fn.zTree.getZTreeObj("tmplCategoryTree");
                        var a = treeobj.getNodes(), node;
                        if (!init) {
                            if (a.length > 0) {
                                node = a[0];
                            }
                            init = true;
                        } else {
                            var node = treeobj.getNodeByTId(mvvm.curParent.tId);
                            if (!node) {
                                if (mvvm.curParent) {
                                    node = mvvm.curParent.$model.getParentNode();
                                } else {
                                    node = a[0];
                                }
                            }
                        }
                        if (node) {
                            mvvm.getSublist(node);
                        }
                    })
                }

                function _getNodeIds(id) {
                    var tree = $.fn.zTree.getZTreeObj("tmplCategoryTree");
                    var nodes = tree.getNodes();
                    var node = getzTreeNode(nodes, id);
                    return node == null ? [] : getNodeIds(node);
                }
                //mvvm.getSublist(0);
                require('commonui', function () {
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
                    getCategoryList();

                })
            }
        }
        //员工部门筛选
        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
                    }
                    groups.push(m);
                    item.Posts.forEach(function (item2) {
                        var mm = {
                            Id: item2.Id, Name: item2.Name, ParentId: item2.Group, iconSkin: item2.iconSkin
                        }
                        groups = groups.concat(mm);
                        item2.Users.forEach(function (item3) {
                            var mmm = {
                                Id: item3.Id,
                                Name: item3.FullName,
                                ParentId: item3.PositionId,
                                iconSkin: item3.iconSkin,
                                Phone: item3.Phone,
                                Email: item.Email
                            }
                            groups = groups.concat(mmm);
                        });
                    });
                });
            }
            return groups;
        };
        //过滤掉没有人员的职位
        var groupPostFilter2 = function (treeId, parentNode, responseData) {
            var CBCRM = avalon.vmodels.CBCRM
            var ret = [], len = 0, curr, phasEmp = false, ghasEmp = false;
            if (responseData.data && responseData.data.groups.length)
                len = responseData.data.groups.length
            while (len) {
                curr = responseData.data.groups[--len]
                //curr.nocheck = true
                ghasEmp = false
                curr.Posts.forEach(function (p, i) {
                    phasEmp = p.Users.length > 0;
                    if (phasEmp) ghasEmp = true;
                    curr.Posts[i].ParentId = p.Boss ? p.Boss.Id : p.Group
                    //curr.Posts[i].nocheck = true
                    p.Users.forEach(function (u, i) {
                        var u = p.Users[i]
                        if (u.Id === CBCRM.memberShip.Id) return true
                        u.ParentId = u.PositionId
                        u.Name = u.FullName
                        if (u.Phone) u.Name += "(" + u.Phone + ")"
                        ret.push(u)
                    })
                    if (phasEmp) {
                        ret.push(p)
                    }
                })
                ret.push(curr)
            }
            return ret
        }
        //下拉配置过滤数据 只可选员工
        var notMemberFilter = function (treeId, parentNode, responseData) {
            var CBCRM = avalon.vmodels.CBCRM
            var ret = [], len = 0, curr, hasEmp = false
            if (responseData.data && responseData.data.groups.length)
                len = responseData.data.groups.length
            while (len) {
                curr = responseData.data.groups[--len]
                curr.nocheck = true
                hasEmp = false
                curr.Posts.forEach(function (p, i) {
                    curr.Posts[i].ParentId = p.Boss ? p.Boss.Id : p.Group
                    curr.Posts[i].nocheck = true
                    p.Users.forEach(function (u, i) {
                        var u = p.Users[i]
                        if (u.Id === CBCRM.memberShip.Id) return true
                        u.ParentId = u.PositionId
                        u.Name = u.FullName
                        ret.push(u)
                    })
                    if (!hasEmp) {
                        hasEmp = p.Users.length > 0
                    }
                    if (hasEmp) {
                        ret.push(p)
                    }
                })
                if (hasEmp) ret.push(curr)
            }
            return ret
        }
        return Tools;
    });