define('Customer', ['modelFactory', 'json', 'ConditionFactory', 'plugins', 'Jpin', 'common', 'leftMenu', 'kindedit', 
   'jqselect', 'jqPrint', 'cookie', 'leftMenu', 'lightbox', 'jcal'], function (factory, json, conditionFactory, plugins) {
       var customerType = [{ label: '企业', val: '0' }
                           , { label: '个人', val: '1' }
                           , { label: '事业单位', val: '2' }
                           , { label: '政府机构', val: '3' }
                           , { label: '社会团体', val: '4' }
       ],
       //客户字典id与权限id的对应关系
       cuDiRes = { 10107: 1020101, 10103: 1020201, 10131: 1020301, 10132: 1020401, 10133: 1020501, 10134: 1020601, 10135: 1020701, 11170: 1020801 },
       getCuRes=function(){
           var res=[];
           for(var key in cuDiRes){
               var re=cuDiRes[key]
               if(typeof(re)=="number")res.push(re);
           }
           return res.join(",");
       },
           setMenu = function (menuId, root, curr) {
               var menu = avalon.vmodels[menuId],
               CBCRM = avalon.vmodels.CBCRM,
               menus
               if (menu) {
                   if (root) {
                       menus = CBCRM.getMenus(root)
                       menu.menus.removeAll()
                       menus.children.forEach(function (m) {
                           if (m.isAction) return true
                           menu.menus.push(m)
                       })
                       menu.module = '全部客户'
                   }
                   menu.menus.forEach(function (m) {
                       m.selected = m.id === curr
                   })
               }
           },
           upload = function () {
               var dialogId
                    , vmodels = this.$vmodels
                    , data = $(this).data()
                    , duplex = data.duplex
                    , CBCRM = avalon.vmodels.CBCRM
               CBCRM.disableModuleBefore = true
               CBCRM.fillContentBefore = function (tmpl, lang, contentId, module, vm) {
                   var d = messageBox.openHtml('上传文件', '1000px', '500px', tmpl),
                   $content = $(d.content())
                   avalon.scan($content[0], vm)
                   dialogId = d.config.id
                   return false;
               }
               CBCRM.loadModule('/Upload/Center')
               CBCRM.onModuleReady = function (data) {
                   if (!avalon.vmodels.upload) return;
                   avalon.vmodels.upload.itemSelected = function (node, data, file) {
                       CBCRM.disableModuleBefore = false
                       if (duplex) {
                           var props = duplex ? duplex.split('.') : ''
                               , vms = vmodels
                               , prop = null
                               , nearVM = null
                               , VM = null
                               , VMIndex = 0
                               , VMLen = vms.length
                               , i = 0
                               , propLen = 0
                               , end = false
                           propLen = props.length
                           do {
                               nearVM = vms[VMIndex]
                               for (i = 0; prop = props[i++];) {
                                   if (i === propLen) {
                                       duplex = prop
                                       end = true
                                       break
                                   }
                                   if (nearVM.hasOwnProperty(prop)) {
                                       nearVM = nearVM[prop]
                                   }
                               }
                               if (end)
                                   break
                               VMIndex++
                           } while (VMIndex < VMLen)
                           try {
                               if (nearVM) {
                                   nearVM[duplex] = '/upload/' + file.Path
                               }
                           } catch (e) {
                               avalon.log(e)
                           }
                       }
                       /*只关闭上传组件弹出窗*/
                       messageBox.close(dialogId)
                   }
               }
           },
           initSociall = function (m, ret) {
               m.category.removeAll()
               m.customerEntity.Type = ''
               m.customerEntity.Type = '1'
               if (!m.customerEntity.Id) {
                   m.customerEntity.CategoryId = ''
                   m.customerEntity.SuperiorCategoryId = 11170 //社会关系
               }
           },
           initCompetitor = function (m, ret) {
               var marketPos = ret.data.Dicts.MarketPosition,
               thRaty = avalon.vmodels.threatenRaty
               if (!m.customerEntity.Id) {
                   m.category.removeAll()
                   m.customerEntity.CategoryId = ''
                   m.customerEntity.SuperiorCategoryId = 10135 //竞争对手
               }
               if (marketPos.length) {
                   marketPos.forEach(function (p) {
                       m.marketPosition.push(p)
                   })
               }
               if (m.customerEntity.MarketPosition)
                   m.customerEntity.MarketPosition += ''
               /*绑定威胁估值*/
               if (thRaty && m.customerEntity.Id) {
                   thRaty.val = m.customerEntity.Threaten
               }
           },
           initAdvertising = function (m, ret) {
               if (!m.customerEntity.Id) {
                   m.category.removeAll()
                   m.customerEntity.CategoryId = ''
                   m.customerEntity.SuperiorCategoryId = 10134 //媒体资源
               }
           },
           initSupply = function (m, ret) {
               var propMap = {
                   quality: m.customerEntity.Quality
                   , ability: m.customerEntity.Ability
                   , price: m.customerEntity.Price
                   , technology: m.customerEntity.Technology
                   , service: m.customerEntity.Service
                   , reputation: m.customerEntity.Reputation
                   , cooperation: m.customerEntity.Cooperation
               }, raty = 'Raty', ui, val, quas = []
               if (!m.customerEntity.Id) {
                   m.category.removeAll()
                   m.customerEntity.CategoryId = ''
                   m.customerEntity.SuperiorCategoryId = 10133 //供应商
               }
               for (var prop in propMap) {
                   ui = avalon.vmodels[prop + raty]
                   val = propMap[prop]
                   if (ui && val) {
                       ui.val = val
                   }
               }
               m.suppliersStage = ret.data.Dicts.SuppliersStage
               m.supplierLevel = ret.data.Dicts.SuppliersLevel
               m.qualification = ret.data.Dicts.Qualification
               if (m.customerEntity.Qualification && m.customerEntity.Qualification.length) {
                   m.customerEntity.Qualification.forEach(function (q) {
                       quas.push(q + '')
                   })
                   m.customerEntity.Qualification.removeAll()
                   m.customerEntity.Qualification = quas
               }
               m.customerEntity.SupplierLevel += ''
           },
           viewCustomer = function (id) {
               var url = "/Customer/DetailCustomer/" + id;
               goto(url, true);
           },
           sendSms = function (mobile) {
               var url = "/Tools/Message/" + mobile + "/send";
               goto(url, true);
           }, getGridChecked = function (rows) {
               var list = []
               rows.forEach(function (c) {
                   if (c.checked) list.push(c)
               });
               return list;
           },
           //只要部门和用户
            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
            }
       Customer = {
           //通用服务（尝试）
           Service:function(){
               var baseUrl = "/Customer/",
                   CBCRM = avalon.vmodels.CBCRM;
               this.MoveToInternational= function (ids,callback) {
                   if (!ids || ids.length == 0) {
                       messageBox.error("请选择需要放入公海的客户！");
                       return;
                   }
                   var data=jsonToSubmit("ids",ids);
                   var msg = prompt("请输入放入公海的原因，如果不用原因请直接点击[确定],要放弃本次操作请点击[取消]");
                   if (msg == null) return;
                   data.msg = msg;
                   var url = baseUrl + "MoveToInternational";
                   $.post(url, data, function (ret) {
                       CBCRM.showResult(ret,callback);
                   });
               }
           },
           //客户动态
           Dynamic: function (tmpl, lang, contentId, module) {
               var that = this
               , CBCRM = avalon.vmodels.CBCRM
               , model = null

               delete avalon.vmodels.Dynamic
               model = avalon.define('Dynamic', function (vm) {
                   vm.entityList = []
               })

               CBCRM.fillContent(tmpl, lang, contentId, module, model)
               return model
           },
           /*联系人*/
           Contacts: function (tmpl, lang, contentId, module,paramData) {
               var that = this, detail
               var CBCRM = avalon.vmodels.CBCRM,
               conditions = conditionFactory.create('Contacts'),
               init = false, model, detail
               conditions.conditionChanged = function (item, conditions) {
                   //重写查询条件改变事件
                   model.queryData = conditions
                   model.loadData(model.queryData)
               }
               var action = that.params.action, id = that.params.id;
               model = CBCRM.define('Contacts', function (scope) {
                   avalon.mix(true, scope, conditions)
                   scope.$skipArray = ['lang', 'loadCustomer', 'queryData']
                   scope.lang = lang
                   scope.$action = "";
                   scope.destroy = function () {
                       delete avalon.vmodels.Contacts;
                   }
                   scope.customerName = ''
                   scope.customers = []
                   scope.sendSms = function (mobile) {
                       var m = model.entity;
                       if (!m.Id) {
                           var vm = this.$vmodel, m = vm[vm.$itemName];
                       }
                       var d = model.getBirthday(m.Birthday);
                       var modelc = {
                           '姓名': m.Name, '称谓': m.AppellationName, '部门': m.Department, '职位': m.Post,
                           '对应客户': m.CustomerName, '生日': d, '性别': m.Sex == 0 ? "男" : "女"
                       };
                       CBCRM.sendSmsTmpl("联系人", mobile, modelc);
                   }
                   scope.sendSmsMulti = function () {
                       var list = getGridChecked(model.contacts);
                       if (!list.length) {
                           messageBox.error('请选择数据。');
                           return;
                       }
                       var mos = [], listData = [];
                       list.forEach(function (m) {
                           var mobile = m.MobileNumber1;
                           if (mobile && gRegExp.mobile.test(mobile)) {
                               mos.push(mobile);
                               var d = model.getBirthday(m.Birthday);
                               var modelc = {
                                   '姓名': m.Name, '称谓': m.AppellationName, '部门': m.Department, '职位': m.Post,
                                   '对应客户': m.CustomerName, '生日': d, '性别': m.Sex == 0 ? "男" : "女"
                               };
                               listData.push({ mobile: mobile, model: modelc });
                           }
                       });
                       var tableName = "联系人";
                       CBCRM.sendSmsMulti(tableName, mos.join(","), listData);
                   }
                   scope.getBirthday = function (d) {
                       if (d) {
                           try {
                               d = new Date(d);
                               d = (d.getMonth() + 1) + '-' + d.getDate();
                           } catch (ex) {
                               d = '';
                           }
                       } else {
                           d = '';
                       }
                       return d;
                   }
                   /*公用按钮权限*/
                   scope.ADD = true
                   scope.DELETE = true
                   scope.NOPAGE = false
                   /*联系人*/
                   scope.entity = {}
                   scope.cardTypes = []
                   scope.contactRoles = []
                   scope.titles = []
                   scope.readonly = false
                   scope.letters = [];
                   scope.nameLetters = {};
                   scope.viewPicture = function (e) {
                       var $toView = $("#toView")
                       $toView.lightbox_me({
                           centered: true,
                           zIndex: 3000
                       })
                       e.preventDefault();
                   }
                   scope.toCustomerDetail = function () {
                       messageBox.close()
                       avalon.router.navigate('/Customer/DetailCustomer/' + model.entity.CustomerId)
                   }
                   scope.uploadPic = function () {
                       var upwin=CBCRM.upload(true, function (node, data, file) {
                           console.log(node);
                           console.log(data);
                           model.entity.Picture = model.entity.Thumbnail = '/Upload/' + file.Path;
                           upwin.close();
                       });
                   }
                   scope.pCustomerOpts = {
                       treeopts: {
                           callback: {
                               onClick: function (e, id, node) {
                                   model.entity.CustomerName = node.Name
                                   model.entity.CustomerId = node.Id
                               }
                           }
                       }
                   }
                   scope.selectCustomer = function () {
                       var listData = [];
                       if (model.entity.CustomerId) listData.push({ id: model.entity.CustomerId });
                       plugins.selectCustomer({
                           listData:listData,
                           callback: function (list) {
                               var item = list[0];
                               model.entity.CustomerName = item.Name
                               model.entity.CustomerId = item.Id
                               return true;
                           }
                       });
                   }
                   scope.birthOpts = {
                       onSelect: function (date, formatDate, format) {
                           model.entity.Birthday = formatDate
                       },
                       format: '%Y-%m-%d'
                   }
                   scope.goto = goto;
                   scope.getPY = function () {
                       var $that = $(this), py
                       if ($that.val()) {
                           py = $that.toPinyin()
                           model.entity.FirstName = model.entity.Name.substr(0, 1)
                           model.entity.FirstNameLetter = py.substr(0, 1)
                           avalon.log('FirstName : ' + model.entity.FirstName
                               + ' FirstNameLetter : ' + model.entity.FirstNameLetter)
                       }
                   }
                   scope.onEnter = function (e) {
                       if (e.keyCode == 13) {
                           model.queryData = model.createDyQuery()
                           model.loadData(model.queryData);
                       }
                   }
                   scope.action = "";
                   scope.init = function (id) {
                       $.post('/Customer/InitContacts/' + (id || ''))
                       .done(function (ret) {
                           if (!ret.result) {
                               CBCRM.showResult(ret);
                               return;
                           }
                           var dicts = dicts = ret.data.dicts,
                           formatFields = ['AppellationId', 'IdCardType', 'ContactRoleId', 'Sex']
                           if (dicts) {
                               model.cardTypes = dicts.IdCardType
                               model.contactRoles = dicts.ContactRole
                               model.titles = dicts.Appellation
                           }
                           if (ret.data.contacts) {
                               formatFields.forEach(function (f) {
                                   var val = ret.data.contacts[f]
                                   if (val || val === 0) {
                                       ret.data.contacts[f] += ''
                                   }
                               })
                               model.entity = avalon.mix({}, model.entity.$model, ret.data.contacts)
                               if (model.entity.Picture) {
                                   model.entity.Thumbnail = model.entity.Picture
                                   model.entity.hasPicture = true
                               }
                           } else {
                               //model.entity.IdCardType = model.cardTypes[0].Id
                               model.entity.ContactRoleId = getDefDict(model.contactRoles);
                               model.entity.AppellationId = ""
                           }
                           if (model.action != "view") {
                               var d = messageBox.openHtml(id ? '编辑联系人' : '新增联系人', '800px', '600px', '', [{
                                   name: '提交保存',
                                   focus: true,
                                   callback: function () {
                                       var url = id ? '/Customer/UpdateContact/' + id : '/Customer/SetContact',
                                       data = avalon.mix({}, model.entity.$model)
                                       data['Customer.Id'] = data.CustomerId
                                       delete data.AddBy
                                       delete data.AddTime
                                       $.post(url, data, function (ret) {
                                           CBCRM.showResult(ret, function () {
                                               if (d) d.close();
                                               if (paramData && paramData.onSave) paramData.onSave(ret, model.entity.$model)
                                               if (paramData && paramData.reloadCustomer) paramData.reloadCustomer();
                                               if (!isFill) return;
                                               model.loadData(model.queryData);
                                               getContactsFirstName();
                                           })
                                       })
                                       return false
                                   }
                               }], function () {
                                   destroyui(['Contacts_setParetCustomer', 'birthDay']);
                                   model.entity.Id = '';
                               }),
                               $content = $(d.content())
                               //$content.attr('ms-include', 'inputContacts')
                               var inputtmpl = $(tmpl).find("#inputContacts").text();
                               $content.html(inputtmpl);
                               $content.parent().css('textAlign', 'left')
                               avalon.scan($content[0], model)
                           } else {
                               d = messageBox.openHtml('查看联系人', '735px', '540px', '', []),
                               $content = $(d.content());
                               //$content.attr('ms-include', 'viewContacts')
                               var viewtmpl = $(tmpl).find("#viewContacts").text();
                               $content.html(viewtmpl);
                               $content.parent().css('textAlign', 'left')
                               $content.css('paddingRight', "0px").css('paddingLeft', "20px")
                               avalon.scan($content[0], model)
                           }
                       })
                   }
                   scope.toDetail = function (id) {
                       model.action = "view";

                       model.init(id)
                   }
                   scope.toEdit = function () {
                       model.action = "edit";
                       var vm = this.$vmodel,
                       item = vm[vm.$itemName]
                       model.entity = factory.create('Contacts');
                       model.entity.Id = item.Id
                       model.run()
                   }
                   scope.toAdd = function () {
                       model.action = "add";
                       model.entity = factory.create('Contacts');
                       model.run();
                   }
                   scope.run = function () {
                       var id = model.entity.Id,
                           customerid = that.params.id
                       /*赋值对应客户*/
                       if (customerid && detail) {
                           model.entity.CustomerId = customerid
                           model.entity.CustomerName = detail.customerEntity.Name
                       }
                       model.entity.Picture = model.entity.Thumbnail = '/Content/Themes/Base/Images/contract_default.png'
                       model.init(id)
                   }
                   scope.showCondition = true
                   scope.contacts = []
                   scope.checkAll = false
                   scope.contactOpts = {
                       paging: function (pageIndex,pageSize) {
                           model.queryData = model.createDyQuery()
                           model.queryData.page = pageIndex
                           model.queryData.limit = pageSize
                           model.loadData(model.queryData)
                       },
                       initload: false
                   }

                   scope.queryData = {}
                   scope.doRemove = function () {
                       var vm = this.$vmodel,
                       item = vm[vm.$itemName]
                       if (item.Id) {
                           messageBox.confirm('您确定要移除选中的联系人吗？', function () {
                               $.post('/Customer/ContactToRecycleBin/' + item.Id)
                               .done(function (ret) {
                                   CBCRM.showResult(ret, function () {
                                       if (ret.result) {
                                           model.loadData(model.queryData);
                                           getContactsFirstName();
                                           if (paramData && paramData.reloadCustomer) paramData.reloadCustomer();
                                       }
                                   })
                               })
                           })
                       }
                   }
                   scope.doRemoveAll = function () {
                       var ids = []
                       model.contacts.forEach(function (c) {
                           if (c.checked) {
                               ids.push(c.Id)
                           }
                       })
                       if (!ids.length) {
                           messageBox.error('请选择要移除的联系人。')
                       } else {
                           messageBox.confirm('您确定要移除选中的联系人吗？', function () {
                               var data = {}, tmp = 'ids[j]'
                               ids.forEach(function (id, i) {
                                   data[tmp.replace('j', i)] = id
                               })
                               $.post('/Customer/ContactToRecycleBin/', data)
                               .done(function (ret) {
                                   CBCRM.showResult(ret, function () {
                                       if (ret.result) {
                                           model.loadData(model.queryData);
                                           getContactsFirstName();
                                           if (paramData && paramData.reloadCustomer) paramData.reloadCustomer();
                                       }
                                   })
                               })
                           })
                       }
                   }
                   /*查询客户*/
                   scope.findCustomer = function () {
                       model.loadData({
                           onlyCustomer: true,
                           customerName: model.customerName
                       })
                   }
                   scope.toEnter = function (e) {
                       if (e.keyCode === 13)
                           model.findCustomer()
                   }
                   scope.findByLetter = function (letter) {
                       model.removeConditions("firstName");
                       model.addConditions("letter", "首字母：" + letter, letter);
                   }
                   scope.findByFirstName = function (firstName) {
                       model.removeConditions("letter");
                       model.addConditions("firstName", "姓：" + firstName, firstName);
                   }
                   scope.setedCondition = function (key) {
                       if (key == "birthday") {
                           model.removeConditions("birthdayDate");
                       }
                   }
                   scope.addConditions = function (name, label, value, index) {
                       if (index == null) index = 0;
                       var condition = model[name].items[index];
                       condition.label = label
                       condition.val = value;
                       model.currConditions[name] = ''
                       model.currConditions[name] = label
                       model.queryData = model.createDyQuery()
                       model.loadData(model.queryData)
                   }
                   scope.removeConditions = function (name, loaddata) {
                       var condition = model[name];
                       condition.items.forEach(function (c, i) {
                           c.curr = i === 0;
                       });
                       model.currConditions[name] = '';
                       if (loaddata) {
                           model.queryData = model.createDyQuery()
                           model.loadData(model.queryData)
                       }
                   }
                   scope.grid1 = { gridmsg: lang.LoadingMsg };
                   scope.loadData = function (data) {
                       model.grid1.gridmsg = lang.LoadingMsg;
                       var url = '/Customer/Contacts/'
                       if (!init) {
                           data.init = init = true
                       }
                       if (action == "customer" && id !== '0')
                           url += id;
                       $.post(url, data)
                       .done(function (ret) {
                           var dicts
                           if (ret.result) {
                               //if (ret.data.customers && ret.data.customers.Source) {
                               //    model.customers = ret.data.customers.Source
                               //    avalon.vmodels.customerPage.total = ret.data.customers.RecordTotal
                               //}
                               if (ret.data.opts && ret.data.opts.length) {
                                   for (var i = 0, opt; opt = ret.data.opts[i++];) {
                                       if (model[opt.Key] != null)
                                           model[opt.Key] = opt.Value
                                   }
                               }
                               var rows = ret.data.contacts.Source;
                               if (rows) {
                                   model.grid1.gridmsg = rows.length == 0 ? lang.NoListData : "";
                                   model.contacts.removeAll()
                                   rows.forEach(function (cc) {
                                       cc.DetailCustomerUrl = ''
                                       cc.checked = false
                                       model.contacts.push(cc)
                                   })
                                   var page = avalon.vmodels.contactPage;
                                   if (model.NOPAGE) {
                                       if (page && page.destroy) page.destroy();
                                   } else {

                                       if (page) page.total = ret.data.contacts.RecordTotal
                                   }
                               }
                               dicts = ret.data.dicts
                               if (dicts) {
                                   dicts.ContactRole.forEach(function (r) {
                                       model.roles.items.push({
                                           val: r.Id,
                                           label: r.Data,
                                           curr: false
                                       })
                                   })
                               }

                           }
                       })
                   }
                   scope.customerOpts = {
                       paging: function () {
                           var data = {}
                           data.cpage = (this.currentindex + 1) || 1
                           data.climit = this.pagesize
                           data.onlyCustomer = true
                           model.loadData(data)
                       },
                       enablesetsize: false,
                       showtotal: false,
                       showpages: 5,
                       initload: false

                   }
                   scope.bindWatch = function () {
                       model.$watch("checkAll", function (n) {
                           model.contacts.forEach(function (c) {
                               c.checked = n;
                           });
                       });
                   }
               })
               var isFill = false;
               model.$action = action;
               model.bindWatch();
               function initLetters() {
                   var nameLetters = {};
                   for (var i = 65; i < 91; i++) {
                       var c = String.fromCharCode(i);
                       nameLetters[c] = [];
                   }
                   model.nameLetters = nameLetters;
               }
               function getContactsFirstName() {
                   initLetters();
                   $.get("/Customer/GetContactsFirstName", {}, function (ret) {
                       if (ret.result && ret.data) {
                           //for (var c in model.nameLetters.$model) {
                           //    model.nameLetters[c].removeAll();
                           //}
                           ret.data.forEach(function (item) {
                               var l = item.FirstNameLetter;
                               if (model.nameLetters[l]) model.nameLetters[l].push(item.FirstName);
                           });
                       }
                   });
               }
               switch (action) {
                   case "customeradd":
                   case "customer":
                       isFill = true;
                       detail = avalon.vmodels.ViewCustomer
                       /*隐藏其它，只显示列表块*/
                       model.showCondition = false
                       detail.showCustomerHead = true
                       paramData.viewOther(tmpl, model);
                       if (action == "customeradd") {
                           action = "customer";
                           model.toAdd();
                       }
                       model.loadData({})
                       break;
                   case "view":
                       model.toDetail(id);
                       break;
                   case "key":
                       model.key = id;
                       model.execSearch(model);
                       fill();
                       break;
                   case "add":
                       fill();
                       model.toAdd();
                       break;
                   case "toadd":
                       model.toAdd();
                       if (paramData) {
                           var m = model.entity;
                           m.CustomerId = paramData.customerId;
                           m.CustomerName = paramData.customerName;
                       }
                       break;
                   default:
                       fill();

               }
               
               function fill() {
                   isFill = true;
                   getContactsFirstName();
                   CBCRM.fillContent(tmpl, lang, contentId, module, model);
                   //大日历
                   setJCal('#jscalender', function (day, days) {
                       var yy = day.getFullYear();
                       var MM = day.getMonth() + 1;
                       var dd = day.getDate();
                       var date = yy + '-' + (MM < 10 ? ('0' + MM) : MM) + '-' + (dd < 10 ? ('0' + dd) : dd);
                       var md = (MM < 10 ? ('0' + MM) : MM) + '-' + (dd < 10 ? ('0' + dd) : dd);
                       model.removeConditions("birthday");
                       model.addConditions("birthdayDate", "生日：" + md, date);
                   });
                   model.loadData({})
               }

           },
           /// <summary>
           /// 客户模块首页
           /// </summary>
           Index: function (tmpl, lang, contentId, module) {
               var CBCRM = avalon.vmodels.CBCRM,
                   mvvm = CBCRM.define('CustomerController', function (vm) {
                       vm.lang = lang
                       vm.$skipArray = ['lang']
                       vm.destroy = function () {

                       }
                       vm.sTime = CBCRM.sTime.$model;
                       vm.entity = {}
                       vm.keyword = ''
                       vm.currUnit = '';
                       vm.search = function () {
                           var url = $('#sb').val()
                           if (mvvm.keyword) {
                               url += mvvm.keyword+"/key"
                               goto(url)
                           }
                       }
                       vm.enterToSearch = function (e) {
                           if (e.keyCode === 13) {
                               mvvm.search()
                           }
                       }
                       vm.view = function (id) {
                           var url = '/Customer/DetailCustomer/' + id;
                           goto(url, true);
                       }
                       vm.customerNewList = []  //最新客户
                       vm.customerExecutionList = [] //合同阶段执行客户
                       vm.customerFreeList = []  //公海客户
                       vm.customerHotList = [] //热点客户
                       vm.customerNewSiginList = [] //最新签约客户
                       vm.customerVisitList = []   //回访客户
                       vm.customerReclaimList = []  //被专管客户
                   });

               function initWithData() {
                   $.get('/Customer/TopCount', {}, function (ret) {
                       mvvm.entity = ret.data;
                   })
                   $.get('/Customer/TopCharts/', {}, function (ret) {
                       //createPieChart(ret.data.chart1, "chartCustomer1");
                       createJQPieChart("#chartCustomer1", mvvm.sTime.year +'年我的客户分类情况', ret.data.chart1);
                       //createAngularGauge(ret.data.chart2.CustomerNum, ret.data.chart2.CompleteCustomerNum, "chartCustomer2");
                       createJQDashboard("#chartCustomer2", "本月客户数目标", ret.data.chart2.CompleteCustomerNum, ret.data.chart2.CustomerNum);
                       //createColumnChart(ret.data.chart3, "chartCustomer3");
                       createJQBar("#chartCustomer3", mvvm.sTime.year + "年客户回款情况", ret.data.chart3);
                       //createAngularGauge(ret.data.chart2.SignAContract, ret.data.chart2.CompleteSignAContract, "chartCustomer4", '');
                       createJQDashboard("#chartCustomer4", "本月签单数目标", ret.data.chart2.CompleteSignAContract, ret.data.chart2.SignAContract);
                       //createLineChart(ret.data.chartLine, "chartCustomerLine");
                       createJQLinear("#chartCustomerLine", '', ret.data.chartLine);
                   })
                   $.get('/Customer/TopTables', { top: 5 }, function (ret) {
                       mvvm.customerNewList = ret.data.customerNewList
                       mvvm.customerExecutionList = ret.data.customerExecutionList
                       mvvm.customerFreeList = ret.data.customerFreeList
                       mvvm.customerHotList = ret.data.customerHotList
                       mvvm.customerNewSiginList = ret.data.customerNewSiginList
                       mvvm.customerVisitList = ret.data.customerVisitList
                       mvvm.customerReclaimList = ret.data.customerReclaimList
                   })
               }

               //JQ 油表图
               function createJQDashboard(chartId, title, value, max) {
                   $(chartId).empty();
                   data = [value];
                   try{
                       $(chartId).jqplot([data], {
                           title:title,
                           seriesDefaults: {
                               renderer: $.jqplot.MeterGaugeRenderer,
                               rendererOptions: {
                                   min: 0,
                                   max: max,
                                   ticks: [],
                                   showTicks: true,
                                   showTickLabels: true,
                                   intervals: [max / 4, max / 2, max * 3 / 4, max],
                                   intervalInnerRadius: 50,
                                   label: value,
                                   labelHeightAjust: 50,
                                   labelPosition: 'inside',
                                   hubRadius:15
                               }
                           }
                       });
                   }
                   catch (ex) {
                       $(chartId).html("<p class='nodata'>" + ex.message + "</p>");
                   }
               }
               //JQuery 饼图
               function createJQPieChart(chartId, title, chartData) {
                   var pieData = [];
                   $(chartId).empty();
                   try {
                       if (chartId == '#chart_pie') {
                           chartData.forEach(function (item) {
                               var name = item.seriesname;
                               var total = 0;
                               var itemData = item.data;
                               itemData.forEach(function (idata) {
                                   total += parseInt(idata.value);
                               });

                               name += " " + total + '家';
                               pieData.push([name, total])
                           });
                       }
                       else {
                           chartData.forEach(function (item) {
                               pieData.push([item.label + ' ' + item.value, parseInt(item.value)]);
                           });
                       }
                       //console.log(pieData);

                       $(chartId).jqplot([pieData], {
                           title: title,
                           pointLabels: { show: true },
                           seriesDefaults: {
                               fill: true,
                               showMarker: false,
                               shadow: false,
                               renderer: $.jqplot.PieRenderer,
                               rendererOptions: {
                                   diameter: undefined,
                                   padding: 10,
                                   sliceMargin: 2,
                                   fill: true,
                                   shadow: true,
                                   shadowOffset: 2,
                                   shadowDepth: 5,
                                   shadowAlpha: 0.07,
                                   showDataLabels: true
                               },
                               pointLabels: { //数值点标签属性设置，该属性来自于jqplot.pointLabels.min.js
                                   show: true, //是否在图表上显示数值点标签
                                   location: 'e' //标签显示的方位
                               }
                           },
                           legend: {
                               show: true,
                               location: 'ne',
                               xoffset: 12,
                               yoffset: 12
                           }
                       });
                   }
                   catch (ex) {
                       $(chartId).html("<p class='nodata'>" + ex.message + "</p>");
                   }
               }

               //JQuery 线性图
               function createJQLinear(chartId, title, chartData) {
                   var linearData = [];
                   var labels = [];
                   $(chartId).empty();
                   try {
                       chartData.forEach(function (item) {
                           var a = [];
                           labels.push(item.seriesname);
                           item.data.forEach(function (node, i) {
                               a.push([(i + 1) + "月", node.value]);
                           })
                           linearData.push(a);
                       });

                       $(chartId).jqplot(linearData, {
                           title: title,
                           animate: true,
                           animateReplot: true,
                           /*cursor: {
                               show: true,
                               showTooltip: true,
                               followMouse: true,
                               zoom: true,
                               looseZoom: true,
                               showTooltip: true,
                               tooltipOffset: 6,
                               showTooltipUnitPosition: true,
                               ooltipFormatString:'%.2f'
                           }, */
                           series: [
                               {
                                   label: labels[0] || '',
                                   showHighlight: true,
                                   pointLabels: {
                                       show: true
                                   },
                                   rendererOptions: {
                                       animation: {
                                           speed: 2000
                                       }
                                   }
                               }, {
                                   label: labels[1] || '',
                                   showHighlight: true,
                                   pointLabels: {
                                       show: true
                                   },
                                   rendererOptions: {
                                       animation: {
                                           speed: 2000
                                       }
                                   }
                               },
                           ],
                           axes: {
                               xaxis: {
                                   renderer: $.jqplot.CategoryAxisRenderer
                               },
                               yaxis: {
                                   label: '',
                                   tickOptions: {
                                       formatString: '%.1f'
                                   },
                                   rendererOptions: {
                                       forceTickAt0: true
                                   },
                                   lableRenderer: $.jqplot.CanvasAxisLabelRenderer,
                               }
                           },
                           highlighter: {
                               show: true,
                               showLabel: true,
                               tooltipAxes: 'y',
                               sizeAjust: 7.5,
                               tooltipLocation: 'ne'
                           },
                           legend: {
                               renderer: $.jqplot.EnhancedLegendRenderer,
                               show: true,
                               location: 'ne',
                               // placement:'outsideGrid'
                           } 
                       });
                   }
                   catch (ex) {
                       $(chartId).html("<p class='nodata'>" + ex.message + "</p>");
                   }
               }

               //JQuery 线性图
               function createJQBar(chartId, title, chartData) {
                   var barData = [];
                   var labels = [];
                   var a = [];
                   var max = 0.0, base = 1.0;
                   mvvm.currUnit = '(元)';
                   try{
                       console.log(chartData);
                       chartData.forEach(function (item) {
                           labels.push(item.label);
                           a.push(item.value);
                           if (item.value > max)
                               max = item.value;
                       });
                   
                       if (max > 1000000000) {
                           base = 100000000;
                           mvvm.currUnit = '(亿元)';
                       }
                       else if (max > 100000) {
                           base = 10000;
                           mvvm.currUnit = '(万元)';
                       }
                       if (base > 1) {
                           for(i = 0; i < a.length; i++){
                               a[i]= parseFloat(a[i]) / base;
                           }
                       }
                       barData.push(a);                   
                  
                       $(chartId).jqplot(barData, {
                           title: title + mvvm.currUnit,
                           series: [
                              {
                                  //color: '#5FAB78',
                                  renderer: jQuery.jqplot.BarRenderer,
                                  rendererOptions: {
                                      barDirection: 'vertical',
                                      barMargin: 15,
                                      barWidth: 50
                                  }
                              }
                           ],
                           seriesDefaults: {
                               renderer: $.jqplot.BarRenderer,
                               rendererOptions: { fillToZero: true },
                               pointLabels: { //数值点标签属性设置，该属性来自于jqplot.pointLabels.min.js
                                   show: true, //是否在图表上显示数值点标签
                                   location: 'n', //标签显示的方位 'se', 's', 'sw', 'w', 'nw'
                                   edgeTolerance: -15
                               },
                               // Rotate the bar shadow as if bar is lit from top right.
                               shadowAngle: 135
                           },
                           cursor: {
                               show: true, //是否显示提示信息
                               zoom: true, //是否启用变焦，鼠标左键选中图表去拖动可放大图标
                               looseZoom: true //扩展变焦范围，提供更全面的刻度值信息，目前仅对有时间轴和线性轴的图表有效
                           },

                           axesDefaults: {
                               tickRenderer: $.jqplot.CanvasAxisTickRenderer,
                               tickOptions: {
                                   fontFamily: 'Georgia',
                                   angle: -30,
                                   fontSize: '10pt'
                               }
                           },
                           axes: {
                               xaxis: {
                                   renderer: $.jqplot.CategoryAxisRenderer,
                                   ticks: labels,
                               },
                               yaxis: {
                                   label: '',
                                   lableRenderer: $.jqplot.CanvasAxisLableRenderer,
                               }
                           },
                       });
                   }
                   catch (ex) {
                       $(chartId).html("<p class='nodata'>" + ex.message + "</p>");
                   }
                   //p.replot();
               }

               require("jqPlotPie,jqBar,jqCanvasAxisTick,jqPointLabels,jqCategory,jqCanvasText,jqCanvasAxisLabel,jqEnhancedLegend,jqPointLabel,jqCursor,jqHighlighter,jqMeterGauge",
               function () {
                   initWithData()
                   CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
               });

               $('#sb').selectbox()
               $('#sb_input').removeAttr('readonly')
           },
           History: function (tmpl, lang, contentId, module,paramData) {
               var that = this,CBCRM=avalon.vmodels.CBCRM,
                   model = CBCRM.define('CustomerHistory', function (scope) {
                       scope.histories = []
                       scope.grid1 = { gridmsg: "" };
                       scope.popts = {
                           paging: function () {
                               model.loadData({
                                   page: (this.currentindex + 1) || 1,
                                   limit: this.pagesize
                               })
                           }
                       }
                       scope.loadData = function (params) {
                           model.grid1.gridmsg = lang.LoadingMsg;
                           $.post('/Customer/History/' + that.params.id, params || {})
                           .done(function (ret) {
                               if (ret.result) {
                                   model.grid1.gridmsg = ret.data.history.RecordTotal ? "" : lang.NoListData;
                                   model.histories = ret.data.history.Source
                                   avalon.vmodels.hpaing.total = ret.data.history.RecordTotal
                               }
                           })
                       }
                   })
               paramData.viewOther(tmpl, model);
           },
           //潜在客户
           Latent: function (tmpl, lang, contentId, module,paramData) {
               module.All.call(this, tmpl, lang, contentId, module,paramData)
           },
           //终端客户
           Official: function (tmpl, lang, contentId, module,paramData) {
               module.All.call(this, tmpl, lang, contentId, module,paramData, null, 10107)
           },
           //合作伙伴
           Collaborate: function (tmpl, lang, contentId, module,paramData) {
               module.All.call(this, tmpl, lang, contentId, module,paramData, null, 10131)
               avalon.vmodels.Customer.addAction = 'AddCollaborate'
           },
           //渠道代理商
           Channel: function (tmpl, lang, contentId, module,paramData) {
               module.All.call(this, tmpl, lang, contentId, module, paramData, null, 10132)
               var vm = avalon.vmodels.Customer
               vm.addAction = 'AddChannel';
               var items = vm.channelArea.items;
               items.splice(1, items.length);
               $.get("/Market/ChannelArea", { parentId: 0 }, function (ret) {
                   if (ret.result) {
                       ret.data.forEach(function (item) {
                           items.push({ val: item.Id, label: item.Name, curr: false });
                       });
                   }
               })
           },
           //供应商
           Supply: function (tmpl, lang, contentId, module,paramData) {
               module.All.call(this, tmpl, lang, contentId, module, paramData, null, 10133)
               avalon.vmodels.Customer.addAction = 'AddSupply'
           },
           //媒体资源
           Advertising: function (tmpl, lang, contentId, module,paramData) {
               module.All.call(this, tmpl, lang, contentId, module, paramData, null, 10134)
               avalon.vmodels.Customer.addAction = 'AddAdvertising'
           },
           //竞争对手
           Competitor: function (tmpl, lang, contentId, module,paramData) {
               var customer
               module.All.call(this, tmpl, lang, contentId, module, paramData, 'Competitor', 10135)
               customer = avalon.vmodels.Customer
               customer.addAction = 'AddCompetitor'
               customer.initList = function (ret) {
                   var m = customer,
                   marketPos = ret.data.dicts.MarketPosition,
                   cc = ret.data.dicts.SubCategory
                   if (ret.data.dicts) {
                       if (marketPos && marketPos.length) {
                           marketPos.forEach(function (mp) {
                               m.marketPos.items.push({
                                   label: mp.Data,
                                   curr: false,
                                   val: mp.Id
                               })
                           })
                       }
                       if (cc && cc.length) {
                           cc.forEach(function (c) {
                               /*获取竞争对手客户分类*/
                               if (c.ParentId === 10135) {
                                   m.category.items.push({
                                       label: c.Data,
                                       curr: false,
                                       val: c.Id
                                   })
                               }
                           })
                       }
                   }
               }
           },
           //专管客户
           CenterExpert: function (tmpl, lang, contentId, module,paramData) {
               module.All.call(this, tmpl, lang, contentId, module, paramData)
           },
           //公海客户
           International: function (tmpl, lang, contentId, module,paramData) {
               var CBCRM = avalon.vmodels.CBCRM, model, vmid = 'International'
               var treevmid = vmid + '_areaTree';
               model = CBCRM.define(vmid, function (scope) {
                   scope.lang = lang
                   scope.$skipArray = ['lang']
                   scope.NOPAGE = false;
                   scope.RESET = false;
                   initQuerys(scope, function (data, name, val, type) {
                       if (name == "ownertype") {
                           if (type == "remove" || val == "1") model.removeQuery("owner", true);
                       }
                       if (name == "areaType" && (type == "remove" || val=="")) {
                           model.showTree(false);
                           model.removeQuery("area", true);
                       }
                       if (type == "clear")
                           model.showTree(false);
                       model.grid1.loadData(model.createQuery());
                   })
                   scope.queryData = {
                       enterTime: {
                           label: '掉入时间', val: '', valLabel: '',next:'state',
                           items: [{ label: '不限', val: '', curr: true },
                           { label: '今天', val: '0', curr: false },
                           { label: '昨天', val: '1', curr: false },
                           { label: '7天内', val: '7', curr: false },
                           { label: '30天内', val: '30', curr: false }]
                       },
                       state: {
                           label: '申请状态', val: '', valLabel: '',jump:true,
                           items: [
                               { label: "不限", val: "", curr: true },
                               { label: "申请延长", val: "1", curr: false },
                               { label: "拒绝延长", val: "2", curr: false }
                           ]
                       },
                       ownertype: {
                           label: '原 归 属', val: '', valLabel: '', next: 'areaType',
                           items: [
                               { label: "不限", val: "", curr: true },
                               { label: "我自己", val: "1", curr: false },
                               { label: "指定部门员工", val: "2", curr: false, type: "selectUser" }
                           ]
                       },
                       areaType:{
                           label: '指定地区', val: '', valLabel: '',jump:true,
                           items: [
                               { label: "不限", val: "", curr: true },
                               { label: "指定地区", val: "1", curr: false ,type:"areaTree"}
                           ]
                       },
                       key: {
                           label: '关键词', val: '', valLabel: ''
                       },
                       owner: {
                           label: '原归属', val: '', valLabel: ''
                       },
                       area:{
                           label: '指定地区', val: '', valLabel: ''
                       }
                   }
                   scope.selectUser = function (key, r) {
                       var us = model.queryData.owner.val.split(",")
                       plugins.selectUser({
                           multiple: true,
                           isJoin:true,
                           listData: us,
                           callback: function (us) {
                               var uids=where(us, true, "Id");
                               model.addQuery(key, r.val, r.label, true);
                               model.addQuery("owner", uids.join(","))
                           }
                       });
                   }
                   scope.grid1 = createGrid({
                       $lang:lang,
                       url: '/Customer/International',
                       method: "post",
                       pageid: vmid + "_grid1_page",
                       createQuery: function () {
                           return model.createQuery();
                       },
                       onLoadData: function (ret, list) {
                           model.NOPAGE = ret.data.NOPAGE;
                           model.RESET = ret.data.RESET;
                           model.pd = ret.data.pd;
                           var uid = CBCRM.memberShip.Id;
                           list.forEach(function (item) {
                               item.canApply = false;
                               if (item.Owner != uid) item.applyTitle = "不是您的原归属客户"
                               else if (item.State > 0) item.applyTitle = "申请状态已经不是未申请"
                               else {
                                   item.canApply = true;
                                   item.applyTitle = "";
                               }
                               switch (item.State) {
                                   case 1:
                                       item.stateClass = "label5-warning";
                                       break;
                                   case 2:
                                       item.stateClass = "label5-success";
                                       break;
                                   case 3:
                                       item.stateClass = "label5-success";
                                       break;
                                   default:
                                       item.stateClass = "label5-info";
                                       break;
                               }
                           })
                       }
                   });
                   scope.doSearch = function () {
                       var key = model.queryData.key.val;
                       model.addQuery("key", key, key);
                   }
                   scope.setPick = function () {
                       var vm = this.$vmodel,
                           vmItem = vm[vm.$itemName]
                       id = vmItem.Id,
                       index = vm.$index
                       if (!id) {
                           messageBox.error('请选择要领取的客户')
                           return
                       } else if (vmItem.IsPicked) {
                           messageBox.error('非常抱歉，该客户已被领取')
                           return
                       }
                       messageBox.confirm('您确定要领取选中的客户吗？', function () {
                           $.post('/Customer/SetPick/' + id)
                           .done(function (ret) {
                               CBCRM.showResult(ret, function () {
                                   if (ret.result) model.grid1.reloadData();
                               })
                           })
                       })
                   }
                   scope.setPickBySelected = function () {
                       var ids = model.grid1.getCheckedIds("ids");
                       if (ids.length == 0) {
                           messageBox.error('请选择要领取的客户')
                           return
                       }
                       messageBox.confirm('您确定要领取选中的客户吗？', function () {
                           $.post('/Customer/SetPick', ids)
                           .done(function (ret) {
                               CBCRM.showResult(ret)
                               if (ret.result) model.grid1.reloadData();
                           })
                       })
                   }
                   //默认延长天数
                   scope.pd = "";
                   scope.applyEntity = { state: "3", protectDays: "" };

                   //批量申请延长
                   scope.applyResetMore = function () {
                       var items = model.grid1.getChecked();
                       if (items.length == 0) {
                           messageBox.error('请选择要申请延长的客户')
                           return
                       }
                       var check = findArr(items, function (item) { return item.canApply == false });
                       if (check != null) {
                           messageBox.error('所有选择的客户原归属必须是您，并且当前申请状态是[未申请]状态的客户，才能申请延长！')
                           return
                       }
                       var ids = model.grid1.getCheckedIds();
                       model.applyReset(ids);
                   }
                   //申请延长
                   scope.applyReset = function (ids) {
                       messageBox.confirm('您确定要申请延长选中的客户吗？', function () {
                           var data = jsonToSubmit("ids", ids);
                           $.post('/Customer/ApplyResetIwCustomer', data)
                           .done(function (ret) {
                               CBCRM.showResult(ret)
                               if (ret.result) model.grid1.reloadData();
                           })
                       })
                   }
                   //批量审批延长
                   scope.resetApplyIwMore = function () {
                       var items = model.grid1.getChecked();
                       if (items.length == 0) {
                           messageBox.error('请选择要审批延长的客户')
                           return
                       }
                       var check = findArr(items, function (item) { return item.State != 1 });
                       if (check != null) {
                           messageBox.error('所有选择的客户的申请状态都必须是已申请！')
                           return
                       }
                       var ids = model.grid1.getCheckedIds();
                       model.resetApplyIw(ids);
                   }
                   //审批延长
                   scope.resetApplyIw = function (ids) {
                       model.applyEntity.protectDays = model.pd;
                       var dialog = model.openTmpl({
                           title: "审批延长", w: 400, h: 100,padding:"def2",
                           tmpl: tmpl, tmplid: "applyTmpl",
                           btns: [{
                               name: "提交",
                               focus: true,
                               callback: function () {
                                   if (!model.applyEntity.protectDays || model.applyEntity.protectDays < 0)
                                       model.applyEntity.protectDays = 0;
                                   var data = jsonToSubmit("ids", ids);
                                   $.extend(data, model.applyEntity.$model);
                                   $.post('/Customer/ResetApplyIwCustomer', data)
                                   .done(function (ret) {
                                       CBCRM.showResult(ret)
                                       if (ret.result) model.grid1.reloadData();
                                   })
                               }
                           }]
                       });
                   }
                   //恢复原归属
                   scope.resetIw = function () {
                       var items = model.grid1.getChecked();
                       if (items.length == 0) {
                           messageBox.error('请选择要恢复的客户')
                           return
                       }
                       messageBox.confirm('您确定要恢复选中的客户吗？', function () {
                           var ids = model.grid1.getCheckedIds("ids");
                           $.post('/Customer/ResetIwCustomer', ids)
                           .done(function (ret) {
                               CBCRM.showResult(ret)
                               if (ret.result) model.grid1.reloadData();
                           })
                       })
                   }
                   scope.resetIwAll = function () {
                       messageBox.confirm('您确定要恢复所有的客户吗？', function () {
                           var dialog = CBCRM.loading("正在处理，请稍后……");
                           $.post('/Customer/ResetIwCustomer', { resetAll: true })
                           .done(function (ret) {
                               if (dialog) dialog.close();
                               CBCRM.showResult(ret)
                               if (ret.result) model.grid1.reloadData();
                           })
                       });
                   }
                   //指定地区
                   scope.showTree = function (show,r,e) {
                       var treevm, pvm, pvmid = treevmid + "panel",
                       el = this,that = this
                       pvm = avalon.vmodels[pvmid]
                       if (!pvm && (!this || !this.nodeType)) return;
                       if (!pvm) {
                           avalon.ui.dropDownAreasTree(el, {
                               dropDownAreasTreeId: treevmid,
                               dropDownAreasTreeOptions: {
                                   treeopts: {
                                       check: {
                                           enable: true,
                                           chkStyle: "checkbox",
                                           chkboxType: { "Y": "", "N": "" }
                                       },
                                       callback: {
                                           onCheck: function (e, treeId, treeNode) {
                                               var treeObj = $.fn.zTree.getZTreeObj(treeId),
                                               nodes = treeObj.getCheckedNodes(true)
                                               var crids=[],pids = [], cids = [], aids = [];
                                               var crs = where(nodes, function (item) { return item.level == 0; });
                                               var ps = where(nodes, function (item) { return item.level == 1; });
                                               var cs = where(nodes, function (item) { return item.level == 2; });
                                               var as = where(nodes, function (item) { return item.level == 3; });
                                               //如果子节点有选择，就需要忽略父节点的选择
                                               var ignIds = {};
                                               as.forEach(function (a) {
                                                   var c = a.getParentNode(), p = c.getParentNode(), cr = p.getParentNode();
                                                   ignIds[cr.Id] = 1
                                                   ignIds[p.Id] = 1;
                                                   ignIds[c.Id] = 1;
                                               });
                                               cs.forEach(function (c) {
                                                   var  p = c.getParentNode(), cr = p.getParentNode();
                                                   ignIds[cr.Id] = 1
                                                   ignIds[p.Id] = 1;
                                               });
                                               ps.forEach(function (p) {
                                                   ignIds[p.ParentId] = 1;
                                               });
                                               crids = where(crs, function (item) { return !ignIds[item.Id] }, "Id");
                                               pids = where(ps, function (item) { return !ignIds[item.Id] }, "Id");
                                               cids = where(cs, function (item) { return !ignIds[item.Id] }, "Id");
                                               aids = where(as, true, "Id");
                                               var ids = crids.join(",") + "_" + pids.join(",") + "_" + cids.join(",") + "_" + aids.join(",");
                                               model.addQuery("areaType", r.val, r.label, true, false);
                                               model.addQuery("area", ids);
                                           }
                                       }
                                   },
                                   enablesearch: false,
                                   initevent: false
                               }
                           }, that.$vmodels)
                           pvm = avalon.vmodels[pvmid]
                       }
                       pvm.toggle(show)
                       if (!show) {
                           model.removeQuery('area', true);
                           treevm = avalon.vmodels[treevmid];
                           if (treevm) {
                               var treeObj = treevm.getTree();
                               if (treeObj) treeObj.checkAllNodes(false);
                           }
                       }
                   }

                   //查看客户
                   scope.viewCustomer = function (id) {
                       model.gotoview(id, null, {
                           reloadData: function (cu) {
                               model.grid1.reloadData();
                           }
                       });
                   }

                   scope.destroy = function () {
                       destroyui([treevmid]);
                       delete avalon.vmodels[vmid];
                   }
               })
               model.grid1.init();
               avalon.filters.iwState = function (val) {
                   if (!val) return "未申请";
                   if (val == 1) return "申请延长"
                   if (val == 2) return "拒绝延长"
                   if (val == 3) return "已批准"
               }
               CBCRM.fillContent(tmpl, lang, contentId, module, model)
           },
           //社会关系
           Sociall: function (tmpl, lang, contentId, module,paramData) {
               module.All.call(this, tmpl, lang, contentId, module, paramData, null, 11170)
               avalon.vmodels.Customer.addAction = 'AddSociall'
           },
           All: function (tmpl, lang, contentId, module, paramData, conditionKey, Category) {
               Category = Category || 0;
               var service =new Customer.Service();
               var router = this,
                   conditions = conditionFactory.create(conditionKey || 'Customer')
               , model, init = false, menus
               notMemberFilter = function (treeId, parentNode, responseData) {
                   var ret = [], len, curr, hasMember = false
                   if (responseData.data && responseData.data.groups.length) {
                       len = responseData.data.groups.length
                       if (len) {
                           for (var i = 0; i < len; i++) {
                               curr = responseData.data.groups[i]
                               curr.nocheck = true
                               ret.push(curr)
                               curr.Posts.forEach(function (p, i) {
                                   if (!p.Users.length) return true
                                   hasMember = true
                                   p.Users.forEach(function (u, i) {
                                       var u = p.Users[i]
                                       u.ParentId = u.PositionId
                                       u.Name = u.FullName
                                   })
                                   curr.Posts[i].ParentId = p.Boss ? p.Boss.Id : p.Group
                                   curr.Posts[i].nocheck = true
                                   ret.push(curr.Posts[i])
                                   ret = ret.concat(p.Users)
                               })
                           }
                       }
                   }
                   return ret
               }
               CBCRM = avalon.vmodels.CBCRM,noChangeBeLong=false
               , watchOnlyMy = function (n, o) {
                   if (n != o) {
                       model.conditionChanged.call(this, null, model.createDyQuery())
                       model.currConditions.onlyMy = n ? model.belongTo.items[0].label : ''
                       model.checkCondition()
                   }
               }
               , watchCustom = function (n, o) {
                   var that = this;
                   if (n) {
                       model.currConditions.belongCustom = model.belongTo.items[1].label
                       plugins.selectUser({
                           dataAuth: cuDiRes[Category] || "1020101,1020301,1020401,1020501,1020601,1020701,1020801",
                           multiple: true,
                           callback: function (us) {
                               model.users = where(us, true, "Id");
                               model.conditionChanged.call(that, null, model.createDyQuery())
                           }
                       });   
                   } else {
                       model.users = [];
                       model.currConditions.belongCustom = ''
                       model.conditionChanged.call(that, null, model.createDyQuery())
                   }
                   model.checkCondition()
               }
               //cacheModel = CBCRM.$cache[router.path]
               conditions.conditionChanged = function (item, conditions, key) {
                   //重写查询条件改变事件
                   // this.$vmodels[1] = avalon.define('xxxx',function(){})
                   /*var vm = model
                   if (vm.onlyMy) {
                       conditions.onlyMy = vm.onlyMy
                   }
                   if (vm.custom) {
                       ['groups', 'posts', 'users'].forEach(function (word) {
                           var tmp = word + '[i]'
                           vm[word].forEach(function (g, i) {
                               conditions[tmp.replace('i', i)] = g
                           })
                       })
                   }*/
                   switch (key) {
                       case "addTime":
                           if (item.val === "") {
                               model.currConditions.addTime1 = "";
                               model.currConditions.addTime2 = "";
                           } else {
                               return;
                           }
                           break;
                   }
                   model.loadData(conditions)
               }
               conditions.removedItem = function (key) {
                   switch (key) {
                       case 'belongCustom':
                           model.$unwatch('custom', watchCustom)
                           model.custom = false
                           model.$watch('custom', watchCustom)
                           break
                       case 'onlyMy':
                           model.$unwatch('onlyMy', watchOnlyMy)
                           model.onlyMy = false
                           model.$watch('onlyMy', watchOnlyMy)
                           break
                       case 'areas':
                           model.hasAreas = false
                           break
                       case "addTime":
                           model.currConditions.addTime1 = "";
                           model.currConditions.addTime2 = "";
                           break;
                   }
               }
               conditions.onClearAll = function () {
                   model.$unwatch('onlyMy', watchOnlyMy)
                   model.$unwatch('custom', watchCustom)
                   model.custom = false
                   model.hasAreas = false
                   model.onlyMy = false
                   model.$watch('onlyMy', watchOnlyMy)
                   model.$watch('custom', watchCustom)
               }
               conditions.keyCol = 'name'
               conditions.keyDynamic = false
               if (conditions.addTime != null) conditions.TIMESPAN = conditions.addTime.items[1].label;
               /*if (cacheModel) {
                   conditions.currConditions = cacheModel.currConditions
                   conditions.key = cacheModel.key
               }*/
               model = CBCRM.define('Customer', function (scope) {
                   avalon.mix(true, scope, conditions)
                   scope.destroy = function () {
                       destroyui(['customBelongTree', 'dropDownAreasTree'])
                       delete avalon.vmodels.customerMenu
                   }
                   scope.Category = Category;
                   scope.page = ''
                   scope.limit = ''
                   scope.total = 0
                   scope.lang = lang
                   /*公用按钮权限设置参数 start*/
                   scope.ADD = true
                   scope.DELETE = true
                   scope.TURN = true
                   scope.SHARE = true
                   scope.SEA = true
                   scope.EXPERT = false
                   scope.EXPORT = true
                   scope.NOPAGE = false
                   /*scope.NOTE = true
                   scope.EMAIL = true
                   scope.EXECL = true
                   scope.WORD = true
                   scope.PDF = true*/
                   /*公用按钮权限设置参数 end*/
                   scope.UserId = CBCRM.memberShip.Id;
                   /*客户 start*/
                   scope.addTime1Ops = {
                       format: '%Y-%m-%d',
                       onSelect: function (date, formatDate, format) {
                           model.addCondition("addTime1", formatDate);
                       }
                   }
                   scope.addTime2Ops = {
                       format: '%Y-%m-%d',
                       onSelect: function (date, formatDate, format) {
                           model.addCondition("addTime2",formatDate);
                       }
                   }
                   scope.grid1 = { gridmsg: "" };
                   scope.listOpts = { //列表分页组件
                       paging: function () {
                           var m = model,
                           data = m.createDyQuery()
                           if (action == "area" && !init) {
                               data.areaId = paramid
                               model.currConditions.areas = paramid ? '指定地区' : ''
                               model.checkCondition()
                           }
                           //ok = true
                           data.page = (this.currentindex + 1) || 1
                           data.limit = this.pagesize
                           if (!init) {
                               data.init = true
                               init = true
                           }
                           //if (ok) {
                           m.page = data.page
                           m.limit = data.limit
                           m.loadData(data)
                           //}
                       }
                   }
                   scope.exportExcel = function (act) {
                       var url = router.path || '/Customer/All';
                       var m = model,
                           data = m.createDyQuery()
                       if (action == "area" && !init) {
                           data.areaId = paramid
                           model.currConditions.areas = paramid ? '指定地区' : ''
                           model.checkCondition()
                       }
                       data.exportExcel = true;
                       if (act == 1) {
                           var page = avalon.vmodels.listPage;
                           if (page != null) {
                               data.limit = page.pagesize;
                               data.page = page.currentindex + 1;
                           }
                       } else {
                           data.page = -1;
                       }
                       frameSubmit(url, "post", data);
                   }
                   /*竞争对手威胁值raty ui*/
                   scope.threatenOpts = {
                       ratyChanged: function (val) {
                           var m = model,
                           data
                           m.threaten.items.forEach(function (t) {
                               t.curr = t.val === val
                               if (t.curr)
                                   m.currConditions.threaten = t.label
                           })
                           data = m.createDyQuery()
                           m.loadData(data)
                       }
                   }
                   scope.toggleMore = function (key) {
                       if (!model[key]) return;
                       model[key].showMore = !model[key].showMore;
                   }
                   scope.setArea = function (ret) {
                       var data
                       model.hasAreas = ret
                       if (!model.hasAreas) {
                           data = model.createDyQuery()
                           data.areaId = ''
                           model.conditionChanged(null, data)
                           model.currConditions.areas = ''
                           model.checkCondition()
                       }
                   }
                   scope.queryArea = function (areaid) {
                       model.areaId = areaid
                       data = model.createDyQuery()
                       data.areaId = model.areaId
                       model.conditionChanged.call(model, null, data)
                       model.currConditions.areas = model.areaId ? '指定地区' : ''
                       model.checkCondition()
                   }
                   scope.areaId = ''
                   scope.hasAreas = false
                   scope.dropDownAreasTreeOpts = {
                       treeopts: {
                           callback: {
                               onCheck: function (event, treeId, treeNode) {
                                   var treeObj = $.fn.zTree.getZTreeObj(treeId)
                                   , nodes = treeObj.getCheckedNodes(true)
                                   , data, ids = [];
                                   nodes.forEach(function (item) {
                                       ids.push(item.Id);
                                   });
                                   model.queryArea(ids.join(","));
                               }
                           }
                           , check: {
                               enable: true,
                               chkStyle: "checkbox",
                               chkboxType: { "Y": "", "N": "" }
                           }
                       }
                   }
                   scope.addAction = 'AddCustomer'
                   scope.editAction = 'EditCustomer'
                   scope.customers = []
                   scope.onlyMy = false
                   scope.custom = false
                   scope.groups = []
                   scope.posts = []
                   scope.users = []
                   scope.checkAll = false
                   scope.doPublicSea = function () {
                       var m = model
                       var ids = where(m.customers, function (d) { return d.checked; }, "Id");
                       service.MoveToInternational(ids, function (ret) {
                           m.conditionChanged(null, m.createDyQuery());
                       });
                   }
                   scope.doCenterExpert = function () {
                       var m = model
                       m.getChecked(function (ids, customers) {
                           messageBox.confirm('您确定要将选中的客户放入专管客户吗？', function () {
                               data = jsonToSubmit("ids", ids)
                               $.post('/Customer/MoveToCenterExpert', data)
                               .done(function (ret) {
                                   CBCRM.showResult(ret, function () {
                                       model.conditionChanged(null, m.createDyQuery())
                                   })
                               })
                           })
                       }, function () {
                           messageBox.warning('请选择需要专管的客户')
                       })
                   }
                   scope.resetCenterExpert = function () {
                       var m = model
                       m.getChecked(function (ids, customers) {
                           messageBox.confirm('您确定要将选中的客户移出专管，恢复原归属吗？', function () {
                               data = jsonToSubmit("ids", ids)
                               $.post('/Customer/MoveOutCenterExpert/', data)
                               .done(function (ret) {
                                   avalon.vmodels.CBCRM.showResult(ret, function () {
                                       model.conditionChanged(null, m.createDyQuery())
                                   })
                               })
                           })
                       }, function () {
                           messageBox.warning('请选择需要移出专管的客户')
                       })
                   }

                   scope.viewopen = function (item) {
                       var paths = '/Customer/DetailCustomer/'  + item.Id;
                       goto(paths, true);
                   }

                   scope.doRemoveAll = function () {
                       var m = model
                       m.getChecked(function (ids, customers) {
                           messageBox.confirm(lang.RemoveConfirm, function () {
                               var idsTmp = 'ids[j]',
                               data = {}
                               ids.forEach(function (id, i) {
                                   data[idsTmp.replace('j', i)] = id
                               })
                               $.post('/Customer/CustomerToRecycleBin/', data)
                               .done(function (ret) {
                                   CBCRM.showResult(ret, function () {
                                       var m = model
                                       m.conditionChanged(null, m.createDyQuery())
                                   })
                               })
                           })
                       }, function () {
                           messageBox.warning(lang.RemoveAllCustomerError)
                       })
                   }
                   scope.doRemove = function () {
                       var that = this
                       messageBox.confirm(lang.RemoveConfirm, function () {
                           var curVm = that.$vmodel,
                           curItem = curVm[curVm.$itemName]
                           $.post('/Customer/CustomerToRecycleBin/' + curItem.Id)
                           .done(function (ret) {
                               CBCRM.showResult(ret, function () {
                                   model.conditionChanged(null, model.createDyQuery())
                               })
                           })
                       })
                   }
                   /*客户 end*/
                   /*转移归属 start*/
                   scope.changeBelongTo = ''
                   scope.changeBelongToName = ''
                   scope.changeBelongToRemark = ''
                   scope.selectBelongTo = function () {
                       plugins.selectUser({
                           dataAuth: cuDiRes[Category] || getCuRes(),
                           callback: function (us) {
                               var u = us[0];
                               model.changeBelongTo = u.Id
                               model.changeBelongToName = u.FullName
                           }
                       })
                   }
                   scope.getChecked = function (okCall, failCall) {
                       var ids = [], checkedCustomers = []
                       model.customers.forEach(function (c) {
                           if (c.checked) {
                               ids.push(c.Id)
                               checkedCustomers.push(c)
                           }
                       })
                       if (!ids.length) {
                           if (typeof failCall !== 'function') {
                               avalon.log('缺少failCall函数')
                               return
                           }
                           failCall()
                       } else {
                           if (typeof okCall !== 'function') {
                               avalon.log('缺少okCall函数')
                               return
                           }
                           okCall(ids, checkedCustomers)
                       }

                   }
                   scope.doBelongTo = function () {
                       var ids = [], checkedCustomers = []
                       model.customers.forEach(function (c) {
                           if (c.checked) {
                               ids.push(c.Id)
                               checkedCustomers.push(c)
                           }
                       })
                       if (!ids.length) {
                           messageBox.warning(lang.BelongToError)
                       } else {
                           var d = model.openTmpl({
                               title: lang.TransferBelong,
                               w: 600, h: 200,padding:"def2",
                               tmplId: "belongToForm", tmpl: tmpl,
                               button: [{
                                   name: lang.SubmitBtn,
                                   focus: true,
                                   callback: function () {
                                       messageBox.confirm(lang.BelongToConfirm, function () {
                                           var data = {}, tmp = 'ids[j]'
                                           ids.forEach(function (id, i) {
                                               data[tmp.replace('j', i)] = id
                                           })
                                           if (model.changeBelongTo) {
                                               data.belongTo = model.changeBelongTo
                                           } else {
                                               messageBox.error('请选择新的归属人！')
                                               return
                                           }
                                           data.remark = model.changeBelongToRemark
                                           $.post('/Customer/ChangeBelongTo/', data, function (data) {
                                               CBCRM.showResult(data, function () {
                                                   model.conditionChanged(null, model.createDyQuery())
                                                   messageBox.close()
                                               })
                                           })
                                       })
                                       return false
                                   }
                               }],
                               onClose: function () {
                                   model.changeBelongTo = ''
                                   model.changeBelongToName = ''
                                   model.changeBelongToRemark = ''
                               }
                           });
                       }
                   }
                   /*转移归属 end*/
                   /*共享 start*/
                   scope.shareMore = false;
                   scope.shareCustomers = []
                   scope.currShare = {}
                   scope.setShare = function (curShareCustomer) {
                       var ids = curShareCustomer.ShareTo || [];
                       ids = ids.$model || ids;
                       plugins.selectUser({
                           dataAuth: getCuRes(),
                           multiple: true,
                           listData:ids,
                           callback: function (us) {
                               var a = where(us, true, ["Id", "FullName"]);
                               if (!model.shareMore) {
                                   curShareCustomer.ShareTo = a[0]
                                   curShareCustomer.ShareToNames = a[1].join('，')
                               } else {
                                   model.shareCustomers.forEach(function (item) {
                                       item.ShareTo = a[0]
                                       item.ShareToNames = a[1].join('，')
                                   });
                               }
                           }
                       })
                   }
                   scope.doShare = function () {
                       model.shareMore = false;
                       model.getChecked(function (ids, customers) {
                           var m = model;
                           var d = m.openTmpl({
                               title: lang.ShareCustomerTitle,
                               w: 800, h: 200,
                               tmplId: "shareToForm", tmpl: tmpl,
                               button: [{
                                   name: lang.SubmitBtn,
                                   focus: true,
                                   callback: function () {
                                       messageBox.confirm(lang.ShareCustomerToConfirm, function () {
                                           var data = {}, ctmp = 'customerId[j]',
                                           stmp = 'shareMemberIds[k]'
                                           m = model,
                                           CBCRM = avalon.vmodels.CBCRM
                                           m.shareCustomers.forEach(function (c, i) {
                                               data[ctmp.replace('j', i)] = c.Id
                                               data[stmp.replace('k', i)] = c.ShareTo.length ? c.ShareTo.join(',')
                                                   : '0'
                                           })
                                           $.post('/Customer/ShareCustomerTo/', data, function (ret) {
                                               CBCRM.showResult(ret, function () {
                                                   m.conditionChanged(null, m.createDyQuery())
                                                   messageBox.close()
                                               })
                                           })
                                       })
                                       return false
                                   }
                               }],
                               onClose: function () {
                                   model.shareCustomers = [];
                               }
                           });
                           model.shareCustomers = [];
                           customers.forEach(function (c) {
                               m.shareCustomers.push({
                                   Id: c.Id,
                                   Name: c.Name,
                                   ShareTo: c.ShareTo || [],
                                   ShareToNames: c.ShareToNames.join('，')
                               })
                           })
                       }, function () {
                           messageBox.warning(lang.ShareCustomerError)
                       })
                   }
                   /*共享 end*/
                   scope.initList = function (ret) {
                       avalon.log('ret is server response data')
                   }
                   scope.loadData = function (param) {
                       var vm = model
                       vm.grid1.gridmsg = lang.LoadingMsg;
                       vm.customers.removeAll()
                       if (vm.onlyMy) {
                           param.onlyMy = vm.onlyMy
                       }
                       if (vm.custom) {
                           ['groups', 'posts', 'users'].forEach(function (word) {
                               var tmp = word + '[i]'
                               vm[word].forEach(function (g, i) {
                                   param[tmp.replace('i', i)] = g
                               })
                           })
                       }

                       $.post(router.path || '/Customer/All', param)
                       .done(function (ret) {
                           var lst, stages
                           model.grid1.gridmsg = ret.data.total > 0 ? "" : lang.NoListData;
                           if (ret.data.customers) {
                               lst = CBCRM.parseGridData(ret.data.customers)
                               lst.forEach(function (c) {
                                   setOptUrl(c)
                                   c.CustomerTypeDisplay = avalon.filters.customerType(c.Type);
                                   if (!c.FirstContacts) c.FirstContacts = {};
                               })
                               model.customers = lst
                           }
                           if (ret.data.opts && ret.data.opts.length) {
                               for (var i = 0, opt; opt = ret.data.opts[i++];) {
                                   if (model[opt.Key] != null)
                                       model[opt.Key] = opt.Value
                               }
                           }
                           if (model.NOPAGE) {
                               destroyui(["listPage"])
                           } else {
                               model.total = avalon.vmodels.listPage.total = ret.data.total || 0
                           }
                           if (ret.data.dicts) {
                               var keys = {
                                   "stages": "Stage", "subCategory": "SubCategory",
                                   "businessType": "BusinessType", "serviceLabel": "ServiceLabel",
                                   "supplierLevel": "SuppliersLevel", "memberGrade": "MemberGrade"
                               }
                               var a = [];
                               for (var key in keys) {
                                   var arr = ret.data.dicts[keys[key]];
                                   if (model[key] && arr) {
                                       model[key].items.splice(1, model[key].items.length);
                                       var length = 0;
                                       arr.forEach(function (d) {
                                           if (key != "subCategory" || d.ParentId == Category) {
                                               var item = {
                                                   label: d.Data || d.Name,
                                                   val: d.Id,
                                                   curr: false
                                               }
                                               model[key].items.push(item);
                                               length += item.label.length;
                                           }
                                       })
                                       model[key].length = length;
                                   }
                               }

                           }
                           if (typeof model.initList === 'function') {
                               model.initList(ret)
                           }
                       }).error(function () { model.grid1.gridmsg=lang.LoadingError})
                   }

                   //群发短信
                   scope.sendSmsMulti = function () {
                       var list = getGridChecked(model.customers);
                       if (!list.length) {
                           messageBox.error('请选择数据。');
                           return;
                       }
                       var mos = [], listData = [];
                       list.forEach(function (m) {
                           if (!m.FirstContacts) return;
                           var mobile = m.FirstContacts.MobileNumber1;
                           if (!mobile || !gRegExp.mobile.test(mobile))
                               mobile = m.CompanyTel1;
                           if (mobile && gRegExp.mobile.test(mobile)) {
                               mos.push(mobile);
                               var modelc = {
                                   '名称': m.Name, '类型': model.customerTypeDisplay, '会员级别': m.MemberGradeDisplay ? m.MemberGradeDisplay : "无",
                                   '分类': m.CategoryDisplay, '公司电话': m.CompanyTel1, '公司地址': m.CompanyAddress, 'Email': m.Email, 'QQ': m.QQ
                               };
                               listData.push({ mobile: mobile, model: modelc });
                           }
                       });
                       if (mos.length == 0) {
                           messageBox.warning("所选择的客户未录有手机号码，请先录入！");
                           return;
                       }
                       var tableName = "客户";
                       CBCRM.sendSmsMulti(tableName, mos.join(","), listData);
                   }
                   scope.sendSms = CBCRM.sendSms;
                   /*左边导航权限*/
                   scope.authCustomer = true
                   scope.authContacts = false
                   scope.authSalesOpportunities = false
                   scope.authContract = false
                   scope.authProductList = false
                   scope.authAccounting = false
                   scope.authCalendar = false
                   scope.authCalls = false
                   scope.authFollowUp = false
                   scope.authCServices = false
                   scope.authComplaints = false
                   scope.authHistory = false
                   scope.authCredentials = false
                   scope.authDocumentaryOffer = false
                   scope.authDynamic = false
                   scope.getAuthForView = function () {
                       model.authContacts = CBCRM.hasAuth(1030000)
                       model.authSalesOpportunities = CBCRM.hasAuth(2020400)
                       model.authContract = CBCRM.hasAuth(2020600)
                       model.authProductList = CBCRM.hasAuth(2020700)
                       model.authAccounting = CBCRM.hasAuth(7020000)
                       model.authCalendar = CBCRM.hasAuth(4030000)
                       model.authCalls = CBCRM.hasAuth(3020000)
                       model.authFollowUp = CBCRM.hasAuth(3030000)
                       model.authCServices = CBCRM.hasAuth(3040000)
                       model.authComplaints = CBCRM.hasAuth(3050000)
                       model.authHistory = CBCRM.hasAuth(1050100)
                       model.authCredentials = CBCRM.hasAuth(302)
                       model.authDocumentaryOffer = CBCRM.hasAuth(2020500)
                       model.authDynamic = CBCRM.hasAuth(1060000)
                   }

                   //查看传递参数
                   scope.getViewOps = function () {
                       var ops={
                           reloadData: function () {
                               model.conditionChanged(null, model.createDyQuery());
                           }
                       };
                       return ops;
                   }
                   //查看
                   scope.doview = function () {
                       var path = $(this).attr('path')
                       goto(path, true, model.getViewOps());
                   }

                   //快捷菜单
                   scope.$curC = {};
                   scope.doview2 = function (nav) {
                       var c = model.$curC;
                       var url = c.DetailUrl.substring(1) + c.Id + "/" + nav;
                       goto(url,true,model.getViewOps());
                   }
                   scope.ifShowDMenu = false;
                   scope.showDmenu = function (b) {
                       model.ifShowDMenu = b;
                   }
                   scope.loadDmenu = function (c) {
                       var a = $(this), o = a.offset(), m = $("#cDMenu");
                       var l = o.left + 20, t = o.top + a.height();
                       if (m.height() + t > $(document.body).height()) {
                           t = t - m.height() - a.height();
                       }
                       m.css({ left: l, top: t });
                       model.$curC = c;
                       model.showDmenu(true);
                   }
                   //显示客户更多信息
                   scope.curshowid = "";
                   scope.curCEntity = {};
                   scope.curshow = function (c) {
                       if (c.Id == scope.curCEntity.Id) {
                           scope.curshowid = "";
                           scope.curCEntity = {};
                       } else {
                           scope.curshowid = c.Id;
                           scope.curCEntity = c.$model;
                       }
                   }

                   /*查看地图*/
                   scope.$mapLoaded = false;
                   scope.$map = null;
                   scope.loadMap = function (callback) {
                       if (!scope.$mapLoaded) {
                           var _t = window.setTimeout(function () {
                               messageBox.close();
                               messageBox.warning("连接地图服务器超时，请检查您的网络连接 ！");
                           }, 10000)
                           require(["bdmapTool", "ready!"], function (bdmapTool) {
                               if (_t) window.clearTimeout(_t);
                               scope.$map = new bdmapTool({
                                   tmpl: "line",
                                   mapContent: "#dmap",
                                   linepanel: "divline",
                                   left: 0,
                                   right: 820,
                                   height: 520,
                                   pstart: scope.curCEntity.Address,
                                   pend: scope.curCEntity.CompanyAddress
                               });
                               scope.$maploaded = true;
                               if (callback) callback.call(scope.$map);
                           });
                       } else {
                           if (callback) {
                               callback.call(scope.$map);
                           }
                       }
                   }
                   scope.$marker = null;
                   scope.detailMap = function () {
                       var win = art.dialog({
                           width: 300,
                           height: 100,
                           title: "地图加载中……",
                           content: "<img src='/Content/Themes/Base/images/loading2.gif' />"
                       });
                       scope.loadMap(function () {
                           var map = scope.$map;
                           var point, city;
                           var cmyInfo = CBCRM.cmyInfo || {};
                           city = scope.curCEntity.CompanyCityDisplay;
                           if (city == "") city = scope.curCEntity.CompanyAddress;
                           if (model.curCEntity.Lng) {
                               point = new BMap.Point(model.curCEntity.Lng, model.curCEntity.Lat);
                           } else {
                               point = null;
                               messageBox.error("抱歉，地图还未标注！");
                               return;
                           }
                           var pointStart;
                           if (cmyInfo.Lng) {
                               pointStart = new BMap.Point(cmyInfo.Lng, cmyInfo.Lat);
                               map.ops.pointStart = pointStart;
                           }
                           map.ops.customer = model.curCEntity.$model;
                           map.ops.company = model.curCEntity.$model;
                           map.ops.city = city;
                           map.ops.point = point;
                           map.ops.pointEnd = point;
                           map.openMap(function () {
                               if (win) win.close();
                               if (point) {
                                   map.map.panTo(point);
                                   //map.map.setCenter(point);
                               } else {
                                   map.map.setCenter(city);
                               }
                           });
                       });
                   }

                   //新增
                   scope.doadd = function (path) {
                       if (!path) {
                           if (router.path.indexOf('/Customer/Collaborate') > -1) {
                               path = '/Customer/AddCollaborate'
                           } else if (router.path.indexOf('/Customer/Channel') > -1) {
                               path = '/Customer/AddChannel'
                           }
                           else if (router.path.indexOf('/Customer/Supply') > -1) {
                               path = '/Customer/AddSupply'
                           }
                           else if (router.path.indexOf('/Customer/Advertising') > -1) {
                               path = '/Customer/AddAdvertising'
                           }
                           else if (router.path.indexOf('/Customer/Competitor') > -1) {
                               path = '/Customer/AddCompetitor'
                           }
                           else if (router.path.indexOf('/Customer/Sociall') > -1) {
                               path = '/Customer/AddSociall'
                           } else {
                               path = '/Customer/AddCustomer'
                           }
                       }
                       goto(path)
                   }

                   //编辑
                   scope.doedit = function () {
                       var path = $(this).attr('path')
                       goto(path)
                   }

                   //新增下拉菜单
                   scope.IsShowAddList = false
                   scope.showAddList = function () {
                       if (router.path.indexOf('/Customer/All') > -1)
                           model.IsShowAddList = !model.IsShowAddList
                   }
                   scope.IsAllCustomer = false
                   scope.exportExcel2 = function () {
                       var fileName = "客户列表";
                       var colModel = {
                           "ShortName": "助记简称",
                           "Name": "客户名称",
                           "CustomerTypeDisplay": "类型",
                           "SuperiorCategoryDisplay": "分类",
                           "OwnerBy": "归属",
                           "StageDisplay": "阶段",
                           "AddTime": "创建时间",
                           "LastEditTime": "最后修改时间",
                           "LastVisit": "最后回访时间"
                       };
                       ExportExcel(fileName, colModel, model.customers);
                   }

                   //排序
                   scope.sort = "AddTime"
                   scope.sortValue = 0;
                   scope.sortModel = {
                       AddTime: 0,
                       LastDocumentary: 1,
                       LastVisit: 1,
                       LastSign: 1
                   }
                   scope.autosort = function (colname) {
                       var sortvalue = model.sortModel[colname] == 0 ? 1 : 0;
                       model.sort = colname;
                       model.sortValue = sortvalue;
                       model.sortModel[colname] = sortvalue;
                       conditions = model.createDyQuery()
                       conditions.orderName = colname;
                       conditions.orderValue = sortvalue;
                       model.loadData(conditions)
                   }
               })
               var action = router.params.action, paramid = router.params.id;
               model.$watch('onlyMy', watchOnlyMy)

               model.$watch('checkAll', function (n, o) {
                   if (n != o) {
                       model.customers.forEach(function (c) {
                           c.checked = n
                       })
                   }
               })
               model.getAuthForView();
               model.$watch('custom', watchCustom)
               if (paramData) {
                   for (var key in paramData) {
                       avalon.log(key+":"+paramData[key])
                       model.addCondition(key, paramData[key], true);
                   }
               }
               CBCRM.loadView('/Customer/CustomerList.html', function (t) {
                   tmpl = tmpl.replace('{{gridTmpl|html}}', t)
                   avalon.vmodels.CBCRM.fillContent(tmpl, lang, contentId, module, model)
                   menus = avalon.vmodels.customerMenu
                   if (menus && router.path.indexOf('/Customer/All') > -1) {
                       menus.menus.forEach(function (m) {
                           m.selected = false
                       })
                       CBCRM.gps.removeAt(CBCRM.gps.size() - 1)
                       model.IsAllCustomer = true;
                   }
                   switch (action) {
                       case "key":
                           model.key = paramid;
                           model.execSearch(model)
                           break;
                       case "area":
                           //model.listOpts.paging.initload = false;
                           //model.queryArea(paramid);
                           model.areaId = paramid
                           break;
                   }

               })
           },
           AddCollaborate: function (tmpl, lang, contentId, module) {
               var inputCustomer, addMenu
               module.AddCustomer.call(this, tmpl, lang, contentId, module)
               inputCustomer = avalon.vmodels.InputCustomer
               inputCustomer.initComplete = function (m, ret) {
                   m.category.removeAll()
                   m.customerEntity.CategoryId = ''
                   m.customerEntity.SuperiorCategoryId = 10131 //合作伙伴

               }
               inputCustomer.AddCustomerTitle = lang.AddCollaborateTitle
               inputCustomer.AddCustomerDesc = lang.AddCollaborateDesc
               //addMenu = avalon.vmodels.addMenu
               //addMenu.menus.forEach(function (m) {
               //    m.selected = m.id === 1020302 //高亮合作伙伴菜单
               //})
           },
           AddChannel: function (tmpl, lang, contentId, module) {
               var inputCustomer, addMenu
               module.AddCustomer.call(this, tmpl, lang, contentId, module)
               inputCustomer = avalon.vmodels.InputCustomer
               inputCustomer.AddCustomerUrl = '/Customer/SetChannel'
               inputCustomer.initComplete = function (m, ret) {
                   m.category.removeAll()
                   m.customerEntity.CategoryId = ''
                   m.customerEntity.SuperiorCategoryId = 10132 //渠道代理商
               }
               //addMenu = avalon.vmodels.addMenu
               //addMenu.menus.forEach(function (m) {
               //    m.selected = m.id === 1020402 //高亮渠道代理商菜单
               //})
           },
           AddSupply: function (tmpl, lang, contentId, module) {
               var inputCustomer, addMenu
               module.AddCustomer.call(this, tmpl, lang, contentId, module)
               inputCustomer = avalon.vmodels.InputCustomer
               inputCustomer.initComplete = initSupply
               inputCustomer.AddCustomerUrl = '/Customer/SetSupply'
               //addMenu = avalon.vmodels.addMenu
               //addMenu.menus.forEach(function (m) {
               //    m.selected = m.id === 1020502 //高亮供应商菜单
               //})
           },
           AddAdvertising: function (tmpl, lang, contentId, module) {
               var inputCustomer, addMenu
               module.AddCustomer.call(this, tmpl, lang, contentId, module)
               inputCustomer = avalon.vmodels.InputCustomer
               inputCustomer.initComplete = initAdvertising
               inputCustomer.AddCustomerUrl = '/Customer/SetAdvertising'
               //addMenu = avalon.vmodels.addMenu
               //addMenu.menus.forEach(function (m) {
               //    m.selected = m.id === 1020602 //高亮媒体资源菜单
               //})
           },
           AddCompetitor: function (tmpl, lang, contentId, module) {
               var inputCustomer, addMenu
               module.AddCustomer.call(this, tmpl, lang, contentId, module)
               inputCustomer = avalon.vmodels.InputCustomer
               inputCustomer.initComplete = initCompetitor
               inputCustomer.AddCustomerUrl = '/Customer/SetCompetitor'
               //addMenu = avalon.vmodels.addMenu
               //addMenu.menus.forEach(function (m) {
               //    m.selected = m.id === 1020702 //高亮竞争对手菜单
               //})

           },
           AddSociall: function (tmpl, lang, contentId, module) {
               var inputCustomer, addMenu
               module.AddCustomer.call(this, tmpl, lang, contentId, module)
               inputCustomer = avalon.vmodels.InputCustomer
               inputCustomer.initComplete = initSociall
               //addMenu = avalon.vmodels.addMenu
               //addMenu.menus.forEach(function (m) {
               //    m.selected = m.id === 1020802 //高亮社会关系菜单
               //})
           },
           EditCustomer: function (tmpl, lang, contentId, module) {
               module.AddCustomer.call(this, tmpl, lang, contentId, module)
               /*加载全部客户下的子菜单*/
               //setMenu('addMenu', 1020000)

           },
           EditCollaborate: function (tmpl, lang, contentId, module) {
               module.AddCustomer.call(this, tmpl, lang, contentId, module)
               /*加载全部客户下的子菜单*/
               //setMenu('addMenu', 1020000)

           },
           EditChannel: function (tmpl, lang, contentId, module) {
               var inputCustomer
               module.AddCustomer.call(this, tmpl, lang, contentId, module)
               inputCustomer = avalon.vmodels.InputCustomer
               inputCustomer.UpdateCustomerUrl = '/Customer/UpdateChannel/'
               /*加载全部客户下的子菜单*/
               //setMenu('addMenu', 1020000)
           },
           EditSupply: function (tmpl, lang, contentId, module) {
               var inputCustomer
               module.AddCustomer.call(this, tmpl, lang, contentId, module)
               inputCustomer = avalon.vmodels.InputCustomer
               inputCustomer.initComplete = initSupply
               inputCustomer.UpdateCustomerUrl = '/Customer/UpdateSupply/'
               /*加载全部客户下的子菜单*/
               //setMenu('addMenu', 1020000)
           },
           EditAdvertising: function (tmpl, lang, contentId, module) {
               var inputCustomer
               module.AddCustomer.call(this, tmpl, lang, contentId, module)
               inputCustomer = avalon.vmodels.InputCustomer
               inputCustomer.initComplete = initAdvertising
               inputCustomer.UpdateCustomerUrl = '/Customer/UpdateAdvertising/'
               /*加载全部客户下的子菜单*/
               //setMenu('addMenu', 1020000)
           },
           EditCompetitor: function (tmpl, lang, contentId, module) {
               var inputCustomer, addMenu
               module.AddCustomer.call(this, tmpl, lang, contentId, module)
               inputCustomer = avalon.vmodels.InputCustomer
               inputCustomer.initComplete = initCompetitor
               inputCustomer.UpdateCustomerUrl = '/Customer/UpdateCompetitor/'
               /*加载全部客户下的子菜单*/
               //setMenu('addMenu', 1020000)
           },
           EditSociall: function (tmpl, lang, contentId, module) {
               var inputCustomer, addMenu
               module.AddCustomer.call(this, tmpl, lang, contentId, module)
               inputCustomer = avalon.vmodels.InputCustomer
               inputCustomer.initComplete = initSociall
               /*加载全部客户下的子菜单*/
               //setMenu('addMenu', 1020000)
           },
           AddCustomer: function (tmpl, lang, contentId, module) {
               var groupPostFilter = function (treeId, parentNode, responseData) {
                   var ret = [], len, curr, hasMember = false
                   if (responseData.data && responseData.data.groups.length) {
                       len = responseData.data.groups.length
                       if (len) {
                           for (var i = 0; i < len; i++) {
                               curr = responseData.data.groups[i]
                               ret.push(curr)
                               curr.Posts.forEach(function (p, i) {
                                   if (!p.Users.length) return true
                                   hasMember = true
                                   p.Users.forEach(function (u, i) {
                                       var u = p.Users[i]
                                       u.ParentId = u.PositionId
                                       u.Name = u.FullName
                                   })
                                   curr.Posts[i].ParentId = p.Boss ? p.Boss.Id : p.Group
                                   ret.push(curr.Posts[i])
                                   ret = ret.concat(p.Users)
                               })
                           }
                       }
                   }
                   return ret
               },
               CBCRM = avalon.vmodels.CBCRM,
               getUserUrl = function () {
                   switch (model.customerEntity.SuperiorCategoryId) {
                       case '10103':
                           return "/Settings/GetGroupPostUser/1020200"
                       case '10107':
                           return "/Settings/GetGroupPostUser/1020100"
                       case '10131':
                           return "/Settings/GetGroupPostUser/1020300"
                       case '10132':
                           return "/Settings/GetGroupPostUser/1020400"
                       case '10133':
                           return "/Settings/GetGroupPostUser/1020500"
                       case '10134':
                           return "/Settings/GetGroupPostUser/1020600"
                       case '10135':
                           return "/Settings/GetGroupPostUser/1020700"
                       case '11170':
                           return "/Settings/GetGroupPostUser/1020800"
                       case 10103:
                           return "/Settings/GetGroupPostUser/1020200"
                       case 10107:
                           return "/Settings/GetGroupPostUser/1020100"
                       case 10131:
                           return "/Settings/GetGroupPostUser/1020300"
                       case 10132:
                           return "/Settings/GetGroupPostUser/1020400"
                       case 10133:
                           return "/Settings/GetGroupPostUser/1020500"
                       case 10134:
                           return "/Settings/GetGroupPostUser/1020600"
                       case 10135:
                           return "/Settings/GetGroupPostUser/1020700"
                       case 11170:
                           return "/Settings/GetGroupPostUser/1020800"
                   }
               },
               model = CBCRM.define('InputCustomer', function (scope) {
                   scope.destroy = function () {
                       var uis = ['shareToTree', 'belongToTree', 'setParetCustomer', 'setProxyArea', 'creditRaty', 'valueRaty', 'threatenRaty']
                       mvvm.destroyui(uis);
                       delete avalon.vmodels.addMenu
                   }
                   scope.$skipArray = ['lang', 'rootCategory', 'AddCustomerUrl', 'UpdateCustomerUrl', 'DetailCustomerUrl']
                   scope.lang = lang
                   scope.TRUN = true
                   scope.SHARE = true
                   scope.IsSuperAdmin = CBCRM.memberShip.IsSuperAdmin
                   scope.uploadFiles = upload
                   scope.AddCustomerTitle = lang.AddCustomerTitle
                   scope.AddCustomerDesc = lang.AddCustomerDesc
                   scope.EditCustomerTitle = lang.EditCustomerTitle
                   scope.EditCustomerDesc = lang.EditCustomerDesc
                   scope.AddCustomerUrl = '/Customer/SetCustomer'
                   scope.UpdateCustomerUrl = '/Customer/UpdateCustomer/'
                   scope.DetailCustomerUrl = '#/Customer/DetailCustomer/'
                   scope.InitCustomerUrl = '/Customer/AddCustomer'
                   scope.customerEntity = {}
                   scope.settingEntity = {};
                   scope.initComplete = function (m) {
                       //avalon.log('m is model')
                       if (!m.customerEntity.Id) {
                           m.customerEntity.CategoryId = ''
                           m.customerEntity.SuperiorCategoryId = 10107 //终端客户
                       }
                   }
                   scope.createCheckInfo = function (keys) {
                       var checkInfo = {};
                       keys.split(",").forEach(function (key) {
                           checkInfo[key] = { exists: false, title: "" };
                       });
                       return checkInfo;
                   }
                   scope.$checkInfoKeys = "CompanyTel1,CompanyTel2,Email,QQ,Wangwang";
                   scope.checkInfo = scope.createCheckInfo(scope.$checkInfoKeys);
                   scope.viewCheckInfo = function (key) {
                       var info = model.checkInfo[key];
                       var msgs = info.title.split("\n");
                       for (var i = 0, l = msgs.length; i < l; i++) {
                           if (i == 0) {
                               msgs[i] = "<h2 class='tipTitle'>" + msgs[i] + "</h2>";
                           } else {
                               msgs[i] = "<li>" + msgs[i] + "</li>";
                           }
                       }
                       messageBox.warning(msgs.join(""));
                   }
                   scope.checkCustomerTel = function (key) {
                       var cu = model.customerEntity.$model, tel = cu[key], cid = cu.Id;
                       if (tel == null || $.trim(tel) == "") return;
                       $.post("/Customer/CheckCustomerTel", {cid:cid,tel:tel}, function (ret) {
                           var msgs = [];
                           if (ret.data.exists) {
                               msgs.push("系统中已存在该号码(" + tel + ")的客户");
                               ret.data.customers.forEach(function (m) { msgs.push(m.Name ) });
                           }
                           model.checkInfo[key] = {exists:ret.data.exists, title: msgs.join("\n") };
                       });
                   }
                   scope.checkContactsTel = function (ct,key) {
                       var cu = model.customerEntity.$model, cid = cu.Id, id = ct.Id, ctkey = key;
                       key = key.split("_")[1];
                       var tel = ct[key];
                       if (tel == null || $.trim(tel) == "") {
                           model.checkInfo[ctkey] = { exists: false, title: "" };
                           createTip("checkInfo", ctkey, false);
                           return;
                       }
                       $.post("/Customer/CheckContactsTel", {cid:cid,tel:tel,id:id}, function (ret) {
                           var msgs = [];
                           if (ret.data.exists) {
                               msgs.push("系统中已存在该号码(" + tel + ")的联系人");
                               ret.data.contacts.forEach(function (m) {"联系人："+ msgs.push(m.Name + "，客户："+ m.CName) });
                           }
                           model.checkInfo[ctkey] = { exists: ret.data.exists, title: msgs.join("\n") };
                           createTip("checkInfo", ctkey, ret.data.exists);
                       });
                   }
                   scope.checkCustomerExists = function (key,title) {
                       var cu = model.customerEntity.$model, value = cu[key];
                       if (title == null) title = key;
                       if (value == null || $.trim(value) == "") return;
                       $.post("/Customer/CheckCustomerExists", { cid: cu.Id, key: key,value:value }, function (ret) {
                           if (!ret || !ret.result) {
                               model.checkInfo[key] = { exists: false, title: ""};
                               return CBCRM.showResult(ret);
                           }
                           var msgs = [];
                           if (ret.data.exists) {
                               msgs.push("系统中已存在该" + title + "(" + value + ")的客户");
                               ret.data.customers.forEach(function (m) { msgs.push(m.Name) });
                           }
                           model.checkInfo[key] = { exists: ret.data.exists, title: msgs.join("\n") };
                       });
                   }
                   scope.checkContactsExists = function (ct,key, title) {
                       ct = ct.$model;
                       var ctkey = key;
                       key = key.split("_")[1];
                       var value = ct[key];
                       if (title == null) title = key;
                       if (value == null || $.trim(value) == "") {
                           model.checkInfo[ctkey] = { exists: false, title: "" };
                           createTip("checkInfo", ctkey, false);
                           return;
                       }
                       $.post("/Customer/CheckContactsExists", { cid: ct.Id, key: key, value: value }, function (ret) {
                           if (!ret || !ret.result) {
                               model.checkInfo[ctkey] = { exists: false, title: "" };
                               createTip("checkInfo", ctkey, false);
                               return CBCRM.showResult(ret);
                           }
                           var msgs = [];
                           if (ret.data.exists) {
                               msgs.push("系统中已存在该" + title + "(" + value + ")的联系人");
                               ret.data.contacts.forEach(function (m) { "联系人："+msgs.push(m.Name + "，客户：" + m.CName) });
                           }
                           model.checkInfo[ctkey] = { exists: ret.data.exists, title: msgs.join("\n") };
                           createTip("checkInfo", ctkey, ret.data.exists);
                       });
                   }
                   scope.$mapwin = null;
                   scope.addressKey = "";
                   /*地图标注*/
                   scope.$mapLoaded = false;
                   scope.$map = null;
                   scope.loadMap = function (callback) {
                       if (!scope.$mapLoaded) {
                           var win = art.dialog({
                               width: 300,
                               height: 100,
                               title: "地图加载中……",
                               content: "<img src='/Content/Themes/Base/images/loading2.gif' />"
                           });
                           require(["bdmapTool", "ready!"], function (bdmapTool) {
                               scope.$map = new bdmapTool({
                                   mapContent: "#dmap",
                                   tmpl: "search",
                                   searchpanel: "seekpanel",
                                   left: 285,
                                   pointCallBack: function (p, box) {
                                       model.customerEntity.CompanyAddress = p.address;
                                       model.customerEntity.Lng = p.point.lng;
                                       model.customerEntity.Lat = p.point.lat;
                                       box.close();
                                   },
                                   searchCallBack: function (p, box) {
                                       model.customerEntity.CompanyAddress = p.address;
                                       model.customerEntity.Lng = p.point.lng;
                                       model.customerEntity.Lat = p.point.lat;
                                       box.close();
                                   }
                               });
                               if (win) win.close();
                               scope.$mapLoaded = true;
                               if (callback) callback.call(scope.$map);
                           });
                       } else {
                           if (callback) callback.call(vm.$map);
                       }
                   }
                   scope.markInMap = function () {
                       scope.loadMap(function () {
                           var map = scope.$map;
                           map.ops.city = model.customerEntity.CompanyCityDisplay;
                           if (",市辖区,县,".indexOf(map.ops.city) > -1 || map.ops.city == "") map.ops.city = scope.customerEntity.CompanyProvinceDisplay;
                           var point;
                           if (model.customerEntity.Lng) {
                               point = new BMap.Point(model.customerEntity.Lng, model.customerEntity.Lat);
                               console.log(point);
                           } else {
                               point = null;
                           }
                           map.openMap(function () {
                               if (point) {
                                   map.ops.point = point;
                                   map.addMarker(point, model.customerEntity.Name, { html: model.customerEntity.Name, ops: { width: 250 } });
                               } else {
                                   if (model.customerEntity.CompanyAddress != "") {
                                       map.searchMap(model.customerEntity.CompanyAddress);
                                   }
                               }
                           });
                       });
                   }
                   scope.existsCustomer = function () {
                       var name = model.customerEntity.Name
                       if (name) {
                           name = name.trim()
                           model.customerEntity.Name = name
                           $.post('/Customer/ExistsCustomer', { name: name })
                           .done(function (ret) {
                               var m = model, tmpl
                               , d, content, vm
                               if (ret.result) {
                                   messageBox.ok(ret.message)
                               } else {
                                   m = model
                                   tmpl = '<div style="overflow-y:auto;height:500px;width:800px;">'
                                    + '<div style="font-size:14px;color:#666;font-weight:bold;">系统中检测到以下类似或重复客户：</div>'
                                    + '<table ms-controller="repeatCustomers" width="100%" border="0" cellspacing="1" cellpadding="0" class="tableList bottom10" id="tableList">'
                                    + '<thead>'
                                    + '<tr class="head">'
                                    + '<td width="15%" align="center">客户名称</td>'
                                    + '<td width="15%" align="center">地址</td>'
                                    + '<td width="10%" align="center">电话</td>'
                                    //+ '<td width="10%" align="center">开放客户</td>'
                                    + '<td width="8%" align="center">电子邮件</td>'
                                    + '<td width="10%" align="center">归属人</td>'
                                    + '<td width="8%" align="center">创建时间</td>'
                                    //+ '<td width="15%" align="center">共享人</td>'
                                    + '</tr></thead><tbody><tr ms-repeat-ec="list">'
                                    + '<td align="center" ms-html="ec.name"></td>'
                                    + '<td align="center" ms-html="ec.address"></td>'
                                    + '<td align="center" ms-html="ec.mobileNumber1"></td>'
                                    //+ '<td align="center" ms-html="ec.openDisplay"></td>'
                                    + '<td align="center" ms-html="ec.email"></td>'
                                    + '<td align="center">'
                                    + "<a href='javascript:void(0);' ms-widget='userCard' ms-data-userid='ec.userId' ms-html='ec.userName'></a>"
                                    + '</td>'
                                    + '<td align="center" ms-html="ec.addTime"></td>'
                                    //+ '<td align="left"><a ms-repeat-user="ec.shareTo" style="margin-right:5px;" href="javascripg:void(0)" ms-html="user.FullName" ms-data-id="user.Id" ms-widget="userCard"></a></td>'
                                    + '</tbody></table></div>',
                                    d = messageBox.openHtml('检测重复客户', '800px', '', tmpl)
                                   content = $(d.content())
                                   vm = avalon.define('repeatCustomers', function (scope) {
                                       scope.list = []
                                   })
                                   vm.list = ret.data
                                   avalon.scan(content[0], vm)
                               }
                           })
                       }
                   }
                   scope.lockSubmit = false
                   scope.checkSubmit = function () {
                       var data = model.customerEntity.$model;
                       data.Name = $.trim(data.Name);
                       if (data.Name == "") {
                           messageBox.warning("请填写客户名称！");
                           return false;
                       }
                       var postForm = where(data, true, {});
                       model.submitForm();
                   }
                   scope.submitForm = function () {
                       model.customerEntity.Intro = kind.html()
                       var data = model.customerEntity.$model,
                       formatData = avalon.mix({}, data),
                       j = 0,
                       has = false,
                       //tmp = 'FirstContacts.', 
                       shareTmp = 'ShareTo[i]',
                       labelTmp = data.Id ? 'ServerLabel[i]' : 'ServerLabel[i]',
                       regionTmp = 'AuthorizedRegionals[j]',
                       quaTmp = 'Qualification[j]',
                       expamdoTmp = 'Expandos[{0}].{1}',
                       expandoVal
                       model.lockSubmit = true
                       delete formatData.FirstContacts
                       delete formatData.ShareTo
                       delete formatData.ServerLabel

                       formatData["AddById"] = model.customerEntity.$model.AddBy.Id

                       if (data.Type !== '1') {
                           /*不是个人客户，填充联系人*/
                           var conlist = []
                           for (var i = 0, tmp; tmp = model.contactsList[i]; i++) {
                               if (tmp.Name) {
                                   conlist.push(tmp)
                               }
                           }
                           for (var i = 0, tmp; tmp = conlist[i]; i++) {
                               //if (i == 0) tmp.IsFirst = true
                               formatData['Contacts[' + i + '].IsFirst'] = tmp.IsFirst
                               formatData['Contacts[' + i + '].Id'] = tmp.Id
                               formatData['Contacts[' + i + '].Name'] = tmp.Name
                               formatData['Contacts[' + i + '].Sex'] = tmp.Sex
                               formatData['Contacts[' + i + '].Post'] = tmp.Post
                               formatData['Contacts[' + i + '].MobileNumber1'] = tmp.MobileNumber1
                               formatData['Contacts[' + i + '].OfficeTel'] = tmp.OfficeTel
                               formatData['Contacts[' + i + '].QQ'] = tmp.QQ
                               formatData['Contacts[' + i + '].Email'] = tmp.Email

                           }
                           /*填充删除的联系人*/
                           for (var i = 0, tmp; tmp = model.contactDelList[i]; i++) {
                               formatData['ContactsDels[' + i + '].Id'] = tmp.Id
                               formatData['ContactsDels[' + i + '].Name'] = tmp.Name
                               formatData['ContactsDels[' + i + '].Sex'] = tmp.Sex
                               formatData['ContactsDels[' + i + '].Post'] = tmp.Post
                               formatData['ContactsDels[' + i + '].MobileNumber1'] = tmp.MobileNumber1
                               formatData['ContactsDels[' + i + '].OfficeTel'] = tmp.OfficeTel
                               formatData['ContactsDels[' + i + '].QQ'] = tmp.QQ
                               formatData['ContactsDels[' + i + '].Email'] = tmp.Email
                           }
                       }
                       /*填充供应商相关资质*/
                       for (var i = 0, tmp; tmp = data.Qualification[i]; i++) {
                           formatData[quaTmp.replace('j', i)] = tmp
                       }
                       /*填充代理商区域*/
                       for (var i = 0, tmp; tmp = data.AuthorizedRegionals[i];) {
                           formatData[regionTmp.replace('j', i)] = tmp
                           i++
                       }

                       /*填充共享人员*/
                       for (var i = 0, tmp; tmp = data.ShareTo[i];) {
                           formatData[shareTmp.replace('i', i)] = tmp
                           i++
                           has = true
                       }
                       if (!has) formatData[shareTmp.replace('i', 0)] = ''
                       /*填充服务标签*/
                       has = false
                       for (var i = 0, tmp; tmp = model.serviceLabel[i++];) {
                           if (tmp.checked) {
                               has = true
                               formatData[labelTmp.replace('i', j)] = tmp.Id
                               j++
                           }
                       }
                       if (!has) formatData[labelTmp.replace('i', 0)] = ''
                       j = 0
                       for (var expando in model.expando.$model) {
                           var editor = editors[expando];
                           if (editor) {
                               model.expando[expando] = editor.html();
                           }
                           expandoVal = data[expando] != null ? data[expando] : model.expando[expando];//model.expando[expando] 无值
                           if ($.isArray(expandoVal))
                               expandoVal = expandoVal.join(',')
                           formatData[expamdoTmp.replace('{0}', j).replace('{1}', 'Key')] = expando
                           formatData[expamdoTmp.replace('{0}', j).replace('{1}', 'Value')] = expandoVal
                           j++
                       }
                       //formatData.Intro = kind.html()

                       /*业务分类*/
                       formatData.BusinessTypes = formatData.BusinessTypesArr.join(",");
                       delete formatData.BusinessTypesArr;

                       delete formatData.AuthorizedRegionals
                       formatData.Name = formatData.Name.trim()
                       $.post(data.Id ? model.UpdateCustomerUrl + data.Id : model.AddCustomerUrl, formatData)
                       .done(function (ret) {
                           model.lockSubmit = false
                           CBCRM.showResult(ret, function () {
                               if (ret.result) {
                                   messageBox.close()
                                   if (avalon.vmodels.listPage) {
                                       avalon.vmodels.listPage.reload()
                                   }
                               }
                           })
                       })
                   }
                   scope.stage = []
                   scope.source = []
                   scope.scale = []
                   scope.industry = []
                   scope.relation = []
                   scope.mode = []
                   scope.contactRole = []
                   scope.bank = []
                   scope.serviceLabel = []
                   scope.businessType = []
                   scope.idcardType = []
                   scope.category = []
                   scope.subCategory = []
                   scope.types = []
                   scope.country = []
                   scope.province = []
                   scope.city = []
                   scope.area = []
                   scope.stateGrade = [];
                   scope.stateGrades = [];
                   scope.memberGrade = [];
                   scope.suppliersStage = []
                   scope.supplierLevel = [] //供应商等级
                   scope.qualification = [] //供应商相关资质
                   scope.marketPosition = [] //竞争对手市场地位
                   scope.proxyOpts = { //代理商区域
                       treeopts: {
                           callback: {
                               onCheck: function (e, id, node) {
                                   var tree = $.fn.zTree.getZTreeObj(id),
                                   nodes = tree.getCheckedNodes(true),
                                   data = [], names = [],
                                   m = model
                                   nodes.forEach(function (n, i) {
                                       data.push(n.Id)
                                       names.push(n.Name)
                                   })
                                   m.customerEntity.AuthorizedRegionals = data
                                   m.customerEntity.AuthorizedRegionalsDisplay = names.join(',')
                               }
                           }
                       }
                   }
                   scope.isPerson = false //是否个人客户
                   scope.showCompanyInfo = false
                   scope.getPY = function () {
                       var $that = $("#txtCustomerName"), py
                       if ($that.val()) {
                           py = $that.toPinyin().substring(0, 10);
                           model.customerEntity.ShortName = py
                           model.customerEntity.FirstName = model.customerEntity.Name.substr(0, 1)
                           model.customerEntity.FirstNameLetter = py.substr(0, 1)
                           avalon.log('ShortName : ' + model.customerEntity.ShortName)
                       }
                   }
                   scope.setCompanyInfo = function () {
                       model.showCompanyInfo = !model.showCompanyInfo
                   }
                   /*热度*/
                   scope.hotOpts = {
                       valChanged: function (val) {
                           model.customerEntity.Temperature = val
                           avalon.log('model.customerEntity.Temperature : ' + model.customerEntity.Temperature)
                       }
                   }
                   /*价值评估*/
                   scope.valueRatyOpts = {
                       ratyChanged: function (val) {
                           model.customerEntity.Value = val
                           avalon.log('model.customerEntity.Value : ' + model.customerEntity.Value)
                       }
                   }
                   /*威胁值评估*/
                   scope.threatenRatyOpts = {
                       ratyChanged: function (val) {
                           model.customerEntity.Threaten = val
                           avalon.log('model.customerEntity.Threaten : ' + model.customerEntity.Threaten)
                       }
                   }
                   /*信用等级*/
                   scope.creditRatyOpts = {
                       ratyChanged: function (val) {
                           model.customerEntity.Credit = val
                           avalon.log('model.customerEntity.Credit : ' + model.customerEntity.Credit)
                       },
                       ratyon: '/Content/Themes/Base/Images/raty/medal-on.png', //选中评级图标
                       ratyoff: '/Content/Themes/Base/Images/raty/medal-off.png' //未选中评级图标
                   }
                   /*归属员工、录入员工*/
                   scope.selectUser = function (type) {
                       plugins.selectUser({
                           dataAuth: cuDiRes[model.customerEntity.SuperiorCategoryId] || getCuRes(),
                           callback: function (us) {
                               var customerEntity = model.customerEntity
                               var u = us[0];
                               if (type == "Owner") {
                                   customerEntity.OwnerName = u.FullName
                                   customerEntity.Owner = u.Id
                               } else {
                                   model.customerEntity.AddBy.FullName = u.FullName
                                   model.customerEntity.AddBy.Id = u.Id
                               }
                           }
                       });
                   }
                   //共享员工
                   scope.selectShareUsers = function() {
                       var listData = model.customerEntity.ShareTo;
                       plugins.selectUser({
                           multiple: true,
                           required:false,
                           listData: listData,
                           isJoin:true,
                           callback: function (us) {
                               var names = [], ids = [];
                               us.forEach(function (u) {
                                   names.push(u.FullName);
                                   ids.push(u.Id);
                               });
                               model.customerEntity.ShareNames = names.join(',')
                               model.customerEntity.ShareTo = ids
                               model.customerEntity.Share = ids.join(',')
                           }
                       });
                   }
                   //选择上级客户
                   scope.selectCustomer = function () {
                       var customerEntity = model.customerEntity
                       var listData = [];
                       if (customerEntity.HigherCustomerId) listData.push({ id: customerEntity.HigherCustomerId });
                       plugins.selectCustomer({
                           listData: listData,
                           callback: function (list) {
                               var item = list[0];
                               if (item.Id == customerEntity.Id) {
                                   messageBox.warning("客户的上级客户不能是自己，请重新选择！");
                                   return false;
                               }
                               customerEntity.HigherCustomerId = item.Id
                               customerEntity.ParentName = item.Name
                           }
                       });
                   }

                   //质量水平星级ui
                   scope.qualityOpts = {
                       ratyChanged: function (val) {
                           model.customerEntity.Quality = val
                       }
                   }
                   //交货能力星级ui
                   scope.abilityOpts = {
                       ratyChanged: function (val) {
                           model.customerEntity.Ability = val
                       }
                   }
                   //价格水平星级ui
                   scope.priceOpts = {
                       ratyChanged: function (val) {
                           model.customerEntity.Price = val
                       }
                   }
                   //技术和生产能力星级ui
                   scope.technologyOpts = {
                       ratyChanged: function (val) {
                           model.customerEntity.Technology = val
                       }
                   }
                   //后援服务星级ui
                   scope.serviceOpts = {
                       ratyChanged: function (val) {
                           model.customerEntity.Service = val
                       }
                   }
                   //企业声誉星级ui
                   scope.reputationOpts = {
                       ratyChanged: function (val) {
                           model.customerEntity.Reputation = val
                       }
                   }
                   //现有合作状况星级ui
                   scope.cooperationOpts = {
                       ratyChanged: function (val) {
                           model.customerEntity.Cooperation = val
                       }
                   }
                   //日期选择
                   scope.birthdayOpts = {
                       format: '%Y-%m-%d',
                       onSelect: function (date, formatDate, format) {
                           /*
                               date:javascript Date object
                               formatDate:使用format格式化后的日期
                               format :日期格式
                           */
                           model.customerEntity.Birthday = formatDate
                           avalon.log('model.customerEntity.Birthday : ' + model.customerEntity.Birthday)
                       }
                   }
                   scope.rootCategory = [10103, 10107]

                   //自定义字段
                   scope.expando = {}
                   scope.expandoTmpl = ''

                   //tab切换
                   scope.tab = 'tab1'
                   scope.tabChange = function () {
                       var tabid = $(this).attr("val")
                       model.tab = tabid
                   }
                   //联系人
                   scope.contactsList = []
                   scope.contactDelList = []  //存客户删除的联系人
                   scope.firstChange = function (m) {
                       if (!this.checked) return;
                       model.contactsList.forEach(function (c) {
                           c.IsFirst = false;
                       });
                       avalon.nextTick(function () {
                           m.IsFirst = true;
                       });
                   }
                   scope.contactsAdd = function () {
                       var contactsData = factory.create('Contacts')
                       contactsData.ContactRoleId = 10047   //默认为重要联系人
                       model.contactsList.push(contactsData)
                       var index=model.contactsList.length - 1;
                       model.watchContacts(model.contactsList[index],index);
                   }
                   scope.contactsDel = function () {
                       var index = parseInt($(this).attr("index"))
                       var con = model.contactsList.$model[index]
                       if (con.Id > 0) model.contactDelList.push(con)
                       model.contactsList.removeAt(index)
                   }
                   scope.watchContacts = function (item,i) {
                       "MobileNumber1,OfficeTel".split(",").forEach(function (key) {
                           var ctkey = "ct_" + key + "_" + i;
                           item.$watch(key, delayWatch.get(ctkey, function (k,n,o) {
                               model.checkContactsTel(item, k);
                           }));
                       });
                       "QQ,Email".split(",").forEach(function (key) {
                           var ctkey = "ct_" + key + "_" + i;
                           item.$watch(key, delayWatch.get(ctkey, function (k, n, o) {
                               model.checkContactsExists(item, k);
                           }));
                       });
                   }
               }),
               allSubCategory = [],
               allLocations = [],
               kind, that = this,
               addMenus = CBCRM.getMenus(102), //获取新增客户菜单
               init = function () {
                   $.get(that.path)
                   .done(function (ret) {
                       var customerEntity = model.customerEntity,
                       rootCategory = model.rootCategory,
                       propDataMaps = {
                           StageId: 'Stage'
                        , SourceId: 'Source'
                        , ScaleId: 'Scale'
                        , IndustryId: 'Industry'
                        , RelationId: 'Relation'
                        , ModeId: 'Mode'
                        , contactRole: 'ContactRole'
                        , Bank: 'Bank'
                        , BusinessType: 'BusinessType'
                        , IdCardTypeId: 'IdCardType'
                       }, data, hasDefault = false
                       , uis = ['creditRaty', 'valueRaty', 'hotprocessbar']
                       ret.data.Dicts.ServiceLabel.forEach(function (s) {
                           s.checked = false
                       })
                       if (ret.data.opts) {
                           model.TRUN = ret.data.opts.TRUN
                           model.SHARE = ret.data.opts.SHARE
                       }
                       model.stage = ret.data.Dicts.Stage
                       model.source = ret.data.Dicts.Source
                       model.scale = ret.data.Dicts.Scale
                       model.industry = ret.data.Dicts.Industry
                       model.relation = ret.data.Dicts.Relation
                       model.mode = ret.data.Dicts.Mode
                       model.contactRole = ret.data.Dicts.ContactRole
                       model.bank = ret.data.Dicts.Bank
                       model.serviceLabel = ret.data.Dicts.ServiceLabel
                       model.businessType = ret.data.Dicts.BusinessType
                       model.idcardType = ret.data.Dicts.IdCardType
                       model.memberGrade = ret.data.Dicts.MemberGrade
                       model.stateGrade = ret.data.Dicts.StateGrade
                       model.category.removeAll()
                       model.subCategory.removeAll()
                       allSubCategory = ret.data.Dicts.SubCategory
                       allLocations = ret.data.Dicts.Locations
                       ret.data.Dicts.Category.forEach(function (c) {
                           if (!c.ParentId) {
                               if (rootCategory.length && rootCategory.indexOf(c.Id) < 0) {
                                   return true
                               }
                               model.category.push(c)
                           }
                       })
                       for (var m = 0, target ; target = uis[m++];) {
                           if (avalon.vmodels[target])
                               avalon.vmodels[target].val = target == 'hotprocessbar' ? 10 : 1
                       }

                       if (ret.data.customFields) {
                           model.expando = ret.data.customFields
                           createEditors();
                       }
                       if (ret.data.Customer) {
                           model.customerEntity = avalon.mix(true, factory.create('Customer'), ret.data.Customer)
                           model.customerEntity.Type += ''
                           model.customerEntity.IsHot += ''
                           model.customerEntity.IsBlackList += ''
                           model.customerEntity.Sex += ''
                           model.customerEntity.FirstContacts.Sex += ''
                           model.customerEntity.FirstContacts.ContactRoleId += ''
                           model.customerEntity.ShareNames = ret.data.ShareToNames.join(',')
                           model.customerEntity.BusinessTypesArr = ret.data.Customer.BusinessTypes ? ret.data.Customer.BusinessTypes.split(",") : [];
                           model.isPerson = model.customerEntity.Type == 1
                           if (model.customerEntity.ServerLabel) {
                               model.serviceLabel.forEach(function (s, i) {
                                   model.serviceLabel[i].checked = (model.customerEntity.ServerLabel.indexOf(s.Id) > -1)
                               })
                           }
                           if (avalon.vmodels.creditRaty)
                               avalon.vmodels.creditRaty.val = model.customerEntity.Credit
                           if (avalon.vmodels.valueRaty)
                               avalon.vmodels.valueRaty.val = model.customerEntity.Value
                           if (avalon.vmodels.hotprocessbar)
                               avalon.vmodels.hotprocessbar.val = model.customerEntity.Temperature
                           if (ret.data.Customer.Expandos) {
                               model.expando = ret.data.Customer.Expandos
                               createEditors();
                           }

                           //公司介绍编辑器
                           if (kind) kind.html(model.customerEntity.Intro);
                       }
                       bindWatch(model.customerEntity)
                       allLocations.forEach(function (l) {
                           if (l.ParentId === 0) {
                               model.country.push(l)
                               if (!model.customerEntity.Id) {
                                   model.customerEntity.CompanyCountryId = 0
                                   model.customerEntity.CompanyCountryId = l.Id
                               }
                           }
                       })
                       if (model.customerEntity.Id) {
                           //绑定watch后重新赋值刷新视图
                           var tmp = model.customerEntity.SuperiorCategoryId
                           if (tmp) {
                               model.customerEntity.SuperiorCategoryId = 0
                               model.customerEntity.SuperiorCategoryId = tmp + ''
                           }
                           tmp = model.customerEntity.CategoryId
                           if (tmp) {
                               model.customerEntity.CategoryId = 0
                               model.customerEntity.CategoryId = tmp + ''
                           }
                           tmp = ret.data.Customer.CompanyCountryId
                           if (tmp) {
                               model.customerEntity.CompanyCountryId = 0
                               model.customerEntity.CompanyCountryId = tmp + ''
                               avalon.log('model.customerEntity.CompanyCountryId : ' + model.customerEntity.CompanyCountryId)
                           }
                           tmp = ret.data.Customer.CompanyProvinceId
                           if (tmp) {
                               model.customerEntity.CompanyProvinceId = 0
                               model.customerEntity.CompanyProvinceId = tmp + ''
                               avalon.log('model.customerEntity.CompanyProvinceId : ' + model.customerEntity.CompanyProvinceId)
                           }
                           tmp = ret.data.Customer.CompanyCityId
                           if (tmp) {
                               model.customerEntity.CompanyCityId = 0
                               model.customerEntity.CompanyCityId = tmp + ''
                               avalon.log('model.customerEntity.CompanyCityId : ' + model.customerEntity.CompanyCityId)
                           }
                           tmp = ret.data.Customer.CompanyAreaId
                           if (tmp) {
                               model.customerEntity.CompanyAreaId = 0
                               model.customerEntity.CompanyAreaId = tmp + ''
                               avalon.log('model.customerEntity.CompanyAreaId : ' + model.customerEntity.CompanyAreaId)
                           }
                       }
                       else {
                           //if (model.category.size()) {
                           //    model.customerEntity.SuperiorCategoryId = model.category[0].Id
                           //}
                           var cmyInfo = CBCRM.cmyInfo;
                           if (cmyInfo) {
                               model.customerEntity.CompanyCountryId = cmyInfo.CountryId;
                               model.customerEntity.CompanyProvinceId = cmyInfo.ProvinceId;
                               model.customerEntity.CompanyCityId = cmyInfo.CityId;
                               model.customerEntity.CompanyAreaId = cmyInfo.AreaId;
                           }
                       }
                       var tmp = model.customerEntity.State;
                       model.customerEntity.State = "";
                       model.customerEntity.State = tmp;
                       for (var p in propDataMaps) {
                           hasDefault = false
                           data = ret.data.Dicts[propDataMaps[p]]
                           avalon.log('bind model.customerEntity.' + p + ' : ' + model.customerEntity[p])
                           if (data.length && !model.customerEntity[p]) {
                               data.forEach(function (d) {
                                   if (d.IsDefault) {
                                       model.customerEntity[p] = d.Id
                                       hasDefault = true
                                       return false
                                   }
                               })
                               if (!hasDefault && p != 'Bank') {
                                   model.customerEntity[p] = data[0].Id
                               }
                           }
                       }
                       if (ret.data.CountryId) {
                           model.customerEntity.CompanyCountryId = 0
                           model.customerEntity.CompanyCountryId = ret.data.CountryId + ''
                       }
                       if (ret.data.ProvinceId) {
                           model.customerEntity.CompanyProvinceId = 0
                           model.customerEntity.CompanyProvinceId = ret.data.ProvinceId + ''
                       }
                       if (ret.data.CityId) {
                           model.customerEntity.CompanyCityId = 0
                           model.customerEntity.CompanyCityId = ret.data.CityId + ''
                       }
                       if (ret.data.AreaId) {
                           model.customerEntity.CompanyAreaId = 0
                           model.customerEntity.CompanyAreaId = ret.data.AreaId + ''
                       }

                       if (model.initComplete)
                           model.initComplete(model, ret)

                       $("#txtCustomerName").select();
                   })

                   if (that.params.id) {
                       $.get('/Customer/Contacts', { 'customerId': that.params.id }, function (ret) {
                           model.contactsList = ret.data.contacts.Source
                           model.contactsList.forEach(function (item,i) {
                               model.watchContacts(item,i);
                           });
                       })
                   } else {
                       if (model.contactsList.length == 0) {
                           model.contactsList.push(contactsData)
                           var index=model.contactsList.length - 1;
                           model.contactsList[index].IsFirst = true;
                           model.watchContacts(model.contactsList[index],index);
                       }
                   }

                   model.types = customerType
                   model.customerEntity.Type = '0' //客户类别默认为企业
                   model.customerEntity.Owner = CBCRM.memberShip.Id //默认归属人
                   model.customerEntity.OwnerName = CBCRM.memberShip.FullName
                   model.customerEntity.AddBy.Id = CBCRM.memberShip.Id
                   model.customerEntity.AddBy.FullName = CBCRM.memberShip.FullName

                   //公司介绍编辑器
                   if (kind) kind.html(model.customerEntity.Intro);
               },
               _getIndex = function (arr, id) {
                   for (var i = 0, l = arr.size() ; i < l; i++) {
                       if (arr[i].Id == id) return i;
                   }
                   return -1;
               },
               delayWatch = {
                   times: {},
                   get: function (key, callback) {
                       var times = delayWatch.times;
                       var fn = function (n, o) {
                           if (times[key]) clearTimeout(times[key]);
                           if (n == o) return;
                           times[key] = setTimeout(function () {
                               callback(key, n, o);
                           }, 500);
                       }
                       return fn;
                   }
               },
               bindWatch = function (entity) {
                   entity.$watch('SuperiorCategoryId', function (n, o) {
                       if (n != o) {
                           model.subCategory.removeAll()
                           allSubCategory.forEach(function (c) {
                               if (c.ParentId == n) {
                                   model.subCategory.push(c)
                               }
                           })
                           if (model.subCategory.length && !model.customerEntity.CategoryId)
                               model.customerEntity.CategoryId = model.subCategory[0].Id
                       }
                   })
                   entity.$watch('Type', function (n, o) {
                       if (n != o) {
                           model.isPerson = n === '1'
                       }
                   })

                   entity.$watch("State", function (n, o) {
                       model.stateGrades.removeAll();
                       if (n === "" || n == null) return;
                       model.stateGrade.forEach(function (item) {
                           if (item.ParentId == (n == 0 ? 100120 : 100121)) model.stateGrades.push(item);
                       });
                       if (_getIndex(model.stateGrades, model.customerEntity.StateGrade) == -1) {
                           model.customerEntity.StateGrade = model.stateGrades.length > 0 ? model.stateGrades[0].Id : "";
                       }
                   });

                   /*国家地区级联*/
                   entity.$watch('CompanyCountryId', function (n, o) {
                       var name = ''
                       if (n != o) {
                           model.province.removeAll()

                           allLocations.forEach(function (c) {
                               if (c.ParentId == n) {
                                   //name = c.Data
                                   model.province.push(c)
                               } else if (c.Id == n) {
                                   model.customerEntity.CompanyCountryDisplay = c.Data
                               }
                           })
                           avalon.log('CompanyCountryId : ' + model.customerEntity.CompanyCountryId)
                           if (model.province.size()) {
                               if (_getIndex(model.province, model.customerEntity.CompanyProvinceId) == -1) {
                                   model.customerEntity.CompanyProvinceId = model.province[0].Id
                                   model.customerEntity.CompanyProvinceDisplay = model.province[0].Data
                               }
                           } else {
                               model.customerEntity.CompanyProvinceId = ''
                               model.customerEntity.CompanyProvinceDisplay = ''
                           }
                           if (model.country.size() == 0) {
                               mod.province.removeAll();
                               model.city.removeAll();
                               model.area.removeAll();
                               model.customerEntity.CompanyProvinceId = ''
                               model.customerEntity.CompanyProvinceDisplay = ''
                               model.customerEntity.CompanyCityId = ''
                               model.customerEntity.CompanyCityDisplay = ''
                               model.customerEntity.CompanyAreaId = ''
                               model.customerEntity.CompanyAreaDisplay = ''
                           }
                       }
                   })
                   entity.$watch('CompanyProvinceId', function (n, o) {
                       if (n != o) {
                           model.city.removeAll()

                           allLocations.forEach(function (c) {
                               if (c.ParentId == n) {
                                   //name = c.Data
                                   model.city.push(c)
                               } else if (c.Id == n) {
                                   model.customerEntity.CompanyProvinceDisplay = c.Data
                               }
                           })
                           avalon.log('CompanyProvinceId : ' + model.customerEntity.CompanyProvinceId)
                           if (model.city.size()) {
                               if (_getIndex(model.city, model.customerEntity.CompanyCityId) == -1) {
                                   model.customerEntity.CompanyCityId = model.city[0].Id
                                   model.customerEntity.CompanyCityDisplay = model.city[0].Data
                               }
                           } else {
                               model.customerEntity.CompanyCityId = ''
                               model.customerEntity.CompanyCityDisplay = ''
                           }
                           if (model.province.size() == 0) {
                               model.city.removeAll();
                               model.area.removeAll();
                               model.customerEntity.CompanyCityId = ''
                               model.customerEntity.CompanyCityDisplay = ''
                               model.customerEntity.CompanyAreaId = ''
                               model.customerEntity.CompanyAreaDisplay = ''
                           }
                       }
                   })
                   entity.$watch('CompanyCityId', function (n, o) {
                       if (n != o) {
                           model.area.removeAll()

                           allLocations.forEach(function (c) {
                               if (c.ParentId == n) {
                                   //name = c.Data
                                   model.area.push(c)
                               } else if (c.Id == n) {
                                   model.customerEntity.CompanyCityDisplay = c.Data
                               }
                           })
                           avalon.log('CompanyCityId : ' + model.customerEntity.CompanyCityId)
                           if (model.area.size()) {
                               if (_getIndex(model.area, model.customerEntity.CompanyAreaId) == -1) {
                                   model.customerEntity.CompanyAreaId = model.area[0].Id
                                   model.customerEntity.CompanyAreaDisplay = model.area[0].Data
                               }
                           } else {
                               model.customerEntity.CompanyAreaId = ''
                               model.customerEntity.CompanyAreaDisplay = ''
                           }
                           if (model.city.size() == 0) {
                               model.area.removeAll();
                               model.customerEntity.CompanyAreaId = ''
                               model.customerEntity.CompanyAreaDisplay = ''
                           }
                       }
                   })
                   entity.$watch('CompanyAreaId', function (n, o) {
                       var index = _getIndex(model.area, n);
                       if (index != -1) {
                           model.customerEntity.CompanyAreaDisplay = model.area[index].Data
                       } else {
                           model.customerEntity.CompanyAreaDisplay = ''
                       }
                   })
                   /*国家地区级联*/
                   "CompanyTel1,CompanyTel2".split(",").forEach(function (key) {
                       entity.$watch(key, delayWatch.get(key, function (k, n, o) {
                           if (!n) return;
                           model.checkCustomerTel(k);
                       }));
                   });
                   "Email,QQ,Wangwang".split(",").forEach(function (key) {
                       entity.$watch(key, delayWatch.get(key, function (k, n, o) {
                           if (!n) return;
                           var title = k == "Wangwang" ? "旺旺" : k;
                           model.checkCustomerExists(k,title);
                       }));
                   });
               }, addMenu, hasSelected = false, len
               model.customerEntity = factory.create('Customer')
               model.settingEntity = factory.create('SettingsCustomer');
               model.settingEntity.IsStart += '';
               model.settingEntity.DisableChangeName += '';
               $.get('/Settings/CustomerSettings/', {}, function (result) {
                   if (result.data) {
                       result.data.IsStart = result.data.IsStart + ''
                       result.data.DisableChangeName += '';
                       model.settingEntity = result.data;
                   }
               });
               var contactsData = factory.create('Contacts')
               contactsData.ContactRoleId = 10047   //默认为重要联系人
               model.contactsList = []
               model.contactDelList = []
               var editors = {};
               function createEditors() {
                   $("textarea").each(function () {
                       var txt = $(this), name = txt.attr("data-editor");
                       if (name != null && name != "") {
                           var width = txt.attr("data-ewidth");
                           if (!width) width = 380;
                           txt.width(width);
                           if (editors[name]) editors[name].remove();
                           var editor = setEditerSimple("editor_" + name, width);
                           if (editor) {
                               var _html = model.expando[name];
                               if (_html == null) _html = "";
                               editor.html(_html);
                               editors[name] = editor;
                           }
                       }
                   });
               }
               //model.customerEntity.FirstContacts = factory.create('Contacts')
               //avalon.vmodels.CBCRM.fillContent(tmpl, lang, contentId, module, model)
               function createTip(vmkey,keys,show) {
                   keys.split(",").forEach(function (key) {
                       var tipTarget = $("input[data-tipkey=" + key + "]");
                       if (tipTarget.length == 0) return;
                       var oldEl = $("span[data-tipkey=" + key + "]");
                       if (oldEl.length > 0) {
                           if (show != null) {
                               if (show) oldEl.show();
                               else oldEl.hide();
                           }
                           return;
                       }
                       var tipEl = $('<span ms-if="' + vmkey + '.' + key + '.exists" class="info_warn hand" ms-attr-title="' + vmkey + '.' + key + '.title" ms-click="viewCheckInfo(\'' + key + '\')"></span>');
                       tipEl.css({ position: "relative", "margin-left": "-20px" }).attr("data-tipkey", key);
                       tipTarget.after(tipEl);
                       if (detailDialog) avalon.scan(detailDialog.content(), model);
                   });
               }
               var detailDialog = null;
               CBCRM.loadView('/Customer/ExpandoFieldInput.html?v=' + Math.random(), function (tmpl) {
                   //CBCRM.loadView('/Customer/formTemplate.html', function (tmpl) {
                   //CBCRM.loadView('/Settings/ExpandoFieldInput.html?v=' + Math.random(), function (expandoTmpl) {
                   //    model.expandoTmpl = expandoTmpl || ''
                   //})
                   var titles = {
                       'AddCustomer': '新增终端客户',
                       'AddCollaborate': '新增合作伙伴',
                       'AddChannel': '新增渠道代理商',
                       'AddSupply': '新增供应商',
                       'AddAdvertising': '新增媒体资源',
                       'AddCompetitor': '新增竞争对手',
                       'AddSociall': '新增社会关系',
                       'EditCustomer': '编辑终端客户',
                       'EditCollaborate': '编辑合作伙伴',
                       'EditChannel': '编辑渠道代理商',
                       'EditSupply': '编辑供应商',
                       'EditAdvertising': '编辑媒体资源',
                       'EditCompetitor': '编辑竞争对手',
                       'EditSociall': '编辑社会关系'
                   }
                   var ctype = that.path.split('/')[2];
                   detailDialog = openTmpl({
                       vm: model, title: titles[ctype], w: 880, h: 500,
                       tmplId: tmpl, isContent: true,
                       button: [{
                           name: '提交',
                           focus: true,
                           callback: function () {
                               model.checkSubmit()
                               return false
                           }
                       }],
                       onClose:function () {
                           var ui = ['shareToTree', 'belongToTree', 'setParetCustomer', 'setProxyArea', 'creditRaty', 'valueRaty', 'threatenRaty', 'addbytreeid']
                           delete avalon.vmodels.InputCustomer
                           delete avalon.vmodels.addMenu
                           ui.forEach(function (word) {
                               if (avalon.vmodels[word])
                                   avalon.vmodels[word].destroy()
                           })
                           model.expandoTmpl = ''
                           model.expando = {}
                           if (kind) kind.remove();
                           for (var key in editors) {
                               if (editors[key]) {
                                   editors[key].remove();
                                   delete editors[key];
                               }
                           }
                       },
                       onScan: function () {
                           if (document.getElementById('ArtContent')) {
                               kind = setEditerSimple('ArtContent', '763px', '100px')
                           }
                           createTip("checkInfo", model.$checkInfoKeys);
                           init()
                       }
                   });
               })
               //CBCRM.onLoadModuleBefore = function () {
               //    if (!/\/Customer\/(?:add|edit)/gi.test(this.path)) {
               //        var ui = ['shareToTree', 'belongToTree', 'setParetCustomer', 'setProxyArea', 'creditRaty', 'valueRaty', 'threatenRaty']
               //        delete avalon.vmodels.InputCustomer
               //        delete avalon.vmodels.addMenu
               //        ui.forEach(function (word) {
               //            if (avalon.vmodels[word])
               //                avalon.vmodels[word].destroy()
               //        })
               //    }
               //}
           },
           /*客户详情*/
           DetailCustomer: function (tmpl, lang, contentId, module,paramData) {
               var notMemberFilter = function (treeId, parentNode, responseData) {
                   var ret = [], len = 0, curr, hasEmp = false,
                   CBCRM = avalon.vmodels.CBCRM
                   if (responseData.data && responseData.data.groups.length)
                       len = responseData.data.groups.length
                   while (len) {
                       curr = responseData.data.groups[--len]
                       curr.nocheck = true
                       hasEmp = false
                       curr.Posts.forEach(function (p, i) {
                           curr.Posts[i].ParentId = p.Boss ? p.Boss.Id : p.Group
                           curr.Posts[i].nocheck = true
                           p.Users.forEach(function (u, i) {
                               var u = p.Users[i]
                               if (u.Id === CBCRM.memberShip.Id) return true
                               u.ParentId = u.PositionId
                               u.Name = u.FullName
                               ret.push(u)
                           })
                           if (!hasEmp) {
                               hasEmp = p.Users.length > 0
                           }
                           if (hasEmp) {
                               ret.push(p)
                           }
                       })
                       if (hasEmp) ret.push(curr)
                   }
                   return ret
               }
               var service = new Customer.Service();
               var that = this,
                   action = this.params.action, paramid = this.params.id
               blackImg = '/Content/Themes/Base/Images/customerblack.png',
               CBCRM = avalon.vmodels.CBCRM,
               vmid = 'ViewCustomer';
               //if (avalon.vmodels[vmid]) {
               //    vmid = vmid + "_" + paramid;
               //}
               var model = avalon.vmodels[vmid]
               if (model) {
                   model.otherContent = ''
                   model.isCustInfo = true
                   model.tab = "tab1"
               } else {
                   model = CBCRM.define(vmid, function (scope) {
                       scope.lang = lang
                       scope.customerEntity = {}
                       scope.companyEntity = {}
                       scope.$viewdialog = false;
                       scope.isPerson = false
                       scope.tabId = 1
                       scope.doShowTab = function (tabid) {
                           scope.tabId = tabid
                       }
                       scope.blackImg = ''
                       scope.expandoTmpl = ''
                       scope.expando = {}
                       scope.otherContent = ''
                       scope.isCustInfo = true
                       scope.viewCustomer = viewCustomer;
                       scope.uid = CBCRM.memberShip.Id;
                       /*左边导航权限*/
                       scope.authEntity = false;
                       scope.authCustomer = true
                       scope.authContacts = false
                       scope.authSalesOpportunities = false
                       scope.authContract = false
                       scope.authProductList = false
                       scope.authAccounting = false
                       scope.authCalendar = false
                       scope.authCalls = false
                       scope.authFollowUp = false
                       scope.authCServices = false
                       scope.authComplaints = false
                       scope.authHistory = false
                       scope.authCredentials = false
                       scope.authDocumentaryOffer = false
                       scope.authDynamic = false
                       scope.authTree = true;
                       scope.authAnalysis = true;
                       scope.authPriceList = true;
                       scope.getAuthForView = function () {
                           model.authContacts = CBCRM.hasAuth(1030000)
                           model.authSalesOpportunities = CBCRM.hasAuth(2020400)
                           model.authContract = CBCRM.hasAuth(2020600)
                           model.authProductList = CBCRM.hasAuth(2020700)
                           model.authAccounting = CBCRM.hasAuth(7020000)
                           model.authCalendar = CBCRM.hasAuth(4030000)
                           model.authCalls = CBCRM.hasAuth(3020000)
                           model.authFollowUp = CBCRM.hasAuth(3030000)
                           model.authCServices = CBCRM.hasAuth(3040000)
                           model.authComplaints = CBCRM.hasAuth(3050000)
                           model.authHistory = CBCRM.hasAuth(1050100)
                           model.authCredentials = CBCRM.hasAuth(302)
                           model.authDocumentaryOffer = CBCRM.hasAuth(2020500)
                           model.authDynamic = CBCRM.hasAuth(309)
                           model.authTree = CBCRM.hasAuth(307);
                           model.authAnalysis = CBCRM.hasAuth(308);
                       }

                       scope.currNav = 1
                       /*导航切换*/
                       scope.doChangeNav = function (navid, act) {
                           var cId = model.customerEntity.Id;
                           if (!cId) {
                               messageBox.warning("客户信息尚未加载，请稍候…");
                               return;
                           }
                           model.currNav = navid
                           if (navid == 1) {
                               model.isCustInfo = true
                               if (model.needReLoad) model.reloadCustomer();
                           }
                           else {
                               model.isCustInfo = false
                           }
                           //$(this).attr('val')
                           var rId
                           if (navid > 15) {
                               rId = $(this).attr('val')
                           }
                           var paths = {
                               1: '/Customer/DetailCustomer/' + cId,
                               2: '/Customer/Contacts/' + cId + "/customer",
                               3: '/Market/SalesOpportunities/' + cId + '/customer',
                               4: '/Market/Contract/' + cId + '/customer',
                               5: '/Market/ProductList/' + cId + '/customer',
                               6: '/FinancialAffairs/Accounting/' + cId + '/customer',
                               7: '/Office/CbCalendar/' + cId + '/customer',
                               8: '/Services/Calls/' + cId + '/customer',
                               9: '/Services/FollowUp/' + cId+ '/customer',
                               10: '/Services/CServices/' + cId + '/customer',
                               11: '/Services/Complaints/' + cId + '/customer',
                               12: '/Customer/History/' + cId,
                               13: '/Customer/DetailCredentials/' + cId,
                               14: '/Market/DocumentaryOffer/' + cId + '/customer',
                               15: '/Customer/CustomerDynamics/' + cId + '/customer',
                               16: '/Customer/RecordDetails/' + rId + '/' + cId + '/NumderTag/' + model.CustomerRecordModel.configs.NumderTag,
                               17: '/Customer/RecordTag/' + rId + '/' + cId + '/TagPositionTag',
                               18: '/Customer/RecordList/' + rId + '/' + cId + '/ListPositionTag',
                               19: '/Customer/Tree/' + cId + "/customer",
                               20: '/Customer/Analysis/' + cId + "/customer",
                               21: '/Customer/PriceList/' + cId + "/customer"
                           }
                           var path = paths[navid];
                           if (navid == 2 && act)
                               path += "add";
                           if (navid != 1)
                               goto(path, true, {
                                   entity: model.customerEntity.$model,
                                   viewOther:model.viewOther,
                                   reloadCustomer: function () {
                                       //标记下次点击客户面板左边导航的客户详情是需要重新读取客户信息
                                       model.needReLoad = true;
                                   }});
                       }

                       //点击客户记事左边多菜单
                       scope.ChangeNav = function (navid,title) {
                           model.isCustInfo = false
                           model.currNav = navid;
                           var id = navid > 0 ? navid : 0;
                           var cId=model.customerEntity.Id
                           var url = '/Customer/RecordDetails/' + id + '/' + cId + '/PositionTag/' + title;
                           goto(url, true, {
                               entity: model.customerEntity.$model,
                               viewOther: model.viewOther,
                               reloadCustomer: function () {
                                   model.needReLoad = true;
                               }
                           });
                       }
                       scope.$otherContentid = "#otherContent";
                       scope.viewOther = function (tmpl,otherVm,select) {
                           var el = $(model.$otherContentid).html("");
                           el.append(select == null ? tmpl : $(tmpl).find(select));
                           avalon.scan(el[0], otherVm);
                       }
                       //客户记事
                       scope.Record = []
                       scope.CustomerRecordleftlist = []
                       scope.CustomerRecordSettings = {
                           Id: '0',//编号
                           RecordTag: '',//菜单标题
                           RecordContent: '',//菜单内容
                           CoustomId: 0,//客户编号
                           CreateId: 0,//创建人
                           CreateDate: '',//创建时间
                           UpdateId: 0,//更新人
                           UpdateDate: '',//更新时间
                           RecordName: ''//菜单标记

                       }

                       //客户记事实体
                       scope.CustomerRecordModel = {
                           cname: "CustomerRecord",
                           configs: {
                               ShowStart: 0,
                               ShowNumder: 0,
                               ShowPosition: 0,//编号
                               NumderTag: '',
                               TagPositionTag: '',
                               ListPositionTag: ''
                           }
                       }

                       //多条左侧菜单形式
                       scope.RecordMode = {
                           Cname: 'CustomerRecordPosition',
                           Name: "PositionTag",
                           Value: ""
                       }
                       scope.IsDate = 0 //是否存在数据
                       //显示客户记事列表
                       scope.getConfig = function (cid) {
                           Config.get(scope.CustomerRecordModel, function (result) {

                               if (model.CustomerRecordModel.configs.ShowNumder == 0)
                                   GetCustomerMenu(cid, 'NumderTag');
                               else {
                                   var val = model.CustomerRecordModel.configs.ShowPosition;
                                   switch (val) {
                                       case "0":
                                           $.get("/Customer/GetCustomerRecordByList", { id: cid, type: 'PositionTag' }, function (ret) {
                                               if (ret.data.Source.length != 0) {
                                                   model.CustomerRecordleftlist = []
                                                   model.IsDate = 1
                                                   var count = 0
                                                   for (var i = 0, tmp; tmp = ret.data.Source[i]; i++) {
                                                       count++
                                                       model.CustomerRecordleftlist.push({ count: count, id: tmp.Id, Name: tmp.RecordName, Val: tmp.RecordTag });
                                                   }
                                               }
                                               else {
                                                   model.IsDate = 0
                                                   model.CustomerRecordleftlist = []
                                                   $.get("/Settings/GetSettingConfigs", { cname: model.RecordMode.Cname }, function (relt) {
                                                       if (relt.data.length != 0) {
                                                           var count = 18
                                                           if (model.CustomerRecordleftlist.length == 0) {
                                                               for (var i = 0, tmp; tmp = relt.data[i]; i++) {
                                                                   count++;
                                                                   // model.Record.push({ Cname: tmp.Cname, Name: tmp.Name, Value: tmp.Value });
                                                                   model.CustomerRecordleftlist.push({ count: count, id: -count, Name: tmp.Name, Val: tmp.Value });
                                                               }
                                                           }
                                                       }
                                                   });
                                               }
                                           });
                                           break;
                                   }
                               }
                           });
                       }
                       /*发送短信*/
                       scope.sendSms = function (mobile) {
                           var m = model.customerEntity;
                           var modelc = {
                               '名称': m.Name, '类型': model.customerTypeDisplay, '会员级别': m.MemberGradeDisplay ? m.MemberGradeDisplay : "无",
                               '分类': m.CategoryDisplay, '公司电话': m.CompanyTel1, '公司地址': m.CompanyAddress, 'Email': m.Email, 'QQ': m.QQ
                           };
                           CBCRM.sendSmsTmpl("客户", mobile, modelc);
                       };

                       /*热度*/
                       scope.hotOpts = {
                           readonly: true,
                           valChanged: function (val) {
                               return
                           }
                       }
                       /*价值评估*/
                       scope.valueRatyOpts = {
                           readonly: true,
                           ratyChanged: function (val) {
                               return
                           }
                       }
                       /*信用等级*/
                       scope.creditRatyOpts = {
                           readonly: true,
                           ratyChanged: function (val) {
                               return
                           },
                           ratyon: '/Content/Themes/Base/Images/raty/medal-on.png', //选中评级图标
                           ratyoff: '/Content/Themes/Base/Images/raty/medal-off.png' //未选中评级图标
                       }
                       /*竞争对手威胁值raty ui*/
                       scope.threatenRatyOpts = {
                           readonly: true,
                           ratyChanged: function (val) {
                               return
                           }
                       }
                       /*查看地图*/
                       scope.$mapLoaded = false;
                       scope.$map = null;
                       scope.loadMap = function (callback) {
                           if (!scope.$mapLoaded) {
                               require(["bdmapTool", "ready!"], function (bdmapTool) {
                                   scope.$map = new bdmapTool({
                                       tmpl: "line",
                                       mapContent: "#dmap",
                                       linepanel: "divline",
                                       left: 0,
                                       right: 820,
                                       height: 520,
                                       pstart: scope.companyEntity.Address,
                                       pend: scope.customerEntity.CompanyAddress
                                   });
                                   scope.$maploaded = true;
                                   if (callback) callback.call(scope.$map);
                               });
                           } else {
                               if (callback) {
                                   callback.call(scope.$map);
                               }
                           }
                       }
                       scope.$marker = null;
                       scope.detailMap = function () {
                           var win = art.dialog({
                               width: 300,
                               height: 100,
                               title: "地图加载中……",
                               content: "<img src='/Content/Themes/Base/images/loading2.gif' />"
                           });
                           scope.loadMap(function () {
                               var map = scope.$map;
                               var point, city;
                               city = scope.customerEntity.CompanyCityDisplay;
                               if (city == "") city = scope.customerEntity.CompanyAddress;
                               if (model.customerEntity.Lng) {
                                   point = new BMap.Point(model.customerEntity.Lng, model.customerEntity.Lat);
                               } else {
                                   point = null;
                                   messageBox.error("抱歉，地图还未标注！");
                                   return;
                               }
                               var pointStart;
                               var cmyInfo = CBCRM.cmyInfo || {};
                               if (cmyInfo.Lng) {
                                   pointStart = new BMap.Point(cmyInfo.Lng, cmyInfo.Lat);
                                   map.ops.pointStart = pointStart;
                               }
                               map.ops.customer = model.customerEntity.$model;
                               map.ops.company = model.companyEntity.$model;
                               map.ops.city = city;
                               map.ops.point = point;
                               map.ops.pointEnd = point;
                               map.openMap(function () {
                                   if (win) win.close();
                                   if (point) {
                                       map.map.panTo(point);
                                       //map.map.setCenter(point);
                                   } else {
                                       map.map.setCenter("南宁市");
                                   }
                               });
                           });
                       }
                       scope.customerTypeDisplay = ''
                       scope.editHerf = ''
                       scope.doedit = function () {
                           messageBox.close()
                           goto(model.editHerf.substr(1),true)

                       }

                       /*转移归属 start*/
                       scope.changeBelongTo = ''
                       scope.changeBelongToName = ''
                       scope.changeBelongToRemark = ''
                       scope.selectBelongTo = function () {
                           plugins.selectUser({
                               dataAuth: cuDiRes[model.customerEntity.SuperiorCategoryId]||getCuRes(),
                               callback: function (us) {
                                   var u = us[0];
                                   model.changeBelongTo = u.Id
                                   model.changeBelongToName = u.FullName
                               }
                           })
                       }
                       scope.getChecked = function (okCall, failCall) {
                           var ids = [], checkedCustomers = []
                           ids.push(model.customerEntity.Id)
                           checkedCustomers.push(model.customerEntity)

                           if (!ids.length) {
                               if (typeof failCall !== 'function') {
                                   avalon.log('缺少failCall函数')
                                   return
                               }
                               failCall()
                           } else {
                               if (typeof okCall !== 'function') {
                                   avalon.log('缺少okCall函数')
                                   return
                               }
                               okCall(ids, checkedCustomers)
                           }

                       }
                       scope.doBelongTo = function () {
                           var d = model.openTmpl({
                               title: lang.TransferBelong, w: 600, h: 200,
                               tmplId: "belongToForm2", tmpl: tmpl,padding:"def2",
                               button: [{
                                   name: lang.SubmitBtn,
                                   focus: true,
                                   callback: function () {
                                       messageBox.confirm(lang.BelongToConfirm, function () {
                                           var ids = [model.customerEntity.Id];
                                           var data = jsonToSubmit("ids", ids);
                                           if (model.changeBelongTo) {
                                               data.belongTo = model.changeBelongTo
                                           } else {
                                               messageBox.error('请选择新的归属人！')
                                               return
                                           }
                                           data.remark = model.changeBelongToRemark
                                           $.post('/Customer/ChangeBelongTo/', data, function (data) {
                                               CBCRM.showResult(data, function () {
                                                   model.customerEntity.OwnerBy = model.changeBelongToName
                                                   messageBox.close(d.config.id)
                                                   if (paramData && paramData.reloadData) paramData.reloadData(model.customerEntity);
                                               })
                                           })
                                       })
                                       return false
                                   }
                               }]
                           });
                       }
                       /*转移归属 end*/
                       /*共享 start*/
                       scope.shareCustomers = []
                       scope.currShare = {}
                       scope.doPrint = function () {
                           messageBox.confirm('您确定要打印当前客户信息吗？', function () {
                               $("#customerPanelPrint").printArea()
                           })
                       }
                       scope.setShare = function (curShareCustomer) {
                           var ids = curShareCustomer.ShareTo || [];
                           ids = ids.$model || ids;
                           plugins.selectUser({
                               dataAuth: cuDiRes[curShareCustomer.SuperiorCategoryId] || getCuRes(),
                               multiple: true,
                               listData: ids,
                               callback: function (us) {
                                   var a = where(us, true, ["Id", "FullName"]);
                                   curShareCustomer.ShareTo = a[0]
                                   curShareCustomer.ShareToNames = a[1].join('，')
                               }
                           })
                       }
                       scope.doShare = function () {
                           model.shareMore = false;
                           var m = model;
                           var d = m.openTmpl({
                               title: lang.ShareCustomerTitle,
                               w: 800, h: 200,padding:"def2",
                               tmplId: "shareToForm2", tmpl: tmpl,
                               button: [{
                                   name: lang.SubmitBtn,
                                   focus: true,
                                   callback: function () {
                                       messageBox.confirm(lang.ShareCustomerToConfirm, function () {
                                           var data = {}, ctmp = 'customerId[j]',
                                           stmp = 'shareMemberIds[k]'
                                           m = model
                                           m.shareCustomers.forEach(function (c, i) {
                                               data[ctmp.replace('j', i)] = c.Id
                                               data[stmp.replace('k', i)] = c.ShareTo.length ? c.ShareTo.join(',')
                                                   : '0'
                                           })
                                           $.post('/Customer/ShareCustomerTo/', data, function (ret) {
                                               CBCRM.showResult(ret, function () {
                                                   if (paramData && paramData.reloadData) paramData.reloadData(model.customerEntity);
                                                   messageBox.close()
                                               })
                                           })
                                       })
                                       return false
                                   }
                               }],
                               onClose: function () {
                                   model.shareCustomers = [];
                               }
                           });
                           var c = model.customerEntity;
                           model.shareCustomers = [{
                               Id: c.Id,
                               Name: c.Name,
                               ShareTo: c.ShareTo || [],
                               ShareToNames: (c.ShareToNames || []).join('，')
                           }];
                       }
                       /*共享 end*/
                       /*删除*/
                       scope.doRemove = function () {
                           var that = this
                           messageBox.confirm(lang.RemoveConfirm, function () {
                               var curVm = that.$vmodel,
                               curItem = curVm[curVm.$itemName]
                               $.post('/Customer/CustomerToRecycleBin/' + model.customerEntity.Id)
                               .done(function (ret) {
                                   avalon.vmodels.CBCRM.showResult(ret, function () {
                                       var m = model
                                       if (paramData && paramData.reloadData) paramData.reloadData(m.customerEntity);
                                       messageBox.close()
                                   })
                               })
                           })
                       }
                       scope.doMoveToInternaional = function () {
                           service.MoveToInternational([model.customerEntity.Id], function (ret) {
                               model.reloadCustomer();
                               if (paramData && paramData.reloadData) paramData.reloadData(model.customerEntity);
                           })
                       },
                       scope.hasPrevious = false
                       scope.previousLabel = ''
                       scope.previousId = ''
                       scope.hasNext = false
                       scope.nextLabel = ''
                       scope.nextId = ''

                       /* 转移形态 */
                       scope.newSuperiorCategoryId = "";
                       scope.newCategoryId = "";
                       scope.categorys = [];
                       scope.subCategorys = [];
                       scope.$subCategorys = [];
                       scope.changeCategory = function () {
                           model.newSuperiorCategoryId = model.customerEntity.SuperiorCategoryId;
                           model.newCategoryId = model.customerEntity.CategoryId;
                           var d = model.openTmpl({
                               title: "变更客户形态", w: 680, h: 200,padding:"def2",
                               tmplId: "changeCatogryTmpl", tmpl: tmpl,
                               button: [{
                                   name: lang.SubmitBtn,
                                   focus: true,
                                   callback: function () {
                                       if (!model.newSuperiorCategoryId || !model.newCategoryId) {
                                           messageBox.error('操作失败！<br />请选择新客户形态与客户分类。')
                                           return false;
                                       }
                                       if (model.newSuperiorCategoryId == model.customerEntity.SuperiorCategoryId) {
                                           messageBox.error('操作失败！<br />新旧形态相同，不用变更。')
                                           return;
                                       }
                                       messageBox.confirm("您确认要变更客户形态吗？<br />因不同形态字段有差别，变更客户形态会导致在新形态信息面板部分字段无法显示。", function () {
                                           var data = { id: model.customerEntity.Id, newSuperiorCategoryId: model.newSuperiorCategoryId, newCategoryId: model.newCategoryId };
                                           $.post('/Customer/ChangeCategory/', data, function (ret) {
                                               CBCRM.showResult(ret, function () {
                                                   if (ret.result) {
                                                       if (d) d.close();
                                                       if (model.$viewdialog) model.$viewdialog.close();
                                                       if (paramData && paramData.reloadData) paramData.reloadData();
                                                   }
                                               })
                                           })
                                       })
                                       return false
                                   }
                               }]
                           });
                       }
                       //tab切换
                       scope.tab = 'tab1'
                       scope.tabChange = function () {
                           var tabid = $(this).attr("val")
                           model.tab = tabid
                       }

                       scope.conList = [];

                       scope.needReLoad = false;
                       scope.reloadCustomer = function () {
                           model.needReLoad = false;
                           loaddialog = CBCRM.loading("正在刷新客户信息……");
                           GetCustomerData(model.customerEntity.Id);
                       }
                   },false)
               }

               var editUrl = {
                   10103: '#/Customer/EditCustomer/',
                   10107: '#/Customer/EditCustomer/',
                   10131: '#/Customer/EditCollaborate/',
                   10132: '#/Customer/EditChannel/',
                   10133: '#/Customer/EditSupply/',
                   10134: '#/Customer/EditAdvertising/',
                   10135: '#/Customer/EditCompetitor/',
                   11170: '#/Customer/EditSociall/'
               }

               //显示客户信息,或者是联系人等信息
               model.otherContent = ''
               model.currNav = action ? action : 1
               model.isCustInfo = model.currNav == 1 ? true : false;

               function getPreviousNextCustomer(data) {
                   if (!data) return;
                   var m = model;
                   var c = data.preCustomer;
                   if (c) {
                       m.hasPrevious = c.Id ? true : false;
                       m.previousLabel = c.Id ? '上一个：' + c.Name : '';
                       m.previousId = c.Id ? c.Id : '';
                   }
                   var c = data.nextCustomer;
                   if (c) {
                       m.hasNext = c.Id ? true : false;
                       m.nextLabel = c.Id ? '下一个：' + c.Name : '';
                       m.nextId = c.Id ? c.Id : '';
                   }
               }

               function GetCustomerData(id) {
                   model.CustomerRecordSettings.Id = '0',
                   model.CustomerRecordSettings.RecordTag = '',
                   model.CustomerRecordSettings.RecordContent = '',
                   model.CustomerRecordleftlist = []
                   $.get("/Customer/DetailCustomer/"+id, {}, function (ret) {
                       if (loaddialog && loaddialog.close) loaddialog.close();
                       if (!ret || !ret.result) {
                           CBCRM.showResult(ret);
                           return;
                       }
                       getPreviousNextCustomer(ret.data);
                       if (ret.data.Expandos) {
                           model.expando = ret.data.Expandos
                       }
                       model.conList = ret.data.Contacts
                       delete ret.data.Contacts;
                       //修正潜在客户
                       if (ret.data.SuperiorCategoryId == 10103) {
                           ret.data.SuperiorCategoryId = 10107;
                           ret.data.SuperiorCategoryDisplay = "终端客户";
                           ret.data.CategoryId = 10108;
                           ret.data.CategoryDisplay = "普通客户";
                           ret.data.State = 0;
                           ret.data.StateGrade = 100120;
                           ret.data.StateGradeDisplay = "意向一般"
                       }
                       model.authEntity = ret.data.authEntity;
                       model.customerEntity = ret.data
                       if (!model.customerEntity.FirstContacts) model.customerEntity.FirstContacts = {};
                       model.customerEntity.BusinessTypesArr = ret.data.BusinessTypes ? ret.data.BusinessTypes.split(",") : [];
                       if (ret.data.Type || ret.data.Type === 0)
                           model.customerTypeDisplay = customerType[ret.data.Type].label
                       if (avalon.vmodels.creditRaty)
                           avalon.vmodels.creditRaty.val = model.customerEntity.Credit
                       if (avalon.vmodels.valueRaty)
                           avalon.vmodels.valueRaty.val = model.customerEntity.Value
                       if (avalon.vmodels.hotprocessbar)
                           avalon.vmodels.hotprocessbar.val = model.customerEntity.Temperature
                       if (avalon.vmodels.threatenRaty)
                           avalon.vmodels.threatenRaty.val = model.customerEntity.Threaten
                       model.isPerson = ret.data.Type === 1
                       model.editHerf = editUrl[model.customerEntity.SuperiorCategoryId] + model.customerEntity.Id
                       if (model.customerEntity.IsBlackList) {
                           model.blackImg = blackImg
                       } else {
                           model.blackImg = ''
                       }
                       model.newSuperiorCategoryId = model.customerEntity.SuperiorCategoryId;
                       model.newCategoryId = model.customerEntity.CategoryId;
                       bindWatch();
                       getViewDicts();
                       model.getConfig(model.customerEntity.Id);
                       if (action) model.doChangeNav(action);
                   })
               }

               //获取记事表数据
               function GetCustomerMenu(id, name) {
                   $.get("/Customer/GetCustomerRecord", { id: id, cname: name }, function (result) {
                       if (result.data) {
                           model.IsDate = 1;
                           model.CustomerRecordSettings = result.data;
                       } else {
                           model.IsDate = 0;
                       }
                   });
               }
               function bindWatch() {
                   model.$watch("newSuperiorCategoryId", function (n) {
                       model.subCategorys = [];
                       if (!n) return;
                       var has = false;
                       model.$subCategorys.forEach(function (item) {
                           if (item.ParentId == n) {
                               model.subCategorys.push(item);
                               if (item.Id == model.newCategoryId) has = true;
                           }
                       });
                       if (has) {
                           var t = model.newCategoryId;
                           model.newCategoryId = "";
                           model.newCategoryId = t;
                       } else {
                           model.newCategoryId = "";
                       }
                   });
               }
               function getCompany() {
                   //$.get('/Settings/DetailCompanyInfo/', {}, function (ret) {
                   //    if (ret.result)
                   //        model.companyEntity = ret.data.model;
                   //    else
                   //        model.companyEntity = factory.create('CompanyInfo');
                   //    if (!model.companyEntity.Logo)
                   //        model.companyEntity.Logo = model.defaultLogo;
                   //})
                   model.companyEntity = CBCRM.cmyInfo.$model;
                   if (!model.companyEntity.Logo)
                       model.companyEntity.Logo = model.defaultLogo;
               }
               function getViewDicts() {
                   if (model.$subCategorys.length == 0) {
                       var data = { "categorys": "100026", "$subCategorys": "100027" };
                       getDicts(data, model, function (ret) {
                           _set();
                       });
                   } else {
                       _set();
                   }
                   function _set() {
                       var t = model.newSuperiorCategoryId;
                       model.newSuperiorCategoryId = "";
                       model.newSuperiorCategoryId = t;
                   }
               }
               model.customerEntity = factory.create('Customer')
               var loaddialog = null;
               if (model.$viewdialog) model.$viewdialog.close();
               var dialog=model.openTmpl({
                   title: "查看客户详情", w: 1000, h: 400, padding: "0px",
                   url: "/Customer/ExpandoFieldDetails.html?_v=" + CBCRM.version,
                   extParam: { id: "cusutomerdetails",top:10 },
                   onLoad: function () {
                       loaddialog = CBCRM.loading("数据载入中");
                       getCompany()
                       model.getAuthForView()
                   },
                   onScan: function () {
                       GetCustomerData(paramid)
                   },
                   onClose: function () {
                       model.blackImg = ''
                       model.$viewdialog=null
                   }
               })
               model.$viewdialog = dialog;
               //CBCRM.loadView('/Customer/ExpandoFieldDetails.html?t=' + Math.random(), function (tmpl) {
               //    //CBCRM.loadView('/Customer/viewTemplate.html', function (tmpl) {
               //    /*CBCRM.loadView('/Settings/ExpandoFieldDetails.html?v=' + Math.random(), function (expandoTmpl) {
               //        model.expandoTmpl = expandoTmpl || ''
               //    })*/
               //    var dialog = art.dialog.list['cusutomerdetails']
               //    if (dialog) dialog.close();
               //    //
               //    var dialog = messageBox.openHtml('查看客户详情', '1000px', '400px', '', false, function () {
               //        model.blackImg = ''
               //    }, 'cusutomerdetails', { top: 5 });
               //    var content = $(dialog.content());
               //    content.html(tmpl);
               //    avalon.scan(content[0], model)
               //    content.css({ 'padding': '0px', 'margin-bottom': '-5px' })
               //    loaddialog = CBCRM.loading("数据载入中");
               //    model.$viewdialog = dialog;
               //    getCompany()
               //    model.getAuthForView()
               //    avalon.nextTick(function () {
               //        GetCustomerData(paramid)
               //    });
               //})

               CBCRM.onLoadModuleBefore = function () {
                   //avalon.vmodels.model = null
               }
           },
           //客户记事详情
           RecordDetails: function (tmpl, lang, contentid, module,paramData) {
               var CBCRM = avalon.vmodels.CBCRM, RecordContent, detail, meun, that = this,
               model = avalon.vmodels.RecordDetails
               if (model) {
                   if (model.Show == 1) {
                       model.Show = 0
                   }
               } else {

                   model = avalon.define('RecordDetails', function (vm) {
                       vm.lang = lang
                       vm.Show = 0;//编辑和提交的显示
                       //客户记事详情
                       vm.Detailsmodel = {
                           Id: 0,
                           RecordTag: "",
                           RecordContent: "",
                           CoustomId: 0,
                           CreateId: 0,
                           CreateDate: "",
                           UpdateId: 0,
                           UpdateDate: "",
                           RecordName: "",
                       }
                       vm.cancelEdit = function () {
                           model.Show = 0;
                       }
                       vm.EditDetails = function () {
                           model.Show = 1;
                           avalon.nextTick(function () {
                               setEditor();
                           });
                       }
                       vm.formSubmit = function () {
                           model.Detailsmodel.RecordContent = editor ? editor.html() : "";
                           if (model.Detailsmodel.RecordTag == "") {
                               messageBox.warning('请输入标题');
                               return false
                           }
                           $.post("/Customer/EditCustomerRecord", model.Detailsmodel.$model, function (ret) {
                               if (ret.message != "") {
                                   $.get("/Customer/GetCustomerRecordById", { id: ret.message }, function (result) {
                                       if (result.data) {
                                           model.Detailsmodel = result.data
                                       }
                                       model.Show = 0;
                                       meun = avalon.vmodels.ViewCustomer
                                       meun.getConfig(model.Detailsmodel.CoustomId)

                                   });
                               }
                           });
                       }
                   })
               }
               GetCustomerRecord(that.params.id);
               //获取数据
               function GetCustomerRecord(id) {
                   model.Detailsmodel.Id = 0
                   model.Detailsmodel.RecordContent = "";
                   model.Detailsmodel.RecordTag = ""
                   model.Detailsmodel.CoustomId = ""
                   $.get("/Customer/GetCustomerRecordById", { id: id }, function (result) {
                       if (result.data) {
                           model.Detailsmodel = result.data
                       }
                       else {
                           model.Detailsmodel.Id = id
                           model.Detailsmodel.RecordContent = "";
                           model.Detailsmodel.RecordTag = that.params.name
                           model.Detailsmodel.CoustomId = that.params.ation
                           model.Detailsmodel.CreateId = that.params.user
                           model.Detailsmodel.UpdateId = that.params.user
                           model.Detailsmodel.RecordName = that.params.type
                       }
                   })
               }
               paramData.viewOther(tmpl, model);
               var editor;
               function setEditor() {
                   editor = ketool.full("RecordContent", 800, 500);
                   if (editor) editor.html(model.Detailsmodel.RecordContent);
               }
           },
           //右侧列表客户记事
           RecordList: function (tmpl, lang, contentid, module,paramData) {
               var CBCRM = avalon.vmodels.CBCRM, RecordContent, detail, meun, that = this,
               model = CBCRM.define('RecordList', function (vm) {
                   vm.lang = lang
                   vm.destroy = function () {

                   }
                   vm.CustomerRecordList = []

                   //客户记事详情
                   vm.Detailsmodel = {
                       Id: 0,
                       RecordTag: "",
                       RecordContent: "",
                       CoustomId: 0,
                       CreateId: 0,
                       CreateDate: "",
                       CreateName: "",
                       UpdateName: "",
                       UpdateId: 0,
                       UpdateDate: "",
                       RecordName: "",
                   }

                   //新增
                   vm.doadd = function () {

                       var curr = CBCRM.memberShip
                       model.Detailsmodel.Id = 0
                       model.Detailsmodel.RecordContent = ''
                       model.Detailsmodel.RecordTag = ''
                       model.Detailsmodel.CreateId = curr.Id
                       model.Detailsmodel.CreateName = curr.FullName
                       model.Detailsmodel.CreateDate = GetDateTime()
                       model.Detailsmodel.UpdateId = curr.Id
                       model.Detailsmodel.UpdateName = curr.FullName
                       model.Detailsmodel.UpdateDate = GetDateTime()
                       model.Detailsmodel.RecordName = 'ListPositionTag'
                       model.Detailsmodel.CoustomId = that.params.ation
                       FormSubmit("新增客户记事")
                   }

                   //查看
                   vm.doview = function () {
                       var id = 0
                       if (that.params.key == 'view' && that.params.id) {
                           id = that.params.id
                       } else {
                           id = $(this).val()
                       }
                       $.get('/Customer/GetCustomerRecordRightListById', { id: id }, function (ret) {
                           model.Detailsmodel = ret.data.Source[0]
                       })
                       var dialog = messageBox.openHtml('客户记录详情', '600px', '90px', '');
                       var content = $(dialog.content())
                       var inputTmpl = $(tmpl).find("#viewTemplate").text()
                       content.html(inputTmpl)
                       avalon.scan(content[0], model)
                   }

                   //编辑
                   vm.doedit = function () {
                       var id = 0
                       if (that.params.key == 'edit' && that.params.id) {
                           id = that.params.id
                       } else {
                           id = $(this).val()
                       }

                       $.get('/Customer/GetCustomerRecordRightListById', { id: id }, function (ret) {
                           model.Detailsmodel = ret.data.Source[0]
                           if (RecordContent)
                               RecordContent.html(model.Detailsmodel.RecordContent)
                       })
                       FormSubmit("编辑客户记录")


                   }
                   //删除 移除回收站问题
                   vm.dodel = function () {
                       var index = parseInt($(this).attr('index'))
                       var id = $(this).val()
                       messageBox.confirm('确定删除此数据吗？', function () {
                           $.post('/Customer/CustomerRecordDelete/' + id, {}, function (ret) {
                               if (ret.result)
                                   model.CustomerRecordList.removeAt(index)
                               messageBox.succeed(ret.message)
                           })
                       });

                   }

                   //批量删除 移除回收站问题
                   vm.doalldel = function () {
                       var deleteIds = checkAll();
                       messageBox.confirm('确定删除选中的数据吗？', function () {
                           $.post('/Customer/CustomerRecordAllDelete/', deleteIds, function (ret) {
                               if (ret.result) {
                                   GetCustomerRecord()
                                   messageBox.succeed(ret.message);
                               } else {
                                   messageBox.succeed(ret.message);
                               }
                           });
                       });
                   }
                   vm.grid1 = { gridmsg: "" };
                   //分页数据
                   vm.RecordListpaing = {
                       paging: function (pageIndex, pageSize) {
                           GetCustomerRecord({
                               id: that.params.ation, name: that.params.type,
                               pageSize: pageSize, pageIndex: pageIndex
                           });
                       }
                   }
               })
               //GetCustomerRecord({id: that.params.ation, name: that.params.type, pageSize: 20, pageIndex: 1});
               //获取数据
               function GetCustomerRecord(data) {
                   model.grid1.gridmsg = lang.LoadingMsg;
                   $.get("/Customer/GetCustomerRecordRightList", data, function (result) {
                       if (result.data) {
                           model.grid1.gridmsg = result.data.RecordTotal > 0 ? "" : lang.NoListData;
                           model.CustomerRecordList = result.data.Source
                           avalon.vmodels.upaing.total = result.data.RecordTotal
                       }
                   })
               }

               //保存
               function FormSubmit(title) {
                   var dialog = openTmpl({
                       vm: model,
                       title: title,
                       tmpl: tmpl,
                       tmplid: "formTemplate",
                       w: 600,
                       onclose: function () {
                           if (avalon.vmodels.employeeTreeId)
                               avalon.vmodels.employeeTreeId.destroy()
                       },
                       btns: [{
                           name: '提交',
                           focus: true,
                           callback: function () {
                               model.Detailsmodel.RecordContent = RecordContent.html()
                               var models = model.Detailsmodel.$model
                               if (models.RecordTag == "") {
                                   messageBox.warning('请输入标题');
                                   return false
                               }
                               var url = (models.Id == 0 ? "/Customer/CustomerRecordAdd/" : "/Customer/CustomerRecordUpdate/")
                               $.post(url + models.Id, models, function (ret) {
                                   if (ret.result) {
                                       messageBox.ok(ret.message, function () {
                                           GetCustomerRecord({ id: that.params.ation, name: that.params.type, pageSize: 20, pageIndex: 1 });
                                           if (RecordContent) RecordContent.remove()
                                           dialog.close();
                                       })
                                   }
                                   else {
                                       messageBox.fail(ret.message, function () { })
                                   }
                               })
                               return false
                           }
                       }]
                   });
                   if (document.getElementById('RecordContent')) {
                       RecordContent = setEditerSimple('RecordContent', '500px', '200px')
                   }
               }
               paramData.viewOther(tmpl, model);
           },
           //右侧标签客户记事
           RecordTag: function (tmpl, lang, contentid, module,paramData) {
               var CBCRM = avalon.vmodels.CBCRM, RecordContent, detail, meun, that = this,
               model = avalon.define('RecordTag', function (vm) {
                   vm.lang = lang
                   vm.Show = 3
                   vm.count = 0
                   vm.IfAdd = true
                   vm.tab = '0'
                   vm.tabChange = function () {
                       model.Show = 0;
                       var tabid = $(this).attr("val")
                       model.tab = tabid
                       $.get('/Customer/GetCustomerRecordRightListById', { id: tabid }, function (ret) {
                           model.Detailsmodel = ret.data.Source[0]
                       })


                   }

                   vm.CustomerRecordTag = []
                   //客户记事详情
                   vm.Detailsmodel = {
                       Id: 0,
                       RecordTag: "",
                       RecordContent: "",
                       CoustomId: 0,
                       CreateId: 0,
                       CreateDate: "",
                       CreateName: "",
                       UpdateName: "",
                       UpdateId: 0,
                       UpdateDate: "",
                       RecordName: "",
                   }
                   //新增记事
                   vm.AddCustomerRecord = function () {
                       var curr = CBCRM.memberShip
                       model.Detailsmodel.Id = 0
                       model.Detailsmodel.RecordContent = ''
                       model.Detailsmodel.RecordTag = '客户标签'
                       model.Detailsmodel.CreateId = curr.Id
                       model.Detailsmodel.CreateName = curr.FullName
                       model.Detailsmodel.CreateDate = GetDateTime()
                       model.Detailsmodel.UpdateId = curr.Id
                       model.Detailsmodel.UpdateName = curr.FullName
                       model.Detailsmodel.UpdateDate = GetDateTime()
                       model.Detailsmodel.RecordName = 'TagPositionTag'
                       model.Detailsmodel.CoustomId = that.params.ation
                       model.Show = 1;
                       model.tab = '0'
                       if (RecordContent)
                           RecordContent.remove()
                       if (document.getElementById('RecordContent')) {
                           RecordContent = setEditerSimple('RecordContent', '800px', '400px')
                       }
                       if (RecordContent)
                           RecordContent.html(model.Detailsmodel.RecordContent)
                       //$.post("/Customer/CustomerRecordTagAdd/0", model.Detailsmodel.$model, function (ret) {
                       //    if (ret.result) {
                       //        model.tab = ret.message;
                       //        GetCustomerRecord(2);
                       //    }

                       //})
                   }

                   //编辑记事标签
                   vm.EditDetails = function () {
                       model.Show = 1;
                       if (RecordContent)
                           RecordContent.remove()
                       if (document.getElementById('RecordContent')) {
                           RecordContent = setEditerSimple('RecordContent', '800px', '400px')
                       }
                       if (RecordContent)
                           RecordContent.html(model.Detailsmodel.RecordContent)
                   }

                   //删除记事标签
                   vm.DeleteDetails = function (id) {

                       $.post("/Customer/CustomerRecordDelete", { id: id }, function (ret) {
                           CBCRM.showResult(ret);
                           model.Show = 0
                           GetCustomerRecord(1)
                       });
                   }
                   //提交记事标签
                   vm.formSubmit = function () {
                       model.Detailsmodel.RecordContent = RecordContent.html();
                       if (model.Detailsmodel.RecordTag == "") {
                           messageBox.warning('请输入标题');
                           return false
                       }
                       $.post("/Customer/EditCustomerRecord", model.Detailsmodel.$model, function (ret) {
                           $.get("/Customer/GetCustomerRecordById", { id: ret.message }, function (result) {
                               if (result.data) {
                                   model.Detailsmodel = result.data
                                   model.tab = model.Detailsmodel.Id
                               }
                               model.Show = 0
                               GetCustomerRecord(2)
                           });
                       });
                   }
               })
               GetCustomerRecord(1);

               //获取数据
               function GetCustomerRecord(val) {
                   $.get("/Customer/GetCustomerRecordByList", { id: that.params.ation, type: that.params.type, pageIndex: 1, pageSize: 9 }, function (result) {
                       if (result.data.Source.length != 0) {
                           model.CustomerRecordTag = []
                           model.count = result.data.Source.length
                           if (model.count > 8) {
                               model.IfAdd = false
                           } else {
                               model.IfAdd = true
                           }
                           for (var i = 0, tmp; tmp = result.data.Source[i]; i++) {
                               model.CustomerRecordTag.push({ id: tmp.Id, Name: tmp.RecordName, Val: tmp.RecordTag })
                               if (val != 1) {
                                   if (tmp.Id == model.tab) {
                                       model.Detailsmodel = result.data.Source[i]
                                   }
                               } else {

                                   model.Detailsmodel = result.data.Source[0]
                                   model.tab = model.Detailsmodel.Id
                               }
                           }
                           model.Show = 0

                       } else {
                           model.Show = 3
                           model.CustomerRecordTag = []
                       }
                   })
               }
               paramData.viewOther(tmpl, model);
               CBCRM.onLoadModuleBefore = function () {
                   avalon.vmodels.RecordTag = null
               }
           },
           //客户证件
           DetailCredentials: function (tmpl, lang, contentid, module,paramData) {
               var CBCRM = avalon.vmodels.CBCRM, that = this,
               model = CBCRM.define('credentials', function (scope) {
                   scope.lang = lang
                   scope.credentialsEntity = {}
                   scope.credentialsList = []
                   scope.nameData = []
                   scope.ADD = true
                   scope.keyword = ''
                   scope.dosearch = function () {
                       GetCredentials({ keyword: model.keyword });
                   }
                   scope.bindclick = function () {
                       if (event.keyCode == 13)
                           model.dosearch()
                   }
                   scope.hasData = false

                   //查看
                   scope.doView = function () {
                       var href = $(this).attr('val');
                       var dialog = messageBox.openHtml('查看大图', '', '', '<img src="' + href + '" />')
                   }
                   //新增
                   scope.doAdd = function () {
                       model.credentialsEntity = avalon.mix({}, credentialsData)
                       model.credentialsEntity.AddTime = GetDateTime()
                       FormSubmit("新增客户证件")
                   }
                   //修改
                   scope.doEdit = function () {
                       var id = $(this).attr('value')
                       model.credentialsList.$model.forEach(function (item) {
                           if (item.Id == id) {
                               model.credentialsEntity = item
                           }
                       })
                       FormSubmit("修改客户证件")
                   }
                   //删除
                   scope.doDelete = function () {
                       var index = parseInt($(this).attr('index'))
                       var id = $(this).attr('value')
                       messageBox.confirm('确定删除此数据吗？', function () {
                           $.post('/Customer/DelCredentials/' + id, {}, function (ret) {
                               if (ret.result) {
                                   model.credentialsList.removeAt(index)
                                   messageBox.succeed(ret.message)
                               } else {
                                   messageBox.fail(ret.message)
                               }
                           })
                       });
                   }
                   scope.doDelAll = function () {
                       var ids = checkAll()
                       if (!ids['deleteIds[0]']) {
                           messageBox.warning('请选择要删除的数据')
                       } else {
                           messageBox.confirm('确定删除选中数据吗？', function () {
                               $.post('/Customer/DelAllCredentials/', ids, function (ret) {
                                   if (ret.result) {
                                       messageBox.succeed(ret.message)
                                       GetCredentials()
                                   } else {
                                       messageBox.fail(ret.message)
                                   }
                               })
                           })
                       }
                   }
                   scope.isall = false
                   //全选
                   scope.doSelectAll = function () {
                       $("input[name='checkbox']").each(function (i, item) {
                           item.checked = !model.isall
                       })
                       model.isall = !model.isall
                   }

                   //有效时间
                   scope.begindateOpts = {
                       format: '%Y-%m-%d',
                       onSelect: function (date, formatDate, format) {
                           model.credentialsList.BeginDate = formatDate
                       }
                   }
                   scope.enddateOpts = {
                       format: '%Y-%m-%d',
                       onSelect: function (date, formatDate, format) {
                           model.credentialsList.EndDate = formatDate
                       }
                   }

                   scope.doChangName = function () {
                       model.credentialsEntity.Name = $(this).val()
                   }

                   //上传文件
                   scope.uploadpicture = function () {
                       var dialog = CBCRM.upload(true, function (node, data, file) {
                           var f = file.length ? file[0] : file;
                           scope.credentialsEntity.Picture = '/upload/' + f.Path;
                           dialog.close();
                       });
                   }
               })

               //保存
               function FormSubmit(title) {
                   var dialog = messageBox.openHtml(title, '600px', '300px', '', [{
                       name: '提交',
                       focus: true,
                       callback: function () {
                           var credentialsmodel = model.credentialsEntity.$model
                           var url = (credentialsmodel.Id == 0 ? "/Customer/AddCredentials/" : "/Customer/UpdateCredentials/")
                           $.post(url + credentialsmodel.Id, credentialsmodel, function (ret) {
                               if (ret.result) {
                                   messageBox.ok(ret.message, function () { GetCredentials(); dialog.close(); })
                               }
                               else {
                                   messageBox.fail(ret.message, function () { })
                               }
                           })
                           return false;
                       }
                   }])

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

               model.nameData = [{ id: '', data: '请选择证书名称' }, { id: '企业营业执照', data: '企业营业执照' }, { id: '社团法人证书', data: '社团法人证书' }, { id: '身份证', data: '身份证' }
                                 , { id: '户口簿', data: '户口簿' }, { id: '军官证', data: '军官证' }, { id: '护照', data: '护照' }
                                 , { id: '消防安全生产许可证', data: '消防安全生产许可证' }, { id: '对外贸易经营资格备案表', data: '对外贸易经营资格备案表' }
                                 , { id: '海关报关注册登记证', data: '海关报关注册登记证' }, { id: '检验检疫备案证书', data: '检验检疫备案证书' },
               ]

               var credentialsData = {
                   Id: '',
                   CustomerId: that.params.id,
                   Name: '',
                   BeginDate: '',
                   EndDate: '',
                   Picture: '',
                   Remark: '',
                   AddByDsiplay: '',
                   AddTime: ''
               }

               function GetCredentials(data) {
                   $.get(that.path, data || {}, function (ret) {
                       if (!ret || !ret.result) return CBCRM.showResult(ret);
                       model.credentialsList = ret.data
                       if (ret.data.length > 0) {
                           model.hasData = true
                       }
                       else {
                           model.hasData = false
                       }
                   })
               }

               GetCredentials()
               paramData.viewOther(tmpl, model);
           },
           CustomerDynamics: function (tmpl, lang, contentId, module,paramData) {
               var CBCRM = avalon.vmodels.CBCRM, vmid = "CustomerDynamics";
               var action = this.params.action, paramid = this.params.id;
               var mvvm = CBCRM.define(vmid, function (vm) {
                   vm.list = [];
                   vm.queryData = { customerId: '', sminDate: "", smaxDate: "" };
                   vm.$minDate = "";
                   vm.$maxDate = "";
                   vm.doSearch = function () {
                       mvvm.loadData(mvvm.createQuery());
                   }
                   vm.gopage = function (p) {
                       if (p == 1) {
                           vm.queryData.sminDate = mvvm.$minDate;
                           vm.queryData.smaxDate = "";
                       } else {
                           vm.queryData.sminDate = "";
                           vm.queryData.smaxDate = mvvm.queryData.$maxDate;
                       }
                       mvvm.doSearch();
                   }
                   vm.loadData = function (data) {
                       var url = "/Customer/CustomerDynamics/";
                       $.get(url, data, function (ret) {
                           if (ret && ret.result) {
                               var list = ret.data;
                               mvvm.list = list;
                               if (list.length > 0) {
                                   if (list.length == 1) {
                                       mvvm.$maxDate = mvvm.$minDate = list[0].GroupDate;
                                   } else {
                                       mvvm.$minDate = list[list.length - 1].GroupDate;
                                       mvvm.$maxDate = list[0].GroupDate;
                                   }
                               }
                           } else {
                               CBCRM.showResult(ret);
                           }
                       });
                   }
                   vm.createQuery = function () {
                       var data = {};
                       for (var key in mvvm.queryData) {
                           var v = mvvm.queryData[key];
                           if (v != "" && typeof (v) != "function") data[key] = v;
                       }
                       return data;
                   }
               })
               switch (action) {
                   case "customer":
                       fillCustomer();
                       break;
                   default:
                       CBCRM.fillContent(tmpl, lang, contentId, module, model)
                       break;
               }
               function fillCustomer() {
                   mvvm.queryData.customerid = paramid;
                   mvvm.doSearch();
                   paramData.viewOther(tmpl, mvvm);
               }
           },
           /*客户树*/
           Tree: function (tmpl, lang, contentId, module,paramData) {
               var CBCRM = avalon.vmodels.CBCRM, vmid = "CustomerTree";
               var action = this.params.action, paramid = this.params.id;
               var mvvm = CBCRM.define(vmid, function (vm) {
                   var treeid = "customerTree";
                   vm.customerEntity = {};
                   vm.getTreeData = function () {
                       var url = "/Customer/Tree/" + paramid;
                       $.get(url, {}, function (ret) {
                           var data = ret.result ? ret.data : [];
                           mvvm.createTree(data);
                       })
                   }
                   vm.createTree = function (dataSource) {
                       var tree = createZtree(treeid, {
                           callback: {
                               onClick: function (e, id, node) {
                                   mvvm.selectNode(node, this.getZTreeObj(id));
                               }
                           }
                       }, dataSource);
                       var node = tree.getNodeByParam("Id", paramid);
                       if (node) mvvm.selectNode(node, tree);
                   }
                   vm.selectNode = function (node, tree) {
                       mvvm.customerEntity = node;
                       tree.selectNode(node);
                   }
                   vm.viewCustomer = function (id) {
                       if (!id) return;
                       var url = "/Customer/DetailCustomer/" + id;
                       goto(url, true);
                   }
                   vm.destroy = function () {
                       destroyui(["customerTree"]);
                       avalon.vmodels[vmid] = null;
                   }
               })
               switch (action) {
                   case "customer":
                       fillCustomer();
                       break;
                   default:
                       CBCRM.fillContent(tmpl, lang, contentId, module, model)
                       break;
               }
               function fillCustomer() {
                   if (paramData) {
                       paramData.viewOther(tmpl, mvvm);
                       mvvm.getTreeData();
                   }
               }
               CBCRM.onLoadModuleBefore = function () {
                   mvvm.destroy();
               }
           },
           /*客户分析*/
           Analysis: function (tmpl, lang, contentId, module,paramData) {
               //线性图
               function createLineChart(chartData, chartId, width, height) {
                   var data = [], series = [], cats = [], index;
                   cats = chartData.categories[0].category;
                   chartData.dataset.forEach(function (item) {
                       var arr = [];
                       series.push({
                           color: item.color ? "#" + item.color : null,
                           label: item.seriesname
                       });
                       index = 0;
                       item.data.forEach(function (d) {
                           var a = [cats[index].label, d.value];
                           arr.push(a);
                           index++;
                       });
                       data.push(arr);
                   })
                   var ops = {
                       title: chartData.chart.caption,
                       series: series,
                       seriesDefaults: {
                           rendererOptions: { fillToZero: true },
                           // Rotate the bar shadow as if bar is lit from top right.
                           shadowAngle: 135
                       },
                       legend: {
                           show: true,
                           placement: 'outsideGrid'
                       },
                       axes: {
                           xaxis: {
                               renderer: $.jqplot.CategoryAxisRenderer
                           }
                       }
                   };
                   var dChart = $("#" + chartId).empty();
                   if (width) dChart.width(width).height(height);
                   try {
                       dChart.jqplot(data, ops);
                   } catch (ex) {
                       dChart.html("<p class='nodata'>" + ex.message + "</p>")
                   }
               }
               function createColumnChart(chartData, chartId, width, height) {
                   var data = [], series = [], cats = [], index;
                   cats = chartData.categories[0].category;
                   chartData.dataset.forEach(function (item) {
                       var arr = [];
                       series.push({
                           color: item.color ? "#" + item.color : null,
                           label: item.seriesname
                       });
                       index = 0;
                       item.data.forEach(function (d) {
                           var a = [cats[index].label, d.value];
                           arr.push(a);
                           index++;
                       });
                       data.push(arr);
                   })
                   var ops = {
                       title: chartData.chart.caption,
                       series: series,
                       seriesDefaults: {
                           renderer: $.jqplot.BarRenderer,
                           rendererOptions: { fillToZero: true },
                           pointLabels: { //数值点标签属性设置，该属性来自于jqplot.pointLabels.min.js
                               show: true, //是否在图表上显示数值点标签
                               location: 'n', //标签显示的方位 'se', 's', 'sw', 'w', 'nw'
                               edgeTolerance: -15
                           },
                           // Rotate the bar shadow as if bar is lit from top right.
                           shadowAngle: 135
                       },
                       legend: {
                           show: true,
                           placement: 'outsideGrid'
                       },
                       axes: {
                           xaxis: {
                               renderer: $.jqplot.CategoryAxisRenderer
                           }
                       }
                   };
                   var dChart = $("#" + chartId).empty();
                   if (width) dChart.width(width).height(height);
                   try {
                       dChart.jqplot(data, ops);
                   } catch (ex) {
                       dChart.html("<p class='nodata'>" + ex.message + "</p>")
                   }
               }
               var CBCRM = avalon.vmodels.CBCRM, vmid = "CustomerAnalysis";
               var action = this.params.action, paramid = this.params.id;
               var mvvm = CBCRM.define(vmid, function (vm) {
                   initQuerys(vm, function (data, name, val, type) {
                       mvvm.loadData(data);
                   });
                   vm.queryData = {
                       dateType: {
                           label: "时间类型", val: "",
                           items: [
                               { label: "本年", val: 1, curr: true },
                               { label: "本季", val: 2, curr: true },
                               { label: "本月", val: 3, curr: true },
                               { label: "本周", val: 4, curr: true },
                               { label: "本日", val: 5, curr: false }
                           ]
                       },
                       startDate: {
                           label: "起始时间", val: ""
                       },
                       endDate: {
                           label: "截止时间", val: ""
                       },
                       dateType2: {
                           label: "时间类型", val: "",
                           items: [
                               { label: "上年", val: 1, curr: true },
                               { label: "上季", val: 2, curr: true },
                               { label: "上月", val: 3, curr: true },
                               { label: "上周", val: 4, curr: true },
                               { label: "昨日", val: 5, curr: false }
                           ]
                       },
                       startDate2: {
                           label: "起始时间", val: ""
                       },
                       endDate2: {
                           label: "截止时间", val: ""
                       },
                       compare: {
                           label: "比较", val: false
                       }
                   }
                   vm.watchDate = function () {
                       mvvm.queryData.dateType.$watch("val", function (n, o) {
                           var now = new Date(), date = new Date(now.getFullYear(), now.getMonth(), now.getDate())
                           var sd, ed = date;
                           switch (n) {
                               case "1":
                                   sd = new Date(now.getFullYear(), 0, 1)
                                   ed = new Date(now.getFullYear(), 12, 0)
                                   break;
                               case "2":
                                   var m = now.getMonth() + 1;
                                   var c = parseInt(m / 3);
                                   if (m % 3 != 0) c++;
                                   var j = c * 3 - 3;
                                   sd = new Date(now.getFullYear(), j, 1);
                                   ed = new Date(now.getFullYear(), c * 3, 0);
                                   break;
                               case "3":
                                   sd = new Date(now.getFullYear(), now.getMonth(), 1);
                                   ed = new Date(now.getFullYear(), now.getMonth() + 1, 0);
                                   break;
                               case "4":
                                   w = now.getDay();
                                   var nd = now.getDate();
                                   var j = nd - (6 - w - 1);
                                   sd = new Date(now.getFullYear(), now.getMonth(), j);
                                   ed = new Date(now.getFullYear(), now.getMonth(), sd.getDate() + 6);
                                   break;
                               case "5":
                                   sd = date;
                                   ed = date;
                                   break;
                               default:
                                   sd = null;
                                   ed = null;
                                   break;
                           }
                           mvvm.queryData.startDate.val = sd ? GetDateTime(sd, "yyyy-MM-dd") : "";
                           mvvm.queryData.endDate.val = ed ? GetDateTime(ed, "yyyy-MM-dd") : "";
                           mvvm.queryData.dateType2.val = n;
                       });
                       mvvm.queryData.dateType2.$watch("val", function (n, o) {
                           var now = new Date(), date = new Date(now.getFullYear(), now.getMonth(), now.getDate())
                           var sd, ed = date;
                           switch (n) {
                               case "1":
                                   sd = new Date(now.getFullYear() - 1, 0, 1)
                                   ed = new Date(now.getFullYear() - 1, 12, 0)
                                   break;
                               case "2":
                                   var m = now.getMonth() + 1;
                                   var c = parseInt(m / 3);
                                   if (m % 3 != 0) c++;
                                   c--;

                                   var j = c * 3 - 3;
                                   sd = new Date(now.getFullYear(), j, 1);
                                   ed = new Date(now.getFullYear(), c * 3, 0);
                                   break;
                               case "3":
                                   sd = new Date(now.getFullYear(), now.getMonth() - 1, 1);
                                   ed = new Date(now.getFullYear(), now.getMonth(), 0);
                                   break;
                               case "4":
                                   w = now.getDay();
                                   var nd = now.getDate();
                                   var j = nd - (6 - w - 1) - 7;
                                   sd = new Date(now.getFullYear(), now.getMonth(), j);
                                   ed = new Date(now.getFullYear(), now.getMonth(), sd.getDate() + 6);
                                   break;
                               case "5":
                                   sd = date;
                                   ed = new Date(now.getFullYear(), now.getMonth(), sd.getDate() - 1);
                                   break;
                               default:
                                   sd = null;
                                   ed = null;
                                   break;
                           }
                           mvvm.queryData.startDate2.val = sd ? GetDateTime(sd, "yyyy-MM-dd") : "";
                           mvvm.queryData.endDate2.val = ed ? GetDateTime(ed, "yyyy-MM-dd") : "";
                       });
                   }

                   vm.doSearch = function () {
                       mvvm.loadData(mvvm.createQuery());
                   }
                   vm.loadData = function (data) {
                       $.post("/Customer/Analysis/" + paramid, data, function (ret) {
                           if (!ret.result) return CBCRM.showResult(ret);
                           createLineChart(ret.data.chartData1, vmid + "_chart1", 800, 240);
                           createColumnChart(ret.data.chartData2, vmid + "_chart2", 800, 240);
                       })
                   }
               })
               mvvm.watchDate();
               mvvm.queryData.dateType.val = "3";
               switch (action) {
                   case "customer":
                       fillCustomer();
                       break;
                   default:
                       CBCRM.fillContent(tmpl, lang, contentId, module, model)
                       break;
               }
               function fillCustomer() {
                   paramData.viewOther(tmpl, mvvm);
               }
               require(['jqPlot', 'jqBar', 'jqPointLabels', 'jqCategory', 'jqCanvasText', 'jqCanvasAxisLabel', 'jqPointLabel', 'jqEnhancedLegend'], function () {
                   mvvm.loadData(mvvm.createQuery());
               });
           },
           /*享受价格*/
           PriceList: function (tmpl, lang, contentId, module,paramData) {
               var CBCRM = avalon.vmodels.CBCRM, vmid = "CustomerPriceList";
               var action = this.params.action, paramid = this.params.id;
               var queryData = {}, treeid = "customer_ProductCategory_Tree";
               var mvvm = CBCRM.define(vmid, function (vm) {
                   vm.lang = lang;
                   vm.EXPORT = false;
                   vm.editPrice = false;
                   vm.editPrices = false;
                   vm.priceTypes = ["标准价", "级别价", "特供价"];
                   vm.key = "";
                   vm.customer = { Id: "", Name: "", MemberGrade: "", MemberGradeDisplay: "" }
                   //产品分类树配置
                   vm.pCategoryTreeOpts = {
                       treeopts: {
                           async: {
                               url: "/Product/Category",
                               dataFilter: function (treeId, parentNode, ret) {
                                   var list = ret.data;
                                   list.forEach(function (item) {
                                       if (!item.pId) item.open = true;
                                       else item.open = false;
                                   });
                                   return list;
                               }
                           },
                           callback: {
                               onClick: function (e, treeId, treeNode) {
                                   queryData.typeid = treeNode.Id;
                                   mvvm.grid1.doSearch();
                               }
                           },
                           view: {
                               addHoverDom: '',
                               removeHoverDom: ''
                           }
                       }
                   }
                   //分类树展开/收起
                   vm.$expancategory = true;
                   vm.expanCategory = function () {
                       mvvm.$expancategory = !mvvm.$expancategory;
                       $(this).text(mvvm.$expancategory ? "- 收起" : "+ 展开");
                       var tree = $.fn.zTree.getZTreeObj(treeid);
                       if (tree) {
                           var nodes = tree.getNodes();
                           if (nodes.length > 0) tree.expandNode(nodes[0], mvvm.$expancategory, true);
                           //收起的时候让根节点处于展开状态
                           if (!mvvm.$expancategory) tree.expandNode(nodes[0], !mvvm.$expancategory, false);
                       }
                   }
                   vm.createQuery = function () {
                       var data = where(queryData, function (key, val) { return val != null && val != "" });
                       data.key = mvvm.key;
                       return data;
                   }
                   vm.grid1 = createGrid({
                       $lang:lang,
                       url: "/Product/PriceList",
                       pageid: vmid + "_grid1_page",
                       pageinitload: false,
                       createQuery: vm.createQuery,
                       onLoadData: function (ret) {
                           if (!ret || !ret.result) {
                               CBCRM.showResult(ret);
                               return;
                           }
                           mvvm.EXPORT = ret.data.EXPORT;
                           ret.data.productList.Source.forEach(function (item) {
                               item.Edit = false;
                               mvvm.autoPrice(item);
                           })
                           var pdata = ret.data.productList;
                           return pdata;
                       },
                       afterLoadData: function (ret, list) {
                           mvvm.editPrices = false;
                           mvvm.editPrice = false;
                           list.forEach(function (item, index) {
                               item.$watch("PriceType", function (n, o) {
                                   switch (n) {
                                       case "0":
                                           item.CustomerPrice = item.GeneralCustomerPrice;
                                           break;
                                       case "1":
                                           p = findArr(item.PriceList, function (item) { return item.MemberGrade == mvvm.customer.MemberGrade });
                                           item.CustomerPrice = p != null ? p.Prints : "";
                                           break;
                                       case "2":
                                           var p = findArr(item.PriceList, function (item) { return item.Type == 0 && item.Prints });
                                           item.CustomerPrice = p != null ? p.Prints : "";
                                           break;
                                       default:
                                           item.CustomerPrice = "";
                                           break;
                                   }
                               });
                               item.$watch("Edit", function (n, o) {
                                   if (n) {
                                       item.PriceType = "2";
                                   } else {
                                       mvvm.autoPrice(item);
                                   }
                                   var edititem = findArr(list, function (e) { return e.Edit });
                                   mvvm.editPrice = edititem != null;
                               });
                           })
                       }
                   });
                   vm.autoPrice = function (item) {
                       var p = findArr(item.PriceList, function (item) { return item.Type == 0 && item.Prints });
                       if (p != null) {
                           item.PriceType = "2";
                           item.CustomerPrice = p.Prints;
                       } else {
                           p = findArr(item.PriceList, function (item) { return item.Type == 1 && item.Prints });
                           if (mvvm.customer.MemberGrade && p != null) {
                               item.PriceType = "1";
                               item.CustomerPrice = p.Prints;
                           } else {
                               item.PriceType = "0";
                               item.CustomerPrice = item.GeneralCustomerPrice;
                           }
                       }
                   }
                   vm.bindWatch = function () {
                       mvvm.$watch("editPrices", function (n, o) {
                           mvvm.grid1.list.forEach(function (item) {
                               item.Edit = n;
                           });
                           mvvm.editPrice = n;
                       })
                   }
                   vm.saveCustomerPrice = function () {
                       var edits = [];
                       mvvm.grid1.list.forEach(function (item) {
                           if (item.Edit) edits.push({ ProductId: item.Id, PriceType: 2, Price: item.CustomerPrice });
                       });
                       if (edits.length == 0) return;
                       var data = jsonToSubmit("cpriceList", edits);
                       data.customerId = mvvm.customer.Id;
                       $.post("/Customer/SaveCustomerPrice/", data, function (ret) {
                           CBCRM.showResult(ret);
                           if (ret.result) {
                               mvvm.grid1.reloadData();
                           }
                       })
                   }
                   vm.initData = function (id) {
                       queryData.customerId = id;
                       $.post("/Customer/PriceList", { customerId: id }, function (ret) {
                           if (ret && ret.result) {
                               mvvm.customer = ret.data.customer;
                               var mg = mvvm.customer.MemberGrade ? mvvm.customer.MemberGradeDisplay : "无";
                               mvvm.priceTypes[1] += "(" + mg + ")";
                               mvvm.grid1.doSearch();
                           }
                           else CBCRM.showResult(ret);
                       });
                   }
                   vm.viewproduct = function (id) {
                       var url = "/Product/Product/" + id + "/view";
                       goto(url, true);
                   }
                   vm.msdropdown = msdropdown;
                   vm.exportExcel = function (act) {
                       var url = "/Product/PriceList/";
                       var data = mvvm.createQuery();
                       data.exportExcel = true;
                       if (act == 1) {
                           var page = mvvm.grid1.getPage();
                           if (page != null) {
                               data.pageSize = page.pagesize;
                               data.pageIndex = page.currentindex + 1;
                           }
                       }
                       //var cpriceList = [];
                       //mvvm.grid1.list.forEach(function (item) {
                       //    if (item.Edit) cpriceList.push({ ProductId: item.Id, PriceType: item.PriceType, Price: item.CustomerPrice });
                       //});
                       //$.extend(data, jsonToSubmit("cpriceList", cpriceList));
                       frameSubmit(url, "post", data);
                   }
                   vm.destroy = function () {
                       destroyui([treeid]);
                       mvvm.grid1.destroy();
                   }
               })
               mvvm.grid1.init();
               mvvm.bindWatch();
               switch (action) {
                   case "customer":
                       fillCustomer();
                       break;
                   default:
                       CBCRM.fillContent(tmpl, lang, contentId, module, model)
                       break;
               }
               function fillCustomer() {
                   paramData.viewOther(tmpl, mvvm);
                   mvvm.initData(paramid);
               }
           },
           Map: function (tmpl, lang, contentId, module,paramData) {
               var CBCRM = avalon.vmodels.CBCRM, init = false, maptool = null;
               var mvvm = avalon.define('Map', function (vm) {
                   vm.NOPAGE = false;
                   vm.companyEntity = {}
                   vm.entity = {};
                   vm.customers = []
                   vm.eachCountry = []
                   vm.eachProvince = []
                   vm.eachCity = []
                   vm.eachArea = []
                   vm.letters = [];
                   vm.cityLetters = {};
                   vm.cityAreas = [];
                   vm.customerName = ''
                   vm.curCountryId = '';
                   vm.curCountry = '';
                   vm.curProvince = '';
                   vm.curProvinceId = '';
                   vm.curCityId = '';
                   vm.curAreaId = '';
                   vm.curCountry = "请选择";
                   vm.curCity = "请选择";
                   vm.curArea = "请选择";
                   vm.areaId = ''
                   vm.typeId = ''
                   vm.$point1 = null;
                   vm.$point2 = null;
                   vm.customerOpts = {
                       paging: function () {
                           if (!init) {
                               init = true;
                               return;
                           }
                           var data = mvvm.getQueyData();
                           data.cpage = (this.currentindex + 1) || 1
                           data.climit = this.pagesize
                           mvvm.loadData(data)
                       },
                       enablesetsize: false,
                       showtotal: false,
                       showpages: 4,
                       initload: false,
                       pagesize: 20

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

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

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

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

               function fill() {
                   CBCRM.fillContent(tmpl, lang, contentId, module, mvvm);
                   avalon.nextTick(function () {
                       initSelectCity();
                       //mvvm.getCustomerList();
                       mvvm.getGroupDataProvince();
                       var w = 0;
                       if ($.browser.msie) w = 20;
                       if ($.browser.mozilla) w = 0;
                       mvvm.mapwidth = $(document).width() - $("#map_client_l").width() - w;
                       mvvm.mapheight = $(window).height() - $("#topBg").height() - $("#gps").height() - 5;
                   });
               }

               CBCRM.onLoadModuleBefore = function () {
                   avalon.vmodels.Map = null
                   window.map = null
               }
           }
       }
       console.log('已成功加载Customer 模块。')

       

       setOptUrl = function (c) {
           switch (c.SuperiorCategoryId) {
               case 10103:
                   c.EditUrl = '#/Customer/EditCustomer/'
                   c.DetailUrl = '#/Customer/DetailCustomer/'
                   break
               case 10107:
                   c.EditUrl = '#/Customer/EditCustomer/'
                   c.DetailUrl = '#/Customer/DetailCustomer/'
                   break
               case 10131:
                   c.EditUrl = '#/Customer/EditCollaborate/'
                   c.DetailUrl = '#/Customer/DetailCustomer/'
                   break
               case 10132:
                   c.EditUrl = '#/Customer/EditChannel/'
                   c.DetailUrl = '#/Customer/DetailCustomer/'
                   break
               case 10133:
                   c.EditUrl = '#/Customer/EditSupply/'
                   c.DetailUrl = '#/Customer/DetailCustomer/'
                   break
               case 10134:
                   c.EditUrl = '#/Customer/EditAdvertising/'
                   c.DetailUrl = '#/Customer/DetailCustomer/'
                   break
               case 10135:
                   c.EditUrl = '#/Customer/EditCompetitor/'
                   c.DetailUrl = '#/Customer/DetailCustomer/'
                   break
               case 11170:
                   c.EditUrl = '#/Customer/EditSociall/'
                   c.DetailUrl = '#/Customer/DetailCustomer/'
                   break
           }
       }
       return Customer
   })