define('Settings', ['modelFactory','plugins', 'json', 'Jpin', 'dialog', 'common', 'leftMenu'], function (modelFactory,plugins) {
    var notMemberFilter = function (treeId, parentNode, responseData) {
        var ret = [], len = 0, curr, hasEmp = false
        if (responseData.data && responseData.data.groups.length)
            len = responseData.data.groups.length
        while (len) {
            curr = responseData.data.groups[--len]
            curr.nocheck = true
            hasEmp = false
            curr.Posts.forEach(function (p, i) {
                curr.Posts[i].ParentId = p.Boss ? p.Boss.Id : p.Group
                curr.Posts[i].nocheck = true
                curPostId = curr.Posts[i].Id
                curPostName = curr.Posts[i].Name
                p.Users.forEach(function (u, i) {
                    var u = p.Users[i]
                    if (u.Id === CBCRM.memberShip.Id) return true
                    u.ParentId = u.PositionId
                    u.groupId = curr.Id
                    u.groupName = curr.Name
                    u.postId = curPostId
                    u.postName = curPostName
                    u.Name = u.FullName
                    ret.push(u)
                })
                if (!hasEmp) {
                    hasEmp = p.Users.length > 0
                }
                if (hasEmp) {
                    ret.push(p)
                }
            })
            if (hasEmp) ret.push(curr)
        }
        return ret
    }
    var onlyPostFilter = function (treeId, parentNode, responseData) {
        var CBCRM = avalon.vmodels.CBCRM
        var ret = [], len = 0, curr, hasPsot = false
        if (responseData.data && responseData.data.groups.length)
            len = responseData.data.groups.length
        while (len) {
            curr = responseData.data.groups[--len]
            curr.nocheck = true
            curr.Posts.forEach(function (p, i) {
                curr.Posts[i].ParentId = p.Boss ? p.Boss.Id : p.Group
                curr.Posts[i].nocheck = false
                ret.push(p)
            })
            ret.push(curr)
        }
        return ret
    }
    //只要部门和用户
    var notPostFilter = function (treeId, parentNode, responseData) {
        var CBCRM = avalon.vmodels.CBCRM
        var ret = [], len = 0, curr, hasEmp = false
        if (responseData.data && responseData.data.groups.length)
            len = responseData.data.groups.length
        while (len) {
            curr = responseData.data.groups[--len]
            //curr.nocheck = true
            hasEmp = false
            curr.Posts.forEach(function (p, i) {
                p.Users.forEach(function (u, i) {
                    if (u.Id === CBCRM.memberShip.Id) return true
                    u.ParentId = p.Boss ? p.Boss.Id : p.Group
                    u.Post = p.Name;
                    u.Name = u.FullName + "(" + u.Post + ")";
                    ret.push(u)
                })
                if (!hasEmp) {
                    hasEmp = p.Users.length > 0
                }
            })
            ret.push(curr);
        }
        return ret
    }
    var Settings = {

        /// <summary>
        /// 单位信息
        /// </summary>
        /// <param name="tmpl">加载的远程模板</param>
        /// <param name="lang">语言包</param>
        /// <param name="contentId">主页面内容区id</param>
        /// <param name="module">当前模块</param>
        DetailCompanyInfo: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM;
            var allLocations = [];
            var $model = avalon.define('CompanyInfo', function (vm) {
                vm.bindApp = function (code) {
                    $.post("/mobile/DeviceBind", { phone: "13744338888", deviceSn: "123",verifyCode:code }, function (ret) {
                        console.log(ret);
                    })
                }
                vm.sendSms = function () {
                    $.post("/mobile/SendSmsVerify", { phone: "13744338888"}, function (ret) {
                        console.log(ret);
                    })
                }
                vm.lang = lang;
                vm.defaultLogo = '/Content/Themes/Base/Images/Logo.jpg';
                vm.entity = {}
                vm.country = []
                vm.province = []
                vm.city = []
                vm.area = []
                vm.industry = [];
                vm.click = function () {
                    $.post('/Settings/UpdateCompanyInfo/' + $model.entity.Id, $model.entity.$model, function (data) {
                        avalon.vmodels.CBCRM.showResult(data)
                    });
                }
                vm.reset = function () {
                    $model.entity.Logo = $model.defaultLogo;
                }
                vm.open = function () {
                    var upwin=CBCRM.upload(true, function (node, data, file) {
                        if (file) {
                            $model.entity.Logo = '/upload/' + file.Path;
                            upwin.close();
                        }
                    })
                }

                /*地图标注*/
                vm.addressKey = "";
                vm.$mapLoaded = false;
                vm.$map = null;
                vm.loadMap = function (callback) {
                    if (!vm.$mapLoaded) {
                        require(["bdmapTool", "ready!"], function (bdmapTool) {
                            $model.$map = new bdmapTool({
                                mapContent: "#dmap",
                                tmpl: "search",
                                searchpanel: "seekpanel",
                                left: 285,
                                pointCallBack: function (p, box) {
                                    $model.entity.Address = p.address;
                                    $model.entity.Lng = p.point.lng;
                                    $model.entity.Lat = p.point.lat;
                                    box.close();
                                },
                                searchCallBack: function (p, box) {
                                    $model.entity.Address = p.address;
                                    $model.entity.Lng = p.point.lng;
                                    $model.entity.Lat = p.point.lat;
                                    box.close();
                                }
                            });

                            $model.$maploaded = true;
                            if (callback) callback.call($model.$map, $model.$map);
                        });
                    } else {
                        if (callback) callback.call($model.$map, $model);
                    }
                }
                vm.markInMap = function () {
                    $model.loadMap(function () {
                        var map = $model.$map;
                        map.ops.city = $model.entity.CityDisplay;
                        if (",市辖区,县,".indexOf(map.ops.city) > -1 || map.ops.city == "") map.ops.city = $model.entity.ProvinceDisplay;
                        var point;
                        if ($model.entity.Lng) {
                            point = new BMap.Point($model.entity.Lng, $model.entity.Lat);
                        } else {
                            point = null;
                        }
                        map.openMap(function () {
                            if (point) {
                                map.ops.point = point;
                                var html = "<p>地址：" + $model.entity.Address + "</p>";
                                html += "<p>电话:" + $model.entity.OfficeTel1 + "</p>";
                                map.addMarker(point, $model.entity.CompanyName, { html: html, ops: { title: $model.entity.CompanyName, width: 250 } });
                            } else {
                                if ($model.entity.Address != "") {
                                    map.searchMap($model.entity.Address);
                                }
                            }
                        });
                    });
                }
            });
            function _getIndex(arr, id) {
                for (var i = 0, l = arr.size() ; i < l; i++) {
                    if (arr[i].Id == id) return i;
                }
                return -1;
            }
            function bindWatch() {
                /*国家地区级联*/
                $model.entity.$watch('CountryId', function (n, o) {
                    var name = ''
                    if (n != o) {
                        $model.province.removeAll()

                        allLocations.forEach(function (c) {
                            if (c.ParentId == n) {
                                $model.province.push(c)
                            } else if (c.Id == n) {
                                $model.entity.CountryDisplay = c.Data
                            }
                        })
                        //avalon.log('CountryId : ' + $model.entity.CountryId)
                        if ($model.province.size()) {
                            if (_getIndex($model.province, $model.entity.ProvinceId) == -1) {
                                $model.entity.ProvinceId = $model.province[0].Id
                                $model.entity.ProvinceDisplay = $model.province[0].Data;
                            }
                        } else {
                            $model.entity.ProvinceId = ''
                            $model.entity.ProvinceDisplay = ''
                        }
                        if ($model.country.size() == 0) {
                            $model.province.removeAll();
                            $model.city.removeAll();
                            $model.area.removeAll();
                            $model.entity.ProvinceId = ''
                            $model.entity.ProvinceDisplay = ''
                            $model.entity.CityId = ''
                            $model.entity.CityDisplay = ''
                            $model.entity.AreaId = ''
                            $model.entity.AreaDisplay = ''
                        }
                    }
                })
                $model.entity.$watch('ProvinceId', function (n, o) {
                    if (n != o) {
                        $model.city.removeAll()
                        allLocations.forEach(function (c) {
                            if (c.ParentId == n) {
                                $model.city.push(c)
                            } else if (c.Id == n) {
                                $model.entity.ProvinceDisplay = c.Data
                            }
                        })
                        //avalon.log('ProvinceId : ' + $model.entity.ProvinceId)
                        if ($model.city.size()) {
                            if (_getIndex($model.city, $model.entity.CityId) == -1) {
                                $model.entity.CityId = $model.city[0].Id
                                $model.entity.CityDisplay = $model.city[0].Data
                            }
                        } else {
                            $model.entity.CityId = ''
                            $model.entity.CityDisplay = ''
                        }
                        if ($model.province.size() == 0) {
                            $model.city.removeAll();
                            $model.area.removeAll();
                            $model.entity.CityId = ''
                            $model.entity.CityDisplay = ''
                            $model.entity.AreaId = ''
                            $model.entity.AreaDisplay = ''
                        }
                    }
                })
                $model.entity.$watch('CityId', function (n, o) {
                    //if (n != o) {
                    $model.area.removeAll()

                    allLocations.forEach(function (c) {
                        if (c.ParentId == n) {
                            $model.area.push(c)
                        } else if (c.Id == n) {
                            $model.entity.CityDisplay = c.Data
                        }
                    })
                    //avalon.log('CityId : ' + $model.entity.CityId)
                    if ($model.area.size()) {
                        if (_getIndex($model.area, $model.AreaId) == -1) {
                            $model.entity.AreaId = $model.area[0].Id
                            $model.entity.AreaDisplay = $model.area[0].Data;
                        }
                    } else {
                        $model.entity.AreaId = ''
                        $model.entity.AreaDisplay = ''
                    }
                    if ($model.city.size() == 0) {
                        $model.area.removeAll();
                        $model.entity.AreaId = ''
                        $model.entity.AreaDisplay = ''
                    }
                    //}
                })
                $model.entity.$watch('AreaId', function (n, o) {
                    var index = _getIndex($model.area, n);
                    if (index != -1) {
                        $model.entity.AreaDisplay = $model.area[index].Data;
                    } else {
                        $model.entity.AreaDisplay = ''
                    }
                })
                /*国家地区级联*/
            }
            $model.entity = modelFactory.create('CompanyInfo');
            bindWatch();
            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.CompanyInfo = null
            }
            $.get("/Settings/GetLocations", {}, function (d) {
                allLocations = d.data;
                allLocations.forEach(function (l) {
                    if (l.ParentId === 0) {
                        $model.country.push(l);
                        if ($model.entity.CountryId == "") $model.entity.CountryId = l.Id;
                    }
                });
                $.get('/Settings/DetailCompanyInfo/', {}, function (ret) {
                    if (ret.data) {
                        $model.industry = ret.data.industry;
                        avalon.mix($model.entity, modelFactory.create('CompanyInfo'));
                        avalon.mix($model.entity, ret.data.model);
                    }
                    if (!$model.entity.Logo)
                        $model.entity.Logo = $model.defaultLogo;

                    CBCRM.fillContent(tmpl, lang, contentId, module, $model)
                })
            });

        },
        /// <summary>
        /// 全局设置
        /// </summary>
        SiteGolbal: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM,
                model = CBCRM.define('SiteGolbal', function (vm) {
                    vm.Frequencys = [{ val: "day", text: "每天" }, { val: "week", text: "每周" }];
                    vm.weeks = [
                            { val: "1", text: "星期一" },
                            { val: "2", text: "星期二" },
                            { val: "3", text: "星期三" },
                            { val: "4", text: "星期四" },
                            { val: "5", text: "星期五" },
                            { val: "6", text: "星期六" },
                            { val: "0", text: "星期日" }
                    ];
                    vm.entity = {
                        SiteOff: false,
                        SiteOffMsg: '系统维护中，请稍后再访问',
                        IfLock: false,
                        LockNum: '10',
                        IsEnable: false,
                        CharLength: '',
                        OpenTime: false,
                        OpenFrequency: "day",
                        OpenWeekdays:[],
                        StartHour: '',
                        StartMinute: '',
                        Endhour: '',
                        EndMinute: '',
                        AppOn: false,
                        AppOffMsg:"手机APP连接关闭中，请稍后再访问",
                        AppOpenTime: false,
                        AppStartHour: '',
                        AppStartMinute: '',
                        AppEndhour: '',
                        AppEndMinute: '',
                        OffTime: false,
                        OffTimes:"",
                        AppTrackInterval: '',
                        AppTrackRemoveDay:'',
                        FileExt: '*.gif;*.jpg;*.png;*.bmp;*.doc;*.docx;*.xls;*.xlsx;*.txt;*.rar;*.zip',
                        FileSize: '4',
                        IfBlackIp: false,
                        BlackIp: '',
                        LogSaveDay: 30
                    }
                    vm.userCount = 0;
                    vm.trackDataSize = 0;
                    vm.trackDataSizeP = 0;
                    vm.$trackRSize = 411;
                    vm.blackIpList = [];
                    vm.addNewBlackIp = function () {
                        var ip = { Id: 0, Cname: "BlackIpList", Name: "", Value: "" };
                        model.blackIpList.push(ip);
                    }
                    vm.lang = lang
                    vm.submit = function () {
                        var m = $.extend({}, model.entity.$model);
                        if (m.OpenTime) {
                            if (isNaN(m.StartHour) || isNaN(m.StartMinute) || isNaN(m.Endhour) || isNaN(m.EndMinute)) {
                                messageBox.error("操作错误！<br />时间段只能是数字，请检查！");
                                return false;
                            }
                            m.StartHour = parseInt(m.StartHour, 10);
                            m.StartMinute = parseInt(m.StartMinute, 10);
                            m.Endhour = parseInt(m.Endhour, 10);
                            m.EndMinute = parseInt(m.EndMinute, 10);
                            if ((m.StartHour >= 24 || m.StartHour < 0) || (m.Endhour >= 24 || m.Endhour < 0)) {
                                messageBox.error("操作错误！<br />小时的数值只能是0-23之间的整数！");
                                return false;
                            }
                            if ((m.StartMinute >= 60 || m.StartMinute < 0) || (m.EndMinute >= 60 || m.EndMinute < 0)) {
                                messageBox.error("操作错误！<br />分钟的数值只能是0-59之间的整数！");
                                return false;
                            }
                        }
                        if (isNaN(m.LogSaveDay) || m.LogSaveDay <= 0) {
                            messageBox.error("操作错误！<br />登陆/操作日志保留天数只能是大于0的数字，请检查！");
                            return false;
                        }
                        var list = [],val;
                        for (var key in m) {
                            if (typeof (m[key]) == "function") continue;
                            val = m[key];
                            if ($.isArray(val)) val = val.join(",");
                            list.push({ Code: key, Value: val });
                        }
                        var i = 0;
                        model.blackIpList.forEach(function (item) {
                            i++;
                            item.Value = i;
                        });
                        var data = jsonToSubmit("globals", list);
                        //$.extend(data, jsonToSubmit("blackIpList", model.blackIpList));

                        $.post('/Settings/SiteGolbal', data)
                        .done(function (ret) {
                            avalon.vmodels.CBCRM.showResult(ret);
                            if (ret.result) {
                                model.entity = m;
                            }
                        })
                    }
                    vm.selectOffTimes = function () {
                        var jcal;
                        model.openTmpl({
                            title: "选择要禁止的日期", w: 260, h: 200,padding:"def2",
                            tmpl: tmpl, tmplId: "selectTimesTmpl",
                            button: [
                                {
                                    name: "确定",
                                    focus:true,
                                    callback: function () {
                                        var da = jcal.getDayArr(),a=[];
                                        da.forEach(function (t) {
                                            a.push(GetDateTime(t, "yyyy-MM-dd"));
                                        });
                                        model.entity.OffTimes = a.join(",");
                                    }
                                },
                                {
                                    name: "清空日期",
                                    callback: function () {
                                        model.entity.OffTimes = "";
                                    }
                                }
                            ],
                            onScan: function () {
                                var a = model.entity.OffTimes ? model.entity.OffTimes.split(",") : [];
                                for (var i = 0, l = a.length; i < l; i++) {
                                    a[i] = new Date(a[i]+" 0:0");
                                }
                                jcal = setJCal("#dSelectTimes", function (day,days,dayArr) {

                                }, {multiple:true, dayArr: a });
                            }
                        })
                    }
                })
            $.get('/Settings/SiteGolbal?d=' + new Date(), {})
            .done(function (ret) {
                if (ret.result) {
                    var globals = ret.data.globals;
                    //model.blackIpList = blackIpList;
                    model.userCount = ret.data.userCount;
                    globals.forEach(function (item) {
                        if (item.Value == "true") item.Value = true;
                        if (item.Value == "false") item.Value = false;
                        if (item.Code == "OpenWeekdays") {
                            item.Value = item.Value ? item.Value.split(",") : [];
                        }
                        if (model.entity.hasOwnProperty(item.Code))
                            model.entity[item.Code] = item.Value
                    })
                }
            })
            model.entity.$watch("AppTrackInterval", function (n) {
                if (!n) {
                    model.trackDataSize = 0;
                    model.trackDataSizeP = 0;
                } else {
                    model.trackDataSizeP = (model.$trackRSize * (24 * 3600 / n) / 1024 / 1024).toFixed(2);
                    model.trackDataSize = model.trackDataSizeP * model.userCount;
                }
            });
            require("jcal", function () {
                CBCRM.fillContent(tmpl, lang, contentId, module, model)
            })
        },
        /// <summary>
        /// 客户模块设置
        /// </summary>
        CustomerSettings: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM
            var Mvvm = avalon.define('CustomerSettings', function (vm) {
                vm.lang = lang
                vm.entity = {}
                vm.submit = function () {
                    var id = Mvvm.entity.Id;
                    $.post('/Settings/UpdateCustomerSettings/' + id, Mvvm.entity.$model, function (data) {
                        avalon.vmodels.CBCRM.showResult(data)
                    })
                }
                vm.hours = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
                vm.minutes = ['00', '10', '20', '30', '40', '50']
            })
            Mvvm.entity = modelFactory.create('SettingsCustomer');
            $.get('/Settings/CustomerSettings/', {}, function (result) {
                if (result.data) {
                    //result.data.IsStart = result.data.IsStart + ''
                    //result.data.DisableChangeName += '';
                    //Mvvm.entity = result.data;
                    avalon.mix(Mvvm.entity, result.data);
                }
                Mvvm.entity.IsStart += '';
                Mvvm.entity.DisableChangeName += '';
            })

            CBCRM.fillContent(tmpl, lang, contentId, module, Mvvm)
            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.CustomerSettings = null
            }
        },
        /// <summary>
        /// 办公模块设置
        /// </summary>
        OfficeSettings: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM
            var mvvm = avalon.define('OfficeSettings', function (vm) {
                vm.lang = lang
                vm.weeks = [
                    { val: 0, text: "周一" },
                    { val: 1, text: "周二" },
                    { val: 2, text: "周三" },
                    { val: 3, text: "周四" },
                    { val: 4, text: "周五" },
                    { val: 5, text: "周六" },
                    { val: 6, text: "周日" },
                ];
                vm.monthdays = [1, 2, 3, 4, 5];
                vm.config = {
                    cname: "DailyReport",
                    configs: {
                        CurDayDelay: "0",
                        CurDayHour: "18",
                        CurDayMinute: "30",
                        NextDayHour: "9",
                        NextDayMinute: "30",
                        CurWeekDelay: "0",
                        CurWeekDay: "4",
                        CurWeekHour: "18",
                        CurWeekMinute: "30",
                        NextWeekDay: "0",
                        NextWeekHour: "9",
                        NextWeekMinute: "30",
                        CurMonthDelay: "0",
                        CurMonthLastDay: "5",
                        CurMonthHour: "18",
                        CurMonthMinute: "30",
                        NextMonthBeginDay: "5",
                        NextMonthHour: "9",
                        NextMonthMinute: "30",
                        UseSendTo: "1"
                    }
                }
                vm.setConfig = function () {
                    Config.set(mvvm.config.$model, function (ret) {
                        CBCRM.showResult(ret);
                    });
                }
                vm.getConfig = function () {
                    Config.get(mvvm.config);
                }
            })
            mvvm.getConfig();


            CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.OfficeSettings = null
            }
        },
        /// <summary>
        /// 客户记事设置
        /// </summary>
        RecordSettings: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM
            var mvvm = avalon.define('RecordSettings', function (vm) {
                vm.lang = lang

                vm.showCount = false
                vm.showOne = false
                vm.showTow = false
                vm.showTag = false
                vm.showList = false

                vm.showOneName = false
                vm.showTowName = false
                vm.showTagName = false
                vm.showListName = false

                //客户记事配置
                vm.config = {
                    cname: "CustomerRecord",
                    configs: {
                        ShowNumder: "0",
                        ShowPosition: "0",
                        ShowStart: "1",
                        NumderTag: "客户记事",
                        TagPositionTag: "客户记事1",
                        ListPositionTag: "客户记事2"
                    }
                }
                //查看
                vm.doview = function (val) {
                    var dialog = messageBox.openHtml('预览客户记事', '500px', '500px', '');
                    var content = $(dialog.content())
                    var inputTmpl
                    switch (val) {
                        case 0:
                            inputTmpl = $(tmpl).filter("#leftTwomeun").text()
                            break;
                        case 1:
                            inputTmpl = $(tmpl).filter("#Tagmeun").text()
                            break;
                        case 2:
                            inputTmpl = $(tmpl).filter("#Listmeun").text()
                            break;
                        case 3:
                            inputTmpl = $(tmpl).filter("#leftOnemeun").text()
                            break;
                    }
                    content.html(inputTmpl)
                }

                vm.Show = function (start, numder, position) {
                    if (start == 0) {
                        mvvm.showCount = false

                        if (numder == 0) {
                            mvvm.showOne = false
                            mvvm.showTow = true
                            mvvm.showTag = true
                            mvvm.showList = true

                            mvvm.config.configs.ShowPosition = "3"
                            mvvm.showOneName = false
                            mvvm.showTowName = true
                            mvvm.showTagName = true
                            mvvm.showListName = true
                        } else {

                            mvvm.showOne = true
                            mvvm.showTow = false
                            mvvm.showTag = false
                            mvvm.showList = false
                            if (position == 3) {
                                mvvm.config.configs.ShowPosition = "0"
                                ShowName(mvvm.config.configs.ShowPosition)
                            } else {
                                ShowName(position)
                            }
                        }

                    } else {
                        mvvm.showCount = true
                        mvvm.showOne = true
                        mvvm.showTow = true
                        mvvm.showTag = true
                        mvvm.showList = true
                        mvvm.showOneName = true
                        mvvm.showTowName = true
                        mvvm.showTagName = true
                        mvvm.showListName = true
                    }
                }


                //多条左侧菜单形式
                vm.RecordMode = {
                    Cname: 'CustomerRecordPosition',
                    Name: "PositionTag",
                    Value: ""
                }

                vm.CustomerRecordSettings = {
                    Id: '0',//编号
                    RecordTag: '',//菜单标题
                    RecordContent: '',//菜单内容
                    CoustomId: 0,//客户编号
                    CreateId: 0,//创建人
                    CreateDate: '',//创建时间
                    UpdateId: 0,//更新人
                    UpdateDate: '',//更新时间
                    RecordName: ''//菜单标记
                }

                vm.lilist = []
                vm.customerRecordAdd = function () {
                    mvvm.lilist.push({ Cname: 'CustomerRecordPosition', Name: "PositionTag", Value: "" });
                }
                vm.customerRecordDel = function () {
                    var index = parseInt($(this).attr("index"))
                    var con = vm.lilist.$model[index]
                    vm.lilist.removeAt(index)
                }

                vm.setConfig = function () {
                    Config.set(mvvm.config.$model, function (ret) {
                        var list = []
                        for (var i = 0, tmp; tmp = mvvm.lilist[i]; i++) {
                            list.push({ Cname: tmp.Cname, Name: tmp.Name, Value: tmp.Value });
                        }
                        var data = jsonToSubmit("configs", list);
                        $.post("/Settings/UpdateSettingConfigs", data, function (ret) {
                            //  $.post("/Customer/EditCustomerRecord", data, function (ret) {
                            CBCRM.showResult(ret);
                            //  });
                            avalon.vmodels.ViewCustomer = null
                            avalon.vmodels.RecordDetails = null
                        });
                    });
                }
                vm.getConfig = function () {
                    var modellist
                    Config.get(mvvm.config, function (ret) {
                        mvvm.Show(mvvm.config.configs.ShowStart, mvvm.config.configs.ShowNumder, mvvm.config.configs.ShowPosition)
                        $.get("/Settings/GetSettingConfigs", { cname: mvvm.RecordMode.Cname }, function (result) {
                            if (result.data != "") {
                                modellist = result.data;
                                for (var i = 0, tmp; tmp = modellist[i]; i++) {
                                    mvvm.lilist.push({ Cname: tmp.Cname, Name: tmp.Name, Value: tmp.Value });
                                }
                            } else {
                                mvvm.lilist.push({ Cname: 'CustomerRecordPosition', Name: "PositionTag", Value: "客户记事1" }, { Cname: 'CustomerRecordPosition', Name: "PositionTag", Value: "客户记事2" }, { Cname: 'CustomerRecordPosition', Name: "PositionTag", Value: "客户记事3" })
                            }

                        });
                    });
                }
            })
            mvvm.getConfig();


            function ShowName(val) {
                switch (val) {
                    case "0":
                        mvvm.showTowName = false
                        mvvm.showTagName = true
                        mvvm.showOneName = true
                        mvvm.showListName = true
                        break;
                    case "1":
                        mvvm.showTowName = true
                        mvvm.showTagName = false
                        mvvm.showOneName = true
                        mvvm.showListName = true
                        break;
                    case "2":
                        mvvm.showTowName = true
                        mvvm.showTagName = true
                        mvvm.showOneName = true
                        mvvm.showListName = false
                        break;
                    case "3":
                        mvvm.showTowName = true
                        mvvm.showTagName = true
                        mvvm.showOneName = false
                        mvvm.showListName = true
                        break;
                }
            }


            CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.RecordSettings = null
            }
        },
        /// <summary>
        /// 考勤时间设置
        /// </summary>
        CheckInTime: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM, vmid = "Settings_CheckInTime";
            var mvvm = CBCRM.define(vmid, function (vm) {
                vm.lang = lang
                vm.checkWeek = function (w) {
                    w.checked = !w.checked;
                }
                vm.changeEnable = function (item) {
                    item.Enable = !item.Enable;
                }
                vm.list = [];
                vm.doAdd = function () {
                    var entity = modelFactory.create("CheckInConfig");
                    mvvm.initWeeks([entity]);
                    mvvm.list.push(entity);
                }
                vm.doRemove = function (index) {
                    if (messageBox.confirm2("您确定要删除该时间段吗？", function () {
                        mvvm.list.removeAt(index);
                    }));
                }
                vm.doSubmit = function () {
                    if (mvvm.list.length == 0) {
                        messageBox.warning("至少要有一个时间段才能提交！");
                        return;
                    }
                    mvvm.commitWeeks();
                    var list = []
                    mvvm.list.$model.forEach(function (item) {
                        var copy = $.extend(true, {}, item);
                        delete copy.weeks;
                        delete copy.WeekDayList;
                        list.push(copy);
                    });
                    var data = jsonToSubmit("list", list);
                    $.post("/Settings/CheckInTimeSubmit", data, function (ret) {
                        CBCRM.showResult(ret);
                        if (ret.result) mvvm.getList();
                    });
                }
                vm.getList = function () {
                    $.get("/Settings/CheckInTime", function (ret) {
                        var list = [];
                        if (ret.result) {
                            list=list.concat(ret.data);
                        }
                        mvvm.initWeeks(list);
                        mvvm.list = list;
                        if (list.length == 0) mvvm.doAdd();
                    });
                }
                vm.initWeeks = function (list) {
                    list.forEach(function (item) {
                        item.weeks = [
                            { val: 1, text: "周一", checked: false },
                            { val: 2, text: "周二", checked: false },
                            { val: 3, text: "周三", checked: false },
                            { val: 4, text: "周四", checked: false },
                            { val: 5, text: "周五", checked: false },
                            { val: 6, text: "周六", checked: false },
                            { val: 0, text: "周日", checked: false }
                        ];
                        item.weeks.forEach(function (w) {
                            w.checked = item.WeekDayList.indexOf(w.val) != -1;
                        });
                    }); 
                }
                vm.commitWeeks = function () {
                    mvvm.list.forEach(function (item) {
                        var vals = where(item.weeks.$model, function (w) { return w.checked }, "val");
                        item.WeekDays = vals.join(",");
                        item.WeekDayList = vals;
                    });
                }
            })
            mvvm.getList();
            CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
        },
        /// <summary>
        /// 考勤地点设置
        /// </summary>
        CheckInArea: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM, vmid = "Settings_CheckInArea";
            var mvvm = CBCRM.define(vmid, function (vm) {
                vm.lang = lang
                vm.changeEnable = function (item) {
                    item.Enable = !item.Enable;
                }
                vm.list = [];
                vm.configList = [];
                vm.doAdd = function () {
                    var entity = modelFactory.create("CheckInArea");
                    mvvm.list.push(entity);
                }
                vm.doRemove = function (index) {
                    if (messageBox.confirm2("您确定要删除该考勤地点吗？", function () {
                        mvvm.list.removeAt(index);
                    }));
                }
                vm.doSubmit = function () {
                    var list = []
                    mvvm.list.$model.forEach(function (item) {
                        var copy = $.extend(true, {}, item);
                        copy.ConfigIds = copy.ConfigIdList.join(",");
                        delete copy.ConfigIdList;
                        list.push(copy);
                    });
                    var data = jsonToSubmit("list", list);
                    $.post("/Settings/CheckInAreaSubmit", data, function (ret) {
                        CBCRM.showResult(ret);
                        if (ret.result) mvvm.getList();
                    });
                }
                vm.getList = function () {
                    $.get("/Settings/CheckInArea", function (ret) {
                        var list = [];
                        if (ret.result) {
                            list = list.concat(ret.data);
                        }
                        mvvm.list = list;
                        if (list.length == 0) mvvm.doAdd();
                    });
                }

                /*地图标注*/
                vm.$mapLoaded = false;
                vm.$map = null;
                vm.markInMap = function (index) {
                    var cmyInfo=CBCRM.cmyInfo.$model;
                    var entity = mvvm.list[index];
                    var _t = null;
                    if (!mvvm.$mapLoaded) {
                        var win = art.dialog({
                            width: 300,
                            height: 100,
                            title: "地图加载中……",
                            content: "<img src='/Content/Themes/Base/images/loading2.gif' />"
                        });
                        _t = window.setTimeout(function () {
                            if (win) win.close();
                            messageBox.warning("加载地图超时！<br />请确认您是否已经联网。");
                        }, 10 * 1000);
                    }
                    require(["bdmapTool", "ready!"], function (bdmapTool) {
                        mvvm.$mapLoaded = true;
                        if (win) win.close();
                        if (_t) window.clearTimeout(_t);
                        function _callBack(p, box) {
                            entity.Location = p.address;
                            entity.Lng = p.point.lng;
                            entity.Lat = p.point.lat;
                            box.close();
                        }
                        var point, city = cmyInfo.CityDisplay;
                        if (",市辖区,县,".indexOf(city) > -1 || city == "") city = cmyInfo.ProvinceDisplay;
                        if (entity.Lng) {
                            point = new BMap.Point(entity.Lng, entity.Lat);
                        } else if (cmyInfo.Lng) {
                            point = new BMap.Point(cmyInfo.Lng, cmyInfo.Lat);
                        } else {
                            point = null;
                        }
                        var map = mvvm.$map = new bdmapTool({
                            tmpl: "search",
                            searchpanel: "seekpanel",
                            left: 285,
                            pointCallBack: _callBack,
                            searchCallBack: _callBack,
                            city: city,
                            point: point
                        });
                        map.openMap(function () {
                            var name = "考勤地点";
                            var address = cmyInfo.Address;
                            if (point) {
                                map.addMarker(point, name, { html: name, ops: { width: 250 } });
                            } else {
                                if (address != "") {
                                    map.searchMap(address);
                                }
                            }
                        });
                    });
                }
            })
            function getConfigs() {
                $.get("/Settings/CheckInTime", function (ret) {
                    if (!ret || !ret.result) return CBCRM.showResult(ret);
                    mvvm.configList = ret.data;
                    mvvm.getList();
                });
            }
            getConfigs();
            CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
        },
        /// <summary>
        /// 数据字典
        /// </summary>
        Dictionary: function (tmpl, lang, contentId, module) {
            var formatModel = modelFactory.create('Dictionary');
            var CBCRM = avalon.vmodels.CBCRM
            var Mvvm = avalon.define('Dictionary', function (vm) {
                vm.lang = lang
                vm.newModel = {}
                vm.areaModel = {}
                vm.isArea = false
                vm.leftMenu = []
                vm.defaultId = 0
                vm.pid = 0
                vm.defaultName = ''
                vm.childName = ''
                vm.dictionary = []
                vm.prpvince = []
                vm.district = []

                vm.rdoDefault = function () {
                    Mvvm.dictionary.$model.forEach(function (item, i) {
                        Mvvm.dictionary[i].IsDefault = false
                    })
                    $(this).checked = true
                }
                vm.rdoDefaultChild = function () {
                    var pid = $(this).attr("pid")
                    Mvvm.dictionary.$model.forEach(function (item, i) {
                        if (item.Id == pid) {
                            Mvvm.dictionary.$model[i].Child.forEach(function (item, j) {
                                Mvvm.dictionary[i].Child[j].IsDefault = false
                            })
                        }
                    })
                    $(this).checked = true
                }
                vm.status = "dictionary";
                vm.currItem = { };
                vm.jump = function (item) {
                    Mvvm.currItem = item.$model;
                    var object = $(this);
                    Mvvm.defaultName = object.attr('title');
                    Mvvm.defaultId = object.val();
                    Mvvm.childName = '';
                    var s = object.attr('status');
                    if (!s) s = "dictionary";
                    Mvvm.status = s;
                    switch (s) {
                        case "area":

                            Mvvm.isArea = true;
                            Mvvm.defaultId = 0;
                            GetArea(object.val(), 0, "0");
                        case "membergrade":
                            Mvvm.getMemberGradeList();
                            break;
                        default:
                            Mvvm.isArea = false;
                            GetDictionaryData(object.val());
                            break;
                    }
                }
                vm.disabled = function (e) {
                    var index = this.value;
                    var show = Mvvm.leftMenu[index].show;
                    Mvvm.leftMenu[index].show = show ? false : true;
                }
                //点击字典
                vm.child = function () {
                    var row = $(this),
                        parent = row.attr('data-id')
                    Mvvm.childName = row.attr('data-name');
                    GetDictionaryParent(parent);
                }

                vm.region = ''
                //点击地区
                vm.areaChild = function (item, index) {
                    var row = $(this);
                    Mvvm.defaultId = item.Id;
                    Mvvm.childName = item.Data;
                    Mvvm.pid = item.ParentId;
                    //getLocations(item.Id, "0");
                    Mvvm.region = item.Id
                    Mvvm.parseLeters(index)
                }


                //vm.showArea = false
                ////点击地区
                //vm.areaShowChild = function () {
                //    var row = $(this);
                //    Mvvm.defaultId = row.attr('data-parentid');
                //    Mvvm.childName = row.attr('data-name');
                //    Mvvm.pid = row.attr('data-pid');
                //    if (Mvvm.showArea == true)
                //        Mvvm.showArea = false;
                //    else
                //        Mvvm.showArea = true;
                //    GetTreeArea(row.attr('data-id'))
                //}

                ////点击上级地区
                //vm.titleChild = function () {
                //    var row = $(this);
                //    $.get('/Settings/AreaModel/' + row.attr('data-pid'), {}, function (res) {
                //        if (res.data) {
                //            Mvvm.childName = res.data.Data;
                //            Mvvm.defaultId = res.data.Id;
                //            Mvvm.pid = res.data.ParentId;
                //            GetArea(row.attr('data-pid'));
                //        }
                //    });
                //}
                //新增字典
                vm.doadd = function () {
                    var d = messageBox.openHtml('新增字典', '400px', '200px', '', [{
                        name: lang.SubmitBtn,
                        focus: true,
                        callback: function () {
                            var model = Mvvm.newModel.$model;
                            if (model.Data != '') {
                                $.post('/Settings/DictionaryAdd/', Mvvm.newModel.$model, function (data) {
                                    GetDictionaryData(Mvvm.defaultId);
                                    messageBox.close();
                                });
                            }
                            else messageBox.warning('请填写地区名称');
                            return false;
                        }
                    }]);
                    var content = $(d.content())
                    content.attr('ms-include', 'dictionaryAdd')
                    Mvvm.newModel = formatModel;
                    Mvvm.newModel.DictionaryId = Mvvm.defaultId
                    avalon.scan(content[0], Mvvm)
                }
                //新增字典子类
                vm.doaddchild = function () {
                    var row = $(this)
                    var pid = row.attr('data-pid')
                    var did = pid
                    switch (Mvvm.defaultId) {
                        case 100026:
                            //客户二级分类
                            did = 100027;
                            break;
                        case 100108:
                            //客户状态二级分类
                            did = 100120;
                            break;
                    }
                    var d = messageBox.openHtml('新增字典', '400px', '200px', '', [{
                        name: lang.SubmitBtn,
                        focus: true,
                        callback: function () {
                            var model = Mvvm.newModel.$model;
                            if (model.Data != '') {
                                $.post('/Settings/DictionaryAdd/', Mvvm.newModel.$model, function (data) {
                                    GetDictionaryData(Mvvm.defaultId);
                                    messageBox.close();
                                });
                            }
                            else messageBox.warning('请填写地区名称');
                            return false;
                        }
                    }]);
                    var content = $(d.content())
                    content.attr('ms-include', 'dictionaryAdd')
                    Mvvm.newModel = formatModel
                    Mvvm.newModel.ParentId = pid
                    Mvvm.newModel.DictionaryId = did //100027
                    avalon.scan(content[0], Mvvm)
                }
                //编辑字典
                vm.doedit = function () {
                    var index = $(this).attr('data-index');
                    var d = messageBox.openHtml('编辑字典', '400px', '200px', '', [{
                        name: lang.SubmitBtn,
                        focus: true,
                        callback: function () {
                            var model = Mvvm.newModel.$model;
                            if (model.Data != '') {
                                $.post('/Settings/DictionaryUpdate/' + model.Id, model, function (data) {
                                    GetDictionaryData(Mvvm.defaultId);
                                    messageBox.close();
                                });
                            }
                            else messageBox.warning('请填写字典名称');

                            return false;
                        }
                    }]);
                    var content = $(d.content())
                    content.attr('ms-include', 'dictionaryAdd')
                    var index = $(this).attr('data-index');
                    Mvvm.newModel = Mvvm.dictionary.$model[index];
                    avalon.scan(content[0], Mvvm)
                }
                //编辑字典子类
                vm.doeditchild = function () {
                    var d = messageBox.openHtml('编辑字典', '400px', '200px', '', [{
                        name: lang.SubmitBtn,
                        focus: true,
                        callback: function () {
                            var model = Mvvm.newModel.$model;
                            if (model.Data != '') {
                                $.post('/Settings/DictionaryUpdate/' + model.Id, model, function (data) {
                                    GetDictionaryData(Mvvm.defaultId);
                                    messageBox.close();
                                });
                            }
                            else messageBox.warning('请填写地区名称');
                            return false;
                        }
                    }]);

                    var content = $(d.content())
                    content.attr('ms-include', 'dictionaryAdd')
                    var id = $(this).attr('data-id')
                    var pid = $(this).attr('data-pid')
                    Mvvm.dictionary.$model.forEach(function (item, i) {
                        if (item.Id == pid) {
                            Mvvm.dictionary.$model[i].Child.forEach(function (childitem, j) {
                                if (childitem.Id == id) {
                                    Mvvm.newModel = Mvvm.dictionary.$model[i].Child[j]
                                }
                            })
                        }
                    })
                    avalon.scan(content[0], Mvvm)
                }
                //删除字典
                vm.del = function () {
                    if (confirm('确定删除吗?')) {
                        var id = $(this).attr('data-id');
                        var index = $(this).attr('data-index');
                        $.post('/Settings/DictionaryDel/' + id, {}).done(function () {
                            GetDictionaryData(Mvvm.defaultId);
                        });
                    }
                }
                //背景颜色
                vm.bg = function (i) {
                    return (i % 2 == 0) ? '#FAFAFA' : '#FFFFFF';
                }
                //保存
                vm.doFromSave = function () {
                    var model = {}
                    Mvvm.dictionary.$model.forEach(function (item, i) {
                        model['dicts[' + i + '].Data'] = item.Data
                        model['dicts[' + i + '].DictionaryId'] = item.DictionaryId
                        model['dicts[' + i + '].Enable'] = item.Enable
                        model['dicts[' + i + '].Id'] = item.Id
                        model['dicts[' + i + '].IsDefault'] = item.IsDefault
                        model['dicts[' + i + '].ParentId'] = item.ParentId
                        model['dicts[' + i + '].Sort'] = item.Sort
                        model['dicts[' + i + '].Type'] = item.Type
                        if (item.Child && item.Child.length > 0) {
                            item.Child.forEach(function (item, j) {
                                model['dicts[' + i + '].Child[' + j + '].Data'] = item.Data
                                model['dicts[' + i + '].Child[' + j + '].DictionaryId'] = item.DictionaryId
                                model['dicts[' + i + '].Child[' + j + '].Enable'] = item.Enable
                                model['dicts[' + i + '].Child[' + j + '].Id'] = item.Id
                                model['dicts[' + i + '].Child[' + j + '].IsDefault'] = item.IsDefault
                                model['dicts[' + i + '].Child[' + j + '].ParentId'] = item.ParentId
                                model['dicts[' + i + '].Child[' + j + '].Sort'] = item.Sort
                                model['dicts[' + i + '].Child[' + j + '].Type'] = item.Type
                            })
                        }
                    })
                    $.post('/Settings/DictionaryListSave', model, function (ret) {
                        GetDictionaryData(Mvvm.defaultId)
                        messageBox.ok(ret.message)
                    })

                }

                //会员级别
                vm.memberGradeModel = {};
                vm.memberGradeList = [];
                vm.hasChangeDiscount = false;
                //新增
                vm.doMemberGradeAdd = function () {
                    Mvvm.memberGradeModel = $.extend(true, {}, modelFactory.create('MemberGrade'));
                    var l = Mvvm.memberGradeList.length;
                    var sort = l == 0 ? 1 : Mvvm.memberGradeList[l - 1].Sort + 1;
                    Mvvm.memberGradeModel.Sort = sort;
                    Mvvm.showMemberGradeInput("新增会员级别");
                }
                //编辑
                vm.doMemberGradeEdit = function (item) {
                    Mvvm.memberGradeModel = item;
                    Mvvm.showMemberGradeInput("编辑会员级别");
                }
                //录入界面
                vm.dwidth = 420;
                vm.showMemberGradeInput = function (title) {
                    var dialog = messageBox.openHtml(title, Mvvm.dwidth, null, '', [{
                        name: lang.SubmitBtn,
                        focus: true,
                        callback: function () {
                            var model = Mvvm.memberGradeModel.$model;
                            if (model.Name == '') {
                                messageBox.warning("请输入名称！");
                                return false;
                            }
                            if (model.Discount == '') {
                                messageBox.warning("请输入折扣！");
                                return false;
                            }
                            var url = model.Id ? "/Settings/MemberGradeUpdate/" + model.Id : "/Settings/MemberGradeAdd/";
                            $.post(url, model, function (ret) {
                                CBCRM.showResult(ret, function () {
                                    if (ret.result) {
                                        dialog.close();
                                        Mvvm.getMemberGradeList();
                                    }
                                });
                            });
                            return false;
                        }
                    }]);
                    var content = $(dialog.content()),
                        htmltmpl = $(tmpl).find("#memberGradeInputTmpl").text();
                    content.html(htmltmpl).css({ padding: "10px" });
                    avalon.scan(content[0], Mvvm)
                }
                //删除
                vm.delMemberGrade = function (id, index) {
                    if (confirm('确定删除吗?')) {
                        $.post('/Settings/MemberGradeDel/' + id, {}).done(function (ret) {
                            CBCRM.showResult(ret);
                            if (ret.result) Mvvm.memberGradeList.removeAt(parseInt(index, 10));
                        });
                    }
                }
                //保存排序
                vm.doMemberGradeListSave = function (callback) {
                    var data = jsonToSubmit("list", Mvvm.memberGradeList);
                    $.post('/Settings/MemberGradeListSave', data, function (ret) {
                        Mvvm.hasChangeDiscount = false;
                        Mvvm.getMemberGradeList();
                        if (callback && ret.result) callback();
                        else CBCRM.showResult(ret);
                    })
                }
                //更新产品会员价格
                vm.doMemberGradeUpdateProductPrice = function () {
                    var msg = "确定要重置更新产品的会员价格吗？<br />1.本操作会按当前设定的产品折扣更新替换所有产品对应的会员级别价格！<br />2.原单独设定有会员价格的产品亦会被新价格替换。";
                    messageBox.confirm2(msg, "确定重置", "取消", function () {
                        if (Mvvm.hasChangeDiscount) {
                            //messageBox.warning("您已经更改了折扣，请先保存！");
                            Mvvm.doMemberGradeListSave(_post);
                            return;
                        } else {
                            _post();
                        }
                    });
                    function _post() {
                        $.post('/Settings/MemberGradeUpdateProductPrice', {}, function (ret) {
                            CBCRM.showResult(ret);
                        });
                    }
                }
                //获取列表
                vm.getMemberGradeList = function () {
                    Mvvm.memberGradeList = [];
                    $.get('/Settings/MemberGradeList', {}, function (ret) {
                        if (ret.result) {
                            Mvvm.memberGradeList = ret.data.list;
                            Mvvm.hasChangeDiscount = false;
                            var _init = false, l = ret.data.list.length - 1;
                            Mvvm.memberGradeList.forEach(function (item, i) {
                                item.$watch("Discount", function (n, o) {
                                    if (_init == false && i > 0) return;
                                    if (_init == false && i == 0) {
                                        _init = true;
                                        return;
                                    }
                                    Mvvm.hasChangeDiscount = true;
                                });
                            });
                        } else CBCRM.showResult(ret);
                    })
                }
                //会员级别结束

                //展开收缩树
                vm.doNode = function () {
                    var stu = parseInt($(this).attr('stu'))
                    if (stu == 1) {
                        var id = $(this).attr('id')
                        $(this).removeClass('treehaschild')
                        $(this).addClass('treehaschildexp')
                        $('.parentid' + id).hide()
                        $(this).attr('stu', 2)
                    } else if (stu == 2) {
                        var id = $(this).attr('id')
                        $(this).removeClass('treehaschildexp')
                        $(this).addClass('treehaschild')
                        $('.parentid' + id).show()
                        $(this).attr('stu', 1)
                    }
                }

                //新增地区
                vm.doRegionAdd = function (id, type) {
                    Mvvm.areaModel = modelFactory.create('Area');
                    Mvvm.areaModel.ParentId = id
                    var btns = [{
                        name: lang.SubmitBtn,
                        focus: true,
                        callback: function () {
                            var $that = $("#txtAreaName"), letter
                            letter = $that.toPinyin();
                            Mvvm.areaModel.Letter = letter.substring(0, 10)
                            Mvvm.areaModel.FirstLetter = Mvvm.areaModel.Letter.substr(0, 1)
                            var model = Mvvm.areaModel.$model;
                            if (model.Data != '') {
                                $.post('/Settings/RegionAdd/', model, function (data) {
                                    if (type == 3) Mvvm.getRegionArea(id);
                                    else GetArea(function () {
                                        if (type == 2) Mvvm.scrollToId(id);
                                    });
                                    messageBox.close();
                                });
                            }
                            else messageBox.warning('请填写国家地区名称');
                            return false;
                        }
                    }]
                    var d = openTmpl({
                        vm: Mvvm, title: "新增国家地区", w: 400, h: 160,
                        tmpl: tmpl, tmplid: "areaAdd", btns: btns
                    })
                }


                //编辑地区
                vm.doRegionEdit = function (item, type) {
                    Mvvm.areaModel = modelFactory.create('Area');
                    Mvvm.areaModel.Id = item.Id
                    Mvvm.areaModel.Sort = item.Sort
                    Mvvm.areaModel.Data = item.Data;
                    Mvvm.areaModel.ParentId = item.ParentId;
                    //var index = $(this).attr('data-index');
                    var btns = [{
                        name: lang.SubmitBtn,
                        focus: true,
                        callback: function () {
                            var $that = $("#txtAreaName"), letter
                            letter = $that.toPinyin();
                            Mvvm.areaModel.Id = item.Id
                            Mvvm.areaModel.Letter = letter.substring(0, 10)
                            Mvvm.areaModel.FirstLetter = Mvvm.areaModel.Letter.substr(0, 1)
                            var model = Mvvm.areaModel.$model;
                            if (model.Data != '') {
                                $.post('/Settings/RegionUpdate/' + model.Id, model, function (data) {
                                    //item = Mvvm.areaModel.$model;
                                    if (type==3) Mvvm.getRegionArea(item.ParentId)
                                    else GetArea(function () {
                                        if (type == 1) Mvvm.scrollToId(item.Id);
                                        else if (type == 2) Mvvm.scrollToId(item.ParentId);
                                    });
                                    messageBox.close();
                                });
                            }
                            else messageBox.warning('请填写地区名称');
                            return false;
                        }
                    }]
                    openTmpl({
                        vm: Mvvm, title: "编辑地区", w: 400, h: 200,
                        tmpl: tmpl, tmplid: "areaAdd", btns: btns
                    });
                }

                //删除地区
                vm.delRegionArea = function (item,type) {
                    if (confirm('确定删除吗?')) {
                        $.post('/Settings/AreaDel/' + item.Id, {}).done(function (ret) {
                            if (!ret.result) return CBCRM.showResult(ret);
                            if (type==3) Mvvm.getRegionArea(item.ParentId)
                            else GetArea(function () {
                                if (type == 2) Mvvm.scrollToId(item.ParentId);
                            });
                            //-- getLocations(Mvvm.region);
                            //GetTreeArea(item.ParentId);
                        });
                    }
                }
                vm.RegionAreaList = []

                vm.areaId = 0
                vm.getRegionArea = function (id, e) {
                    Mvvm.RegionAreaList = []; //item.children;

                    $.get("/Settings/GetChildAreas", { parentId: id }, function (ret) {
                        if (ret.result) {
                            Mvvm.areaId = id;
                            Mvvm.RegionAreaList = ret.data;
                            if (Mvvm.areaId != id)
                                Mvvm.showSelectArea = true
                            else
                                Mvvm.showSelectArea = !Mvvm.showSelectArea;
                            $('body').bind('mousedown', function () {
                                vm.showSelectArea = false
                                Mvvm.areaId = "";
                                $('body').unbind('mousedown')
                            })
                            var dcity = $("#Regiondiv"), areadiv = $("#AreaShowDiv"), treeArea = $("#treeArea_" + id), off = treeArea.offset();
                            dcity.css({ left: "400px", top: (off.top + 30) + "px" });
                        } else
                            CBCRM.showResult(ret);
                    });
                }
                vm.mousedownstop = function (e) {
                    e.stopPropagation()
                }
                vm.areaItem = modelFactory.create('Area');
                vm.showSelectArea = false;

                vm.keyword = ''
                vm.scrollToId = function (id) {
                    avalon.nextTick(function () {
                        var el = $("#province_" + id);
                        if(el.length>0)el[0].scrollIntoView();
                    });
                }
                vm.doSearch = function () {
                    var name = Mvvm.keyword;
                    var _find = function (item) {
                        var ls = item.Letter.toUpperCase(), l = item.FirstLetter.toUpperCase(), data = item.Data, key = name.toUpperCase();
                        return l == key || ls.indexOf(key) != -1 || data.indexOf(key) != -1
                    }
                    Mvvm.areaId = "";
                    Mvvm.showSelectArea = false;
                    var ps = Mvvm.countrys[Mvvm.curCountryIndex].children.$model;
                    var p = findArr(ps, _find);
                    if (p != null) {
                        Mvvm.scrollToId(p.Id);
                        return;
                    }
                    for (var i = 0, l = ps.length; i < l; i++) {
                        var pv = ps[i];
                        var cs = pv.children;
                        p = findArr(cs, _find);
                        if (p != null) {
                            Mvvm.scrollToId(pv.Id);
                            Mvvm.areaId = p.Id;
                            return;
                        }
                    }
                }
                vm.locations = [];
                //vm.letters = []
                vm.cityLetters = []
                vm.locationsTmp = []
                vm.cityLettersTmp = []
                vm.model = {}
                vm.hotCitys = []

                vm.RegionList = []
                vm.tabPath = ''
                vm.doviewArea = function (item) {
                    var url = "/Customer/All/" + item.Id + "/area";
                    goto(url);

                }
                vm.countrys = [];
                vm.curCountryIndex = 0;
                vm.provinces = {};
                vm.allletters = [];
                vm.letters = [];
                vm.scrollTo = function (n) {
                    $("a[name=" + n + "]")[0].scrollIntoView();
                }
                vm.parseLeters = function parseLeters(index) {
                    Mvvm.curCountryIndex = index;
                    Mvvm.region = Mvvm.countrys[index].Id;
                    var allletters = Mvvm.allletters.$model;
                    var letters = allletters.length > 0 ? allletters[index] : [];
                    var provinces = {};
                    if (letters.length == 0) {
                        Mvvm.letters = letters;
                        Mvvm.provinces = provinces;
                        return;
                    }
                    var parr = Mvvm.countrys[index].children.$model;
                    letters.forEach(function (l) {
                        var ps = parr.filter(function (p) { return p.FirstLetter.toUpperCase() == l });
                        provinces[l] = ps;
                    });
                    Mvvm.letters = letters;
                    Mvvm.provinces = provinces
                }
            });

            

            //拉取地区列表
            function GetArea(fn) {
                $.get('/Settings/AreaByNum/', {}, function (ret) {
                    if (!ret || !ret.result) return CBCRM.showResult(ret);
                    Mvvm.countrys = ret.data.areaList
                    Mvvm.hotCitys = ret.data.hotCitys;
                    var allletters = ret.data.letters.map(function (item) { return item.split(","); });
                    Mvvm.allletters = allletters;
                    Mvvm.parseLeters(Mvvm.curCountryIndex);
                    if (typeof(fn)=="function") fn(ret);
                });
            }

            function getLocations(id, type) {
                Mvvm.locationsTmp = []
                Mvvm.cityLettersTmp = []
               // $.get("/Settings/GetAreaLocations/" + id, { type: type }, function (ret) {
                $.get("/Settings/GetAreaLocationsAll/" + id, { type: type }, function (ret) {

                    if (ret.data) {
                        for (var i = 65; i < 91; i++) {
                            var c = String.fromCharCode(i);
                            for (var a = 0, m; m = ret.data.Alist[a]; a++) {
                                if (m == c)
                                    Mvvm.locationsTmp.push(c)
                            }
                            for (var b = 0, m; m = ret.data.AreaArray[b]; b++) {
                                if (m.letter == c)
                                    Mvvm.cityLettersTmp.push(m)
                            }
                        }
                        Mvvm.locations = Mvvm.locationsTmp // 字母列表
                        Mvvm.cityLetters = Mvvm.cityLettersTmp //数据列表
                        Mvvm.CityList = ret.data.CityData //热门城市
                        Mvvm.RegionList = ret.data.AreatoList //第三级地区
                    }
                });
            }



            //拉取三级地区列表
            function GetTreeArea(dicId) {
                $.get('/Settings/Area/' + dicId, {}, function (result) {
                    Mvvm.RegionAreaList = result.data;
                });
            }

            //字典大类
            Mvvm.leftMenu = [
           {
               title: '客户', show: false, child: [
                   { id: 100026, name: '客户分类', showtree: true, disabledAddRoot: true },
                   { id: 100108, name: '客户状态', showtree: true, disabledAddRoot: true },
                   { id: 100008, name: '称谓' },
                   { id: 100009, name: '联系人角色' },
                   { id: 100010, name: '证件类型' },
                   { id: 100011, name: '服务阶段' },
                   { id: 100012, name: '客户来源' },
                   { id: 100013, name: '人员规模' },
                   { id: 100014, name: '主营行业' },
                   { id: 100015, name: '关系等级' },
                   { id: 100016, name: '开发模式' },
                   { id: 100017, name: '银行' },
                   { id: 100025, name: '服务标签' },
                   { id: 100075, name: '供应商阶段' },
                   { id: 100077, name: '纪念日类型' },
                   { id: 100078, name: '单位性质' },
                   { id: 100079, name: '福利类型' },
                   { id: 100080, name: '福利发放形式' },
                   { id: 100081, name: '福利发放渠道' },
                   { id: 100103, name: '业务分类' },
                   { id: 100107, name: '会员级别', status: 'membergrade' }
               ]
           },
                    {
                        title: '市场', show: false, child: [
                            { id: 100102, name: '市场地位' },
                            { id: 100052, name: '机会跟单阶段' },
                            { id: 100053, name: '跟单服务标签' },
                            { id: 100051, name: '机会状态' },
                            { id: 100030, name: '战役类型' },
                            { id: 100050, name: '活动类型' },
                            { id: 100047, name: '市场调查反馈类型' },
                            { id: 100058, name: '发货方式' },
                            { id: 100054, name: '报价类型' },
                            { id: 100066, name: '合同/订单类型' },
                            { id: 100065, name: '合同/订单阶段' },
                            { id: 100064, name: '合同状态' },
                            { id: 100028, name: '渠道开发维护行为' },
                            { id: 100074, name: '物流快递' },
                            { id: 100062, name: '广告素材分类' },
                            { id: 100063, name: '假期节庆' },
                            { id: 100061, name: '素材格式' },
                            { id: 100099, name: '媒体类型' },
                            { id: 100034, name: '物料类型' },
                            { id: 100033, name: '礼品类型' }
                        ]
                    },
                    {
                        title: '服务', show: false, child: [
                            { id: 100082, name: '来电分类' },
                            { id: 100083, name: '来电快捷短语' },
                            { id: 100084, name: '回访方式' },
                            { id: 100085, name: '公司主营业务' },
                            { id: 100086, name: '投诉分类' },
                            { id: 100091, name: '投诉方式' },
                            { id: 100087, name: '服务类型' },
                            { id: 100088, name: '服务方式' },
                            { id: 100089, name: '耗时' }
                        ]
                    },
                    {
                        title: '内部办公', show: false, child: [
                            { id: 100095, name: '文章来源' },
                            { id: 100096, name: '书籍存放位置' },
                            { id: 100104, name: '物品类别' },
                            { id: 100105, name: '车辆保险险种' }
                        ]
                    },
                    {
                        title: '人事', show: false, child: [
                            { id: 100032, name: '人资规划分类' },
                            { id: 100004, name: '学历' },
                            { id: 100006, name: '招聘渠道' },
                            { id: 100018, name: '民族' },
                            { id: 100019, name: '政治面貌' },
                            { id: 100020, name: '职业资格证书' },
                            { id: 100021, name: '职称' },
                            { id: 100022, name: '语言' },
                            { id: 100023, name: '外语水平' },
                            { id: 100024, name: '计算机水平' },
                            { id: 100005, name: '驾照' },
                            { id: 100007, name: '交通工具' },
                            { id: 100035, name: '点评简历结论' },
                            { id: 100036, name: '培训对象' },
                            { id: 100037, name: '培训科目' },
                            { id: 100038, name: '课程层面' },
                            { id: 100039, name: '培训方式' },
                            { id: 100040, name: '培训类别' },
                            { id: 100041, name: '考核方式' },
                            { id: 100097, name: '职位级别' },
                            { id: 100101, name: '通知面试状态' },
                            { id: 100048, name: '沟通类别' },
                            { id: 100049, name: '沟通方式' },
                            { id: 100150, name: '招聘性质' },
                            { id: 100151, name: '职位性质' },
                            { id: 100201, name: '简历目前状态' },
                            { id: 100203, name: '婚姻状况' },
                            { id: 100204, name: '人才类型' },
                            { id: 100046, name: '合同类型' },
                            { id: 190011, name: '奖励类型' },
                            { id: 190012, name: '惩处类型' }
                        ]
                    },
                    {
                        title: '财务', show: false, child: [
                            //{ id: 100098, name: '收入' },
                            //{ id: 100099, name: '支出' },
                            //{ id: 100100, name: '转账' },
                            { id: 100055, name: '付款/收款方式' },
                            { id: 100057, name: '收费凭据/票据类型' },
                            //{ id: 100070, name: '(收费)资金账户' },
                            //{ id: 100067, name: '货币单位' }, 
                            { id: 100071, name: '票据内容' },
                            { id: 100056, name: '结算方式' },
                            { id: 100072, name: '回款类型' },
                            { id: 190010, name: '收款说明' }
                        ]
                    },
                    {
                        title: '产品', show: false, child: [
                            { id: 100110, name: '计量单位' },
                            { id: 100111, name: '重量单位' },
                            //{ id: 100112, name: '仓库类别' }/*此id已经使用，暂时隐藏*/
                        ]
                    },
                    //{
                    //    title: '工具', show: false, child: [
                    //        { id: 100059, name: '短信模板分类', showtree: true },
                    //        { id: 100060, name: '短信模板' }
                    //    ]
                    //},
                    {
                        title: '地区', show: false, child: [
                            { id: 0, name: '地区管理', status: 'area' }
                        ]
                    }
            ]
            //设置默认值
            Mvvm.currItem = Mvvm.leftMenu.$model[0].child[0];
            Mvvm.defaultId = Mvvm.leftMenu.$model[0].child[0].id;
            Mvvm.defaultName = Mvvm.leftMenu.$model[0].child[0].name

            //拉取右边列表
            function GetDictionaryData(dicId) {
                $.get('/Settings/DictionaryAndChild/' + dicId, {}, function (result) {
                    Mvvm.dictionary = result.data;
                });
            }
            GetDictionaryData(Mvvm.defaultId);
            //拉取右边二级列表
            function GetDictionaryParent(dicId) {
                $.get('/Settings/DictionaryParent/' + dicId, {}, function (result) {
                    Mvvm.dictionary = result.data;
                });
            }

            ////拉取地区列表
            //function GetArea(dicId) {
            //    $.get('/Settings/Area/' + dicId, {}, function (result) {
            //        Mvvm.dictionary = result.data;

            //    });
            //}

            CBCRM.fillContent(tmpl, lang, contentId, module, Mvvm)
            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.Dictionary = null

            }

            $('#left_menu_top').html('<h2>数据字典</h2>').show()
        },
        /// <summary>
        /// 拉取短信设置列表 
        /// </summary>
        InterfaceSettings: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM
            var Mvvm = avalon.define('InterfaceSettings', function (vm) {
                vm.lang = lang;
                vm.title = lang.SmsInterface
                vm.description = lang.SmsInterfaceInfo
                vm.smsMobile = ''
                vm.smsMessage = ''
                vm.show = 'sms'
                vm.isDefault = "1" //默认第一个;
                vm.smsSign =CBCRM.memberShip.FullName+ "【" + CBCRM.cmyInfo.ShortName + "】";
                /*=====================================手机短信设置=====================================*/
                vm.smsEntity = {}
                vm.smsList = []
                //切换栏目
                vm.leftClick = function () {
                    $(this).parent().siblings().removeAttr('class');
                    $(this).parent().attr('class', 'selected');

                    Mvvm.show = $(this).attr('value');
                    initWithList();
                }
                //保存短信设置
                vm.smsSubmit = function () {
                    var m = $.extend(true, {}, Mvvm.smsEntity.$model);
                    delete m.Version;
                    delete m.InRecycleBin;
                    delete m.hasOwnProperty;
                    $.post('/Settings/InterfaceSettingsSave/' + m.Id, m, function (res) {
                        if (res.result) {
                            messageBox.succeed(res.message);
                            Mvvm.getSMSBalance();
                            GetSmsInterface();
                        } else {
                            messageBox.warning(res.message);
                        }
                    })

                }
                //测试发送
                vm.sendSubmit = function () {
                    if (Mvvm.smsMobile && Mvvm.smsMessage) {
                        var dialog = loading("短信发送中……");
                        $.post('/Settings/InterfaceSend/', {
                            mobile: Mvvm.smsMobile,
                            message: Mvvm.smsMessage + Mvvm.smsSign
                        }, function (ret) {
                            if (dialog) dialog.close();
                            if (ret.result) {
                                messageBox.succeed(ret.message);
                            }
                            else
                                messageBox.error(ret.message);
                        })
                    }
                    else messageBox.error('请输入接收短信的手机号码和短信内容');
                }
                //点击选择接口平台
                vm.change = function (index) {
                    Mvvm.smsList.forEach(function (item) {
                        item.IsDefault = false;
                    });
                    Mvvm.smsList[index].IsDefault = true;
                    Mvvm.smsEntity = Mvvm.smsList[index];
                }
                vm.Balance = "0";
                vm.getSMSBalance = function () {
                    var url = "/Tools/SMSBalance/";
                    $.get(url, {}, function (ret) {
                        if (ret.result && ret.data) {
                            var bl = ret.data.Balance;
                            if (!ret.data.Success && ret.data.Message) bl += "(" + ret.data.Message + ")";
                            Mvvm.Balance = bl;
                        } else {
                            Mvvm.Balance = "-1(余额查询错误，请检查短信接口设置)";
                            //messageBox.warning(ret.message);
                            console.log(ret);
                        }
                    });
                }
            });
            //初始化实体
            Mvvm.smsEntity = modelFactory.create("MessageInterface");

            //拉取短信设置列表
            function GetSmsInterface() {
                $.get('/Settings/InterfaceSettings/', {}, function (res) {
                    Mvvm.smsList = res.data;
                    Mvvm.smsList.forEach(function (item) {
                        if (item.IsDefault) {
                            Mvvm.smsEntity = item.$model
                            Mvvm.isDefault = item.Id + ''
                        }
                    })
                });
            }

            //根据显示的模块来拉取列表和标题
            function initWithList() {

                GetSmsInterface();
                Mvvm.title = lang.SmsInterface
                Mvvm.description = lang.SmsInterfaceInfo

            }
            initWithList();
            Mvvm.getSMSBalance();

            CBCRM.fillContent(tmpl, lang, contentId, module, Mvvm)
            menus = avalon.vmodels.customerMenu
            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.InterfaceSettings = null
            }
        },
        //电子邮件设置
        EmailInterface: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM
            var Mvvm = avalon.define('EmailInterface', function (vm) {
                vm.lang = lang;
                vm.title = lang.SmsInterface
                vm.description = lang.SmsInterfaceInfo
                vm.smsMobile = ''
                vm.smsMessage = ''
                vm.show = 'sms'
                vm.isDefault = "1" //默认第一个


                /*=====================================电子邮件设置=====================================*/
                vm.emailEntity = modelFactory.create('EmailInterface');//{}
                vm.emailList = []
                vm.selectItem = "0"
                //电子邮件提交
                vm.emailSubmit = function () {
                    var model = Mvvm.emailEntity.$model;
                    if (model.hasOwnProperty) delete model.hasOwnProperty;
                    if (model.Email && model.SMTP && model.MailAccount && model.MailPassword) {
                        $.post('/Settings/EmailPost/' + model.Id, model, function (res) {
                            if (res.result) {
                                messageBox.succeed(res.message);
                            }
                        });
                    }
                    else messageBox.error('不能提交空值,请输入必填项!');
                }
                //删除
                vm.emailDel = function () {
                    var model = Mvvm.emailEntity.$model;
                    if (!model.Id) return;
                    $.post('/Settings/EmailDel/' + model.Id, {}, function (ret) {
                        CBCRM.showResult(ret);
                        if (ret.result) {
                            //GetEmailInterface();
                            var item = findArr(Mvvm.emailList, model.Id);
                            if (item != null) Mvvm.emailList.remove(item);
                        }
                    })
                }
            });

            //监控下拉菜单
            Mvvm.$watch('selectItem', function (n, o) {
                Mvvm.emailList.forEach(function (item) {
                    if (item.Id == n)
                        Mvvm.emailEntity = item;
                });
            });
            //初始化实体

            Mvvm.emailEntity = modelFactory.create("EmailInterface");
            //拉取邮件列表
            function GetEmailInterface() {
                $.get('/Settings/Email/', {}, function (res) {
                    Mvvm.emailList = res.data;
                    var model = modelFactory.create('EmailInterface');
                    Mvvm.emailList.unshift(model);
                })
            }


            //根据显示的模块来拉取列表和标题
            function initWithList() {
                GetEmailInterface();
                Mvvm.title = lang.EmailSettings;
                Mvvm.description = lang.EmailSettingsInfo;
            }
            initWithList();

            CBCRM.fillContent(tmpl, lang, contentId, module, Mvvm)
            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.EmailInterface = null
            }
        },
        //超博网接口设置
        CBInterface: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM
            var Mvvm = avalon.define('CBInterface', function (vm) {
                vm.lang = lang;
                vm.title = lang.SmsInterface
                vm.description = lang.SmsInterfaceInfo
                vm.smsMobile = ''
                vm.smsMessage = ''
                vm.show = 'sms'
                vm.isDefault = "1" //默认第一个


                /*=====================================超博网接口设置=====================================*/
                vm.vcbEntity = {}
                vm.vcbSubmit = function () {
                    var model = Mvvm.vcbEntity.$model;
                    if (model.VCBAccount && model.VCBPassword) {
                        $.post('/Settings/VcbPost/' + model.Id, model, function (res) {
                            if (res.result)
                                messageBox.succeed(res.message);
                        });
                    }
                    else messageBox.error('不能提交空值,请输入必填项!');
                }


            });


            //初始化实体 
            Mvvm.vcbEntity = modelFactory.create('VCBInterface');
            //拉取超博网实体数据
            function GetVcbInterface() {
                $.get('/Settings/Vcb/', {}, function (res) {
                    Mvvm.vcbEntity = res.data;
                })
            }

            //根据显示的模块来拉取列表和标题
            function initWithList() {
                GetVcbInterface();
                Mvvm.title = lang.VcbInterface;
                Mvvm.description = lang.VcbInterfaceInfo;
            }
            initWithList();

            CBCRM.fillContent(tmpl, lang, contentId, module, Mvvm)
            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.CBInterface = null
            }
        },
        //公司网站借口设置
        CompanyInterface: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM
            var Mvvm = avalon.define('CompanyInterface', function (vm) {
                vm.lang = lang;
                vm.title = lang.SmsInterface
                vm.description = lang.SmsInterfaceInfo
                vm.smsMobile = ''
                vm.smsMessage = ''
                vm.show = 'sms'
                vm.isDefault = "1" //默认第一个


                /*=====================================公司网站设置=====================================*/
                vm.siteEntity = {}
                vm.siteSubmit = function () {
                    var model = Mvvm.siteEntity.$model;
                    if (model.CompanySiteAccount && model.CompanySitePassword && model.CompanySiteAdminURL) {
                        $.post('/Settings/SitePost/' + model.Id, model, function (res) {
                            if (res.result)
                                messageBox.succeed(res.message);
                        });
                    }
                    else messageBox.error('不能提交空值,请输入必填项!');
                }


            });

            Mvvm.siteEntity = modelFactory.create('CompanySiteInterface');



            //拉取公司网站数据
            function GetCompanyInterface() {
                $.get('/Settings/Site/', {}, function (res) {
                    Mvvm.siteEntity = res.data;
                })
            }

            //根据显示的模块来拉取列表和标题
            function initWithList() {
                GetCompanyInterface();
                Mvvm.title = lang.SiteInterface;
                Mvvm.description = lang.SiteInterfaceInfo;
            }
            initWithList();

            CBCRM.fillContent(tmpl, lang, contentId, module, Mvvm)
            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.CompanyInterface = null
            }
        },
        //来电弹屏设置
        CallInterface: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM
            var Mvvm = avalon.define('CallInterface', function (vm) {
                vm.lang = lang;
                vm.title = lang.SmsInterface
                vm.description = lang.SmsInterfaceInfo
                vm.smsMobile = ''
                vm.smsMessage = ''
                vm.show = 'sms'
                vm.isDefault = "1" //默认第一个

                /*=====================================手机短信设置=====================================*/
                vm.smsEntity = {}
                vm.smsList = []
                //切换栏目
                vm.leftClick = function () {
                    $(this).parent().siblings().removeAttr('class');
                    $(this).parent().attr('class', 'selected');

                    Mvvm.show = $(this).attr('value');
                    initWithList();
                }
                //保存短信设置
                vm.smsSubmit = function () {
                    var m = Mvvm.smsEntity.$model;
                    delete m.Version;
                    delete m.InRecycleBin;

                    $.post('/Settings/InterfaceSettingsSave/' + m.Id, m, function (res) {
                        if (res.result)
                            messageBox.succeed(res.message);
                    })

                }
                //测试发送
                vm.sendSubmit = function () {
                    if (Mvvm.smsMobile && Mvvm.smsMessage) {
                        $.post('/Settings/InterfaceSend/', {
                            mobile: Mvvm.smsMobile,
                            message: Mvvm.smsMessage
                        }, function (ret) {
                            if (ret.result)
                                messageBox.succeed(ret.message);
                            else
                                messageBox.error(ret.message);
                        })
                    }
                    else messageBox.error('请输入接收短信的手机号码和短信内容');
                }
                //点击选择接口平台
                vm.change = function () {
                    Mvvm.smsList.forEach(function (item) {
                        item.IsDefault = false;
                    });
                    var index = $(this).attr('index');
                    Mvvm.smsList[index].IsDefault = true;
                    Mvvm.smsEntity = Mvvm.smsList[index];
                }

                /*=====================================电子邮件设置=====================================*/
                vm.emailEntity = modelFactory.create('EmailInterface');//{}
                vm.emailList = []
                vm.selectItem = "0"
                //电子邮件提交
                vm.emailSubmit = function () {
                    var model = Mvvm.emailEntity.$model;
                    if (model.hasOwnProperty) delete model.hasOwnProperty;
                    if (model.Email && model.SMTP && model.MailAccount && model.MailPassword) {
                        $.post('/Settings/EmailPost/' + model.Id, model, function (res) {
                            if (res.result) {
                                messageBox.succeed(res.message);
                            }
                        });
                    }
                    else messageBox.error('不能提交空值,请输入必填项!');
                }

                /*=====================================超博网接口设置=====================================*/
                vm.vcbEntity = {}
                vm.vcbSubmit = function () {
                    var model = Mvvm.vcbEntity.$model;
                    if (model.VCBAccount && model.VCBPassword) {
                        $.post('/Settings/VcbPost/' + model.Id, model, function (res) {
                            if (res.result)
                                messageBox.succeed(res.message);
                        });
                    }
                    else messageBox.error('不能提交空值,请输入必填项!');
                }

                /*=====================================公司网站设置=====================================*/
                vm.siteEntity = {}
                vm.siteSubmit = function () {
                    var model = Mvvm.siteEntity.$model;
                    if (model.CompanySiteAccount && model.CompanySitePassword && model.CompanySiteAdminURL) {
                        $.post('/Settings/SitePost/' + model.Id, model, function (res) {
                            if (res.result)
                                messageBox.succeed(res.message);
                        });
                    }
                    else messageBox.error('不能提交空值,请输入必填项!');
                }

                /*=====================================来电弹屏设置=====================================*/
                vm.callEntity = {}
                vm.telipList = []
                vm.callSubmit = function () {
                    var model = Mvvm.callEntity.$model;
                    Mvvm.telipList.$model.forEach(function (item, index) {
                        model['TelList[' + index + '].EmployeeId'] = item.EmployeeId
                        model['TelList[' + index + '].TelNum'] = item.TelNum
                    })

                    if (model.TelPopupWindowServer) {
                        $.post('/Settings/CallPost/' + model.Id, model, function (res) {
                            if (res.result)
                                messageBox.succeed(res.message);
                        });
                    }
                    else messageBox.error('不能提交空值,请输入必填项!');
                }
                vm.onAdd = function () {
                    var telEntity = { Id: '', EmployeeId: '', EmployeeName: '', TelNum: '' };
                    Mvvm.telipList.push(telEntity);
                }
                vm.onDel = function () {
                    var index = parseInt($(this).attr('index'));
                    Mvvm.telipList.removeAt(index);
                }
                vm.currEmpIndex = 0
                vm.setEmps = function () {
                    var curItem = this.$vmodel,
                        index = curItem.$index,
                        panel = avalon.vmodels.employeeTreepanel,
                        tree = avalon.vmodels.employeeTree
                    Mvvm.currEmpIndex = index
                    if (!panel) {
                        avalon.ui.dropDownGroupPostUserTree(this, {
                            dropDownGroupPostUserTreeId: 'employeeTree',
                            dropDownGroupPostUserTreeOptions: {
                                treeopts: {
                                    callback: {
                                        onCheck: function (e, treeId, treeNode) {
                                            var curr = Mvvm.telipList[Mvvm.currEmpIndex];
                                            curr.EmployeeName = treeNode.Name;
                                            curr.EmployeeId = treeNode.Id;
                                        }
                                    },
                                    async: {
                                        url: function (treeId, treeNode) {
                                            var url = "/Settings/GetGroupPostUser/9070000"
                                            vmtree = avalon.vmodels.campaignSponsorTree
                                            if (vmtree && vmtree.q && vmtree.q !== vmtree.qcopy) {
                                                url += '?empName=' + vm.q
                                            }
                                            return url
                                        },
                                        dataFilter: function (treeId, parentNode, responseData) {
                                            var CBCRM = avalon.vmodels.CBCRM
                                            var ret = [], len = 0, curr, hasEmp = false
                                            if (responseData.data && responseData.data.groups.length)
                                                len = responseData.data.groups.length
                                            while (len) {
                                                curr = responseData.data.groups[--len]
                                                curr.nocheck = true
                                                hasEmp = false
                                                curr.Posts.forEach(function (p, i) {
                                                    curr.Posts[i].ParentId = p.Boss ? p.Boss.Id : p.Group
                                                    curr.Posts[i].nocheck = true
                                                    p.Users.forEach(function (u, i) {
                                                        var u = p.Users[i]
                                                        if (u.Id === CBCRM.memberShip.Id) return true
                                                        u.ParentId = u.PositionId
                                                        u.Name = u.FullName
                                                        ret.push(u)
                                                    })
                                                    if (!hasEmp) {
                                                        hasEmp = p.Users.length > 0
                                                    }
                                                    if (hasEmp) {
                                                        ret.push(p)
                                                    }
                                                })
                                                if (hasEmp) ret.push(curr)
                                            }
                                            return ret
                                        }
                                    },
                                    check: {
                                        enable: true,
                                        chkStyle: 'radio',
                                        radioType: "all"
                                    }
                                }
                            },
                            initevent: false
                        }, this.$vmodels)
                        panel = avalon.vmodels.employeeTreepanel
                        tree = avalon.vmodels.employeeTree
                    } else {
                        panel.target = this
                    }
                    panel.toggle(true)
                }
            });

            //监控下拉菜单
            Mvvm.$watch('selectItem', function (n, o) {
                Mvvm.emailList.forEach(function (item) {
                    if (item.Id == n)
                        Mvvm.emailEntity = item;
                });
            });
            //初始化实体

            Mvvm.callEntity = modelFactory.create('TelPopupWindow');


            //拉取来电弹屏数据
            function GetCallInterface() {
                $.get('/Settings/Call/', {}, function (res) {
                    res.data.EnableTelPopupWindow = res.data.EnableTelPopupWindow + ''
                    Mvvm.callEntity = res.data;
                })
                $.get('/Settings/TellNumber/', {}, function (res) {
                    Mvvm.telipList = res.data;
                    if (res.data == null || res.data.length == 0) Mvvm.onAdd();
                })
            }
            //根据显示的模块来拉取列表和标题
            function initWithList() {

                GetCallInterface()
                Mvvm.title = lang.CallInterface;
                Mvvm.description = "需要购买超博电话录音系统(包含硬件设备、驱动及服务端安装包)，来电弹屏功能才能使用。"  //lang.CallInterfaceInfo;

            }
            initWithList();

            CBCRM.fillContent(tmpl, lang, contentId, module, Mvvm)
            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.CallInterface = null
            }
        },

        /// <summary>
        /// 用户管理
        /// </summary>
        Users: function (tmpl, lang, contentId, module,paramData) {
            var CBCRM = avalon.vmodels.CBCRM, vmid = "Users",
            that = this;
            var action=this.params.action,paramid=this.params.id;
            mvvm = CBCRM.define(vmid, function (vm) {
                vm.lang = lang
                vm.$skipArray = ['lang'] //不监听语言包
                vm.oldPassword = ''
                vm.keyword = ''
                vm.userEntity = {}
                vm.userList = []
                vm.roleList = []
                vm.ADD = false;
                vm.DELETE = false;
                vm.LOCK = false
                vm.UNLOCK = false
                vm.allChecked = false
                vm.query1 = createQuerys({
                    key: { label: "关键词", val: "", valLabel: '' },
                    roleId: { label: "角色", val: "", valLabel: '' },
                    depart: { label: "关键词", val: "", valLabel: '' },
                    enable: {
                        label: "状态", val: "true", valLabel: "启用",
                        items: [
                            { label: "不限", val: '', curr: false },
                            { label: "启用", val: 'true', curr: true },
                            { label: "禁用", val: 'false', curr: false }
                        ]
                    }
                }, function (data, name, val, type) {
                    if (type == "clear" || type == "remove") {
                        var rolevm = avalon.vmodels["roleList"];
                        var tree = avalon.vmodels["groupTree"];
                        if (type == "clear") {
                            if (rolevm) rolevm.unSelectAll();
                            if (tree) tree.$tree.selectNode({});
                        } else {
                            switch (name) {
                                case "roleId":
                                    if (rolevm) rolevm.unSelectAll();
                                    break;
                                case "depart":
                                    if (tree) tree.$tree.selectNode({});
                                    break;
                            }
                        }
                    }
                    mvvm.grid1.loadData(data);
                });
                vm.query1.setVm();

                vm.grid1 = createGrid({
                    url: "/Settings/Users",
                    entityUrl: "/Settings/GetUser",
                    pageid: vmid + "_grid1_page",
                    entityId:"User",
                    modelFactory: modelFactory,
                    tmpl: tmpl,
                    $lang: lang,
                    createQuery: function () {
                        return mvvm.query1.createQuery();
                    },
                    onLoadData: function (ret,list) {
                        mvvm.ADD = ret.data.ADD;
                        mvvm.DELETE = ret.data.DELETE;
                        mvvm.LOCK = ret.data.LOCK;
                        mvvm.UNLOCK = ret.data.UNLOCK;
                    },
                    onRemove: function (deleteIds, ids) {
                        $.get('/Settings/UsersAllDelete/', deleteIds, function (ret) {
                            CBCRM.showResult(ret);
                            if (ret.result) mvvm.grid1.reloadData();
                        });
                    }
                });

                vm.toSearch = function () {
                    mvvm.query1.addQuery("key", mvvm.query1.data.key.val, mvvm.query1.data.key.val, false, true);
                }
                vm.pwdFocus = function () {
                    mvvm.userEntity.Password = "";
                }
                vm.pwdBlur = function () {
                    if (mvvm.userEntity.Password == "") mvvm.userEntity.Password = mvvm.oldPassword;
                }
                //角色检索
                vm.roleListOpts = {
                    roleChanged: function () {
                        var vm = this.$vmodel,
                            item = vm[vm.$itemName];
                        mvvm.query1.addQuery("roleId", item.Id, item.Name);
                    }
                }
                //部门检索
                vm.groupTreeOpts = {
                    treeopts: {
                        async: {
                            enable: true,
                            url: '/Settings/GetGroupPostUser/9060000'
                        },
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                mvvm.query1.addQuery("depart", getNodeIds(treeNode).join(","), treeNode.Name);
                            }
                        },
                        view: {
                            addHoverDom: false,
                            removeHoverDom: false
                        } //替换默认
                    }
                }
                vm.posts = []
                vm.postslist = []
                //选择部门
                vm.postGroupTreeOpts = {
                    treeopts: {
                        async: {
                            enable: true,
                            url: '/Settings/GetGroupPostUser/9060000'
                        },
                        callback: {
                            onClick: function (event, treeId, treeNode) {
                                var m = mvvm.userEntity
                                m.Group = { Id: treeNode.Id, Name: treeNode.Name }
                                mvvm.posts = treeNode.Posts
                                if (treeNode.Posts.length)
                                    mvvm.userEntity.PositionId = treeNode.Posts[0].Id
                            }
                        }
                    }
                }
                //新增
                vm.doadd = function () {
                    mvvm.grid1.getEntity(null,function (entity) {
                        initEntity(entity);
                        mvvm.userEntity = entity;
                        mvvm.posts = [];
                        formSubmit('新增用户');
                    });
                }
                //编辑
                vm.doedit = function (id) {
                    mvvm.grid1.getEntity(id,function (entity) {
                        initEntity(entity);
                        if (entity.Roles) {
                            mvvm.roleList.forEach(function (item) {
                                if (entity.Roles.indexOf(item.Id.toString()) > -1) item.checked = true;
                                else item.checked = false;
                            });
                        }
                        mvvm.userEntity = entity;
                        mvvm.oldPassword = entity.Password;
                        if (entity.Group) getQueryPost(entity.Group.Id);
                        formSubmit('编辑用户');
                    },true);
                }
                //查看
                vm.doview = function (id) {
                    mvvm.grid1.getEntity(id, function (entity) {
                        initEntity(entity);
                        var rols = [];
                        if (entity.Roles) {
                            entity.Roles.forEach(function (rid) {
                                var item = findArr(mvvm.roleList.$model, function (item) { return item.Id.toString() == rid });
                                if (item != null) rols.push(item);
                            });
                        }
                        entity.roleList = rols;
                        mvvm.userEntity = entity;
                        var name = mvvm.userEntity.Role.Name
                        var names = mvvm.userEntity.RolesDisplay
                        if (names) {
                            names = names.replace(name, name + '(默认)')
                            mvvm.userEntity.Role.Name = names
                        }
                        openTmpl({
                            w: 820, h: 150,title:"用户详情",
                            vm: mvvm, tmpl: tmpl, tmplid: "detailTemplate"
                        })
                    },true)
                }
                vm.setAvailable = function (id, availabled) {
                    var url = '/Settings/SetUserAvailabled/',
                    data = { state: availabled || false },
                    optLabel = !availabled ? '禁用' : '启用'
                    if (!id) {
                        var ids = mvvm.grid1.getCheckedIds("ids");
                        if (ids.length == 0) {
                            messageBox.error('请选择要' + optLabel + '的用户账号');
                            return;
                        }
                        delete ids.length;
                        $.extend(data, ids);
                    } else {
                        data["ids[0]"]= id
                    }
                    messageBox.confirm('您确定要' + optLabel + '选中的用户账号吗？', function () {
                        $.post(url, data)
                        .done(function (ret) {
                            CBCRM.showResult(ret);
                            if (ret) mvvm.grid1.reloadData();
                        })
                    })
                }
                vm.setContact = function (act) {
                    var optLabel = act ? "加入" : "移出";
                    var data = mvvm.grid1.getCheckedIds("ids");
                    if (data.length == 0) {
                        messageBox.error('请选择要' + optLabel + '通讯录的用户账号');
                        return;
                    }
                    data.act = act;
                    messageBox.confirm('您确定要批量' + optLabel + '通讯录吗？', function () {
                        $.post('/Settings/SetContact/', data, function (ret) {
                            CBCRM.showResult(ret);
                            if (ret.result) {
                                mvvm.grid1.reloadData();
                            }
                        })
                    })
                }
                //设置默认
                vm.roleChange = function (role) {
                    if (!this.checked && role.Id.toString() == mvvm.userEntity.Role.Id) mvvm.userEntity.Role.Id = "";
                }
                vm.defRoleChange = function (index) {
                    var role = mvvm.roleList[index]
                    if (this.checked) role.checked = true;
                }

                //解除App绑定
                vm.unbindAppUser = function (uid,item,index) {
                    messageBox.confirm2("您确定要解除此设备的绑定吗？", function () {
                        $.post("/Settings/UnbindAppUser", { uid: uid, sn: item.Key }, function (ret) {
                            CBCRM.showResult(ret, function () {
                                mvvm.userEntity.DeviceSnList.removeAt(index);
                            });
                        });
                    });
                }
            });
            function init() {
                mvvm.grid1.init();
                //$.get('/Settings/GetPost/', {}, function (ret) { if (ret && ret.result) mvvm.postslist = ret.data; })
                $.get('/Settings/Roles/', {}, function (ret) {
                    ret.data.forEach(function (item) {item.checked=false })
                    mvvm.roleList = ret.data;
                });
            }
            init();

            function initEntity(entity) {
                entity.Sex += '';
                entity.IsAvailable += '';
                if (!entity.Role) entity.Role = { Id: "", Name: "" };
                entity.Role.Id += '';
            }

            function loadUser(id) {
                $.get('/Settings/GetUser/' + id, {}, function (ret) {
                    if (!ret.result) return CBCRM.showResult(ret);
                    initEntity(ret.data);
                    mvvm.userEntity = ret.data;
                    mvvm.oldPassword = ret.data.Password;
                    getQueryPost(mvvm.userEntity.Group.Id);
                    formSubmit('编辑用户');
                });
            }
            var curGid = null;
            function getQueryPost(id) {
                if (curGid == id) return;
                curGid = id;
                $.get('/Settings/GetPost/', { gid: id }, function (ret) {
                    if (!ret.result) return;
                    mvvm.posts = ret.data;
                    var t = mvvm.userEntity.PositionId
                    mvvm.userEntity.PositionId = ""
                    mvvm.userEntity.PositionId = t;
                })
            }
            //打开新增或编辑窗口
            function formSubmit(title) {
                var btns = [{
                    name: '提交',
                    focus: true,
                    callback: function () {
                        var model = mvvm.userEntity.$model, has;
                        if (!model.UserName) {
                            messageBox.warning('请输入用户的账号名称,将用于登陆CRM');
                            return false;
                        }
                        if (!model.Password) {
                            messageBox.warning('请输入用户登陆密码');
                            return false;
                        }
                        if (!model.FullName) {
                            messageBox.warning('请输入用户的真实姓名');
                            return false;
                        }
                        if (model.Group.Id<=0) {
                            messageBox.warning('请选择部门');
                            return false;
                        }
                        if (model.PositionId<=0) {
                            messageBox.warning('请选择用户职位');
                            return false;
                        }
                        if (model.Role.Id <= 0) {
                            messageBox.warning('请指定用户的默认角色');
                            return false;
                        }
                        model.MasterRole = model.Role.Id;
                        var roleIds = where(mvvm.roleList, function (item) { return item.checked; }, "Id");
                        if (roleIds.length == 0) {
                            messageBox.warning('请选择用户的角色');
                            return false;
                        }
                        model.Roles = roleIds;
                        $.extend(model, jsonToSubmit("roleIds", roleIds));
                        delete model.roleIds;
                        delete model.DeviceSnList;
                        //model.roleIds = model.Roles;
                        model.oldPassword = mvvm.oldPassword;
                        if (!model.Id) {
                            hash = CryptoJS.SHA512(model.Password)
                            model.Password = hash.toString(CryptoJS.enc.Base64)
                            model["Group.Id"] = mvvm.userEntity.Group.Id;
                        } else {
                            if (model.Password != mvvm.oldPassword) {
                                hash = CryptoJS.SHA512(model.Password)
                                model.Password = hash.toString(CryptoJS.enc.Base64)
                            }
                            model.groupId = mvvm.userEntity.Group.Id;
                        }
                        var postUrl = model.Id == 0 ? "/Settings/UsersAdd/" : "/Settings/UsersUpdate/";
                        $.post(postUrl + model.Id, model, function (ret) {
                            CBCRM.showResult(ret, function () {
                                if (dialog) dialog.close();
                            });
                            if (ret.result) {
                                if (action == "add" || action == "edit") {
                                    if (paramData && paramData.callback) {
                                        paramData.callback.call(mvvm, model, ret);
                                    }
                                } else {
                                    mvvm.grid1.reloadData();
                                }
                            }   
                        });
                        return false;
                    }
                }];
                var dialog = openTmpl({
                    vm: mvvm,title:title, w:820,h:580,btns:btns,
                    tmpl: tmpl, tmplid: "userTemplate",
                    onclose: function () {
                        destroyui(["setGroup"]);
                    }
                });
            }

            avalon.filters.getpost = function (val) {
                var result = '';
                mvvm.postslist.forEach(function (item) {
                    if (item.Id == val)
                        result = item.Name
                });
                return result;
            }
            switch (action) {
                case 'detail':
                    mvvm.doview(paramid)
                    break
                case 'add':
                    mvvm.doadd();
                    break
                case 'edit':
                    mvvm.doedit(paramid);
                    break
                default:
                    fill();
                    break;
            }
            function fill() {
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            }
        },

        /// <summary>
        /// 数据库备份
        /// </summary>
        DatabaseBackup: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM,
                that = this;
            var Mvvm = avalon.define('DatabaseBackup', function (vm) {
                vm.lang = lang;
                vm.config = { type: "d", hour: "00", minute: "00", week: 0, auto: true };
                vm.types = [{ value: "d", dsc: "每天" }, { value: "w", dsc: "每周" }];
                vm.weeks = [
                    { value: 1, dsc: "星期一" }, { value: 2, dsc: "星期二" }, { value: 3, dsc: "星期三" }, { value: 4, dsc: "星期四" },
                    { value: 5, dsc: "星期五" }, { value: 6, dsc: "星期六" }, { value: 0, dsc: "星期日" }
                ];
                vm.rows = [];
                vm.IsSuperAdmin = false;
                vm.nextTime = "";
                vm.userEntity = {};
                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);
                }
                vm.backup = function () {
                    var url = "/Settings/DatabaseBackupByUser";
                    var box = loading("系统正在执行数据库备份，请稍后……");
                    $.post(url, {}).done(function (ret) {
                        if (box) box.close();
                        if (ret.message.indexOf("无法打开备份设备") > -1) ret.message = "数据库备份失败：无法打开备份设备,请检查数据库服务器跟网站服务器是否是同一台服务器。";
                        if (ret.result) {
                            messageBox.ok("<h1 class='tipTitle'>" + ret.message + "</h1><p class='tipContent'>文件已备份至：" + ret.data.path + "</p>");
                            vm.getList();
                        } else {
                            messageBox.warning(ret.message);
                        }
                    });
                }
                vm.del = function () {
                    var itemVm = this.$vmodel,
                        item = itemVm[itemVm.$itemName];
                    messageBox.confirm("您确定要删除备份吗？", function (r) {
                        messageBox.confirm("您确定要把该数据库备份永久删除吗？", function (r) {
                            delSubmit();
                        })
                    })
                    function delSubmit() {
                        var box = loading("系统正在执行删除备份操作，请稍后……");
                        $.post("/Settings/DatabaseBackupDelete/" + item.Id, {}).done(function (ret) {
                            if (box) box.close();
                            if (ret.result) {
                                messageBox.ok(ret.message);
                                //vm.getList();
                                itemVm.$remove();
                            } else {
                                messageBox.warning(ret.message);
                            }
                        });
                    }
                }
                vm.getList = function () {
                    $.get("/Settings/DatabaseBackupGetList", {}).done(function (ret) {
                        if (ret.result) {
                            vm.rows = ret.data.rows;
                            vm.IsSuperAdmin = ret.data.IsSuperAdmin;
                        } else {
                            vm.rows = [];
                            messageBox.warning(ret.message);
                        }
                    });
                }
                vm.saveConfig = function () {
                    var data = vm.config.$model;
                    $.post("/Settings/DatabaseBackupSaveConfig", data).done(function (ret) {
                        if (ret.result) {
                            vm.loadConfig(ret.data.config);
                            vm.nextTime = ret.data.nextTime;
                            messageBox.ok(ret.message);
                        } else {
                            messageBox.warning(ret.message);
                        }
                    });
                }
                vm.getConfig = function () {
                    $.get("/Settings/DatabaseBackupGetConfig", {}).done(function (ret) {
                        if (ret.result) {
                            vm.loadConfig(ret.data.config);
                            vm.nextTime = ret.data.nextTime;
                        } else {
                            messageBox.warning(ret.message);
                        }
                    });
                }
                vm.loadConfig = function (config) {
                    for (var i = 0, l = config.length; i < l; i++) {
                        var item = config[i];
                        if (item.Value == "True" || item.Value == "True") item.Value = true;
                        if (item.Value == "False" || item.Value == "false") item.Value = false;
                        vm.config[item.Key] = item.Value;
                    }
                }
                vm.getUser = function () {
                    //if (avalon.vmodels.userCard) {
                    //    vm.userEntity = avalon.vmodels.userCard.entity.$model;
                    //    formDetail("用户查看");
                    //    return;
                    //}
                    var userid = avalon(this).data().userid;
                    if (!userid) return;
                    $.get("/Settings/GetUser/" + userid, {}).done(function (ret) {
                        if (ret.result) {
                            vm.userEntity = ret.data;
                            formDetail("用户查看");
                        } else {
                            CBCRM.showResult(ret);
                        }
                    });
                }
            })

            CBCRM.fillContent(tmpl, lang, contentId, module, Mvvm)
            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.DatabaseBackup = null
            }
            Mvvm.getList();
            Mvvm.getConfig();

            function formDetail(title) {
                var dialog = messageBox.openHtml(title, '800px', '300px', '', []);
                var content = $(dialog.content());
                content.attr('ms-include', 'detailTemplate')
                avalon.scan(dialog[0], Mvvm)
            }

            $('#left_menu_top').html('<h2>数据库备份</h2>').show()
        },


        /// <summary>
        /// 回收站管理
        /// </summary>
        RecycleBin: function (temp, lang, contentId, module, params) {
            var CBCRM = avalon.vmodels.CBCRM, vmid = "RecycleBin", that = this;
            var action = this.params.action, paramid = this.params.id;
            mvvm = CBCRM.define(vmid, function (vm) {
                vm.lang = lang
                vm.$skipArray = ['lang'] //不监听语言包
                vm.oldPassword = ''
                vm.keyword = ''
                vm.userEntity = {}
                vm.userList = []
                vm.roleList = []

                vm.customerList = []
                vm.customerEntity = []

                //vm.ADD = false;
                vm.DELETE = false;
                vm.RESTORE = false;
                //vm.LOCK = false
                //vm.UNLOCK = false
                vm.allChecked = false
                vm.query = createQuerys({
                    key: { label: "关键词", val: "", valLabel: '' },
                    roleId: { label: "角色", val: "", valLabel: '' },
                    depart: { label: "关键词", val: "", valLabel: '' },
                    enable: {
                        label: "状态", val: "true", valLabel: "启用",
                        items: [
                            { label: "不限", val: '', curr: false },
                            { label: "启用", val: 'true', curr: true },
                            { label: "禁用", val: 'false', curr: false }
                        ]
                    },
                    customerType: {
                        label: "客户类型", val: "true", valLable: "不限",
                        items: [
                        { label: "不限", val: '', curr: true },
                        { label: "企业", val: '', curr: false },
                        { label: "事业单位", val: '', curr: false },
                        { label: "政府团体", val: '', curr: false },
                        { label: "社会团体", val: '', curr: false },
                        { label: "个人", val: '', curr: false }
                        ]
                    },
                    owner: {
                        label: "客户归属", val: "true", valLable: "不限",
                        items: [
                        { label: "不限", val: '', curr: true },
                        { label: "我的客户", val: '', curr: false },
                        { label: "制定部门/职位/员工", val: '', curr: false }
                        ]
                    },
                    serviceStage: {
                        label: "服务阶段", val: "true", valLable: "不限",
                        items: [
                        { label: "不限", val: '', curr: true },
                        { label: "售前跟踪", val: '', curr: false },
                        { label: "合同执行", val: '', curr: false },
                        { label: "售后服务", val: '', curr: false },
                        { label: "合同期满", val: '', curr: false },
                        { label: "失败", val: '', curr: false },
                        { label: "搁置", val: '', curr: false },
                        { label: "失效", val: '', curr: false }
                        ]
                    }
                }, function (data, name, val, type) {
                    if (type == "clear" || type == "remove") {
                        var rolevm = avalon.vmodels["roleList"];
                        var tree = avalon.vmodels["groupTree"];
                        if (type == "clear") {
                            if (rolevm) rolevm.unSelectAll();
                            if (tree) tree.$tree.selectNode({});
                        } else {
                            switch (name) {
                                case "roleId":
                                    if (rolevm) rolevm.unSelectAll();
                                    break;
                                case "depart":
                                    if (tree) tree.$tree.selectNode({});
                                    break;
                            }
                        }
                    }
                    mvvm.grid1.loadData(data);
                });
                vm.query.setVm();

                vm.grid1 = createGrid({
                    url: "/Settings/Users",
                    entityUrl: "/Settings/GetUser",
                    pageid: vmid + "_grid1_page",
                    entityId: "User",
                    modelFactory: modelFactory,
                    tmpl: tmpl,
                    $lang: lang,
                    createQuery: function () {
                        return mvvm.query.createQuery();
                    },
                    onLoadData: function (ret, list) {
                        mvvm.RESTORE = ret.data.RESTORE;
                        mvvm.DELETE = ret.data.DELETE;
                    },
                    onRemove: function (deleteIds, ids) {
                        $.get('/Settings/CustomerAllDelete/', deleteIds, function (ret) {
                            CBCRM.showResult(ret);
                            if (ret.result) mvvm.grid1.reloadData();
                        });
                    }
                });

                vm.toSearch = function () {
                    mvvm.query.addQuery("key", mvvm.query.data.key.val, mvvm.query.data.key.val, false, true);
                }
                vm.pwdFocus = function () {
                    mvvm.userEntity.Password = "";
                }
                vm.pwdBlur = function () {
                    if (mvvm.userEntity.Password == "") mvvm.userEntity.Password = mvvm.oldPassword;
                }
                //角色检索
                vm.roleListOpts = {
                    roleChanged: function () {
                        var vm = this.$vmodel,
                            item = vm[vm.$itemName];
                        mvvm.query.addQuery("roleId", item.Id, item.Name);
                    }
                }
                //部门检索
                vm.groupTreeOpts = {
                    treeopts: {
                        async: {
                            enable: true,
                            url: '/Settings/GetGroupPostUser/9060000'
                        },
                        callback: {
                            onClick: function (e, treeId, treeNode) {
                                mvvm.query1.addQuery("depart", getNodeIds(treeNode).join(","), treeNode.Name);
                            }
                        },
                        view: {
                            addHoverDom: false,
                            removeHoverDom: false
                        } //替换默认
                    }
                }
                vm.posts = []
                vm.postslist = []
                //选择部门
                vm.postGroupTreeOpts = {
                    treeopts: {
                        async: {
                            enable: true,
                            url: '/Settings/GetGroupPostUser/9060000'
                        },
                        callback: {
                            onClick: function (event, treeId, treeNode) {
                                var m = mvvm.userEntity
                                m.Group = { Id: treeNode.Id, Name: treeNode.Name }
                                mvvm.posts = treeNode.Posts
                                if (treeNode.Posts.length)
                                    mvvm.userEntity.PositionId = treeNode.Posts[0].Id
                            }
                        }
                    }
                }
                //新增
                vm.doadd = function () {
                    mvvm.grid1.getEntity(null, function (entity) {
                        initEntity(entity);
                        mvvm.userEntity = entity;
                        mvvm.posts = [];
                        formSubmit('新增用户');
                    });
                }
                //编辑
                vm.doedit = function (id) {
                    mvvm.grid1.getEntity(id, function (entity) {
                        initEntity(entity);
                        if (entity.Roles) {
                            mvvm.roleList.forEach(function (item) {
                                if (entity.Roles.indexOf(item.Id.toString()) > -1) item.checked = true;
                                else item.checked = false;
                            });
                        }
                        mvvm.userEntity = entity;
                        mvvm.oldPassword = entity.Password;
                        if (entity.Group) getQueryPost(entity.Group.Id);
                        formSubmit('编辑用户');
                    }, true);
                }
                //查看
                vm.doview = function (id) {
                    mvvm.grid1.getEntity(id, function (entity) {
                        initEntity(entity);
                        var rols = [];
                        if (entity.Roles) {
                            entity.Roles.forEach(function (rid) {
                                var item = findArr(mvvm.roleList.$model, function (item) { return item.Id.toString() == rid });
                                if (item != null) rols.push(item);
                            });
                        }
                        entity.roleList = rols;
                        mvvm.userEntity = entity;
                        var name = mvvm.userEntity.Role.Name
                        var names = mvvm.userEntity.RolesDisplay
                        if (names) {
                            names = names.replace(name, name + '(默认)')
                            mvvm.userEntity.Role.Name = names
                        }
                        openTmpl({
                            w: 820, h: 150, title: "用户详情",
                            vm: mvvm, tmpl: tmpl, tmplid: "detailTemplate"
                        })
                    }, true)
                }
                vm.setAvailable = function (id, availabled) {
                    var url = '/Settings/SetUserAvailabled/',
                    data = { state: availabled || false },
                    optLabel = !availabled ? '禁用' : '启用'
                    if (!id) {
                        var ids = mvvm.grid1.getCheckedIds("ids");
                        if (ids.length == 0) {
                            messageBox.error('请选择要' + optLabel + '的用户账号');
                            return;
                        }
                        delete ids.length;
                        $.extend(data, ids);
                    } else {
                        data["ids[0]"] = id
                    }
                    messageBox.confirm('您确定要' + optLabel + '选中的用户账号吗？', function () {
                        $.post(url, data)
                        .done(function (ret) {
                            CBCRM.showResult(ret);
                            if (ret) mvvm.grid1.reloadData();
                        })
                    })
                }
                vm.setContact = function (act) {
                    var optLabel = act ? "加入" : "移出";
                    var data = mvvm.grid1.getCheckedIds("ids");
                    if (data.length == 0) {
                        messageBox.error('请选择要' + optLabel + '通讯录的用户账号');
                        return;
                    }
                    data.act = act;
                    messageBox.confirm('您确定要批量' + optLabel + '通讯录吗？', function () {
                        $.post('/Settings/SetContact/', data, function (ret) {
                            CBCRM.showResult(ret);
                            if (ret.result) {
                                mvvm.grid1.reloadData();
                            }
                        })
                    })
                }
                //设置默认
                vm.roleChange = function (role) {
                    if (!this.checked && role.Id.toString() == mvvm.userEntity.Role.Id) mvvm.userEntity.Role.Id = "";
                }
                vm.defRoleChange = function (index) {
                    var role = mvvm.roleList[index]
                    if (this.checked) role.checked = true;
                }

                //解除App绑定
                vm.unbindAppUser = function (uid, item, index) {
                    messageBox.confirm2("您确定要解除此设备的绑定吗？", function () {
                        $.post("/Settings/UnbindAppUser", { uid: uid, sn: item.Key }, function (ret) {
                            CBCRM.showResult(ret, function () {
                                mvvm.userEntity.DeviceSnList.removeAt(index);
                            });
                        });
                    });
                }
            });
            function init() {
                mvvm.grid1.init();
                //$.get('/Settings/GetPost/', {}, function (ret) { if (ret && ret.result) mvvm.postslist = ret.data; })
                $.get('/Settings/Roles/', {}, function (ret) {
                    ret.data.forEach(function (item) { item.checked = false })
                    mvvm.roleList = ret.data;
                });
            }
            init();

            function initEntity(entity) {
                entity.Sex += '';
                entity.IsAvailable += '';
                if (!entity.Role) entity.Role = { Id: "", Name: "" };
                entity.Role.Id += '';
            }

            function loadUser(id) {
                $.get('/Settings/GetUser/' + id, {}, function (ret) {
                    if (!ret.result) return CBCRM.showResult(ret);
                    initEntity(ret.data);
                    mvvm.userEntity = ret.data;
                    mvvm.oldPassword = ret.data.Password;
                    getQueryPost(mvvm.userEntity.Group.Id);
                    formSubmit('编辑用户');
                });
            }
            var curGid = null;
            function getQueryPost(id) {
                if (curGid == id) return;
                curGid = id;
                $.get('/Settings/GetPost/', { gid: id }, function (ret) {
                    if (!ret.result) return;
                    mvvm.posts = ret.data;
                    var t = mvvm.userEntity.PositionId
                    mvvm.userEntity.PositionId = ""
                    mvvm.userEntity.PositionId = t;
                })
            }
            //打开新增或编辑窗口
            function formSubmit(title) {
                var btns = [{
                    name: '提交',
                    focus: true,
                    callback: function () {
                        var model = mvvm.userEntity.$model, has;
                        if (!model.UserName) {
                            messageBox.warning('请输入用户的账号名称,将用于登陆CRM');
                            return false;
                        }
                        if (!model.Password) {
                            messageBox.warning('请输入用户登陆密码');
                            return false;
                        }
                        if (!model.FullName) {
                            messageBox.warning('请输入用户的真实姓名');
                            return false;
                        }
                        if (model.Group.Id <= 0) {
                            messageBox.warning('请选择部门');
                            return;
                        }
                        if (model.PositionId <= 0) {
                            messageBox.warning('请选择用户职位');
                            return false;
                        }
                        if (model.Role.Id <= 0) {
                            messageBox.warning('请指定用户的默认角色');
                            return false;
                        }
                        model.MasterRole = model.Role.Id;
                        var roleIds = where(mvvm.roleList, function (item) { return item.checked; }, "Id");
                        if (roleIds.length == 0) {
                            messageBox.warning('请选择用户的角色');
                            return false;
                        }
                        model.Roles = roleIds;
                        $.extend(model, jsonToSubmit("roleIds", roleIds));
                        delete model.roleIds;
                        delete model.DeviceSnList;
                        //model.roleIds = model.Roles;
                        model.oldPassword = mvvm.oldPassword;
                        if (!model.Id) {
                            hash = CryptoJS.SHA512(model.Password)
                            model.Password = hash.toString(CryptoJS.enc.Base64)
                            model["Group.Id"] = mvvm.userEntity.Group.Id;
                        } else {
                            if (model.Password != mvvm.oldPassword) {
                                hash = CryptoJS.SHA512(model.Password)
                                model.Password = hash.toString(CryptoJS.enc.Base64)
                            }
                            model.groupId = mvvm.userEntity.Group.Id;
                        }
                        var postUrl = model.Id == 0 ? "/Settings/UsersAdd/" : "/Settings/UsersUpdate/";
                        $.post(postUrl + model.Id, model, function (ret) {
                            CBCRM.showResult(ret);
                            if (ret.result) {
                                if (dialog) dialog.close();
                                if (action == "add" || action == "edit") {
                                    if (paramData && paramData.callback) {
                                        paramData.callback.call(mvvm, model, ret);
                                    }
                                } else {
                                    mvvm.grid1.reloadData();
                                }
                            }
                        });
                        return false;
                    }
                }];
                var dialog = openTmpl({
                    vm: mvvm, title: title, w: 820, h: 580, btns: btns,
                    tmpl: tmpl, tmplid: "userTemplate",
                    onclose: function () {
                        destroyui(["setGroup"]);
                    }
                });
            }

            avalon.filters.getpost = function (val) {
                var result = '';
                mvvm.postslist.forEach(function (item) {
                    if (item.Id == val)
                        result = item.Name
                });
                return result;
            }
            switch (action) {
                case 'detail':
                    mvvm.doview(paramid)
                    break
                case 'add':
                    mvvm.doadd();
                    break
                case 'edit':
                    mvvm.doedit(paramid);
                    break
                default:
                    fill();
                    break;
            }
            function fill() {
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
            }
        },


        /// <summary>
        /// 回收站管理
        /// </summary>
        RecycleBinCustomer: function (tmpl, lang, contentId, module, params) {
            var CBCRM = avalon.vmodels.CBCRM, vmid = 'RecycleBinCustomer',
               that = this,
               mvvm = CBCRM.define(vmid, function (vm) {
                   vm.$skipArray = ['lang']
                   vm.lang = lang
                   vm.checkAll = false
                   vm.DELETE = false
                   vm.RESTORE = false
                   initQuerys(vm, function (data, name, val, type) {
                       mvvm.grid1.loadData(mvvm.createQuery());
                   })
                   vm.queryData = {
                       type: {
                           label: "客户类型", val: "", valLabel: "", next: "stageId",
                           items: [
                           { label: "不限", val: '', curr: true },
                           { label: "企业", val: '0', curr: false },
                           { label: "事业单位", val: '2', curr: false },
                           { label: "政府团体", val: '3', curr: false },
                           { label: "社会团体", val: '4', curr: false },
                           { label: "个人", val: '1', curr: false }
                           ]
                       },
                       stageId: {
                           label: "服务阶段", val: "", valLabel: "", jump: true,
                           items: [
                           { label: "不限", val: '', curr: true }
                           ]
                       },
                       key: {
                           label: '关键词', val: '', valLabel: ''
                       },
                       owner: {
                           label: '客户归属', val: '', valLabel: ''
                       }
                   }
                   
                   vm.grid1 = createGrid({
                       url: "/Settings/RecycleBinCustomer",
                       $lang: lang,
                       pageid: vmid + "grid1_page",
                       tmpl: tmpl,
                       createQuery: function () {
                           return mvvm.createQuery();
                       },
                       onLoadData: function (ret) {
                           if (!ret || !ret.result) {
                               CBCRM.showResult(ret);
                               return;
                           }
                           mvvm.RESTORE = ret.data.RESTORE
                           mvvm.DELETE = ret.data.DELETE
                           return ret.data;
                       },
                       onRemove: function (delIds,ids) {
                           var data = jsonToSubmit("deleteIds", ids);
                           $.post('/Settings/RecycleBinCustomerAllDelete/', data, function (ret) {
                               CBCRM.showResult(ret);
                               if (ret.result) mvvm.grid1.reloadData();
                           });
                       }
                   })

                   vm.doRestore = function (item, id) {
                       var ids = [];
                       ids.push(item.$model.Id);

                       mvvm.doRestoreAll(item,ids);
                   }

                   vm.doRestoreAll = function (item,ids) {
                       if(!ids)
                          var ids = mvvm.grid1.getCheckedIds();
                       if (!ids.length) {
                           messageBox.warning('请选择要还原的客户。')
                           return
                       }
                       messageBox.confirm('确定要还原选中的客户吗？', function () {
                           var data = jsonToSubmit("ids", ids);
                           data.isLock = false;
                           var data = jsonToSubmit("restoreIds", ids);
                           $.post('/Settings/RecycleBinCustomerAllRestore/', data, function (ret) {
                               CBCRM.showResult(ret);
                               if (ret.result) mvvm.grid1.reloadData();
                           });
                       })
                   }
                   vm.customerEntity = {};
                   vm.isPerson = false;
                   vm.doview = function (item) {
                       var url = '/Customer/DetailCustomer2/' + item.Id;
                       CBCRM.loadView("/Customer/DetailCustomer2.html", function (dtmpl) {
                           $.get(url, function (ret) {
                               if (!ret || !ret.result) return CBCRM.showResult(ret);
                               mvvm.customerEntity = ret.data;
                               mvvm.isPerson = ret.data.Type === 1;
                               mvvm.openTmpl({
                                   title: "", w: 1000, h: 400,
                                   tmplId: dtmpl, isContent: true
                               });
                           })
                           
                       })
                   }
                   //tab切换
                   vm.tab = 'tab1'
                   vm.tabChange = function () {
                       var tabid = $(this).attr("val")
                       mvvm.tab = tabid
                   }

                   vm.stageIds = [];
                   vm.$dicts = { stageIds: 100011};
                   vm.getDicts = function () {
                       getDicts(mvvm.$dicts, mvvm, function (ret) {
                           mvvm.stageIds.forEach(function (item) {
                               mvvm.queryData.stageId.items.push({ val: item.Id, label: item.Data, curr: false });
                           });
                       });
                   }
               })
            mvvm.grid1.init();
            mvvm.getDicts();
            CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
        },

        /// <summary>
        /// 组织架构
        /// </summary>
        Organization: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM,
                that = this,
                allGroups, allPosts, allEmployess, allTmpPosts = [], allTmpEmps = [],
                loadData = function (data,callback) {
                    /*加载部门/职位/员工数据*/
                    allTmpPosts = []
                    allTmpEmps = []
                    $.get(that.path, data)
                    .done(function (ret) {
                        if (avalon.vmodels.CBCRM.$debug)
                            avalon.log('加载部门/职位/员工数据')
                        if (ret.result) {
                            if (ret.data.groups.length) {
                                ret.data.groups[0].open = true
                                var vtree = avalon.vmodels["groups"];
                                vtree.datasource = ret.data.groups;
                                var treeobj = vtree.$tree;
                                allGroups = ret.data.groups
                                model.currGroup = ret.data.groups[0]

                                allGroups.forEach(function (g) {
                                    if (g.Posts && g.Posts.length > 0) {
                                        g.Posts.forEach(function (post) {
                                            post.GroupName = g.Name
                                            allTmpPosts.push(post)
                                            post.Users.forEach(function (u) {
                                                u.PostName = post.Name
                                                allTmpEmps.push(u)
                                            })
                                        })
                                    }
                                })

                                var treeNode=model.$curTreeNode
                                if (treeNode) treeNode = treeobj.getNodeByParam("Id",treeNode.Id,null);
                                model.showGroup(treeNode);
                                //model.posts = allTmpPosts
                                //model.employees = allTmpEmps

                                if (avalon.vmodels.CBCRM.$debug)
                                    avalon.log('已成功加载部门/职位/员工数据')
                            }
                            if (ret.data.postLevels && ret.data.postLevels.length) {
                                model.postLevels = ret.data.postLevels
                            }
                            if (callback) callback(treeNode);
                        }
                    })
                },
                model = CBCRM.define('Organization', function (vm) {
                    vm.lang = lang
                    vm.showPost = false
                    vm.employees = []
                    vm.doViewEmp = function () {
                        var itemVm = this.$vmodel,
                        item = itemVm[itemVm.$itemName]
                        avalon.router.navigate('/Settings/Users/' + item.Id + '/detail')
                    }
                    vm.lockEmp = function (id, state) {
                        var ids = [id];
                        var data = { state: state };
                        data = $.extend(data, jsonToSubmit("ids", ids));
                        messageBox.confirm('确定' + (state ? '启用' : '禁用') + '此用户吗？', function () {
                            $.post('/Settings/SetUserAvailabled/', data, function (ret) {
                                CBCRM.showResult(ret, function () {
                                    model.employees.forEach(function (e, i) {
                                        if (e.Id == id)
                                            e.IsAvailable = state;
                                    })
                                    loadData()
                                })
                            })
                        })
                    }

                    /*定义数据字典开始*/
                    vm.postLevels = []
                    /*定义数据字典结束*/
                    /*定义部门实体开始*/
                    vm.groups = []
                    vm.entity = {} //单位信息
                    vm.areaDisplay = ''
                    vm.IsGroups = false
                    vm.$curTreeNode = null;
                    vm.groupTreeOpts = {
                        events: {
                            add: function ($cur, data) {
                                model.doadd(data);
                            },
                            edit: function ($cur, data) {
                                if (!data.id) {
                                    if (avalon.vmodels.CBCRM.$debug)
                                        avalon.log('缺少部门id')
                                    return
                                }
                                model.doedit(data.id)
                            },
                            remove: function ($cur, data) {
                                if (!data.id) {
                                    if (avalon.vmodels.CBCRM.$debug)
                                        avalon.log('缺少部门id')
                                    return
                                }
                                messageBox.confirm(lang.GroupToRecycleBinConfirm.replace('{0}', data.groupname), function () {
                                    $.post('/Settings/GroupToRecycleBin/' + data.id)
                                    .done(function (ret) {
                                        if (ret.result) {
                                            var treeNode = model.$curTreeNode;
                                            if (treeNode) {
                                                var p = treeNode.getParentNode();
                                                model.$curTreeNode = p;
                                            }
                                        }
                                        model.submitCallBack(ret);
                                    })
                                })
                            }
                        },
                        treeopts: {
                            treeId: 'groupTree',
                            callback: {
                                onClick: function (event, treeId, treeNode) {
                                    model.showGroup(treeNode);
                                }
                            },
                            view: {
                                addHoverDom: function (treeId, treeNode) {
                                    var id = treeNode.Id;
                                    if (id == 1) return;
                                    var $addBtn = $("#addBtn_" + id), addStr, dataStr
                                    if ($addBtn.length > 0) {
                                        $addBtn.show()
                                        $("#editBtn_" + id).show()
                                        $("#removeBtn_" + id).show()
                                        return
                                    }
                                    dataStr = ' data-id="' + id + '" data-treeid="' + treeId + '"' +
                                        ' data-groupname="' + treeNode.Name + '"'
                                    addStr = "<span data-call='add' class='button add ongroupevent' id='addBtn_" + id
                                        + "' " + dataStr + " title='添加下属部门' onfocus='this.blur();'></span><span data-call='edit' class='button edit ongroupevent' id='editBtn_" + id
                                        + "' " + dataStr + " title='编辑部门' onfocus='this.blur();'></span><span data-call='remove' class='button remove ongroupevent' id='removeBtn_" + id
                                        + "' " + dataStr + " title='移除部门' onfocus='this.blur();'></span>"
                                    $("#" + treeNode.tId + "_span").after(addStr)
                                },
                                removeHoverDom: function (treeId, treeNode) {
                                    var id = treeNode.Id
                                    $("#addBtn_" + id).hide()
                                    $("#editBtn_" + id).hide()
                                    $("#removeBtn_" + id).hide()
                                },
                                selectedMulti: false
                            },
                            async: {
                                url: null,
                            }
                        }
                    }
                    vm.showGroup = function (treeNode) {
                        model.$curTreeNode = treeNode;
                        if (treeNode == null || treeNode.Id == 1) {
                            model.IsGroups = false
                            model.posts = allTmpPosts
                            model.employees = allTmpEmps
                        }
                        else {
                            var vtree = avalon.vmodels["groups"];
                            var treeobj = vtree.$tree;
                            if (treeNode) {
                                treeobj.selectNode(treeNode);
                                treeobj.expandNode(treeNode, true);
                            }
                            model.IsGroups = true
                            model.posts.removeAll()
                            model.employees.removeAll()
                            var ids = getNodeIds(treeNode).join(",")
                            allGroups.forEach(function (g) {
                                if (g.Id == treeNode.Id) model.currGroup = g
                                if (ids.indexOf(g.Id) > -1 && g.Posts && g.Posts.length > 0) {
                                    g.Posts.forEach(function (post) {
                                        post.GroupName = g.Name
                                        model.posts.push(post)
                                        post.Users.forEach(function (u) {
                                            u.PostName = post.Name
                                            model.employees.push(u)
                                        })
                                    })
                                    model.showPost = false
                                }
                            })
                        }
                    }
                    vm.inputGroupTreeOpts = {
                        drowDownTreeId: '',
                        treeopts: {
                            async: {
                                url: function (treeId, treeNode) {
                                    var url = '/Settings/GetGroupPostUser/9040100'
                                    return url
                                }
                            },
                            callback: {
                                onClick: function (event, treeId, treeNode) {
                                    var m = model.groupEntity
                                    m.ParentGroupName = treeNode.Name
                                    m.ParentId = treeNode.Id
                                    if (avalon.vmodels.CBCRM.$debug)
                                        avalon.log('curr parent group id : ' + treeNode.Id + ' name : ' + treeNode.Name)
                                }
                            }
                        }
                    }
                    vm.currGroup = {}
                    vm.groupEntity = {}
                    //新增
                    vm.doadd = function (p) {
                        model.groupEntity = $.extend(true, {}, modelFactory.create('Group'));
                        if (p.id) {
                            model.groupEntity.ParentId = p.id
                            model.groupEntity.ParentGroupName = p.groupname
                        }
                        model.formSubmitGroup('新增部门')
                    }
                    vm.doeditcurr = function () {
                        if (model.currGroup.Id == 1) {
                            messageBox.warning("不能编辑根节点");
                            return;
                        }
                        model.doedit(model.currGroup.Id)
                        if (avalon.vmodels.CBCRM.$debug)
                            avalon.log('编辑当前部门：' + model.currGroup.Id)
                    }
                    vm.doedit = function (id) {
                        var d
                        if (id) {
                            $.get('/Settings/GetGroup/' + id)
                            .done(function (ret) {
                                if (ret.result) {
                                    model.groupEntity = avalon.mix(modelFactory.create('Group'), ret.data)
                                    if (ret.data.Parent) {
                                        model.groupEntity.ParentGroupName = ret.data.Parent.Name
                                        model.groupEntity.ParentId = ret.data.Parent.Id
                                    }
                                }
                            })
                        }
                        //d = messageBox.openHtml(model.lang.EditGroup, '770px', '600px', '', [{
                        //    name: lang.SubmitBtn,
                        //    focus: true,
                        //    callback: function () { 
                        //        $.post('/Settings/EditGroup/' + id, model.groupEntity.$model, function (data) {
                        //            CBCRM.showResult(data, function () {
                        //                loadData()
                        //                messageBox.close()
                        //            })
                        //        })
                        //        return false
                        //    }
                        //}], function () {
                        //    model.groupEntity = modelFactory.create('Group')
                        //    avalon.vmodels.inputGroupTree.destroy()
                        //}),
                        //$content = $(d.content())
                        //$content.attr('ms-include', 'inputGroup')
                        //avalon.scan($content[0], model)
                        model.formSubmitGroup('编辑部门')
                    }
                    vm.formSubmitGroup = function (title) {
                        var d = messageBox.openHtml(title, '836px', '446px', '', [{
                            name: "提交",
                            focus: true,
                            callback: function () {
                                var path = model.groupEntity.Id > 0 ? '/Settings/EditGroup/' + model.groupEntity.Id : '/Settings/AddGroup/'
                                $.post(path, model.groupEntity.$model, function (ret) {
                                    model.submitCallBack(ret, d);
                                })
                                return false
                            }
                        }], function () {
                            avalon.vmodels.inputGroupTree.destroy()
                            avalon.vmodels.ManagerIdTree.destroy()
                            avalon.vmodels.DeputyManagerIdTree.destroy()
                        }),
                        $content = $(d.content())
                        var inputTmpl = $(tmpl).find("#inputGroup").text()
                        $content.html(inputTmpl)
                        avalon.scan($content[0], model)
                    }
                    vm.submitCallBack = function (ret,dialog) {
                        CBCRM.showResult(ret);
                        if (ret.result) {
                            loadData();
                            if (dialog) dialog.close();
                        }
                    }
                    vm.postGroupTreeOpts = {
                        treeopts: {
                            callback: {
                                onClick: function (event, treeId, treeNode) {
                                    if (treeNode.Id == 1) {
                                        var m = model.postEntity
                                        m.GroupName = ""
                                        m.Group = ""
                                        m.bossId = ''
                                        model.bossPosts = [];
                                    } else {
                                        var m = model.postEntity
                                        m.GroupName = treeNode.Name
                                        m.Group = treeNode.Id
                                        m.bossId = treeNode.Posts.length ? treeNode.Posts[0].Id : ''
                                        model.bossPosts = treeNode.Posts
                                    }
                                }
                            }
                        }
                    }
                    //主管
                    vm.ManagerOpts = {
                        treeopts: {
                            callback: {
                                onCheck: function (e, treeId, treeNode) {
                                    model.groupEntity.ManagerId = treeNode.Id;
                                    model.groupEntity.ManagerDisplay = treeNode.Name;
                                }
                            },
                            check: {
                                enable: true,
                                chkStyle: 'radio',
                                radioType: "all"
                            },
                            async: {
                                url: function (treeId, treeNode) {
                                    var url = "/Settings/GetGroupPostUser/2020100"
                                    vmtree = avalon.vmodels.ManagerIdTree
                                    if (vmtree && vmtree.q && vmtree.q !== vmtree.qcopy) {
                                        url += '?empName=' + vmtree.q
                                    }
                                    return url
                                },
                                dataFilter: notMemberFilter
                            }
                        }
                    }
                    //分管领导
                    vm.DeputyManagerOpts = {
                        treeopts: {
                            callback: {
                                onCheck: function (e, treeId, treeNode) {
                                    model.groupEntity.DeputyManagerId = treeNode.Id;
                                    model.groupEntity.DeputyManagerDisplay = treeNode.Name;
                                }
                            },
                            check: {
                                enable: true,
                                chkStyle: 'radio',
                                radioType: "all"
                            },
                            async: {
                                url: function (treeId, treeNode) {
                                    var url = "/Settings/GetGroupPostUser/2020100"
                                    vmtree = avalon.vmodels.DeputyManagerIdTree
                                    if (vmtree && vmtree.q && vmtree.q !== vmtree.qcopy) {
                                        url += '?empName=' + vmtree.q
                                    }
                                    return url
                                },
                                dataFilter: notMemberFilter
                            }
                        }
                    }
                    vm.doeditcompany = function () {
                        goto('/Settings/DetailCompanyInfo')
                    }
                    /*定义部门实体结束*/
                    /*定义职位实体开始*/
                    vm.posts = []
                    vm.currPost = {}
                    vm.postEntity = {}
                    vm.bossPosts = []
                    vm.bossPostChange = function (e) {
                        if (!model.postEntity.Boss) return
                        var currId = avalon(this).val()
                        model.bossPosts.forEach(function (b) {
                            if (b.Id == currId) {
                                if (avalon.vmodels.CBCRM.$debug)
                                    avalon.log('curr boss post id :' + b.Id + ' post name : ' + b.Name)
                                model.postEntity.Boss.Id = b.Id
                                model.postEntity.BossName = model.postEntity.Boss.Name = b.Name
                            }
                        })
                    }
                    vm.doViewPost = function () {
                        var vm = this.$vmodel, item = vm[vm.$itemName]
                        model.currPost = avalon.mix(modelFactory.create('Post'), item.$model)
                        model.currPost.BossName = item.Boss ? item.Boss.Name : ''
                        model.employees.removeAll()
                        if (model.currPost.Users && model.currPost.Users.length) {
                            model.currPost.Users.forEach(function (u) {
                                u.PostName = model.currPost.Name
                                model.employees.push(u)
                            })
                        }
                        if (!model.currPost.GroupName)
                            model.currPost.GroupName = model.currGroup.Name
                        if (!model.currPost.Group)
                            model.currPost.Group = model.currGroup.Id
                        model.showPost = true
                    }
                    vm.doEditCurrPost = function (e) {
                        var parentPosts = []
                        model.posts.forEach(function (p) {
                            if (p.Id !== model.currPost.Id) parentPosts.push(p)
                        })
                        model.bossPosts = parentPosts
                        model.postEntity = avalon.mix(modelFactory.create('Post'), model.currPost.$model)
                        if (model.postEntity.Boss)
                            model.postEntity.bossId = model.postEntity.Boss.Id
                        model.doPost(e)
                    }
                    vm.doAddPost = function () {
                        model.postEntity = avalon.mix(true, {}, modelFactory.create('Post'));
                        if (model.currGroup && model.currGroup.Id != 1)
                            model.postEntity.GroupName = model.currGroup.Name
                        if (model.currGroup && model.currGroup.Id != 1)
                            model.postEntity.Group = model.currGroup.Id
                        model.doPost();
                    }
                    vm.doPost = function (e, successCall) {
                        var d = messageBox.openHtml(!model.postEntity.Id ? lang.AddPost : lang.EditPost, '836px', '300px', '', [{
                            name: "提交",
                            focus: true,
                            callback: function () {
                                var path = model.postEntity.Id > 0 ? '/Settings/EditPost/' + model.postEntity.Id : '/Settings/AddPost/'
                                $.post(path, model.postEntity.$model, function (ret) {
                                    CBCRM.showResult(ret, function () {
                                        if (typeof successCall === 'function')
                                            successCall.call(ret, model.postEntity)
                                        loadData()
                                        messageBox.close()
                                    })
                                })
                                return false
                            }
                        }], function () {
                            avalon.vmodels.setGroup.destroy()
                            avalon.vmodels.postBossTreeId.destroy()
                        }),
                        $content = $(d.content())
                        var inputTmpl = $(tmpl).find("#inputPost").text()
                        $content.html(inputTmpl)
                        avalon.scan($content[0], model)
                    }
                    vm.doEditPost = function (e) {
                        var vm = this.$vmodel, item = vm[vm.$itemName]
                        index = this.$vmodel.$index
                        parentPosts = []
                        model.posts.forEach(function (p) {
                            if (p.Id !== item.Id) parentPosts.push(p)
                        })
                        model.bossPosts = parentPosts
                        model.postEntity = avalon.mix(modelFactory.create('Post'), item.$model)
                        if (item.Boss) {
                            model.postEntity.bossId = item.Boss.Id;
                            model.postEntity.bossName = item.Boss.Name;
                        }
                        model.doPost(e)
                    }
                    vm.doDelPost = function () {
                        var vm = this.$vmodel, item = vm[vm.$itemName],
                        index = vm.$index
                        messageBox.confirm(lang.PostToRecycleBinConfirm.replace('{0}', item.Name), function () {
                            $.post('/Settings/PostToRecycleBin/' + item.Id)
                            .done(function (ret) {
                                CBCRM.showResult(ret, function () {
                                    /*var id = item.Id
                                    model.posts.splice(index, 1)
                                    model.currGroup.Posts.splice(index, 1)
                                    if (model.currPost.Id == id && model.posts.size()) {
                                        model.currPost = model.posts[0]
                                    }*/
                                    loadData()
                                })
                            })
                        })
                    }
                    //直接上级
                    vm.postBossTreeOpts = {
                        treeopts: {
                            callback: {
                                onCheck: function (event, treeId, treeNode) {
                                    var m = model.postEntity
                                    m.bossId = treeNode.Id
                                    m.bossName = treeNode.Name
                                }
                            },
                            check: {
                                enable: true,
                                chkStyle: 'radio',
                                radioType: "all"
                            },
                            async: {
                                url: function (treeId, treeNode) {
                                    var url = "/Settings/GetGroupPostUser/2020100"
                                    vmtree = avalon.vmodels.ManagerIdTree
                                    if (vmtree && vmtree.q && vmtree.q !== vmtree.qcopy) {
                                        url += '?empName=' + vmtree.q
                                    }
                                    return url
                                },
                                dataFilter: onlyPostFilter
                            }
                        }
                    }
                    vm.tab = 'tab1'
                    vm.tabChange = function () {
                        model.tab = $(this).attr('val')
                    }
                    /*定义职位实体结束*/
                })
            model.currGroup = modelFactory.create('Group')

            function getNodeIds(node) {
                var ids = [node.Id];
                if (!node.children) return ids;
                for (var i = 0, l = node.children.length; i < l; i++) {
                    ids = ids.concat(getNodeIds(node.children[i]));
                }
                return ids;
            }

            avalon.nextTick(function () {
                model.groupEntity = modelFactory.create('Group')
                model.postEntity = modelFactory.create('Post')
                model.currPost = modelFactory.create('Post')

                //单位信息
                $.get('/Settings/DetailCompanyInfo/', {}, function (ret) {
                    if (ret.data) {
                        model.entity = modelFactory.create('CompanyInfo')
                        model.entity = ret.data.model
                        model.areaDisplay = ret.data.areaDisplay
                    }
                })
            })

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


        },

        /// <summary>
        /// 角色权限
        /// </summary>
        Permission: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM,vmid='Permission',
                that = this,
                model = CBCRM.define(vmid, function (scope) {
                    scope.$skipArray = ['lang']
                    scope.roles = []
                    scope.role = {}
                    scope.lang = lang
                    scope.checkAll = false
                    scope.ADD = false
                    scope.DELETE = false
                    scope.ALLOW = false
                    scope.DENY = false

                    initQuerys(scope, function (data, name, val, type) {
                        model.grid1.loadData(data);
                    });
                    scope.queryData = {
                        roleName: {
                            label:"角色名称",val:""
                        }
                    }
                    scope.grid1 = createGrid({
                        url: "/Settings/Permission",
                        entityUrl:"/Settings/GetRole/{id}",
                        $lang: lang,
                        pageid: vmid + "grid1_page",
                        entityId: "Role",
                        modelFactory: modelFactory,
                        createQuery:function(){
                            return model.createQuery();
                        },
                        onLoadData: function (ret) {
                            if (model.$needLoadList) model.$needLoadList = false;
                            if (!ret || !ret.result) {
                                CBCRM.showResult(ret);
                                return;
                            }
                            model.ADD = ret.data.ADD;
                            model.DELETE = ret.data.DELETE
                            model.ALLOW = ret.data.ALLOW
                            model.DENY = ret.data.DENY
                            ret.data.Source.forEach(function (item) {
                                item.hasMembers = item.Users.length > 0;
                            })
                            return ret.data;
                        },
                        onRemove: function (deleteIds,ids) {
                            var data = jsonToSubmit("ids", ids);
                            $.post('/Settings/PermissionDel/', data, function (ret) {
                                CBCRM.showResult(ret);
                                if (ret.result) model.grid1.reloadData();
                            });
                        }
                    })
                    scope.loadRole = function (id,cb) {
                        model.grid1.getEntity(id, function (entity) {
                            model.role = entity;
                            model.role.Users = entity.Users;
                            if (typeof (cb) == "function") cb.call(this, model.role);
                        }, true);
                    }
                    scope.doview = function (id) {
                        model.loadRole(id, function (entity) {
                            var d = model.openTmpl({
                                w: 600, h: 100, title: lang.ViewRole,
                                tmpl: tmpl, tmplid: "viewForm"
                            });
                        },true);
                    }
                    scope.doedit = function (id) {
                        model.grid1.getEntity(id, function (entity) {
                            model.role = entity;
                            model.role.IsAvailable += ''
                            var btns=[{
                                name: lang.SubmitBtn,
                                focus: true,
                                callback: function () {
                                    var data = model.role.$model
                                    if (!data.Name) {
                                        messageBox.warning('角色名称不能空!');
                                        return false;
                                    }
                                    
                                    delete data.Users
                                    delete data.AddBy
                                    delete data.EDIT
                                    delete data.DELETE
                                    delete data.AUTH
                                    delete data.AUTHORIZE
                                    $.post('/Settings/EditRole/' + data.Id, data, function (ret) {
                                        CBCRM.showResult(ret);
                                        if (ret.result) {
                                            if (d) d.close();
                                            model.grid1.reloadData();
                                        }
                                    })
                                }
                            }]
                            var d = openTmpl({
                                w: 600, h: 100,title:lang.EditRole,
                                vm: model, tmpl: tmpl, tmplid: "inputForm",
                                btns:btns
                            });
                        }, true);
                    }
                    scope.lockAll = function () {
                        var ids = model.grid1.getCheckedIds();
                        if (!ids.length) {
                            messageBox.warning('请选择要禁用的角色。')
                            return
                        }
                        messageBox.confirm('确定要禁用选中的角色吗？', function () {
                            var data = jsonToSubmit("ids", ids);
                            data.isLock = false;
                            $.post('/Settings/SetStatus', data)
                            .done(function (ret) {
                                CBCRM.showResult(ret);
                                if (ret.result) {
                                    model.grid1.list.forEach(function (item) {
                                        if(ids.indexOf(item.Id)!=-1)item.IsAvailable = false;
                                    })
                                }
                            })
                        })
                    }
                    scope.unlockAll = function () {
                        var ids = model.grid1.getCheckedIds();
                        if (!ids.length) {
                            messageBox.warning('请选择要启用的角色。')
                            return
                        }
                        messageBox.confirm('确定要启用选中的角色吗？', function () {
                            var data = jsonToSubmit("ids", ids);
                            data.isLock = true;
                            $.post('/Settings/SetStatus', data)
                            .done(function (ret) {
                                CBCRM.showResult(ret);
                                if (ret.result) {
                                    model.grid1.list.forEach(function (item) {
                                        if (ids.indexOf(item.Id)!=-1) item.IsAvailable = true;
                                    })
                                }
                            })
                        })
                    }
                    //新增角色
                    scope.doadd = function () {
                        model.role = model.grid1.getEntity();
                        var btns = [{
                            name: lang.SubmitBtn,
                            focus: true,
                            callback: function () {
                                var data = model.role.$model;
                                if (!model.role.$model.Name) {
                                    messageBox.warning('角色名称不能空!');
                                    return false;
                                }
                                $.post('/Settings/AddRole/', data, function (ret) {
                                    CBCRM.showResult(ret);
                                    if (ret.result) {
                                        if (d) d.close();
                                        model.grid1.reloadData();
                                    }
                                })
                                return false
                            }
                        }];
                        var d = openTmpl({
                            w: 600, h: 150, title: lang.AddRole,
                            vm:model,tmpl: tmpl, tmplid: "inputForm",btns:btns
                        });
                    }
                    //复制角色
                    scope.docopy = function () {
                        var a = model.grid1.getChecked();
                        if (a.length != 1) {
                            messageBox.error("<p>操作失败！</p>请选择一条记录！");
                            return;
                        }
                        var old = a[0].$model;
                        model.role = old;
                        model.role.Id = "";
                        model.role.Name += "副本";
                        var btns=[{
                            name: lang.SubmitBtn,
                            focus: true,
                            callback: function () {
                                var m = avalon.mix(true, {}, model.role.$model);
                                if (!m.Name) {
                                    messageBox.warning('角色名称不能空!');
                                    return false;
                                }
                                delete m.Users;
                                delete m.RoleAuths;
                                var data = jsonToSubmit("role", m);
                                data.oldid = old.Id;
                                $.post('/Settings/CopyRole', data, function (ret) {
                                    CBCRM.showResult(ret, function () {
                                        if (ret.result) {
                                            if (d) d.close()
                                            model.grid1.reloadData();
                                        }
                                    })
                                })
                                return false
                            }
                        }]
                        var d=openTmpl({
                            w:600,h:150,title:"复制角色",
                            vm: model, tmpl: tmpl, tmplid: "inputForm", btns: btns
                        });
                    }
                    scope.$needLoadList = false;
                    scope.$mdialog = null;
                    scope.winSize = {
                        umw:700,umh:400
                    }
                    scope.userManage = function (id) {
                        model.grid1.getEntity(id, function (entity) {
                            model.role = entity;
                            if (model.$mdialog) model.$mdialog.close();
                            model.$mdialog = openTmpl({
                                w: model.winSize.umw, h: model.winSize.umh, title: "角色成员管理",
                                vm: model, tmpl: tmpl, tmplid: "userManage",
                                onclose: function () {
                                    if (model.$needLoadList) model.grid1.reloadData();
                                }
                            });
                        }, true);
                    }
                    scope.removeUser = function (uid) {
                        messageBox.confirm2("确定要移除该用户吗？", function () {
                            $.post("/Settings/RemoveRoleUser/" + model.role.Id, { uids: uid }, function (ret) {
                                CBCRM.showResult(ret, function () {
                                    if (ret.result) {
                                        model.userManage(model.role.Id);
                                        model.$needLoadList = true;
                                    }
                                });
                            });
                        });
                        
                    }
                    scope.selectUser = function () {
                        plugins.selectUser({
                            ignore: where(model.role.Users, true, "Id"),
                            callback: function (us) {
                                if (us.length == 0) {
                                    messageBox.warning("请选择员工！");
                                    return false;
                                }
                                var uids = where(us, true, "Id");
                                $.post("/Settings/AddRoleUser/" + model.role.Id, { uids: uids.join(",") }, function (ret) {
                                    CBCRM.showResult(ret, function () {
                                        if (ret.result) {
                                            model.userManage(model.role.Id);
                                            model.$needLoadList = true;
                                        }
                                    });
                                });
                            }
                        });
                    }
                })
            model.grid1.init();
            CBCRM.fillContent(tmpl, lang, contentId, module, model)
        },

        /// <summary>
        /// 权限设置
        /// </summary>
        Authorize: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM,
                that = this,
                uicache = [],
                loadRole = function () {
                    $.get(that.path)
                    .done(function (ret) {
                        var roleDrop = avalon.vmodels.roleDropDown
                        if (ret.result) {
                            if (ret.data.role) {
                                model.currRole = ret.data.role
                                roleDrop.menus.removeAll()
                                ret.data.all.forEach(function (r) {
                                    roleDrop.menus.push(avalon.mix(r, { curr: ret.data.role.Id === r.Id, label: r.Name, group: false }))
                                })
                            }
                        }
                    })
                },
                model = avalon.define('Authorize', function (scope) {
                    scope.lang = lang
                    scope.modules = []
                    scope.moduleNames = []
                    scope.all = true
                    scope.auths = []
                    scope.currRole = {}
                    scope.roleopts = {
                        itemChanged: function () {
                            var vm = this.$vmodel,
                            item = vm[vm.$itemName]
                            model.currRole = item
                        },
                        rootLabel: lang.SelectRole
                    }
                    scope.setAuth = function (m, auth) {
                        var checked = false, auths = m.auths, modules = model.modules,
                            mm = modules[m.moduleIndex]
                        auth.checked = !auth.checked
                        model.cascadeCheckModule(mm)
                    }
                    scope.cascadeCheckModule = function (modules) {
                        var hasChecked = false, end, m
                        for (var i = 0, item; item = modules[i++];) {
                            for (var j = 0, au; au = item.auths[j++];) {
                                hasChecked = au.checked
                                if (hasChecked) break
                            }
                            //if (!hasChecked) {
                            if (item.threeId)
                                item.threeChecked = hasChecked
                            else if (item.secondId)
                                item.secondChecked = hasChecked
                            //}
                        }
                        hasChecked = false
                        for (i = 0; item = modules[i];) {
                            if (item.secondChildNum) {
                                end = i + item.secondChildNum
                                while (end && end > i) {
                                    m = modules[--end]
                                    if (m.threeId)
                                        hasChecked = m.threeChecked
                                    if (hasChecked)
                                        break
                                }
                                item.secondChecked = hasChecked
                                hasChecked = false
                                i = i + item.secondChildNum
                            } else {
                                i++
                            }
                        }
                        hasChecked = false
                        for (i = 0; item = modules[i++];) {
                            if (item.threeId)
                                hasChecked = item.threeChecked
                            else if (item.secondId)
                                hasChecked = item.secondChecked
                            if (hasChecked) break
                        }
                        modules[0].firstChecked = hasChecked
                    }
                    scope.setColAuth = function (moduleIndex, authIndex, auth) {
                        var modules = model.modules[moduleIndex]
                        auth.checked = !auth.checked
                        for (var i = 0, item; item = modules[i++];) {
                            item.auths[authIndex].checked = auth.checked
                            if (auth.checked) {
                                if (item.threeId)
                                    item.threeChecked = true
                                if (item.secondId)
                                    item.secondChecked = true
                                if (item.firstId)
                                    item.firstChecked = true
                            }
                        }
                        if (!auth.checked) {
                            model.cascadeCheckModule(modules)
                        }
                    }
                    scope.submitBtnLabel = lang.SubmitBtn
                    scope.lockSubmit = false
                    scope.doAuth = function () {
                        var index = 0,
                        modules = {},
                        indexTmp
                        model.lockSubmit = true
                        model.submitBtnLabel = '正在提交数据，请稍后……'
                        model.modules.forEach(function (mm, k) {
                            var mOpt = model.moduleNames[k]
                            if (!mOpt || mOpt.disbaled || !mOpt.checked)
                                return true
                            mm.forEach(function (m) {
                                if ((m.firstChecked && m.firstLabel) || (m.secondChecked && m.secondLabel) ||
                                    (m.threeChecked && m.threeLabel)) {
                                    //console.log('module ： ' + JSON.stringify(m))
                                    m.auths.forEach(function (a) {
                                        if (a.checked) {
                                            indexTmp = '[' + index + '].'
                                            modules[indexTmp + 'Auth'] = a.id
                                            modules[indexTmp + 'Module'] = m.threeId || m.secondId
                                            modules[indexTmp + 'Role'] = model.currRole.Id
                                            if (m.dataAuth === 'custom') {
                                                m.groups.split(',').forEach(function (g, i) {
                                                    if (g)
                                                        modules[indexTmp + 'RoleDataAuth.Groups[' + i + ']'] = g
                                                })
                                                m.posts.split(',').forEach(function (g, i) {
                                                    if (g)
                                                        modules[indexTmp + 'RoleDataAuth.Posts[' + i + ']'] = g
                                                })
                                                m.users.split(',').forEach(function (g, i) {
                                                    if (g)
                                                        modules[indexTmp + 'RoleDataAuth.Users[' + i + ']'] = g
                                                })
                                            }
                                            modules[indexTmp + 'RoleDataAuth.DataAuthModal'] = m.dataAuth
                                            index++
                                        }
                                    })
                                    if (m.firstId && m.firstChecked) {
                                        indexTmp = '[' + index + '].'
                                        modules[indexTmp + 'Module'] = m.firstId
                                        modules[indexTmp + 'Role'] = model.currRole.Id
                                    }/* else if (mm[0] && mm[0].firstChecked) {
                                        indexTmp = '[' + index + '].'
                                        modules[indexTmp + 'Module'] = mm[0].firstId
                                        modules[indexTmp + 'Role'] = model.currRole.Id
                                    }*/
                                    if (m.secondId && m.secondChecked) {
                                        if (m.firstId) {
                                            index++
                                        }
                                        indexTmp = '[' + index + '].'
                                        modules[indexTmp + 'Module'] = m.secondId
                                        modules[indexTmp + 'Role'] = model.currRole.Id
                                    }
                                    if (m.threeId && m.threeChecked) {
                                        if (m.firstId || m.secondId) {
                                            index++
                                        }
                                        indexTmp = '[' + index + '].'
                                        modules[indexTmp + 'Module'] = m.threeId
                                        modules[indexTmp + 'Role'] = model.currRole.Id
                                    }
                                    if (m.dataAuth === 'custom') {
                                        m.groups.split(',').forEach(function (g, i) {
                                            if (g)
                                                modules[indexTmp + 'RoleDataAuth.Groups[' + i + ']'] = g
                                        })
                                        m.posts.split(',').forEach(function (g, i) {
                                            if (g)
                                                modules[indexTmp + 'RoleDataAuth.Posts[' + i + ']'] = g
                                        })
                                        m.users.split(',').forEach(function (g, i) {
                                            if (g)
                                                modules[indexTmp + 'RoleDataAuth.Users[' + i + ']'] = g
                                        })
                                    }
                                    modules[indexTmp + 'RoleDataAuth.DataAuthModal'] = m.dataAuth
                                    index++
                                }
                            })
                        })
                        //console.log('auth for : ' + JSON.stringify(modules))
                        //if (index) {
                        $.post('/Settings/SetAuthorize/' + model.currRole.Id, modules)
                        .done(function (ret) {
                            model.lockSubmit = false
                            model.submitBtnLabel = lang.SubmitBtn
                            avalon.vmodels.CBCRM.showResult(ret)
                        })
                        //}
                    }
                    scope.setGroupPostChecked = function (treeId, modulevm) {
                        var ztree = $.fn.zTree.getZTreeObj(treeId),
                            checkedIds = [], node
                        if (ztree) {
                            ztree.checkAllNodes(false)
                            if (modulevm.groups) {
                                checkedIds = checkedIds.concat(modulevm.groups.split(','))
                            }
                            if (modulevm.posts) {
                                checkedIds = checkedIds.concat(modulevm.posts.split(','))
                            }
                            if (modulevm.users) {
                                checkedIds = checkedIds.concat(modulevm.users.split(','))
                            }
                            if (checkedIds.length) {
                                for (var i = 0, len = checkedIds.length; i < len; i++) {
                                    node = ztree.getNodeByParam('Id', checkedIds[i])
                                    if (node)
                                        ztree.checkNode(node, true, false)
                                }
                            }
                        } else if (avalon.vmodels.CBCRM.$debug) {
                            avalon.log('未能找到id：' + treeId + ' 部门职位树')
                        }
                    }
                    scope.moduleDataAuthChange = function (e) {
                        var vm = this.$vmodel,
                        modulevm = vm[vm.$itemName],
                        elWrapper = avalon(this),
                        mode = elWrapper.val(),
                        val = elWrapper.val(), treeId, tree
                        if (mode === 'custom' || mode === 'm_custom') {
                            //生成部门、员工树
                            treeId = 'auth' + (modulevm.threeId || modulevm.secondId || elWrapper.attr('id') || elWrapper.attr('for'))
                            //如果已经存在树组件，不再重复创建
                            if (!avalon.vmodels[treeId]) {
                                uicache.push(treeId)
                                uicache.push(treeId + 'panel')
                                avalon.ui.dropDownGroupPostUserTree(this, {
                                    dropDownGroupPostUserTreeId: treeId,
                                    dropDownGroupPostUserTreeOptions: {
                                        treeopts: {
                                            async: {
                                                url: function (treeId, treeNode) {
                                                    return '/Settings/GetGroupPostUser/9050000' //角色权限
                                                },
                                                dataFilter: function (treeId, parentNode, responseData) {
                                                    var ret = [], len, curr
                                                    if (responseData.data && responseData.data.groups.length) {
                                                        ret = ret.concat(responseData.data.groups)
                                                    }
                                                    len = ret.length
                                                    if (len) {
                                                        while (len) {
                                                            curr = ret[--len]
                                                            curr.open = false
                                                            curr.Posts.forEach(function (p, i) {
                                                                curr.Posts[i].ParentId = p.Boss ? p.Boss.Id : p.Group
                                                            })
                                                            ret = ret.concat(curr.Posts)
                                                        }
                                                        ret[0].open = true
                                                    }
                                                    ret.unshift({ Name: '自己', Id: '-1000', Posts: [], checked: true, chkDisabled: true })
                                                    return ret
                                                }
                                            },
                                            check: {
                                                enable: true,
                                                chkboxType: { 'Y': 'ps', 'N': 'ps' }
                                            },
                                            callback: {
                                                onCheck: function (e, treeId, treeNode) {
                                                    var treeObj = $.fn.zTree.getZTreeObj(treeId)
                                                        , nodes = treeObj.getCheckedNodes(true),
                                                    groups = [],
                                                    posts = [],
                                                    users = [],
                                                    m
                                                    nodes.forEach(function (node) {
                                                        switch (node.iconSkin) {
                                                            case 'group':
                                                                groups.push(node.Id)
                                                                break
                                                            case 'post':
                                                                posts.push(node.Id)
                                                                break
                                                            case 'emp':
                                                                users.push(node.Id)
                                                                break
                                                        }
                                                    })
                                                    // console.log(nodes)
                                                    switch (val) {
                                                        case 'm_custom':
                                                            model.modules[modulevm.moduleIndex].forEach(function (m) {
                                                                if (CBCRM.$debug) {
                                                                    avalon.log('label :' + (m.threeLabel || m.secondLabel || m.firstLabel))
                                                                }
                                                                m.groups = groups.join(',')
                                                                m.posts = posts.join(',')
                                                                m.users = users.join(',')
                                                            })
                                                            break
                                                        case 'custom':
                                                            m = model.modules[modulevm.moduleIndex][modulevm.rowIndex]
                                                            m.groups = groups.join(',')
                                                            m.posts = posts.join(',')
                                                            m.users = users.join(',')
                                                            break
                                                    }
                                                },
                                                onAsyncSuccess: function (event, treeId) {
                                                    model.setGroupPostChecked(treeId, modulevm)
                                                }
                                            }
                                        }
                                    }
                                }, [model])
                            } else {
                                model.setGroupPostChecked(treeId + 'zTree', modulevm)
                            }
                            $(this).click()
                        }
                    }
                    scope.cascadeSet = function (curr, lv) {
                        var childNum = 0, checked = $(this).attr('checked') ? true : false
                        switch (lv) {
                            case 0:
                                childNum = curr.firstChildNum
                                // checked = curr.firstChecked
                                break
                            case 1:
                                childNum = curr.secondChildNum
                                // checked = curr.secondChecked
                                break
                            case 2:
                                childNum = curr.threeChildNum
                                // checked = curr.threeChecked
                                break
                        }
                        cascadeCheckModule.call(curr, childNum,
                        curr.moduleIndex, checked, lv)
                    }
                }),
                cascadeWatch = true,
                cascadeCheckModule = function (childMax, moduleIndex, n, lv) {
                    /*级联选择模块*/
                    var m,
                    childTmp = this.rowIndex + childMax,
                    //all = 'all',
                    //onlyMy = 'onlyMy',
                    hasChildChecked = false
                    if (avalon.vmodels.CBCRM.$debug)
                        avalon.log('watching module index :' + moduleIndex + ' row index : ' + this.rowIndex + ' childTmp :'
                            + childTmp)
                    if (this.auths.length) {
                        this.auths.forEach(function (item) {
                            if (n && item.label == "禁分页") return;
                            item.checked = n
                        })
                    }
                    if (lv === 0) {
                        this.firstChecked = n
                        this.secondChecked = n
                        this.threeChecked = n
                    } else if (lv === 1) {
                        this.threeChecked = n
                        m = model.modules[moduleIndex]
                        m[this.secondIndex].secondChecked = n
                        for (var i = 0, cm; cm = m[i++];) {
                            if (cm.secondLabel)
                                hasChildChecked = cm.secondChecked
                            if (avalon.vmodels.CBCRM.$debug)
                                avalon.log('sceondLabel : ' + cm.secondLabel + ' secondChecked : ' + cm.secondChecked
                                    + ' hasChildChecked : ' + hasChildChecked)
                            if (hasChildChecked) break
                        }
                        m[0].firstChecked = hasChildChecked
                    } else if (lv === 2) {
                        this.threeChecked = n
                        m = model.modules[moduleIndex]
                        model.cascadeCheckModule(m)
                    }
                    //model.moduleNames[moduleIndex].dataAuth = this.dataAuth = n ? all : onlyMy

                    if (childMax === 0) return
                    while (childTmp) {
                        --childTmp
                        if (childTmp <= this.rowIndex) break
                        m = model.modules[moduleIndex][childTmp]
                        m.secondChecked = m.threeChecked = n
                        //m.dataAuth = n ? all : onlyMy                        
                        m.auths.forEach(function (item) {
                            if (n && item.label == "禁分页") return;
                            item.checked = n
                        })
                    }
                },
                createIndex = function (modules, auths, moduleNames) {
                    var auth, a, j, i = 0, jLen, len = auths.length,
                    module, m, secondIndex
                    for (; i < len; i++) {
                        auth = auths[i]
                        for (j = 0, jLen = auth.length; j < jLen; j++) {
                            a = auth[j]
                            a.index = j
                            a.moduleIndex = i
                            a.$skipArray = ['moduleIndex', 'rowIndex']
                        }
                    }
                    for (i = 0, len = modules.length; i < len; i++) {
                        module = modules[i]
                        for (j = 0, jLen = module.length; j < jLen; j++) {
                            m = module[j]
                            if (m.secondLabel && m.secondId) {
                                secondIndex = j
                            }
                            m.secondIndex = secondIndex
                            m.$skipArray = ['moduleIndex', 'rowIndex']
                            m.moduleIndex = i
                            m.rowIndex = j
                        }
                    }
                    for (i = 0, len = moduleNames.length; i < len; i++) {
                        moduleNames[i].moduleIndex = i
                    }
                },
                watch = function () {
                    /*model.auths.forEach(function (aitem, i) {
                        aitem.forEach(function (a, i) {
                            a.$watch('checked', function (n) {
                                var index = this.index,
                                    moduleIndex = this.moduleIndex
                                model.modules[moduleIndex].forEach(function (m) {
                                    m.auths[index].checked = n
                                })
                            })
                        })
                    })*/

                    model.$watch('currRole', function () {
                        var rmodule = {}, moduleName,
                        module, moduleId, m, auths, moduleDataMaps = {}, moduleData, cascadeWatch = false
                        if (model.currRole.RoleAuths) {
                            model.currRole.RoleAuths.forEach(function (au) {
                                if (!rmodule[au.Module]) {
                                    rmodule[au.Module] = []
                                }
                                rmodule[au.Module].push(au.Auth)
                                if (au.RoleDataAuth)
                                    moduleDataMaps[au.Module] = au.RoleDataAuth
                            })
                        }
                        cascadeWatch = false
                        for (var i = 0, len = model.moduleNames.length; i < len; i++) {
                            moduleName = model.moduleNames[i]
                            if (!moduleName.checked) continue
                            module = model.modules[i]
                            for (var j = 0, mlen = module.length; j < mlen; j++) {
                                m = module[j]
                                moduleId = m.threeId || m.secondId
                                auths = rmodule[moduleId]
                                if (!auths) {
                                    m.firstChecked = m.secondChecked = m.threeChecked = false
                                    m.groups = m.posts = m.users = ''
                                    m.auths.forEach(function (au) {
                                        au.checked = false
                                    })
                                    continue
                                }
                                if (m.firstId) m.firstChecked = true
                                if (m.secondId) m.secondChecked = true
                                if (m.threeId) {
                                    m.threeChecked = m.secondChecked = true
                                    module[m.secondIndex].secondChecked = true
                                }
                                if (m.firstChecked || m.secondChecked || m.threeChecked) {
                                    module[0].firstChecked = true
                                }
                                moduleData = moduleDataMaps[moduleId]
                                m.auths.forEach(function (au) {
                                    au.checked = auths.indexOf(au.id) > -1
                                })
                                if (moduleData) {
                                    m.dataAuth = moduleData.DataAuthModal
                                    if (avalon.vmodels.CBCRM.$debug)
                                        avalon.log('name :' + (m.firstLabel || m.secondLabel || m.threeLabel)
                                            + ' dataAuth : ' + m.dataAuth)
                                    m.groups = (moduleData.Groups && moduleData.Groups.length)
                                     ? moduleData.Groups.join(',') : ''
                                    m.posts = (moduleData.Posts && moduleData.Posts.length)
                                     ? moduleData.Posts.join(',') : ''
                                    m.users = (moduleData.Users && moduleData.Users.length)
                                     ? moduleData.Users.join(',') : ''
                                }
                            }
                        }
                        cascadeWatch = true
                    })
                    model.modules.forEach(function (item, i) {
                        item.forEach(function (m, rowIndex) {
                            if (avalon.vmodels.CBCRM.$debug)
                                avalon.log('watch before module index :' + m.moduleIndex + ' row index : ' + m.rowIndex)
                            m.$watch('dataAuth', function (n) {
                                switch (n) {
                                    case 'onlyMy':
                                        this.authDesc = '授权角色访问自己的数据'
                                        break
                                    case 'all':
                                        this.authDesc = '授权角色访问全部数据'
                                        break
                                    case 'custom':
                                        this.authDesc = '授权角色访问指定部门/职位/员工的数据'
                                        break
                                }
                            })
                        })
                    })

                    model.moduleNames.forEach(function (module) {
                        module.$watch('dataAuth', function (n) {
                            var tmp = n.replace('m_', '')
                            if (tmp === 'custom' && avalon.vmodels.CBCRM.$debug)
                                avalon.log('处理模块索引：' + this.moduleIndex + ' 指定部门、员工数据集权限')
                            else if (avalon.vmodels.CBCRM.$debug)
                                avalon.log('处理模块索引：' + this.moduleIndex + ' 数集权限：' + tmp)
                            model.modules[this.moduleIndex].forEach(function (m) {
                                m.dataAuth = tmp
                            })
                        })
                    })
                }
            model.currRole = modelFactory.create('RoleAuths')

            CBCRM.onLoadModuleBefore = function () {
                uicache.forEach(function (ui) {
                    var vm = avalon.vmodels[ui]
                    if (vm) {
                        if (typeof vm.destroy === 'function')
                            vm.destroy()
                        else
                            delete avalon.vmodels[ui]
                    }
                })
                delete avalon.vmodels.Authorize
                uicache = null
            }
            CBCRM.fillContent(tmpl, lang, contentId, module, model)
            //if (CBCRM.$debug) {

            require('allmodule', function (all) {
                console.log(all);
                createIndex(all.modules, all.auths, all.moduleNames)
                model.modules = all.modules
                model.auths = all.auths
                model.moduleNames = all.moduleNames
                watch()
            })

            //}

            model.$watch('all', function (n) {
                model.moduleNames.forEach(function (item) {
                    item.checked = n
                })
            })
            loadRole()
        },

        /// <summary>
        /// 登录日志
        /// </summary>
        LoginLogs: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM, vmid = "settingloginlogs";
            var model = avalon.define(vmid, function (vm) {
                vm.memberShip = CBCRM.memberShip.$model;
                vm.keyword = "";
                vm.grid1 = createGrid({
                    url: "/Settings/LoginLogs",
                    pageid: vmid + "_grid1_page",
                    createQuery: function () {
                        var data = { keyword: model.keyword };
                        return data;
                    }
                })
                vm.clearLog = function () {
                    messageBox.confirm2("清空日志确认！<br />您确定要清空登录日志吗？此操作不可恢复！", function () {
                        $.post("/Settings/ClearLoginLogs", { type: 1 }, function (ret) {
                            CBCRM.showResult(ret);
                            if (ret.result) {
                                model.grid1.doSearch();
                            }
                        });
                    });
                }
            })
            model.grid1.init();
            CBCRM.fillContentBefore = function (tmpl, lang, contentId, module, vmodel) {
                var content = $("#right");
                if (content.length == 0) return true;
                content.html(tmpl);
                avalon.scan(content[0]);
                return false;
            }
            CBCRM.fillContent(tmpl, lang, contentId, module, model);
            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.LoginLogs = null
            }
            $('#left_menu_top').html('<h2>系统日志</h2>').show()
        },

        /// <summary>
        /// 操作日志
        /// </summary>
        ActionLogs: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM, vmid = "settingactionlogs";
            var model = avalon.define(vmid, function (vm) {
                vm.memberShip = CBCRM.memberShip.$model;
                vm.keyword = "";
                vm.grid1 = createGrid({
                    url: "/Settings/ActionLogs",
                    pageid: vmid + "_grid1_page",
                    createQuery: function () {
                        var data = { keyword: model.keyword };
                        return data;
                    }
                })
                vm.clearLog = function () {
                    messageBox.confirm2("清空日志确认！<br />您确定要清空操作日志吗？此操作不可恢复！", function () {
                        $.post("/Settings/ClearActionLogs", { type: 0 }, function (ret) {
                            CBCRM.showResult(ret);
                            if (ret.result) {
                                model.grid1.doSearch();
                            }
                        });
                    });
                }
            })
            model.grid1.init();
            CBCRM.fillContentBefore = function (tmpl, lang, contentId, module, vmodel) {
                var content = $("#right");
                if (content.length == 0) return true;
                content.html(tmpl);
                avalon.scan(content[0]);
                return false;
            }
            CBCRM.fillContent(tmpl, lang, contentId, module, model);
            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.LoginLogs = null
            }
            $('#left_menu_top').html('<h2>系统日志</h2>').show()
        },

        /// <summary>
        /// 应用程序日志
        /// </summary>
        APPLogs: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM,
            model = avalon.define('settingapplogs', function (vm) {
                vm.info = ''
                var nowlog = GetDateTimeYMD() + '.log'
                vm.nowlog = nowlog
                vm.currentLogs = nowlog
                vm.logsList = []
                vm.del = function () {
                    messageBox.confirm2("删除日志确认！<br />您确定要删除当前日志吗？此操作不可恢复！", function () {
                        $.post("/Settings/DelAPPLogs", { fileName: model.currentLogs }, function (ret) {
                            CBCRM.showResult(ret);
                            if (ret.result) {
                                model.currentLogs = nowlog;
                            }
                        });
                    });
                }
                vm.clear = function () {
                    messageBox.confirm2("清空日志确认！<br />您确定要删除当前日志吗？此操作不可恢复！", function () {
                        $.post("/Settings/ClearAPPLogs", {}, function (ret) {
                            CBCRM.showResult(ret);
                            if (ret.result) {
                                if (model.currentLogs == nowlog) GetAPPLogsList();
                                model.currentLogs = nowlog;
                            }
                        });
                    });
                }
                vm.db = false;
                vm.viewlog = function (logsName) {
                    if (logsName == null) logsName = nowlog;
                    model.db = true;
                    GetAPPLogsList();
                }
                vm.logChange = function () {
                    var logsName = this.value;
                    model.viewlog(logsName);
                }
            })
            function GetAPPLogsList() {
                var data = { 'logsName': model.currentLogs }
                if (model.db) data.db = model.db;
                $.get('/Settings/APPLogs',data , function (ret) {
                    model.info = ret.data.info
                    model.logsList = ret.data.logsList
                    var tmp = model.currentLogs;
                    model.currentLogs = "";
                    model.currentLogs = tmp;
                })
            }

            GetAPPLogsList()
            CBCRM.fillContentBefore = function (tmpl, lang, contentId, module, vmodel) {
                var content = $("#right");
                if (content.length == 0) return true;
                content.html(tmpl);
                avalon.scan(content[0]);
                return false;
            }
            CBCRM.fillContent(tmpl, lang, contentId, module, model)
            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.APPLogs = null
            }
            $('#left_menu_top').html('<h2>应用程序日志</h2>').show()
        },

        /* 扩展字段 */
        ExpandoField: function (tmpl, lang, contentId, module) {
            var CBCRM = avalon.vmodels.CBCRM,
            model = avalon.define('ExpandoField', function (vm) {
                vm.$skipArray = ['lang']
                vm.lang = lang
                vm.ADD = true
                vm.DELETE = true
                vm.dataSource = []
                vm.checkAll = false
                vm.entity = {}
                vm.customerValidator = false
                vm.validators = []
                vm.types = []
                vm.module = ''
                vm.allCheckOptions = false
                vm.hasOptions = false
                vm.modules = []
                vm.addOption = function () {
                    if (!model.entity.Options.length)
                        model.entity.Options = []
                    model.entity.Options.push(modelFactory.create('Options'))
                }
                vm.removeOption = function () {
                    var has = false,
                        item, len = model.entity.Options.length
                    while (len) {
                        item = model.entity.Options[--len]
                        if (!has)
                            has = item.checked
                        if (item.checked)
                            model.entity.Options.splice(len, 1)
                    }
                    if (!model.entity.Options.length)
                        model.allCheckOptions = false
                    if (!has)
                        messageBox.warning('请选择要删除的选项')
                }
                vm.run = function (url) {
                    var d = messageBox.openHtml(model.entity.Id ? '编辑扩展字段' : '新增扩展字段', '600px', '', '', [{
                        name: lang.SubmitBtn,
                        focus: true,
                        callback: function () {
                            var ntest = {};
                            try{
                                eval("ntest."+model.entity.Name);
                            } catch (ex) {
                                messageBox.error("字段名格式非法，请使用字母、数字、下划线组合成字段名，并且不能以数字开头。");
                                return false;
                            }
                            var data = avalon.mix(true, {}, model.entity.$model)
                            , i = 0, item, keyTmp = 'Options[j].Key', valTmp = 'Options[j].Value'
                            , key, val
                            data.Module = model.module
                            for (; item = data.Options[i]; i++) {
                                key = item.Key.trim()
                                val = item.Value.trim()
                                data[keyTmp.replace('j', i)] = key
                                data[valTmp.replace('j', i)] = val || key
                            }
                            delete data.Options
                            $.post(url || '/Settings/AddExpandoField', data)
                            .done(function (ret) {
                                CBCRM.showResult(ret, function () {
                                    avalon.vmodels.listPage.reload()
                                    messageBox.close()
                                })
                            })
                            return false
                        }
                    }], function () {
                        model.entity = modelFactory.create('ExpandoFields')
                        model.entity.Options.removeAll()
                        model.hasOptions = false
                    }),
                    $content = $(d.content())
                    $content.attr('ms-include', 'inputForm')
                    d.position('50%', 10)
                    avalon.scan($content[0], model)
                    bindWatch()
                }
                vm.editField = function () {
                    var vm = this.$vmodel,
                        item = vm[vm.$itemName],
                        url = '/Settings/EditExpandoField/' + item.Id
                    $.get(url)
                    .done(function (ret) {
                        var tmp
                        if (ret.result) {
                            model.entity = ret.data
                            model.run(url)
                            if (model.entity.Type) {
                                tmp = model.entity.Type
                                model.entity.Type = ''
                                model.entity.Type = tmp
                            }
                        } else {
                            CBCRM.showResult(ret)
                        }
                    })
                }
                vm.addField = function () {
                    model.run()
                }
                vm.doRender = function () {
                    messageBox.confirm('您确定要重新生成页面吗？', function () {
                        $.post('/Settings/RenderTmpl', { module: model.module })
                        .done(function (ret) {
                            CBCRM.showResult(ret)
                        })
                    })
                }
                vm.doback = function () {
                    messageBox.confirm('您确定要还原为系统默认表单吗？', function () {
                        $.post('/Settings/RenderSysDefault', { module: model.module })
                        .done(function (ret) {
                            CBCRM.showResult(ret)
                        })
                    })
                }
                vm.dosave = function () {
                    var postData = {}
                        , dataTmpl = 'models[i].'
                        , datas = model.dataSource.$model
                        , key = ''
                    for (var i = 0, item; item = datas[i]; i++) {
                        key = dataTmpl.replace('i', i)
                        postData[key + 'Id'] = item.Id
                        postData[key + 'Display'] = item.Display
                        postData[key + 'IsAvailable'] = item.IsAvailable
                        postData[key + 'IsRequire'] = item.IsRequire
                        postData[key + 'IsSearch'] = item.IsSearch
                        postData[key + 'Order'] = item.Order
                        postData[key + 'Tab'] = item.Tab
                    }
                    $.post('/Settings/SaveExpandoField', postData)
                        .done(function (ret) {
                            CBCRM.showResult(ret)
                        })
                }
                vm.doRemove = function () {
                    var vm = this.$vmodel
                        , itemVM = vm[vm.$itemName]
                    messageBox.confirm('您确定要删除选中的自定义字段吗？', function () {
                        $.post('/Settings/DelExpandoField', { id: itemVM.Id })
                        .done(function (ret) {
                            CBCRM.showResult(ret, function () {
                                avalon.vmodels.listPage.reload()
                            })
                        })
                    })
                }
                vm.doRemoveAll = function () {
                    var data = model.dataSource
                        , postTmp = 'ids[j]'
                        , ids = {}
                        , j = 0
                    for (var i = 0, item; item = data[i++];) {
                        if (item.checked) {
                            ids[postTmp.replace('j', j)] = item.Id
                            j++
                        }
                    }
                    if (j > 0) {
                        messageBox.confirm('您确定要删除选中的自定义字段吗？', function () {
                            $.post('/Settings/DelExpandoField', ids)
                            .done(function (ret) {
                                CBCRM.showResult(ret, function () {
                                    avalon.vmodels.listPage.reload()
                                })
                            })
                        })
                    }
                }
                vm.listOpts = {
                    paging: function () {
                        var data = {
                            limit: this.pagesize,
                            page: this.currentindex + 1
                        }
                        if (model.module)
                            data.module = model.module
                        loadData(data)
                    }
                }
            }),
            loadData = function (data) {
                $.post('/Settings/ExpandoField', data)
                .done(function (ret) {
                    if (ret.result) {
                        model.dataSource = CBCRM.parseGridData(ret.data.Source)
                        model.ADD = ret.data.ADD
                        model.DELETE = ret.data.DELETE
                        avalon.vmodels.listPage.total = ret.data.RecordTotal
                    }
                })
            },
            bindWatch = function () {
                model.entity.$watch('ValidateModa', function (n, o) {
                    if (n !== o) {
                        if (n) {
                            model.customerValidator = n === '1'
                        }
                    }
                })
                model.entity.$watch('Type', function (n, o) {
                    if (n !== o) {
                        model.hasOptions = (n === 'multi-radio' || n === 'multi-checkbox'
                            || n === 'select')
                    }
                    if (n == "editor") model.entity.IsSignalLine = true;
                })
            }
            model.types.push({ label: '单行文本', val: 'single-text' })
            model.types.push({ label: '多行文本', val: 'multi-text' })
            model.types.push({ label: '多行文本带编辑器', val: 'editor' })
            model.types.push({ label: '日期', val: 'date' })
            model.types.push({ label: '文件上传', val: 'upload' })
            //model.types.push({ label: '数字', val: 'num' })
            model.types.push({ label: '复选框', val: 'checkbox' })
            model.types.push({ label: '多项单选', val: 'multi-radio' })
            model.types.push({ label: '多项多选', val: 'multi-checkbox' })
            model.types.push({ label: '下拉选择', val: 'select' })

            //model.validators.push({ label: '不验证', val: '0' })
            //model.validators.push({ label: '国内电话', val: 'phone' })
            //model.validators.push({ label: '手机电话', val: 'mobile' })
            //model.validators.push({ label: '身份证号', val: 'idcard' })
            //model.validators.push({ label: 'EMail', val: 'email' })
            //model.validators.push({ label: '自定义', val: '1' })

            model.modules.push({ val: 'Customer', text: '客户' })

            model.module = 'Customer'

            avalon.filters.toTypeDisplay = function (val) {
                var display = '', i = 0, item
                for (; item = model.types[i++];) {
                    if (val == item.val)
                        display = item.label
                    if (display)
                        break
                }
                return display
            }

            model.entity = modelFactory.create('ExpandoFields')

            bindWatch()

            model.$watch('allCheckOptions', function (n) {
                var i = 0, item
                for (; item = model.entity.Options[i++];) {
                    item.checked = n
                }
            })

            model.$watch('module', function (n, o) {
                var pagingVm
                if (n === o) {
                    pagingVm = avalon.vmodels.listPage
                    pagingVm.reload()
                }
            })

            model.$watch('checkAll', function (n, o) {
                model.dataSource.forEach(function (c) {
                    c.checked = n
                })
            })

            CBCRM.fillContent(tmpl, lang, contentId, module, model)
            loadData({ module: model.module })
            CBCRM.onLoadModuleBefore = function () {
                avalon.vmodels.ExpandoField = null
                delete avalon.filters.toTypeDisplay
            }
        }
    }
    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);
    }
    avalon.filters.SmsChannelformat = function (index) {
        var o = { 1: "ML", 2: "", 3: "YF", 4: "WN" };
        var s = o[index] ? "(" + o[index] + ")" : "";
        return s;
    }
    return Settings
})