define('Services', ['modelFactory','plugins', 'json', 'dialog', 'jscal2', 'common', 'jcal',  'jqselect', 'cookie', 'zclip'],
    function (modelFactory,plugins) {
        var NODATAMSG = "暂无数据", LOADDTTAMSG = "数据载入中……";
        var groupPostFilter = function (treeId, parentNode, responseData) {
            var groups = [];
            if (responseData.data && responseData.data.groups.length) {
                responseData.data.groups.forEach(function (item, i) {
                    var m = {
                        Id: item.Id, Name: item.Name, ParentId: item.ParentId, iconSkin: item.iconSkin,
                        open: i === 0
                    }
                    groups.push(m);
                    item.Posts.forEach(function (item2, j) {
                        var mm = {
                            Id: item2.Id, Name: item2.Name, ParentId: item2.Group, iconSkin: item2.iconSkin,
                            open: j === 0
                        }
                        groups = groups.concat(mm);
                        item2.Users.forEach(function (item3) {
                            var mmm = {
                                Id: item3.Id, Name: item3.FullName, ParentId: item3.PositionId, iconSkin: item3.iconSkin
                            }
                            groups = groups.concat(mmm);
                        });
                    });
                });
            }
            return groups;
        };
        var Services = {
            /// <summary>
            /// 工作台
            /// </summary>
            Index: function (tmpl, lang, contentId, module) {
                var CBCRM = avalon.vmodels.CBCRM
                var that = this;
                var mvvm = CBCRM.define('IndexController', function (vm) {
                    vm.lang = lang;
                    vm.$skipArray = ['lang']
                    vm.keyword = ''
                    vm.sendSms = CBCRM.sendSms;
                    vm.search = function () {
                        $('#sbServices').val()
                        switch ($('#sbServices').val()) {
                            case 'calls':
                                goto('/Services/Calls/' + mvvm.keyword + '/key')
                                break
                            case 'complaints':
                                goto('/Services/Complaints/' + mvvm.keyword + '/key')
                                break
                            case 'services':
                                goto('/Services/CServices/' + mvvm.keyword + '/key')
                                break
                            case 'follow':
                                goto('/Services/FollowUp/' + encodeURIComponent(mvvm.keyword)+'/key')
                                break
                        }
                    }
                    vm.calls = {}
                    vm.complaints = {}
                    vm.follow = {}
                    vm.services = {}

                    vm.followUpNextList = []
                    vm.complaintsList = []
                    vm.followUpNewList = []
                    vm.cusServicesList = []
                    vm.callsList = []
                })

                function initWithData() {
                    $.get('/Services/TopCount/', {}, function (ret) {
                        mvvm.calls = ret.data.calls;
                        mvvm.complaints = ret.data.complaints;
                        mvvm.follow = ret.data.follow;
                        mvvm.services = ret.data.services;
                    })
                    $.get('/Services/TopCharts', {}, function (ret) {
                        //createPieChart(ret.data.chart1, 'chartServices1');
                        createJQPieChart('#chartServices1', '本月来电类型分布', ret.data.chart1);
                        //createAngularGauge(ret.data.chart2.followCount, ret.data.chart2.followCountMax, 'chartServices2');
                        createJQDashboard('#chartServices2', "本月回访仪表",  ret.data.chart2.followCount, ret.data.chart2.followCountMax);
                        //createColumnChart(ret.data.chart3, 'chartServices3');
                        createJQBar('#chartServices3', '本月员工被投诉黑榜', ret.data.chart3);
                        //createAngularGauge(ret.data.chart2.complaintsCount, ret.data.chart2.complaintsCountMax, 'chartServices4');
                        createJQDashboard('#chartServices4', '本月投诉仪表', ret.data.chart2.complaintsCount, ret.data.chart2.complaintsCountMax);
                        //createLineChart(ret.data.chartLine, 'chartServicesLine');
                        createJQLinear('#chartServicesLine', '服务曲线', ret.data.chartLine);
                    })
                    $.get('/Services/TopTables', { top: 5 }, function (ret) {
                        mvvm.followUpNextList = ret.data.followUpNextList
                        mvvm.complaintsList = ret.data.complaintsList
                        mvvm.followUpNewList = ret.data.followUpNewList
                        mvvm.cusServicesList = ret.data.cusServicesList
                        mvvm.callsList = ret.data.callsList
                    })
                }
                

                //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: 0,
                                    labelPosition: 'inside',
                                    hubRadius:5
                                }
                            }
                        });
                    }
                    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);
                        });
                        //console.log(linearData);
                        $(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
                                        }
                                    }
                                },
                                 {
                                     label: labels[2] || '',
                                     showHighlight: true,
                                     pointLabels: {
                                         show: true
                                     },
                                     rendererOptions: {
                                         animation: {
                                             speed: 2000
                                         }
                                     }
                                 },
                                  {
                                      label: labels[3] || '',
                                      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 = [];
                    $(chartId).empty();
                    try {
                        console.log(chartData);
                        chartData.forEach(function (item) {
                            labels.push(item.label);
                            a.push(item.value);
                        });
                        barData.push(a);
                        $(chartId).jqplot(barData, {
                            title: title,
                            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,
                                },
                            },
                        });
                    }
                    catch(ex) {
                        $(chartId).html("<p class='nodata'>" + ex.message + "</p>");
                    }
                    //p.replot();
                }
                require("jqPlotPie,jqBar,jqPointLabels,jqCategory,jqCanvasText,jqCanvasAxisLabel,jqCanvasAxisTick,jqEnhancedLegend,jqPointLabel,jqCursor,jqHighlighter,jqMeterGauge",
                function () {
                    initWithData();
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                });

                $('#sbServices').selectbox()
                $('#sbServices_input').removeAttr('readonly')
            },
            /// <summary>
            /// 来电管理
            /// </summary>
            Calls: function (tmpl, lang, contentId, module, paramData) {
                var CBCRM = avalon.vmodels.CBCRM
                var array = [],
                    request = this, action = this.params.action, paramid = this.params.id
                if (paramid == 0) paramid = "";
                var mvvm = CBCRM.define('Calls', function (vm) {
                    vm.lang = lang;
                    vm.$skipArray = ['lang'] //不监控语言包
                    vm.destroy = function () {
                        //记录自定义列
                        $.cookie('custom_calls', JSON.stringify(mvvm.customList.$model));
                    }
                    vm.searchItem = []
                    vm.callsEntity = {}
                    vm.callsList = []
                    vm.groupList = []
                    vm.category = []
                    vm.status = []
                    vm.kuaijie = []
                    vm.showItem = {}
                    vm.children = []
                    vm.contactsRols = []
                    vm.transForm = []
                    vm.transForm2 = []

                    vm.keyword = ''
                    vm.cuskey = '';
                    vm.cuskeyClick = function () {
                        GetCallsGroup({ key: mvvm.cuskey });
                    }
                    vm.ADD = false
                    vm.DELETE = false
                    vm.showCustomer = true
                    vm.history = []
                    vm.docustom = function () {
                        customBox.show($(this));
                    }
                    vm.sendSms = CBCRM.sendSms;
                    //关键字搜索
                    vm.search = function () {
                        if (mvvm.keyword) {
                            mvvm.showItem.key = mvvm.showItem.keyName = mvvm.keyword;
                            GetDataList(mvvm.showItem.$model);
                            if (mvvm.history.length = 3)
                                mvvm.history.removeAt(2);
                            mvvm.history.unshift(mvvm.keyword);
                        }
                    }
                    //历史搜索
                    vm.historyClick = function () {
                        mvvm.keyword = $(this).val();
                        mvvm.showItem.key = mvvm.showItem.keyName = mvvm.keyword;
                        GetDataList(mvvm.showItem.$model);
                    }
                    //清空
                    vm.clear = function () {
                        mvvm.keyword = '';
                        mvvm.showItem.key = mvvm.showItem.keyName = '';
                        mvvm.showItem.status = mvvm.showItem.statusName = '';
                        mvvm.showItem.category = mvvm.showItem.categoryName = '';
                        mvvm.showItem.date = mvvm.showItem.dateName = '';
                        mvvm.showItem.time = mvvm.showItem.timeName = '';
                        mvvm.showItem.emp = mvvm.showItem.empName = '';
                        mvvm.showItem.customer = '';
                        $(".seacrhField a[index='0']").addClass("selected").siblings().removeClass("selected")
                        GetDataList(mvvm.showItem.$model);
                        GetCallsGroup();
                    }
                    //移除单个条件
                    vm.remove = function () {
                        var val = $(this).attr('val');
                        switch (val) {
                            case "key": mvvm.showItem.key = mvvm.showItem.keyName = ''; break;
                            case "status": mvvm.showItem.status = mvvm.showItem.statusName = '';
                                $(".seacrhField a[index='0']").eq(1).addClass("selected").siblings().removeClass("selected");
                                break;
                            case "category": mvvm.showItem.category = mvvm.showItem.categoryName = '';
                                $(".seacrhField a[index='0']").eq(2).addClass("selected").siblings().removeClass("selected");
                                break;
                            case "date": mvvm.showItem.date = mvvm.showItem.dateName = ''; break;
                            case "time": mvvm.showItem.time = mvvm.showItem.timeName = '';
                                $(".seacrhField a[index='0']").eq(0).addClass("selected").siblings().removeClass("selected");
                                break;
                            case "emp": mvvm.showItem.emp = mvvm.showItem.empName = ''; GetCallsGroup(); break;
                            case "customer": mvvm.showItem.customer = ''; break;
                        }
                        GetDataList(mvvm.showItem.$model);
                    }

                    vm.itemClick = function () {
                        $(this).attr('class', 'selected').siblings().removeClass('selected');
                        var i = $(this).attr('index');
                        var sort = $(this).attr('sort');

                        var model = mvvm.searchItem.$model[sort].item[i];
                        switch (sort) {
                            case "0":
                                mvvm.showItem.time = mvvm.showItem.timeName = '';//先清空
                                if (i != 0) {
                                    mvvm.showItem.time = model.value
                                    mvvm.showItem.timeName = model.key;
                                }
                                break;
                            case "1":
                                mvvm.showItem.status = mvvm.showItem.statusName = '';
                                if (i != 0) {
                                    mvvm.showItem.status = model.value
                                    mvvm.showItem.statusName = model.key;
                                }
                                break;
                            case "2":
                                mvvm.showItem.category = mvvm.showItem.categoryName = '';//先清空
                                if (i != 0) {
                                    mvvm.showItem.category = model.value
                                    mvvm.showItem.categoryName = model.key;
                                }
                                break;
                        }
                        GetDataList(mvvm.showItem.$model);
                    }
                    vm.groupClick = function () {
                        var val = $(this).attr('title');
                        mvvm.showItem.customer = '';//先清空
                        mvvm.showItem.customer = val;
                        GetDataList(mvvm.showItem.$model);
                    }
                    vm.grid1 = { gridmsg: "" };
                    //分页
                    vm.userpaing = {
                        paging: function (pageIndex,pageSize) {
                            var that = this
                            mvvm.showItem.pageSize = pageSize;
                            mvvm.showItem.pageIndex = pageIndex;
                            if (action == "customer") {
                                mvvm.showItem.customerId = paramid;
                            }
                            GetDataList(mvvm.showItem.$model);
                            GetCallsGroup();
                        }
                    }
                    //选客户/联系人
                    vm.selectCustomer = function (onlyCu) {
                        var type = onlyCu ? "customer" : "contacts";
                        plugins.selectCustomer({
                            type: type,
                            required:{con:false},
                            callback: function (cus,cons) {
                                var cu = cus[0];
                                if (onlyCu) {
                                    mvvm.callCenterEntity.CustomerName = cu.Name;
                                } else {
                                    mvvm.callsEntity.Cid = cu.Id;
                                    mvvm.callsEntity.CustomerName = cu.Name;
                                    mvvm.callCenterEntity.Cid = cu.Id;
                                    mvvm.callCenterEntity.CustomerName = cu.Name;
                                    mvvm.children = cu.Contacts || [];

                                    var c = cons.length > 0 ? cons[0] : { Id: 0, Name: "", Sex: "0", QQ: "", ContactRoleDisplay: "" };
                                    mvvm.callsEntity.ContactsId = c.Id;
                                    mvvm.callsEntity.CallsName = c.Name;
                                    mvvm.callsEntity.CallsSex = c.Sex;
                                    mvvm.callsEntity.QQ = c.QQ;
                                    mvvm.callsEntity.CallsRole = c.ContactRoleDisplay;
                                }
                            }
                        })
                    }
                    vm.contactChange = function () {
                        mvvm.callsEntity.CallsName = $(this).find('option:selected').text();
                    }

                    //来电管理
                    vm.callRelated = {
                        callList: [],
                        salesoppList: [],
                        contractList: [],
                        compList: []
                    }
                    vm.callCenterEntity = {};
                    vm.createCallCenterEntity = function () {
                        var entity = modelFactory.create('Calls');
                        mvvm.isnew = entity.IsNewsCustomer;
                        entity.Status += '';
                        entity.ClassDicId += '';
                        entity.IsNewsCustomer += '';
                        entity.IsUpdateContacts = 'true';
                        entity.Transform += '';
                        mvvm.children = [];
                        entity.CallsRoleId = getDefDict(mvvm.contactsRols);
                        for (var key in mvvm.callRelated.$model) {
                            mvvm.callRelated[key] = [];
                        }
                        mvvm.callCenterEntity = entity;
                        return mvvm.callCenterEntity;
                    }
                    vm.callCenter = function (mobile) {
                        CBCRM.loadView('/Services/CallsCenter.html', function (tmpl) {
                            var dialog = messageBox.openHtml("来电管理", '760px', '420px', "", [{
                                name: '提交',
                                focus: true,
                                callback: function () {
                                    var model = mvvm.callCenterEntity.$model;
                                    mvvm.callCenterEntity.CallsMobile = $.trim(model.CallsMobile);
                                    mvvm.callCenterEntity.CallsName = $.trim(model.CallsName);
                                    var dict = findArr(mvvm.contactsRols, model.CallsRoleId);
                                    if (dict != null) model.CallsRole = dict.Data;
                                    
                                    if (!model.CallsMobile) {
                                        messageBox.warning('请填写来电号码');
                                        return false;
                                    }
                                    if (!model.CallsName) {
                                        messageBox.warning('请填写姓名');
                                        return false;
                                    }
                                    if (model.IsNewsCustomer=="true" && !model.CustomerName) {
                                        mvvm.callCenterEntity.CustomerName = model.CallsName;
                                        messageBox.warning('请填写客户名称');
                                        console.log(model);
                                        return false;
                                    }
                                    var url = "/Services/CallCenterAdd/";
                                    var customer = {
                                        Type:"",
                                        CompanyCountryId: "",
                                        CompanyProvinceId: "",
                                        CompanyCityId:"",
                                        CompanyAreaId: ""
                                    };
                                    extendValue(customer, mvvm.customerEntity.$model);
                                    var data = { model: model, customer: customer };
                                    data = jsonToSubmit(data);
                                    $.post(url, data, function (ret) {
                                        if (ret.result) {
                                            var d = ret.data, id = mvvm.callCenterEntity.Id = d.id;
                                            mvvm.callCenterEntity.ContactsId = d.ctid;
                                            mvvm.callCenterEntity.Cid = d.cid;
                                            messageBox.ok(ret.message, function () {
                                                //GetDataList(mvvm.showItem.$model);
                                                if(dialog)dialog.close();
                                                var nexturl = "";
                                                switch (model.Transform) {
                                                    case "1":
                                                        nexturl = "/Market/SalesOpportunities/" + id + "/addfromcallcenter";
                                                        break;
                                                    case "2":
                                                        nexturl = "/Services/Complaints/" + id + "/addfromcallcenter";
                                                        break;
                                                    case "3":
                                                        nexturl = "/Services/CServices/" + id + "/addfromcallcenter";
                                                        break;
                                                    case "4":
                                                        nexturl = "/Market/Contract/" + id + "/addfromcallcenter";
                                                        break;

                                                }
                                                if (nexturl != "") {
                                                    goto(nexturl, true);
                                                } 
                                                //mvvm.loadNumberInfo();
                                            });
                                        }
                                        else {
                                            messageBox.fail(ret.message);
                                        }
                                    })
                                    return false;
                                }
                            }], function () {
                                destroyui(["setParetCustomer"])
                            });
                            var el = $(dialog.content()).html(tmpl);
                            avalon.scan(el[0], mvvm)
                            avalon.nextTick(function () {
                                var abtn = $(".zclip")
                                abtn.zclip({
                                    path: "/Scripts/JqueryZclip/ZeroClipboard.swf",
                                    copy: function () {
                                        var dc = $(this).data();
                                        switch (dc.copy) {
                                            case "mobile":
                                                return mvvm.callCenterEntity.CallsMobile;
                                            case "name":
                                                return mvvm.callCenterEntity.CallsName;
                                        }
                                        return "";
                                    },
                                    afterCopy: function () {
                                        messageBox.alert("已经成功复制到粘贴板！");
                                    }
                                })
                            });
                        })
                        mvvm.createCallCenterEntity();
                        mvvm.createCustomer();
                        mvvm.getAreas();
                        var entity = mvvm.callCenterEntity;
                        entity.CallsMobile = mobile;
                        if (mobile) {
                            var ld = CBCRM.loading();
                            mvvm.getContacts(mobile, function () {
                                if (ld) ld.close();
                            });
                        }
                    }
                    vm.setDefArea = function () {
                        var centity = mvvm.customerEntity;
                        var cmy = CBCRM.cmyInfo;
                        if (cmy) {
                            centity.CompanyCountryId = cmy.CountryId;
                            centity.CompanyProvinceId = cmy.ProvinceId;
                            centity.CompanyCityId = cmy.CityId;
                            centity.CompanyAreaId = cmy.AreaId;
                        }
                    }
                    vm.customerEntity = {};
                    vm.createCustomer = function (entity) {
                        if(!entity)entity=modelFactory.create("Customer");
                        mvvm.customerEntity = entity;
                        mvvm.watchArea();
                        mvvm.setDefArea();
                    }
                    vm.getContacts = function (mobile, callback) {
                        $.get('/Customer/ContactsByCall', { 'telphone': mobile }, function (ret) {
                            var cmid = 0;
                            if (ret.result && ret.data.IsExist) {
                                var entity = mvvm.callCenterEntity;
                                var c = ret.data.contacts;
                                var customer = c.Customer
                                entity.ContactsId = c.Id;
                                entity.CustomerName = customer.Name;
                                entity.Cid = customer.Id;
                                entity.CallsName = c.Name;
                                entity.CallsSex = c.Sex;
                                entity.Address = customer.Address;
                                entity.QQ = c.QQ;
                                entity.CallsRole = c.ContactRoleDisplay
                                entity.CallsRoleId = c.ContactRoleId;
                                entity.IsNewsCustomer = false;
                                var callRelated = ret.data.callRelated;
                                for (var key in callRelated) {
                                    var val = callRelated[key];
                                    if (typeof (key) != "function" && mvvm.callRelated[key]) mvvm.callRelated[key] = callRelated[key];
                                }
                                if (customer && customer.Id) {
                                    cmid = customer.Id;
                                }
                            }
                            else {
                                var _mobile = mvvm.callCenterEntity.CallsMobile;
                                var entity = mvvm.createCallCenterEntity();
                                entity.CallsMobile = _mobile;
                                if (action != "incomingcall") {
                                    messageBox.warning("此号码尚未保存。")
                                }
                                entity.IsNewsCustomer = true;
                            }
                            mvvm.getCustomer(cmid);
                            if (typeof (callback) == "function") callback(ret);
                        });
                    }
                    vm.getCustomer = function (id) {
                        mvvm.createCustomer();
                        if (!id) return;
                        $.get("/Customer/DetailCustomer/" + id, {}, function (ret) {
                            if (ret.result) {
                                mvvm.createCustomer(ret.data)
                            }
                        });
                    }
                    vm.loadNumberInfo = function () {
                        var phone = $.trim(mvvm.callCenterEntity.CallsMobile)
                        if (phone == "") {
                            messageBox.warning("请输入号码");
                            return;
                        }
                        mvvm.getContacts(phone)
                    }
                    vm.viewCustomer = function (id) {
                        if (!id) {
                            messageBox.warning("还未有对应的客户Id");
                            return;
                        }
                        goto('/Customer/DetailCustomer/' + id, true);
                    }
                    vm.calltab = "tab1";
                    vm.calltabChange = function (tab) {
                        mvvm.calltab = tab;
                    }
                    vm.cTypes = vm.getCustomerTypes();
                    vm.isInitArea = false;
                    vm.area = { country: [], province: [], city: [], area: [] };
                    vm.watchArea = function () {
                        mvvm.customerEntity.$watch("CompanyCountryId", function (n,o) {
                            _setChild("country", "province", n);
                        });
                        mvvm.customerEntity.$watch("CompanyProvinceId", function (n, o) {
                            _setChild("province", "city", n);
                        });
                        mvvm.customerEntity.$watch("CompanyCityId", function (n, o) {
                            _setChild("city", "area", n);
                        });

                        function _setChild(k1, k2, id) {
                            var arr = [];
                            if (id) {
                                var a = findArr(mvvm.area[k1], id);
                                if (a != null) arr = a.$children;
                            }
                            mvvm.area[k2] = arr;
                            switch (k2) {
                                case "province":
                                    mvvm.customerEntity.CompanyProvinceId = "";
                                    if (arr.length > 0) mvvm.customerEntity.CompanyProvinceId = arr[0].Id;
                                    break;
                                case "city":
                                    mvvm.customerEntity.CompanyCityId = "";
                                    if (arr.length > 0) mvvm.customerEntity.CompanyCityId = arr[0].Id;
                                    break;
                                case "area":
                                    mvvm.customerEntity.CompanyAreaId = "";
                                    if (arr.length > 0) mvvm.customerEntity.CompanyAreaId = arr[0].Id;
                                    break;
                            }
                        }
                    }
                    vm.getAreas = function () {
                        if (mvvm.isInitArea) return;
                        $.get("/Settings/GetAllArea", function (ret) {
                            if (!ret || !ret.result) return;
                            mvvm.isInitArea = true;
                            var areas = _getChild(ret.data, 0);
                            mvvm.area.country = areas;
                            var tmp = mvvm.customerEntity.CompanyCountryId;
                            if (!tmp && areas.length > 0) {
                                mvvm.customerEntity.CompanyCountryId = areas[0].Id;
                            } else {
                                mvvm.customerEntity.CompanyCountryId = "";
                                mvvm.customerEntity.CompanyCountryId = tmp;
                            }
                            mvvm.setDefArea();
                        });
                        function _getChild(areas,pid) {
                            var arr = [];
                            for (var i = 0, l = areas.length; i < l; i++) {
                                var area = areas[i];
                                if (area.ParentId == pid) {
                                    area.$children = _getChild(areas, area.Id);
                                    arr.push(areas[i]);
                                }
                            }
                            return arr;
                        }
                    }
                    vm.kuaijieVal = "";
                    //新增
                    vm.doadd = function () {
                        mvvm.callsEntity = modelFactory.create('Calls');
                        mvvm.isnew = mvvm.callsEntity.IsNewsCustomer;
                        mvvm.callsEntity.Status += '';
                        mvvm.callsEntity.ClassDicId += '';
                        mvvm.callsEntity.IsNewsCustomer += '';
                        mvvm.callsEntity.IsUpdateContacts += '';
                        mvvm.callsEntity.Transform += '';
                        mvvm.children = [];

                        if (request.params.id) {
                            mvvm.callsEntity.Cid = mvvm.customer.Id;
                            mvvm.callsEntity.CustomerName = mvvm.customer.Name;

                            $.get('/Customer/GetConatactByCustomerId/' + mvvm.customer.Id, {}, function (ret) {
                                mvvm.children = ret.data;
                                if (mvvm.children.length) {
                                    mvvm.callsEntity.ContactsId = mvvm.children.$model[0].Id;
                                    mvvm.callsEntity.CallsName = mvvm.children.$model[0].Name;
                                }
                            });
                        }
                        FormSubmit('新增来电')
                    }
                    //编辑
                    vm.doedit = function (id) {
                        $.get('/Services/CallsDetail/' + id, {}, function (ret) {
                            mvvm.callsEntity = ret.data;
                            mvvm.isnew = mvvm.callsEntity.IsNewsCustomer;
                            mvvm.callsEntity.Status += '';
                            mvvm.callsEntity.ClassDicId += '';
                            mvvm.callsEntity.IsNewsCustomer += '';
                            mvvm.callsEntity.sUpdateContacts += '';
                            mvvm.callsEntity.Transform += '';
                            mvvm.children = ret.data.children;
                            FormSubmit('编辑来电');
                        });
                    }
                    vm.birthdayOpts = {
                        onSelect: function (date, formatDate, format) {
                            mvvm.callsEntity.CallsTime = formatDate
                        }
                    }
                    //查看
                    vm.doview = function (id) {
                        $.get('/Services/CallsDetail/' + id, {}, function (ret) {
                            mvvm.callsEntity = ret.data;
                            mvvm.isnew = mvvm.callsEntity.IsNewsCustomer;
                            mvvm.callsEntity.Status += '';
                            mvvm.callsEntity.ClassDicId += '';
                            mvvm.callsEntity.IsNewsCustomer += '';
                            mvvm.callsEntity.Transform += '';
                            mvvm.children = ret.data.children;
                            ViewSubmit('查看详情');
                        });
                    }
                    //删除
                    vm.dodel = function () {
                        var index = parseInt($(this).attr('index'));
                        var id = $(this).val();
                        messageBox.confirm('确定删除此数据吗？', function () {
                            mvvm.callsList.removeAt(index);
                            $.post('/Services/CallsDel/' + id, {}, function () { })
                        });
                    }
                    //批量删除
                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的来电数据吗？', function () {
                            $.get('/Services/CallsDelAll/', deleteIds, function (ret) {
                                if (ret.result) {
                                    GetDataList();
                                    messageBox.succeed(ret.message);
                                }
                            });
                        });
                    }

                    vm.isnew = false;
                    //是否转为新客户
                    vm.changeCustomer = function () {
                        if ($(this).val() == 'true')
                            mvvm.isnew = true;
                        else {
                            mvvm.isnew = false;
                            mvvm.callsEntity.Address = '';
                        }
                    }
                    //快捷来电内容
                    vm.copy = function () {
                        var val = $(this).val();
                        mvvm.callsEntity.CallsContent = val;
                        mvvm.callCenterEntity.CallsContent = val;
                    }
                    //状态图标
                    vm.statusIcon = function (index) {
                        var res;
                        switch (index) {
                            case 1: res = 'stNam'; break;
                            case 2: res = 'stErr'; break;
                            case 3: res = 'stNo'; break;
                            case 4: res = 'stCom'; break;
                        }
                        return res;
                    }
                    //状态名称
                    vm.statusTitle = function (val) {
                        var result;
                        mvvm.status.forEach(function (item) {
                            if (item.value == val)
                                result = item.key
                        });
                        return result;
                    }
                    vm.showOnlyList = false;
                    vm.customer = { Id: '', Name: '' }
                    vm.isShowChange = true
                    //按登记员工找来电
                    vm.empkey = ''
                    vm.empSearch = function () {
                        var treeObj = $.fn.zTree.getZTreeObj("empTree")
                        if (treeObj != null)
                            treeObj.reAsyncChildNodes(null, "refresh")

                    }
                    //自定义列
                    vm.customList = [
                        { name: '选择', checked: true },
                        { name: '来电分类', checked: true },
                        { name: '来电号码', checked: true },
                        { name: '联系人', checked: true },
                        { name: '来电内容', checked: true },
                        { name: '状态', checked: true },
                        { name: '来电时间', checked: true },
                        { name: '操作', checked: true }
                    ]
                });

                //初始化
                function initWithEntity() {
                    //来电时间
                    var timeSearch = {
                        title: '来电时间', sort: 0,
                        item: [
                            { key: '不限', value: '0', focus: true, click: mvvm.itemClick },
                            { key: '今天', value: '1', focus: false, click: mvvm.itemClick },
                            { key: '昨天', value: '2', focus: false, click: mvvm.itemClick },
                            { key: '本月', value: '3', focus: false, click: mvvm.itemClick },
                            { key: '近三月', value: '4', focus: false, click: mvvm.itemClick },
                            { key: '近半年', value: '5', focus: false, click: mvvm.itemClick }
                        ]
                    }

                    //处理状态
                    var statusSearch = {
                        title: '处理状态', sort: 1,
                        item: [
                            { key: '不限', value: '0', focus: true, click: mvvm.itemClick },
                            { key: '无需处理', value: '1', focus: false, click: mvvm.itemClick },
                            { key: '未处理', value: '2', focus: false, click: mvvm.itemClick },
                            { key: '处理中', value: '3', focus: false, click: mvvm.itemClick },
                            { key: '处理完成', value: '4', focus: false, click: mvvm.itemClick }
                        ]
                    }
                    mvvm.status = statusSearch.item;
                    mvvm.status.removeAt(0); //移除'不限'选项

                    //来电转换
                    mvvm.transForm = [
                        { key: '不转换', value: '0', click: mvvm.itemClick },
                        { key: '新销售机会', value: '1', click: mvvm.itemClick },
                        { key: '新投诉记录', value: '2', click: mvvm.itemClick },
                        { key: '新售后服务请求', value: '3', click: mvvm.itemClick }
                    ]
                    //来电转换
                    mvvm.transForm2 = [
                        { key: '不转换', value: '0' },
                        { key: '新销售机会', value: '1' },
                        { key: '新投诉记录', value: '2' },
                        { key: '新售后服务请求', value: '3' },
                        { key: '新订单', value: '4' }
                    ]

                    //来电分类
                    var categorySearch = {
                        title: '来电分类', sort: 2,
                        item: [{ key: '不限', value: '0', focus: true, click: mvvm.itemClick }]
                    }

                    $.get('/Services/GetCallsDictionary', {}, function (ret) {
                        if (!ret.result) return;
                        ret.data.CallsType.forEach(function (item, i) {
                            categorySearch.item.push({ key: item.Data, value: item.Id, focus: false, click: mvvm.itemClick })
                        });

                        mvvm.category = ret.data.CallsType;
                        mvvm.kuaijie = ret.data.CallsKuai; //快捷来电内容
                        mvvm.contactsRols = ret.data.contactsRols;
                        var roleId = getDefDict(mvvm.contactsRols), roleName = getDefDict(mvvm.contactsRols, "Data");
                        if (mvvm.callsEntity) {
                            mvvm.callsEntity.CallsRoleId = roleId;
                            mvvm.callsEntity.CallsRole = roleName;
                        }
                        if (mvvm.callCenterEntity) {
                            mvvm.callCenterEntity.CallsRoleId = roleId;
                            mvvm.callCenterEntity.CallsRole = roleName;
                        }
                        mvvm.searchItem.push(categorySearch);
                    });

                    mvvm.searchItem.push(timeSearch);
                    mvvm.searchItem.push(statusSearch);

                    if ($.cookie('custom_calls'))
                        mvvm.customList = JSON.parse($.cookie('custom_calls'))
                }
                initWithEntity();

                //主列表
                function GetDataList(data) {
                    if (action == "customer") {
                        data.customerId = paramid
                    }
                    mvvm.grid1.gridmsg = lang.LoadingMsg;
                    $.get('/Services/Calls/', data || {}, function (ret) {
                        mvvm.grid1.gridmsg = ret.data.RecordTotal > 0 ? "" : lang.NoListData;
                        mvvm.callsList = ret.data.Source;
                        mvvm.ADD = ret.data.ADD;
                        mvvm.DELETE = ret.data.DELETE;
                        avalon.vmodels.upaing.total = ret.data.RecordTotal; //分页总数
                    });
                }
                //副列表
                function GetCallsGroup(data) {
                    $.get('/Services/CallsGroup/', data || {}, function (ret) {
                        mvvm.groupList = ret.data;
                    });
                }
                //新增或编辑
                function FormSubmit(title) {
                    CBCRM.loadView('/Services/CallsForm.html', function (tmpl) {
                        var dialog = mvvm.openTmpl({
                            title: title, w: 800, h: 420,
                            tmplId: tmpl, isContent: true,
                            button: [{
                                name: '提交',
                                focus: true,
                                callback: function () {
                                    var model = mvvm.callsEntity.$model;
                                    if (!model.CustomerName) {
                                        messageBox.warning('请选择客户');
                                        return false;
                                    }
                                    if (model.CallsMobile) {
                                        var url = (model.Id == 0 ? "/Services/CallsAdd/" : "/Services/CallsEdit/");
                                        $.post(url + model.Id, model, function (ret) {
                                            if (ret.result) {
                                                messageBox.ok(ret.message, function () {
                                                    if (request.params.id) {
                                                        mvvm.showItem.customerId = request.params.id
                                                    }
                                                    GetDataList(mvvm.showItem.$model);
                                                    dialog.close();
                                                });
                                            }
                                            else {
                                                messageBox.fail(ret.message, function () { });
                                            }
                                        })
                                    }
                                    else messageBox.warning('请填写来电号码');
                                    return false;
                                }
                            }],
                            onClose: function () {
                                if (avalon.vmodels.setParetCustomer)
                                    avalon.vmodels.setParetCustomer.destroy();
                            }
                        });
                    })
                }
                //查看
                function ViewSubmit(title) {
                    CBCRM.loadView('/Services/CallsView.html', function (tmpl) {
                        var dialog = openTmpl({
                            vm: mvvm, title: title, w: 800, h: 400,
                            tmplId: tmpl, isContent: true
                        });
                    })
                }

                function setSearchArray(list, sort) {
                    list.forEach(function (item, index) {
                        if (item.sort == sort)
                            list.splice(index, 1);
                    });
                    return list
                }

                //创建查询对象并提交
                var createDate = {
                    time: '', timeName: '',
                    status: '', statusName: '',
                    category: '', categoryName: '',
                    key: '', keyName: '',
                    date: '', dateName: '',
                    pageSize: 20, pageIndex: 1,
                    emp: '', empName: '',
                    customer: '', customerId: ''
                }
                mvvm.showItem = avalon.mix({}, createDate);

                //自定义过滤器
                avalon.filters.dicname = function (val) {
                    var result;
                    mvvm.category.forEach(function (item) {
                        if (item.Id == val)
                            result = item.Data;
                    });
                    return result;
                }
                avalon.filters.trans = function (val) {
                    var result;
                    mvvm.transForm2.forEach(function (item) {
                        if (item.value == val)
                            result = item.key
                    });
                    return result;
                }
                avalon.filters.statusx = function (val) {
                    var result;
                    mvvm.status.forEach(function (item) {
                        if (item.value == val)
                            result = item.key
                    });
                    return result;
                }

                //客户信息中，合同订单调用
                switch (action) {
                    case "key":
                        mvvm.keyword = mvvm.showItem.key = paramid;
                        fill();
                        break;
                    case "customer":
                        fillCustomer();
                        break;
                    case "callcenter":
                        mvvm.callCenter(paramid)
                        break;
                    case "view":
                        mvvm.doview(paramid)
                        break;
                    case "incomingcall":
                        mvvm.callCenter(paramid)
                        break;
                    default:
                        fill();
                        break;
                }
                function fillCustomer() {
                    /*隐藏其它，只显示列表块*/
                    mvvm.showOnlyList = true
                    var cu = paramData.entity;
                    $('#calls').css({ width: '100%', 'margin-top': '0px', });

                    mvvm.customer.Id = cu.Id;
                    mvvm.customer.Name = cu.Name;
                    mvvm.isShowChange = false;
                    mvvm.showCustomer = false;//隐藏客户选项

                    paramData.viewOther(tmpl, mvvm);
                }
                function fill() {
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                }

                require('commonui', function () {
                    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);

                        mvvm.showItem.date = mvvm.showItem.dateName = date;
                        GetDataList(mvvm.showItem.$model);
                    }); //大日历
                })
                //选择员工
                var setting = {
                    async: {
                        enable: true,
                        url: function () {
                            var url = ''
                            if (mvvm.empkey) {
                                url = '/Settings/GetGroupPostUser/3020001/?empName=' + mvvm.empkey
                            } else {
                                url = '/Settings/GetGroupPostUser/3020001'
                            }
                            return url
                        },
                        type: 'get',
                        dataFilter: groupPostFilter
                    },
                    callback: {
                        onClick: function (e, treeId, treeNode) {
                            var ids = getNodeIds(treeNode, "emp").join(",");
                            if (!ids) ids = "0";
                            //先清空
                            mvvm.showItem.emp = mvvm.showItem.empName = '';
                            if (treeNode.ParentId == null || treeNode.ParentId == 0)
                                GetCallsGroup();
                            else {
                                mvvm.showItem.emp = ids;
                                mvvm.showItem.empName = treeNode.Name
                                GetCallsGroup({ id: ids });
                            }
                            GetDataList(mvvm.showItem.$model);
                        }
                    },
                    data: {
                        simpleData: {
                            enable: true,
                            idKey: 'Id',
                            pIdKey: 'ParentId'
                        },
                        key: {
                            name: 'Name'
                        }
                    }
                }
                $.fn.zTree.init($('#empTree'), setting);
            },
            /// <summary>
            /// 回访关怀
            /// </summary>
            FollowUp: function (tmpl, lang, contentId, module, paramData) {
                var CBCRM = avalon.vmodels.CBCRM, array = [],
                    request = this, action = this.params.action, paramid = this.params.id;
                var mvvm = CBCRM.define('FollowUp', function (vm) {
                    vm.lang = lang;
                    vm.$skipArray = ['lang'] //不监控语言包
                    vm.searchItem = []
                    vm.entity = {}
                    vm.entityList = []
                    vm.groupList = []
                    vm.category = []
                    vm.business = []
                    vm.status = []
                    vm.followChange = []
                    vm.showItem = {}
                    vm.keyword = ''
                    vm.cuskey = ''
                    vm.sendSms = CBCRM.sendSms
                    vm.cuskeyClick = function () {
                        GetFollowGroup({ key: mvvm.cuskey });
                    }
                    vm.groupClick = function () {
                        var title = $(this).attr('title');
                        var val = $(this).attr('val');
                        mvvm.showItem.customer = mvvm.showItem.customerName = '';//先清空
                        mvvm.showItem.customer = val;
                        mvvm.showItem.customerName = title;
                        GetDataList(mvvm.showItem.$model);
                    }
                    vm.children = []
                    vm.history = []
                    vm.ADD = false
                    vm.DELETE = false
                    vm.showOnlyList = false;
                    vm.showCustomer = true;
                    vm.customer = { Id: '', Name: '' }
                    //关键字搜索
                    vm.search = function () {
                        if (mvvm.keyword) {
                            mvvm.showItem.key = mvvm.showItem.keyName = mvvm.keyword;
                            GetDataList(mvvm.showItem.$model);
                            if (mvvm.history.length = 3)
                                mvvm.history.removeAt(2);
                            mvvm.history.unshift(mvvm.keyword);
                        }
                    }
                    //历史搜索
                    vm.historyClick = function () {
                        mvvm.keyword = $(this).val();
                        mvvm.showItem.key = mvvm.showItem.keyName = mvvm.keyword;
                        GetDataList(mvvm.showItem.$model);
                    }
                    //清空
                    vm.clear = function () {
                        mvvm.keyword = '';
                        mvvm.showItem.key = mvvm.showItem.keyName = '';
                        mvvm.showItem.status = mvvm.showItem.statusName = '';
                        mvvm.showItem.category = mvvm.showItem.categoryName = '';
                        mvvm.showItem.date = mvvm.showItem.dateName = '';
                        mvvm.showItem.time = mvvm.showItem.timeName = '';
                        mvvm.showItem.emp = mvvm.showItem.empName = '';
                        mvvm.showItem.customer = mvvm.showItem.customerName = '';
                        $(".seacrhField a[index='0']").addClass("selected").siblings().removeClass("selected")
                        GetDataList(mvvm.showItem.$model);
                    }
                    //移除单个条件
                    vm.remove = function () {
                        var val = $(this).attr('val');
                        switch (val) {
                            case "key": mvvm.showItem.key = mvvm.showItem.keyName = ''; break;
                            case "status": mvvm.showItem.status = mvvm.showItem.statusName = '';
                                $(".seacrhField a[index='0']").eq(1).addClass("selected").siblings().removeClass("selected");
                                break;
                            case "category": mvvm.showItem.category = mvvm.showItem.categoryName = '';
                                $(".seacrhField a[index='0']").eq(2).addClass("selected").siblings().removeClass("selected");
                                break;
                            case "date": mvvm.showItem.date = mvvm.showItem.dateName = ''; break;
                            case "time": mvvm.showItem.time = mvvm.showItem.timeName = '';
                                $(".seacrhField a[index='0']").eq(0).addClass("selected").siblings().removeClass("selected");
                                break;
                            case "emp": mvvm.showItem.emp = mvvm.showItem.empName = ''; break;
                        }
                        GetDataList(mvvm.showItem.$model);
                    }
                    //分类检索
                    vm.itemClick = function () {
                        $(this).attr('class', 'selected').siblings().removeClass('selected');
                        var i = $(this).attr('index');
                        var sort = $(this).attr('sort');

                        var model = mvvm.searchItem.$model[sort].item[i];
                        switch (sort) {
                            case "0":
                                mvvm.showItem.time = mvvm.showItem.timeName = '';//先清空
                                if (i != 0) {
                                    mvvm.showItem.time = model.value
                                    mvvm.showItem.timeName = model.key;
                                }
                                break;
                            case "1":
                                mvvm.showItem.status = mvvm.showItem.statusName = '';
                                if (i != 0) {
                                    mvvm.showItem.status = model.value
                                    mvvm.showItem.statusName = model.key;
                                }
                                break;
                            case "2":
                                mvvm.showItem.category = mvvm.showItem.categoryName = '';//先清空
                                if (i != 0) {
                                    mvvm.showItem.category = model.value
                                    mvvm.showItem.categoryName = model.key;
                                }
                                break;
                        }
                        GetDataList(mvvm.showItem.$model);
                    }
                    //分页
                    vm.grid1 = { gridmsg: "" };
                    vm.userpaing = {
                        paging: function (pageIndex,pageSize) {
                            mvvm.showItem.pageSize = pageSize
                            mvvm.showItem.pageIndex = pageIndex
                            GetDataList(mvvm.showItem.$model);
                            GetFollowGroup();
                        }
                    }
                    //选客户/联系人
                    vm.selectCustomer = function () {
                        plugins.selectCustomer({
                            type: "contacts",
                            required: { con: false },
                            callback: function (cus, cons) {
                                var cu = cus[0];
                                mvvm.entity.CustomerId = cu.Id;
                                mvvm.entity.CustomerName = cu.Name;
                                mvvm.children = cu.Contacts;
                                var c = cons.length > 0 ? cons[0] : { Id: 0, Name: "", Sex: "0", QQ: "", ContactRoleDisplay: "" };
                                mvvm.entity.ContactId = c.Id;
                                mvvm.entity.ContactName = c.Name;
                                avalon.vmodels.contactsCard.id = c.Id
                            }
                        })
                    }
                    //单选员工
                    vm.selectBelongTo = function () {
                        plugins.selectUser({
                            dataAuth: 3030001,
                            callback: function (us) {
                                var u = us[0];
                                mvvm.entity.ReturnExecutor = u.Id;
                                mvvm.entity.ReturnExecutorName = u.FullName;
                            }
                        });
                    }
                    vm.birthdayOpts = {
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.ReturnTime = formatDate
                        }
                    }
                    //新增
                    vm.doadd = function () {
                        mvvm.entity = modelFactory.create('FollowUp');
                        mvvm.entity.State += '';
                        mvvm.isnext = mvvm.entity.IsNext;
                        mvvm.entity.ChangeVal += '';
                        mvvm.entity.ReturnExecutor = CBCRM.memberShip.Id;
                        mvvm.entity.ReturnExecutorName = CBCRM.memberShip.FullName;
                        mvvm.children = [];
                        mvvm.entity.DiplexSales = [];
                        if (action=="customer") {
                            mvvm.entity.CustomerId = mvvm.customer.Id;
                            mvvm.entity.CustomerName = mvvm.customer.Name;

                            $.get('/Customer/GetConatactByCustomerId/' + mvvm.customer.Id, {}, function (ret) {
                                mvvm.children = ret.data;
                                if (mvvm.children.length) {
                                    mvvm.entity.ContactId = mvvm.children.$model[0].Id;
                                    mvvm.entity.ContactName = mvvm.children.$model[0].Name;
                                    avalon.vmodels.contactsCard.id = mvvm.entity.ContactId
                                }
                            });
                        }
                        FormSubmit('新增回访')
                    }
                    //编辑
                    vm.doedit = function () {
                        var id = $(this).val();
                        $.get('/Services/FollowUpDetail/' + id, {}, function (ret) {
                            if (ret.data.DiplexSales)
                                ret.data.DiplexSales = ret.data.DiplexSales.split(',');
                            else
                                ret.data.DiplexSales = []
                            mvvm.entity = ret.data;
                            mvvm.entity.State += '';
                            mvvm.entity.ChangeVal += '';
                            mvvm.isnext = mvvm.entity.IsNext;
                            if (mvvm.isnext)
                                mvvm.nextTheme = mvvm.entity.NextTheme;
                            mvvm.children = ret.data.children;
                            FormSubmit('编辑回访');

                            $.get('/Customer/GetConatactByCustomerId/' + mvvm.customer.Id, {}, function (ret) {
                                mvvm.children = ret.data;
                            });
                        });
                    }
                    //查看
                    vm.entitys = {

                    };
                    vm.doview = function (id) {
                        $.get('/Services/FollowUpDetail/' + id, function (ret) {
                            if (ret && ret.result) {
                                //mvvm.entity = ret.data
                                ViewSubmit(ret.data)
                            } else {
                                CBCRM.showResult(ret);
                            }
                        });
                    }
                    //删除
                    vm.dodel = function () {
                        var index = parseInt($(this).attr('index'));
                        var id = $(this).val();
                        messageBox.confirm('确定删除此数据吗？', function () {
                            mvvm.entityList.removeAt(index);
                            $.post('/Services/FollowUpDel/' + id, {}, function () { })
                        });
                    }
                    //批量删除
                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.get('/Services/FollowUpDelAll/', deleteIds, function (ret) {
                                if (ret.result) {
                                    GetDataList();
                                    messageBox.succeed(ret.message);
                                }
                            });
                        });
                    }
                    vm.isnext = false;
                    vm.nextTheme = '下次回访主题';
                    //是否转为新客户
                    vm.changeNext = function () {
                        if ($(this).val() == 'true') {
                            mvvm.isnext = true;
                            mvvm.entity.NextReturnTime = GetDateTime();
                        }
                        else {
                            mvvm.isnext = false;
                            mvvm.entity.NextReturnTime = '';
                        }
                    }
                    vm.themeClick = function () {
                        if ($(this).val() == '下次回访主题') $(this).val('');
                    }
                    vm.themeBlur = function () {
                        if ($(this).val() == '') $(this).val('下次回访主题');
                    }
                    //快捷来电内容
                    vm.copy = function () {
                        vm.callsEntity.CallsContent = $(this).val();
                    }
                    //状态图标
                    vm.statusIcon = function (index) {
                        var res;
                        switch (index) {
                            case 1: res = 'stNam'; break;
                            case 2: res = 'stNo'; break;
                            case 3: res = 'stCom'; break;
                            case 4: res = 'stErr'; break;
                        }
                        return res;
                    }
                    //状态名称
                    vm.statusTitle = function (val) {
                        var result;
                        mvvm.status.forEach(function (item) {
                            if (item.value == val)
                                result = item.key
                        });
                        return result;
                    }

                    vm.empKey = ''
                    vm.empSearch = function () {
                        var treeObj = $.fn.zTree.getZTreeObj("empTree")
                        if (treeObj != null)
                            treeObj.reAsyncChildNodes(null, "refresh")
                    }
                });
                $('#selectCalls').live('change', function () {
                    mvvm.entity.ContactName = $(this).find('option:selected').text();
                    avalon.vmodels.contactsCard.id = $(this).val()
                })

                //创建查询对象
                var createDate = {
                    time: '', timeName: '',
                    status: '', statusName: '',
                    category: '', categoryName: '',
                    key: '', keyName: '',
                    date: '', dateName: '',
                    pageSize: 20, pageIndex: 1,
                    emp: '', empName: '',
                    customer: '', customerName: '', customerId: ''
                }
                mvvm.showItem = avalon.mix({}, createDate);
                //初始化
                function initWithEntity() {

                    //回访时间
                    var timeSearch = {
                        title: '回访时间', sort: 0,
                        item: [
                            { key: '不限', value: '0', focus: true, click: mvvm.itemClick },
                            { key: '今天', value: '1', focus: false, click: mvvm.itemClick },
                            { key: '昨天', value: '2', focus: false, click: mvvm.itemClick },
                            { key: '本月', value: '3', focus: false, click: mvvm.itemClick },
                            { key: '近三月', value: '4', focus: false, click: mvvm.itemClick },
                            { key: '近半年', value: '5', focus: false, click: mvvm.itemClick }
                        ]
                    }

                    //处理状态
                    var statusSearch = {
                        title: '处理状态', sort: 1,
                        item: [
                            { key: '不限', value: '0', focus: true, click: mvvm.itemClick },
                            { key: '待处理', value: '1', focus: false, click: mvvm.itemClick },
                            { key: '处理中', value: '2', focus: false, click: mvvm.itemClick },
                            { key: '回访完成', value: '3', focus: false, click: mvvm.itemClick }
                        ]
                    }
                    mvvm.status = statusSearch.item;
                    mvvm.status.removeAt(0); //移除'不限'选项

                    //回访方式
                    var categorySearch = {
                        title: '回访方式', sort: 2,
                        item: [{ key: '不限', value: '0', focus: true, click: mvvm.itemClick }]
                    }

                    //回访转换为
                    var followChange = [
                            { key: '不转换', value: '0' },
                            { key: '新销售机会', value: '1' },
                            { key: '新投诉记录', value: '2' },
                            { key: '新售后服务请求', value: '3' }
                    ]
                    mvvm.followChange = followChange

                    $.get('/Services/GetFollowUpDictionary', {}, function (ret) {
                        ret.data.FollowUpType.forEach(function (item, i) {
                            categorySearch.item.push({ key: item.Data, value: item.Id, focus: false, click: mvvm.itemClick })
                        });

                        mvvm.category = ret.data.FollowUpType;
                        mvvm.business = ret.data.FollowUpBusiness;
                        mvvm.searchItem.push(categorySearch);
                    });

                    mvvm.searchItem.push(timeSearch);
                    mvvm.searchItem.push(statusSearch);

                }
                initWithEntity();
                //主列表
                function GetDataList(data) {
                    if (action=="customer") {
                        data.customerId = paramid
                    }
                    mvvm.grid1.gridmsg = lang.LoadingMsg;
                    $.get('/Services/FollowUp/', data || {}, function (ret) {
                        if (!ret || !ret.result) return CBCRM.showResult(ret);
                        mvvm.grid1.gridmsg = ret.data.RecordTotal > 0 ? "" : lang.NoListData;
                        mvvm.entityList = ret.data.Source;
                        mvvm.ADD = ret.data.ADD;
                        mvvm.DELETE = ret.data.DELETE;
                        avalon.vmodels.upaing.total = ret.data.RecordTotal //分页总数                        
                    });
                }
                //副列表
                function GetFollowGroup(data) {
                    $.get('/Services/FollowGroup/', data || {}, function (ret) {
                        mvvm.groupList = ret.data;
                    });
                }
                //新增或编辑
                function FormSubmit(title) {
                    CBCRM.loadView('/Services/FollowUpForm.html', function (vtmpl) {
                        var dialog = mvvm.openTmpl({
                            title: title, w: 800, h: 460, padding: "20px 0px",
                            tmplId: vtmpl, isContent: true,
                            button: [{
                                name: '提交',
                                focus: true,
                                callback: function () {
                                    var model = mvvm.entity.$model;
                                    model.NextTheme = mvvm.nextTheme;
                                    if (!model.CustomerName) {
                                        messageBox.warning('请选择客户');
                                        return false;
                                    }
                                    if (model.Theme) {
                                        model.DiplexSales = model.DiplexSales.toString();
                                        var url = (model.Id == 0 ? "/Services/FollowUpAdd/" : "/Services/FollowUpEdit/");
                                        $.post(url + model.Id, model, function (ret) {
                                            if (ret.result) {
                                                messageBox.ok(ret.message, function () {
                                                    GetDataList(mvvm.showItem.$model);
                                                    dialog.close();
                                                });
                                            }
                                            else {
                                                messageBox.fail(ret.message, function () { messageBox.close(); });
                                            }
                                        })
                                    }
                                    else messageBox.warning('请填写关怀主题');
                                    return false;
                                }
                            }],
                            onClose: function () {
                                avalon.vmodels.contactsCard.id = ''
                            },
                            onScan: function () {
                                avalon.vmodels.contactsCard.id = mvvm.entity.ContactId
                            }
                        });
                    })
                }
                //查看
                function ViewSubmit(entity) {
                    mvvm.entity = entity;
                    CBCRM.loadView('/Services/FollowUpView.html', function (tmpl) {
                        var dialog = openTmpl({
                            vm: mvvm, title: "回访关怀详情", w: 820, h: 340,
                            tmplId: tmpl, isContent: true,
                            onScan: function () {
                                avalon.vmodels.contactsCard.id = entity.ContactId
                            }
                        });
                    })
                }

                function setSearchArray(list, sort) {
                    list.forEach(function (item, index) {
                        if (item.sort == sort)
                            list.splice(index, 1);
                    });
                    return list
                }

                //自定义过滤器
                avalon.filters.dicname = function (val) {
                    var result;
                    mvvm.category.forEach(function (item) {
                        if (item.Id == val)
                            result = item.Data;
                    });
                    return result;
                }
                avalon.filters.statusx = function (val) {
                    var result;
                    mvvm.status.forEach(function (item) {
                        if (item.value == val)
                            result = item.key
                    });
                    return result;
                }
                avalon.filters.change = function (val) {
                    var result;
                    mvvm.followChange.forEach(function (item) {
                        if (item.value == val)
                            result = item.key
                    });
                    return result;
                }
                switch (action) {
                    case "customer":
                        //客户信息中，合同订单调用
                        /*隐藏其它，只显示列表块*/
                        mvvm.showOnlyList = true
                        $('#followUp').css({ width: '100%', 'margin-top': '0px', });
                        var cu = paramData.entity;
                        mvvm.customer.Id = paramid;
                        mvvm.customer.Name = cu.Name;
                        mvvm.showCustomer = false;
                        paramData.viewOther(tmpl, mvvm);
                        break;
                    case "view":
                        mvvm.doview(paramid);
                        break;
                    case "key":
                        mvvm.keyword = mvvm.showItem.key =decodeURIComponent(paramid);
                    default:
                        fill();
                        break;
                }
                function fill() {
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                    require('commonui', function () {
                        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);
                            mvvm.showItem.date = mvvm.showItem.dateName = date;
                            GetDataList(mvvm.showItem.$model);
                        });//大日历
                    })
                    //选择员工
                    var setting = {
                        async: {
                            enable: true,
                            url: function () {
                                var url
                                if (mvvm.empKey)
                                    url = '/Settings/GetGroupPostUser/3030001/?empName=' + mvvm.empKey
                                else
                                    url = '/Settings/GetGroupPostUser/3030001'
                                return url
                            },
                            type: 'get',
                            dataFilter: groupPostFilter
                        },
                        callback: {
                            onClick: function (e, treeId, treeNode) {

                                var ids = getNodeIds(treeNode, "emp").join(",");
                                if (!ids) ids = "0";
                                //先清空
                                mvvm.showItem.emp = mvvm.showItem.empName = '';
                                //再赋值

                                if (treeNode.ParentId == null || treeNode.ParentId == 0)
                                    GetFollowGroup();
                                else {
                                    mvvm.showItem.emp = ids
                                    mvvm.showItem.empName = treeNode.Name

                                    GetFollowGroup({ eid: ids });
                                }
                                GetDataList(mvvm.showItem.$model);
                            }
                        },
                        data: {
                            simpleData: { enable: true, idKey: 'Id', pIdKey: 'ParentId' },
                            key: { name: 'Name' }
                        }
                    }
                    $.fn.zTree.init($('#empTree'), setting);
                }
            },
            /// <summary>
            /// 客户服务
            /// </summary>
            CServices: function (tmpl, lang, contentId, module, paramData) {
                var CBCRM = avalon.vmodels.CBCRM
                var request = this
                var action = this.params.action, paramid = this.params.id;
                var mvvm = CBCRM.define('CServices', function (vm) {
                    vm.lang = lang;
                    vm.showOnlyList = false
                    vm.$skipArray = ['lang'] //不监控语言包
                    vm.destroy = function () {

                    }
                    vm.searchItem = []
                    vm.showItem = {}
                    vm.entity = {}
                    vm.entityList = []
                    vm.entityDisposeDetail = {}
                    vm.entityDisposeDetailList = []
                    vm.groupList = []
                    vm.category = []
                    vm.modeDicIds = []
                    vm.business = []
                    vm.status = []
                    vm.followChange = []
                    vm.tab = 'tab1'
                    vm.tabshow = 'servAdd';
                    vm.direction = [] //服务方向
                    vm.mode = [] //服务方式
                    vm.urgency = []
                    vm.keyword = ''
                    vm.history = []
                    vm.children = []
                    vm.cuskey = '';
                    vm.ADD = false
                    vm.DELETE = false
                    vm.showCustomer = true
                    vm.sendSms = CBCRM.sendSms;
                    vm.customer = { Id: '', Name: '' }
                    vm.cuskeyClick = function () {
                        GetCServerGroup({ key: mvvm.cuskey });
                    }
                    vm.viewCustomer = function () {
                        var vm = this.$vmodel,
                        item = vm[vm.$itemName]
                        goto('/Customer/DetailCustomer/' + item.CustomerId, true)
                    }
                    vm.viewCustomer1 = function (id) {
                        var id = $(this).val();
                        goto('/Customer/DetailCustomer/' + id, true);
                    }
                    vm.groupClick = function () {
                        var title = $(this).attr('title');
                        var val = $(this).attr('val');
                        mvvm.showItem.customer = mvvm.showItem.customerName = '';//先清空
                        mvvm.showItem.customer = val;
                        mvvm.showItem.customerName = title;
                        GetDataList(mvvm.showItem.$model);
                    }
                    //关键字搜索
                    vm.search = function () {
                        if (mvvm.keyword) {
                            mvvm.showItem.key = mvvm.showItem.keyName = mvvm.keyword;
                            GetDataList(mvvm.showItem.$model);
                            if (mvvm.history.length = 3)
                                mvvm.history.removeAt(2);
                            mvvm.history.unshift(mvvm.keyword);
                        }
                    }
                    //历史搜索
                    vm.historyClick = function () {
                        mvvm.keyword = $(this).val();
                        mvvm.showItem.key = mvvm.showItem.keyName = mvvm.keyword;
                        GetDataList(mvvm.showItem.$model);
                    }
                    //清空
                    vm.clear = function () {
                        mvvm.keyword = '';
                        mvvm.showItem.key = mvvm.showItem.keyName = '';
                        mvvm.showItem.urgency = mvvm.showItem.urgencyName = '';
                        mvvm.showItem.status = mvvm.showItem.statusName = '';
                        mvvm.showItem.category = mvvm.showItem.categoryName = '';
                        mvvm.showItem.date = mvvm.showItem.dateName = '';
                        mvvm.showItem.emp = mvvm.showItem.empName = '';
                        mvvm.showItem.customer = mvvm.showItem.customerName = '';
                        mvvm.showItem.modeDicId = mvvm.showItem.modeDicName = '';
                        $(".seacrhField a[index='0']").addClass("selected").siblings().removeClass("selected");
                        GetDataList(mvvm.showItem.$model);
                    }
                    //移除单个条件
                    vm.remove = function () {
                        var val = $(this).attr('val');
                        switch (val) {
                            case "key": mvvm.showItem.key = mvvm.showItem.keyName = ''; break;
                            case "urgency": mvvm.showItem.urgency = mvvm.showItem.urgencyName = '';
                                $(".seacrhField a[index='0']").eq(2).addClass("selected").siblings().removeClass("selected");
                                break;
                            case "status": mvvm.showItem.status = mvvm.showItem.statusName = '';
                                $(".seacrhField a[index='0']").eq(1).addClass("selected").siblings().removeClass("selected");
                                break;
                            case "category": mvvm.showItem.category = mvvm.showItem.categoryName = '';
                                $(".seacrhField a[index='0']").eq(0).addClass("selected").siblings().removeClass("selected");
                                break;
                            case "date": mvvm.showItem.date = mvvm.showItem.dateName = ''; break;
                            case "emp": mvvm.showItem.emp = mvvm.showItem.empName = ''; break;
                            case "customer": mvvm.showItem.customer = mvvm.showItem.customerName = ''; break;
                            case "modeDicId": mvvm.showItem.modeDicId = mvvm.showItem.modeDicName = '';
                                $(".seacrhField a[index='0']").eq(0).addClass("selected").siblings().removeClass("selected");
                                break;
                        }
                        GetDataList(mvvm.showItem.$model);
                    }
                    //分类检索
                    vm.itemClick = function () {
                        $(this).attr('class', 'selected').siblings().removeClass('selected');
                        var i = $(this).attr('index');
                        var sort = $(this).attr('sort');

                        var model = mvvm.searchItem.$model[sort].item[i];
                        switch (sort) {
                            case "0":
                                mvvm.showItem.category = mvvm.showItem.categoryName = '';//先清空
                                if (i != 0) {
                                    mvvm.showItem.category = model.value
                                    mvvm.showItem.categoryName = model.key;
                                }
                                break;
                            case "1":
                                mvvm.showItem.status = mvvm.showItem.statusName = '';
                                if (i != 0) {
                                    mvvm.showItem.status = model.value
                                    mvvm.showItem.statusName = model.key;
                                }
                                break;
                            case "2":
                                mvvm.showItem.urgency = mvvm.showItem.urgencyName = '';
                                if (i != 0) {
                                    mvvm.showItem.urgency = model.value
                                    mvvm.showItem.urgencyName = model.key;
                                }
                                break;
                            case "3":
                                mvvm.showItem.modeDicId = mvvm.showItem.modeDicName = '';//先清空
                                if (i != 0) {
                                    mvvm.showItem.modeDicId = model.value
                                    mvvm.showItem.modeDicName = model.key;
                                }
                                break;
                        }
                        GetDataList(mvvm.showItem.$model);
                    }
                    vm.grid1 = { gridmsg: "" };
                    //分页
                    vm.userpaing = {
                        paging: function (pageIndex,pageSize) {
                            var that = this
                            mvvm.showItem.pageSize = pageSize;
                            mvvm.showItem.pageIndex = pageIndex;
                            GetDataList(mvvm.showItem.$model);
                            GetCServerGroup();
                        }
                    }
                    //选客户/联系人
                    vm.selectCustomer = function () {
                        plugins.selectCustomer({
                            type: "contacts",
                            callback: function (cus,cons) {
                                var cu = cus[0], con = cons[0];
                                mvvm.entity.CustomerId = cu.Id;
                                mvvm.entity.CustomerName = cu.Name
                                mvvm.entity.ContactsId = con.Id;
                                mvvm.entity.ContactsName = con.Name;
                                mvvm.children = cu.Contacts;
                            }
                        });
                    }
                    
                    //单选员工
                    vm.selectUser = function (p) {
                        plugins.selectUser({
                            dataAuth: 3040001,
                            callback: function (us) {
                                var u = us[0];
                                if (p == "FirstEmp") {
                                    mvvm.entity.FirstEmpId = u.Id;
                                    mvvm.entity.FirstEmpName = u.FullName;
                                } else if (p == "Employee") {
                                    mvvm.entityDisposeDetail.EmployeeId = u.Id;
                                    mvvm.entityDisposeDetail.EmployeeName = u.FullName;
                                }
                            }
                        });
                    }
                   
                    vm.birthdayOpts = {
                        onSelect: function (date, formatDate, format) {
                            console.log(this);
                            mvvm.entity.ByTime = formatDate;
                        }
                    }
                    vm.birthdayOpts2 = {
                        onSelect: function (date, formatDate, format) {
                            mvvm.entityDisposeDetail.DisposeTime = formatDate;
                        }
                    }
                    vm.birthdayOpts3 = {
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.EndTime = formatDate;
                        }
                    }
                    //新增
                    vm.doadd = function () {
                        mvvm.entity = modelFactory.create('CServices');
                        mvvm.entity.TypeDicId += '';
                        mvvm.entity.ModeDicId += '';
                        mvvm.entity.Urgency += '';
                        mvvm.entity.Static += '';
                        mvvm.entity.FirstEmpId = CBCRM.memberShip.Id;
                        mvvm.entity.FirstEmpName = CBCRM.memberShip.FullName;
                        mvvm.entityDisposeDetail = modelFactory.create('DisposeDetail');
                        mvvm.tab = 'tab1';
                        mvvm.children = [];

                        if (request.params.id && !request.params.CSId) {
                            mvvm.entity.CustomerId = mvvm.customer.Id;
                            mvvm.entity.CustomerName = mvvm.customer.Name;

                            $.get('/Customer/GetConatactByCustomerId/' + mvvm.customer.Id, {}, function (ret) {
                                mvvm.children = ret.data;
                                if (mvvm.children.length) {
                                    mvvm.entity.ContactsId = mvvm.children.$model[0].Id;
                                    mvvm.entity.ContactsName = mvvm.children.$model[0].Name;
                                }
                            });
                        }
                        FormSubmit('新增服务')
                    }
                    //编辑
                    vm.doedit = function () {
                        var id = $(this).val();
                        $.get('/Services/CServicesDetail/' + id, {}, function (ret) {
                            mvvm.entity = ret.data;
                            mvvm.entity.TypeDicId += '';
                            mvvm.entity.ModeDicId += '';
                            mvvm.entity.Urgency += '';
                            mvvm.entity.Static += '';
                            mvvm.entityDisposeDetail = modelFactory.create('DisposeDetail');
                            mvvm.children = ret.data.children;
                            mvvm.tab = 'tab1';
                            mvvm.tabshow = 'servAdd';
                            EditSubmit('编辑服务');
                        });
                    }
                    //处理结果新增
                    vm.detailAdd = function () {
                        mvvm.entityDisposeDetail = modelFactory.create('DisposeDetail');
                        mvvm.openTmpl({
                            title: "新增处理", w: 800, h: 400,
                            tmplId: "addProcess", tmpl: mvvm.tmpl,
                            button: [{
                                name: '提交',
                                focus: true,
                                callback: function () {
                                    if (!mvvm.entityDisposeDetail.EmployeeName) {
                                        messageBox.warning('请选择处理人');
                                        return false;
                                    }

                                    var model = mvvm.entityDisposeDetail.$model;
                                    model.ServeId = mvvm.entity.Id;
                                    var url = model.Id == 0 ? "/Services/CServicesDisposeAdd/" : "/Services/CServicesDisposeEdit/";
                                    $.post(url + model.Id, model, function (ret) {
                                        if (ret.result) {
                                            mvvm.entity.DetailList = ret.data;
                                            mvvm.entityDisposeDetailList = ret.data;
                                        }
                                        else { messageBox.error(ret.message); }
                                    });
                                }
                            }]
                        })
                    }
                    //处理结果编辑
                    vm.detailEdit = function () {
                        var id = $(this).val();
                        $.get('/Services/CServicesDisposeDetail/' + id, {}, function (ret) {
                            if (ret.result) {
                                mvvm.entityDisposeDetail = ret.data;
                                mvvm.entityDisposeDetailList = ret.data;
                            }
                        });
                        mvvm.openTmpl({
                            title: "编辑处理", w: 800, h: 400,
                            tmplId: "addProcess", tmpl: mvvm.tmpl,
                            button: [{
                                name: '提交',
                                focus: true,
                                callback: function () {
                                    if (!mvvm.entityDisposeDetail.EmployeeName) {
                                        messageBox.warning('请选择处理人');
                                        return false;
                                    }

                                    var model = mvvm.entityDisposeDetail.$model;
                                    model.ServeId = mvvm.entity.Id;
                                    var url = model.Id == 0 ? "/Services/CServicesDisposeAdd/" : "/Services/CServicesDisposeEdit/";
                                    $.post(url + model.Id, model, function (ret) {
                                        if (ret.result) {
                                            mvvm.entity.DetailList = ret.data;
                                            mvvm.entityDisposeDetailList = ret.data;
                                        }
                                        else { messageBox.error(ret.message); }
                                    });
                                }
                            }]
                        })
                    }
                    //处理结果删除
                    vm.detailDel = function () {
                        var id = $(this).val();
                        $.post('/Services/CServicesDisposeDel/' + id, {}, function (ret) {
                            if (ret.result) {
                                mvvm.entity.DetailList = ret.data;
                                mvvm.entityDisposeDetailList = ret.data;
                            }
                        })
                    }
                    //查看
                    vm.doview = function (id) {
                        $.get('/Services/CServicesDetail/' + id, {}, function (ret) {
                            mvvm.entity = ret.data;
                            mvvm.entityDisposeDetailList = ret.data.DetailList;
                            mvvm.tab = 'tab1';
                            ViewSubmit('查看详情');
                        });
                    }
                    //删除
                    vm.dodel = function () {
                        var index = $(this).attr('index');
                        var id = $(this).val();
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/Services/CServicesDel/' + id, {}, function (ret) {
                                if (ret.result) {
                                    GetDataList();
                                }
                            })
                        });
                    }
                    //批量删除
                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.get('/Services/CServicesDelAll/', deleteIds, function (ret) {
                                if (ret.result) {
                                    GetDataList();
                                    messageBox.succeed(ret.message);
                                }
                            });
                        });
                    }

                    //查看处理信息
                    vm.processView = function () {
                        var id = $(this).val();
                        $.get('/Services/CServicesDisposeDetail/' + id, {}, function (ret) {
                            if (ret.result) {
                                mvvm.entityDisposeDetail = ret.data;
                                mvvm.entityDisposeDetailList = ret.data;
                            }
                        });
                        mvvm.openTmpl({
                            title: "编辑处理", w: 800, h: 400,
                            tmplId: "viewProcess", tmpl: mvvm.tmpl
                        })
                    }
                    //状态图标
                    vm.statusIcon = function (index) {
                        var res;
                        switch (index) {
                            case 1: res = 'stNam'; break;
                            case 2: res = 'stErr'; break;
                            case 3: res = 'stNo'; break;
                            case 4: res = 'stCom'; break;
                        }
                        return res;
                    }
                    //状态名称
                    vm.statusTitle = function (val) {
                        var result;
                        mvvm.status.forEach(function (item) {
                            if (item.value == val)
                                result = item.key
                        });
                        return result;
                    }
                    //标签切换
                    vm.tabChange = function () {
                        var val = $(this).attr('val');
                        mvvm.tab = val;
                        $(this).addClass('hover').siblings().removeClass('hover');
                    }

                    vm.empKey = ''
                    vm.empSearch = function () {
                        var treeObj = $.fn.zTree.getZTreeObj("empTree")
                        if (treeObj != null)
                            treeObj.reAsyncChildNodes(null, "refresh")
                    }
                });
                $('.selectCalls').live('change', function () {
                    mvvm.entity.ContactsName = $(this).find('option:selected').text();
                })

                //创建查询对象
                var createDate = {
                    key: '', keyName: '',
                    category: '', categoryName: '',
                    status: '', statusName: '',
                    urgency: '', urgencyName: '',
                    pageSize: 20, pageIndex: 1,
                    date: '', dateName: '',
                    emp: '', empName: '',
                    customer: '', customerName: '', customerId: '',
                    modeDicId: '', modeDicName: ''
                }

                //初始化
                function initWithEntity() {
                    mvvm.showItem = avalon.mix({}, createDate);
                    //紧急程度
                    var timeSearch = {
                        title: '紧急程度', sort: 2,
                        item: [
                            { key: '不限', value: '0', focus: true, click: mvvm.itemClick },
                            { key: '紧急', value: '1', focus: false, click: mvvm.itemClick },
                            { key: '急', value: '2', focus: false, click: mvvm.itemClick },
                            { key: '一般', value: '3', focus: false, click: mvvm.itemClick }
                        ]
                    }
                    mvvm.urgency = timeSearch.item;
                    mvvm.urgency.removeAt(0); //移除'不限'选项

                    //服务状态
                    var statusSearch = {
                        title: '服务状态', sort: 1,
                        item: [
                            { key: '不限', value: '0', focus: true, click: mvvm.itemClick },
                            { key: '无需处理', value: '1', focus: false, click: mvvm.itemClick },
                            { key: '未处理', value: '2', focus: false, click: mvvm.itemClick },
                            { key: '处理中', value: '3', focus: false, click: mvvm.itemClick },
                            { key: '处理完成', value: '4', focus: false, click: mvvm.itemClick }
                        ]
                    }
                    mvvm.status = statusSearch.item;
                    mvvm.status.removeAt(0); //移除'不限'选项

                    //服务方向
                    var direction = [
                        { key: '我们去', value: '0' },
                        { key: '客户来', value: '1' },
                    ]
                    mvvm.direction = direction;

                    //服务分类
                    var categorySearch = {
                        title: '服务分类', sort: 0,
                        item: [{ key: '不限', value: '0', focus: true, click: mvvm.itemClick }]
                    }
                    //服务方式
                    var modeDicIdSearch = {
                        title: '服务方式', sort: 3,
                        item: [{ key: '不限', value: '', focus: true, click: mvvm.itemClick }]
                    }
                    $.get('/Services/GetCServicesDictionary', {}, function (ret) {
                        ret.data.ServiceType.forEach(function (item, i) {
                            categorySearch.item.push({ key: item.Data, value: item.Id, focus: false, click: mvvm.itemClick })
                        });
                        ret.data.ServiceMode.forEach(function (item) {
                            modeDicIdSearch.item.push({ key: item.Data, value: item.Id, focus: false, click: mvvm.itemClick })
                        });
                        mvvm.category = ret.data.ServiceType;
                        mvvm.mode = ret.data.ServiceMode;
                        mvvm.searchItem.push(categorySearch);
                        mvvm.searchItem.push(statusSearch);
                        mvvm.searchItem.push(timeSearch);
                        mvvm.searchItem.push(modeDicIdSearch);
                    });
                }
                initWithEntity();
                //主列表
                function GetDataList(data) {
                    if (action == "customer") {
                        data.customerId = paramid;
                    }
                    mvvm.grid1.gridmsg = lang.LoadingMsg;
                    $.get('/Services/CServices/', data || {}, function (ret) {
                        mvvm.grid1.gridmsg = ret.data.RecordTotal > 0 ? "" : lang.NoListData;
                        mvvm.entityList = ret.data.Source;
                        mvvm.ADD = ret.data.ADD;
                        mvvm.DELETE = ret.data.DELETE;
                        avalon.vmodels.upaing.total = ret.data.RecordTotal //分页总数
                        //传有参数Id,跳到查看
                        if (request.params.CSId) {
                            mvvm.doview()
                        }
                    });

                }
                //副列表
                function GetCServerGroup(data) {
                    $.get('/Services/CServicesGroup/', data || {}, function (ret) {
                        mvvm.groupList = ret.data;
                    });
                }
                function titleFocus(d) {
                    $("#title", d.content()).focus().select();
                }
                //新增
                function FormSubmit(title) {
                    CBCRM.loadView('/Services/CServicesAdd.html', function (tmpl) {
                        var dialog = openTmpl({
                            vm: mvvm, title: title, w: 820, h: 460,
                            tmplId: tmpl, isContent: true,
                            button: [{
                                name: '提交',
                                focus: true,
                                callback: function () {
                                    var model = mvvm.entity.$model;
                                    model['DisposeDetail.Id'] = 0;
                                    model['DisposeDetail.Process'] = mvvm.entityDisposeDetail.Process;
                                    model['DisposeDetail.InformOrFeedback'] = mvvm.entityDisposeDetail.InformOrFeedback;
                                    model['DisposeDetail.DisposeTime'] = mvvm.entityDisposeDetail.DisposeTime;
                                    model['DisposeDetail.ElapsedTime'] = mvvm.entityDisposeDetail.ElapsedTime;
                                    model['DisposeDetail.CreateTime'] = mvvm.entityDisposeDetail.CreateTime;
                                    model['DisposeDetail.Remarks'] = mvvm.entityDisposeDetail.Remarks;
                                    model['DisposeDetail.TypeId'] = mvvm.entityDisposeDetail.TypeId;
                                    model['DisposeDetail.EmployeeId'] = mvvm.entityDisposeDetail.EmployeeId;
                                    model['DisposeDetail.EmployeeName'] = mvvm.entityDisposeDetail.EmployeeName;
                                    model['DisposeDetail.Result'] = mvvm.entityDisposeDetail.Result;
                                    model['DisposeDetail.CreateEmpId'] = mvvm.entityDisposeDetail.CreateEmpId;
                                    model['DisposeDetail.CreateEmpName'] = mvvm.entityDisposeDetail.CreateEmpName;
                                    model.Static = mvvm.entityDisposeDetail.Result;
                                    if (action == "addfromcallcenter") model.callid = paramid;

                                    if (!model.CustomerName) {
                                        messageBox.warning('请选择客户');
                                        return false;
                                    }

                                    if (model.Title) {
                                        var url = (model.Id == 0 ? "/Services/CServicesAdd/" : "/Services/CServicesEdit/");
                                        $.post(url + model.Id, model, function (ret) {
                                            if (ret.result) {
                                                messageBox.ok(ret.message, function () {
                                                    if (request.params.id && !request.params.CSId) {
                                                        mvvm.showItem.customerId = request.params.id
                                                    }
                                                    GetDataList(mvvm.showItem.$model);
                                                    dialog.close();
                                                });
                                            }
                                            else {
                                                messageBox.fail(ret.message, function () { messageBox.close(); });
                                            }
                                        })
                                    }
                                    else messageBox.warning('请填写服务主题');
                                    mvvm.tab = 'tab1';
                                    return false;
                                }
                            }],
                            onClose: function () {
                                if (avalon.vmodels.belongToTree)
                                    avalon.vmodels.belongToTree.destroy()
                                if (avalon.vmodels.belongToTree2)
                                    avalon.vmodels.belongToTree2.destroy()
                                if (avalon.vmodels.setParetCustomer)
                                    avalon.vmodels.setParetCustomer.destroy();
                            },
                            onScan: function () {
                                titleFocus(dialog);
                            }
                        });
                    })
                }
                //编辑
                function EditSubmit(title) {
                    CBCRM.loadView('/Services/CServicesForm.html', function (tmpl) {
                        var button = [{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                if (mvvm.tabshow == 'servAdd') {//新增服务
                                    var model = mvvm.entity.$model;
                                    if (!model.CustomerName) {
                                        messageBox.warning('请选择客户');
                                        return false;
                                    }
                                    // 检查是否所有分派人都处理完成了本次服务
                                    if (!checkServiceStatus()) {
                                        messageBox.warning('所有分派人必须完成服务处理，才能将处理结果改为‘处理完成’！');
                                        return false;
                                    }

                                    if (model.Title) {
                                        $.post("/Services/CServicesEdit/" + model.Id, model, function (ret) {
                                            if (ret.result) {
                                                messageBox.ok(ret.message, function () {
                                                    GetDataList(mvvm.showItem.$model);
                                                    dialog.close(); mvvm.tab = 'tab1';
                                                });
                                            }
                                            else messageBox.fail(ret.message, function () { messageBox.close(); });
                                        })
                                    }
                                    else messageBox.error('请填写服务主题');
                                }
                               
                                return false;
                            }
                        }, {
                            name: '关闭',
                            callback: function () {
                                switch (mvvm.tabshow) {
                                    case "servAdd":
                                        return true;
                                        break;
                                    case "dispAdd":
                                        mvvm.tab = 'tab2'; //切换
                                        mvvm.tabshow = 'servAdd';
                                        return false;
                                        break;
                                }
                            }
                        }];
                        var dialog = openTmpl({
                            vm: mvvm, title: title, w: 800, h: 460,
                            tmplId: tmpl, isContent: true,
                            button: button,
                            onClose: function () { destroyui(["belongToTree", "belongToTree2", "setParetCustomer"]); },
                            onScan: function () {
                                titleFocus(dialog);
                            }
                        });
                    });
                }
                //查看
                function ViewSubmit(title) {
                    CBCRM.loadView('/Services/CServicesView.html', function (tmpl) {
                        var dialog = openTmpl({
                            vm: mvvm, title: title, w: 800, h: 340,
                            tmplId: tmpl, isContent: true
                        });
                    })
                }

                // 检查是否所有分派人都处理完成
                function checkServiceStatus() {
                    if (mvvm.entity.Static != "4") //投诉状态非‘处理完成’
                        return true;
                    for (var i = 0; i < mvvm.entity.DetailList.$model.length; i++) {
                        var item = mvvm.entity.DetailList.$model[i];
                        var result = item.Result;
                        if (result != "1" && result != "4")
                            return false;
                    }
                    return true;
                }

                //自定义过滤器
                avalon.filters.servicesUrgency = function (val) {
                    var result;
                    mvvm.urgency.forEach(function (item) {
                        if (item.value == val)
                            result = item.key;
                    });
                    return result;
                }
                avalon.filters.statusx = function (val) {
                    var result;
                    mvvm.status.forEach(function (item) {
                        if (item.value == val)
                            result = item.key
                    });
                    return result;
                }
                avalon.filters.servicesMode = function (val) {
                    var result;
                    mvvm.mode.forEach(function (item) {
                        if (item.Id == val)
                            result = item.Data
                    });
                    return result;
                }
                avalon.filters.servicesCategory = function (val) {
                    var result;
                    mvvm.category.forEach(function (item) {
                        if (item.Id == val)
                            result = item.Data
                    });
                    return result;
                }

                //客户信息中，合同订单调用
                switch (action) {
                    case "customer":
                        /*隐藏其它，只显示列表块*/
                        mvvm.showOnlyList = true
                        $('#cservices').css({ width: '100%', 'margin-top': '0px', });
                        mvvm.customer.Id = request.params.id;
                        mvvm.customer.Name = paramData.entity.Name;
                        mvvm.showCustomer = false;
                        paramData.viewOther(tmpl, mvvm);
                        break;
                    case "view":
                        mvvm.doview(paramid);
                        break;
                    case "add":
                        mvvm.doadd();
                        break;
                    case "addfromcallcenter":
                        addFromCallCenter();
                        break;
                    case "key":
                        mvvm.showItem.key = mvvm.keyword = paramid;
                        fill();
                        break;
                    default:
                        fill();
                        break;
                }
                function addFromCallCenter() {
                    mvvm.doadd();
                    var callvm = avalon.vmodels.Calls;
                    var customer = callvm.customerEntity, callEntity = callvm.callCenterEntity;
                    if (callEntity.Cid) {
                        mvvm.entity.CustomerId = callEntity.Cid;
                        mvvm.entity.CustomerName = callEntity.CustomerName
                        mvvm.entity.ContactsId = callEntity.ContactsId;
                        mvvm.entity.ContactsName = callEntity.CallsName;
                        mvvm.children = [];
                    }
                }
                function fill() {
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                }
                require('commonui', function () {
                    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);
                        mvvm.showItem.date = mvvm.showItem.dateName = date;
                        GetDataList(mvvm.showItem.$model);
                    });//大日历
                })
                //选择员工
                var setting = {
                    async: {
                        enable: true,
                        url: function () {
                            var url
                            if (mvvm.empKey)
                                url = '/Settings/GetGroupPostUser/3040001/?empName=' + mvvm.empKey
                            else
                                url = '/Settings/GetGroupPostUser/3040001'
                            return url
                        },
                        type: 'get',
                        dataFilter: groupPostFilter
                    },
                    callback: {
                        onClick: function (e, treeId, treeNode) {

                            var ids = getNodeIds(treeNode, "emp").join(",");
                            if (!ids) ids = "0";
                            //先清空
                            mvvm.showItem.emp = mvvm.showItem.empName = '';
                            if (treeNode.ParentId == null || treeNode.ParentId == 0) {
                                GetCServerGroup();
                            }
                            else {
                                mvvm.showItem.emp = ids
                                mvvm.showItem.empName = treeNode.Name
                                GetCServerGroup({ eid: ids });
                            }
                            GetDataList(mvvm.showItem.$model);
                        }
                    },
                    data: {
                        simpleData: { enable: true, idKey: 'Id', pIdKey: 'ParentId' },
                        key: { name: 'Name' }
                    }
                }
                $.fn.zTree.init($('#empTree'), setting);
            },
            /// <summary>
            /// 客户投诉
            /// </summary>
            Complaints: function (tmpl, lang, contentId, module, paramData) {
                var CBCRM = avalon.vmodels.CBCRM
                var request = this
                var detail = null
                var action = this.params.action, paramid = this.params.id;
                var mvvm = CBCRM.define('Complaints', function (vm) {
                    vm.lang = lang
                    vm.showOnlyList = false
                    vm.destroy = function () {

                    }
                    vm.viewCustomer = function () {
                        var vm = this.$vmodel,
                        item = vm[vm.$itemName]
                        goto('/Customer/DetailCustomer/' + item.CustomerId, true)
                    }
                    vm.viewCustomer1 = function (id) {
                        var id = $(this).val();
                        goto('/Customer/DetailCustomer/' + id, true);
                    }
                    vm.$skipArray = ['lang'] //不监控语言包
                    vm.searchItem = []
                    vm.showItem = {}
                    vm.entity = {}
                    vm.entityList = []
                    vm.groupList = []
                    vm.entityDisposeDetail = {}
                    vm.entityDisposeDetailList = []
                    vm.showComplate = true;
                    vm.category = [] //投诉分类
                    vm.business = []
                    vm.status = []
                    vm.followChange = []
                    vm.tab = 'tab1'
                    vm.tabshow = 'servAdd';
                    vm.mode = [] //投诉方式
                    vm.urgency = []
                    vm.keyword = ''
                    vm.cuskey = ''
                    vm.sendSms = CBCRM.sendSms
                    vm.cuskeyClick = function () {
                        GetComplaintsGroup({ key: mvvm.cuskey });
                    }
                    vm.groupClick = function () {
                        var title = $(this).attr('title');
                        var val = $(this).attr('val');
                        mvvm.showItem.customer = mvvm.showItem.customerName = '';//先清空
                        mvvm.showItem.customer = val;
                        mvvm.showItem.customerName = title;
                        GetDataList(mvvm.showItem.$model);
                    }
                    vm.children = []
                    vm.history = []
                    vm.ADD = false
                    vm.DELETE = false
                    vm.showCustomer = true
                    vm.customer = { Id: '', Name: '' }
                    //关键字搜索
                    vm.search = function () {
                        if (mvvm.keyword) {
                            mvvm.showItem.key = mvvm.showItem.keyName = mvvm.keyword;
                            GetDataList(mvvm.showItem.$model);
                            if (mvvm.history.length = 3)
                                mvvm.history.removeAt(2);
                            mvvm.history.unshift(mvvm.keyword);
                        }
                    }
                    //历史搜索
                    vm.historyClick = function () {
                        mvvm.keyword = $(this).val();
                        mvvm.showItem.key = mvvm.showItem.keyName = mvvm.keyword;
                        GetDataList(mvvm.showItem.$model);
                    }
                    //清空
                    vm.clear = function () {
                        mvvm.keyword = '';
                        mvvm.showItem.key = mvvm.showItem.keyName = '';
                        mvvm.showItem.urgency = mvvm.showItem.urgencyName = '';
                        mvvm.showItem.status = mvvm.showItem.statusName = '';
                        mvvm.showItem.category = mvvm.showItem.categoryName = '';
                        mvvm.showItem.date = mvvm.showItem.dateName = '';
                        mvvm.showItem.emp = mvvm.showItem.empName = '';
                        mvvm.showItem.customer = mvvm.showItem.customerName = '';
                        $(".seacrhField a[index='0']").addClass("selected").siblings().removeClass("selected");
                        GetDataList(mvvm.showItem.$model);
                    }
                    //移除单个条件
                    vm.remove = function () {
                        var val = $(this).attr('val');
                        switch (val) {
                            case "key": mvvm.showItem.key = mvvm.showItem.keyName = ''; break;
                            case "urgency": mvvm.showItem.urgency = mvvm.showItem.urgencyName = '';
                                $(".seacrhField a[index='0']").eq(2).addClass("selected").siblings().removeClass("selected");
                                break;
                            case "status": mvvm.showItem.status = mvvm.showItem.statusName = '';
                                $(".seacrhField a[index='0']").eq(1).addClass("selected").siblings().removeClass("selected");
                                break;
                            case "category": mvvm.showItem.category = mvvm.showItem.categoryName = '';
                                $(".seacrhField a[index='0']").eq(0).addClass("selected").siblings().removeClass("selected");
                                break;
                            case "date": mvvm.showItem.date = mvvm.showItem.dateName = ''; break;
                            case "emp": mvvm.showItem.emp = mvvm.showItem.empName = ''; break;
                            case "customer": mvvm.showItem.customer = mvvm.showItem.customerName = ''; break;
                        }
                        GetDataList(mvvm.showItem.$model);
                    }
                    //分类检索
                    vm.itemClick = function () {
                        $(this).attr('class', 'selected').siblings().removeClass('selected');
                        var i = $(this).attr('index');
                        var sort = $(this).attr('sort');

                        var model = mvvm.searchItem.$model[sort].item[i];
                        switch (sort) {
                            case "0":
                                mvvm.showItem.category = mvvm.showItem.categoryName = '';//先清空
                                if (i != 0) {
                                    mvvm.showItem.category = model.value
                                    mvvm.showItem.categoryName = model.key;
                                }
                                break;
                            case "1":
                                mvvm.showItem.status = mvvm.showItem.statusName = '';
                                if (i != 0) {
                                    mvvm.showItem.status = model.value
                                    mvvm.showItem.statusName = model.key;
                                }
                                break;
                            case "2":
                                mvvm.showItem.urgency = mvvm.showItem.urgencyName = '';
                                if (i != 0) {
                                    mvvm.showItem.urgency = model.value
                                    mvvm.showItem.urgencyName = model.key;
                                }
                                break;
                        }
                        GetDataList(mvvm.showItem.$model);
                    }
                    vm.grid1 = { gridmsg: "" };
                    //分页
                    vm.userpaing = {
                        paging: function (pageIndex,pageSize) {
                            mvvm.showItem.pageSize = pageSize
                            mvvm.showItem.pageIndex = pageIndex
                            GetDataList(mvvm.showItem.$model);
                            GetComplaintsGroup();
                        }
                    }

                    //选客户/联系人
                    vm.selectCustomer = function () {
                        plugins.selectCustomer({
                            type: "contacts",
                            callback: function (cus, cons) {
                                var cu = cus[0], con = cons[0];
                                mvvm.entity.CustomerId = cu.Id;
                                mvvm.entity.CustomerName = cu.Name
                                mvvm.children = cu.Contacts;

                                mvvm.entity.ContactsId = con.Id;
                                mvvm.entity.ContactsName = con.Name;
                                
                            }
                        });
                    }

                    //单选员工
                    vm.selectUser = function (p) {
                        plugins.selectUser({
                            dataAuth: 3050001,
                            callback: function (us) {
                                var u = us[0];
                                if (p == "FirstEmp") {
                                    //首次接待人
                                    mvvm.entity.FirstReceiverId = u.Id;
                                    mvvm.entity.FirstReceiverName = u.FullName;
                                } else if (p == "Employee") {
                                    //处理人
                                    mvvm.entityDisposeDetail.EmployeeId = u.Id;
                                    mvvm.entityDisposeDetail.EmployeeName = u.FullName;
                                } else if (p == "ComplainBy") {
                                    //被投诉人
                                    mvvm.entity.ComplainByEmployeeId = u.Id;
                                    mvvm.entity.ComplainByEmployeeName = u.FullName;
                                }
                            }
                        });
                    }
                    vm.birthdayOpts = {
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.BeginTime = formatDate;
                        }
                    }
                    vm.birthdayOpts2 = {
                        onSelect: function (date, formatDate, format) {
                            mvvm.entityDisposeDetail.DisposeTime = formatDate;
                        }
                    }
                    vm.birthdayOpts3 = {
                        onSelect: function (date, formatDate, format) {
                            mvvm.entity.EndTime = formatDate;
                        }
                    }
                    //新增
                    vm.doadd = function () {
                        mvvm.entity = modelFactory.create('Complaints');
                        mvvm.entity.ComplaintsType += '';
                        mvvm.entity.ComplaintsWay += '';
                        mvvm.entity.UrgencyLevel += '';
                        mvvm.entity.Static += '';
                        mvvm.entity.FirstReceiverId = CBCRM.memberShip.Id;
                        mvvm.entity.FirstReceiverName = CBCRM.memberShip.FullName;
                        mvvm.entityDisposeDetail = modelFactory.create('DisposeDetail');
                        mvvm.tab = 'tab1';
                        mvvm.children = [];

                        if (["customer", "addfromcallcenter"].indexOf(action) != -1) {
                            mvvm.entity.CustomerId = mvvm.customer.Id;
                            mvvm.entity.CustomerName = mvvm.customer.Name;

                            $.get('/Customer/GetConatactByCustomerId/' + mvvm.customer.Id, {}, function (ret) {
                                mvvm.children = ret.data;
                                if (mvvm.children.length) {
                                    mvvm.entity.ContactsId = mvvm.children.$model[0].Id;
                                    mvvm.entity.ContactsName = mvvm.children.$model[0].Name;
                                }
                            });
                        }
                        FormSubmit('新增投诉')
                    }
                    //编辑
                    vm.doedit = function () {
                        var id = $(this).val();
                        $.get('/Services/ComplaintsDetail/' + id, {}, function (ret) {
                            mvvm.entity = ret.data;
                            mvvm.entity.ComplaintsType += '';
                            mvvm.entity.ComplaintsWay += '';
                            mvvm.entity.UrgencyLevel += '';
                            mvvm.entity.Static += '';
                            mvvm.entityDisposeDetail = modelFactory.create('DisposeDetail');
                            mvvm.children = ret.data.children;

                            mvvm.tab = 'tab1';
                            mvvm.tabshow = 'servAdd';
                            setShowComplate();
                            EditSubmit('编辑投诉');
                        });
                    }
                    //处理结果新增
                    vm.detailAdd = function () {
                        mvvm.entityDisposeDetail = modelFactory.create('DisposeDetail');
                        mvvm.openTmpl({
                            title: "新增处理", w: 800, h: 400,
                            tmplId: "addProcess", tmpl: mvvm.tmpl,
                            button: [{
                                name: '提交',
                                focus: true,
                                callback: function () {
                                    if (!mvvm.entityDisposeDetail.EmployeeName) {
                                        messageBox.warning('请选择处理人');
                                        return false;
                                    }

                                    var model = mvvm.entityDisposeDetail.$model;
                                    model.ServeId = mvvm.entity.Id;
                                    var url = model.Id == 0 ? "/Services/ComplaintsDisposeAdd/" : "/Services/ComplaintsDisposeEdit/";
                                    $.post(url + model.Id, model, function (ret) {
                                        if (ret.result) {
                                            mvvm.entity.DetailList = ret.data;
                                            mvvm.entityDisposeDetailList = ret.data;
                                            setShowComplate();
                                        }
                                        else
                                        { messageBox.error(ret.message); }
                                    });
                                 }
                            }]
                        })
                    }
                    //处理结果编辑
                    vm.detailEdit = function () {
                        var id = $(this).val();
                        $.get('/Services/CServicesDisposeDetail/' + id, {}, function (ret) {
                            if (ret.result) {
                                mvvm.entityDisposeDetail = ret.data;
                                mvvm.entityDisposeDetailList = ret.data;
                            }
                        });
                        mvvm.openTmpl({
                            title: "编辑处理" , w: 800, h: 400,
                            tmplId: "addProcess", tmpl: mvvm.tmpl,
                            button: [{
                                name: '提交',
                                focus: true,
                                callback: function () {
                                    if (!mvvm.entityDisposeDetail.EmployeeName) {
                                        messageBox.warning('请选择处理人');
                                        return false;
                                    }

                                    var model = mvvm.entityDisposeDetail.$model;
                                    model.ServeId = mvvm.entity.Id;
                                    var url = model.Id == 0 ? "/Services/ComplaintsDisposeAdd/" : "/Services/ComplaintsDisposeEdit/";
                                    $.post(url + model.Id, model, function (ret) {
                                        if (ret.result) {
                                            mvvm.entity.DetailList = ret.data;
                                            mvvm.entityDisposeDetailList = ret.data;
                                            setShowComplate();
                                        }
                                        else { messageBox.error(ret.message); }
                                    });
                                }
                            }]
                        })
                    }
                    //处理结果删除
                    vm.detailDel = function () {
                        var id = $(this).val();
                        $.post('/Services/CServicesDisposeDel/' + id, {}, function (ret) {
                            if (ret.result) {
                                mvvm.entity.DetailList = ret.data;
                                mvvm.entityDisposeDetailList = ret.data;
                            }
                        })
                    }
                    //查看

                    //查看处理信息
                    vm.processView = function () {
                        var id = $(this).val();
                        $.get('/Services/CServicesDisposeDetail/' + id, {}, function (ret) {
                            if (ret.result) {
                                mvvm.entityDisposeDetail = ret.data;
                                mvvm.entityDisposeDetailList = ret.data;
                            }
                        });
                        mvvm.openTmpl({
                            title: "编辑处理" , w: 800, h: 400,
                            tmplId: "viewProcess", tmpl: mvvm.tmpl
                        })
                    }

                    vm.doview = function (id) {
                        $.get('/Services/ComplaintsDetail/' + id, {}, function (ret) {
                            mvvm.entity = ret.data;
                            mvvm.entityDisposeDetailList = ret.data.DetailList;
                            mvvm.tab = 'tab1';
                            ViewSubmit('查看详情');
                        });
                    }

                    //删除
                    vm.dodel = function () {
                        var id = $(this).val();
                        messageBox.confirm('确定删除此数据吗？', function () {
                            $.post('/Services/ComplaintsDel/' + id, {}, function (ret) {
                                if (ret.result) {
                                    GetDataList();
                                } else { messageBox.error(ret.message); }
                            })
                        });
                    }
                    //批量删除
                    vm.doalldel = function () {
                        var deleteIds = checkAll();
                        messageBox.confirm('确定删除选中的数据吗？', function () {
                            $.get('/Services/ComplaintsDelAll/', deleteIds, function (ret) {
                                if (ret.result) {
                                    GetDataList();
                                    messageBox.succeed(ret.message);
                                } else { messageBox.error(ret.message); }
                            });
                        });
                    }
                    //状态图标
                    vm.statusIcon = function (index) {
                        var res;
                        switch (index) {
                            case 1: res = 'stNam'; break;
                            case 2: res = 'stErr'; break;
                            case 3: res = 'stNo'; break;
                            case 4: res = 'stCom'; break;
                        }
                        return res;
                    }
                    //状态名称
                    vm.statusTitle = function (val) {
                        var result;
                        mvvm.status.forEach(function (item) {
                            if (item.value == val)
                                result = item.key
                        });
                        return result;
                    }
                    //标签切换
                    vm.tabChange = function () {
                        var val = $(this).attr('val');
                        mvvm.tab = val;
                        $(this).addClass('hover').siblings().removeClass('hover');
                    }

                    vm.empKey = ''
                    vm.empSearch = function () {
                        var treeObj = $.fn.zTree.getZTreeObj("empTree")
                        if (treeObj != null)
                            treeObj.reAsyncChildNodes(null, "refresh")
                    }
                });
                $('.selectCalls,.selectCalls2').live('change', function () {
                    mvvm.entity.ContactsName = $(this).find('option:selected').text();
                })

                //创建查询对象
                var createDate = {
                    key: '', keyName: '',
                    category: '', categoryName: '',
                    status: '', statusName: '',
                    urgency: '', urgencyName: '',
                    pageSize: 20, pageIndex: 1,
                    date: '', dateName: '',
                    emp: '', empName: '',
                    customer: '', customerName: '', customerId: ''
                }

                //初始化
                function initWithEntity() {
                    mvvm.showItem = avalon.mix({}, createDate);
                    //紧急程度
                    var timeSearch = {
                        title: '紧急程度', sort: 2,
                        item: [
                            { key: '不限', value: '0', focus: true, click: mvvm.itemClick },
                            { key: '紧急', value: '1', focus: false, click: mvvm.itemClick },
                            { key: '急', value: '2', focus: false, click: mvvm.itemClick },
                            { key: '一般', value: '3', focus: false, click: mvvm.itemClick }
                        ]
                    }
                    mvvm.urgency = timeSearch.item;
                    mvvm.urgency.removeAt(0); //移除'不限'选项

                    //投诉状态
                    var statusSearch = {
                        title: '投诉状态', sort: 1,
                        item: [
                            { key: '不限', value: '0', focus: true, click: mvvm.itemClick },
                            { key: '无需处理', value: '1', focus: false, click: mvvm.itemClick },
                            { key: '未处理', value: '2', focus: false, click: mvvm.itemClick },
                            { key: '处理中', value: '3', focus: false, click: mvvm.itemClick },
                            { key: '处理完成', value: '4', focus: false, click: mvvm.itemClick }
                        ]
                    }
                    mvvm.status = statusSearch.item;
                    mvvm.status.removeAt(0); //移除'不限'选项

                    //投诉分类
                    var categorySearch = {
                        title: '投诉分类', sort: 0,
                        item: [{ key: '不限', value: '0', focus: true, click: mvvm.itemClick }]
                    }

                    $.get('/Services/GetComplaintsDictionary', {}, function (ret) {
                        ret.data.ComplaintsType.forEach(function (item, i) {
                            categorySearch.item.push({ key: item.Data, value: item.Id, focus: false, click: mvvm.itemClick })
                        });
                        mvvm.category = ret.data.ComplaintsType;
                        mvvm.mode = ret.data.ComplaintsWay;
                        mvvm.searchItem.push(categorySearch);
                        mvvm.searchItem.push(statusSearch);
                        mvvm.searchItem.push(timeSearch);
                    });
                }
                initWithEntity();
                //主列表
                function GetDataList(data) {
                    if (action == "customer") {
                        data.customerId = paramid;
                    }
                    mvvm.grid1.gridmsg = lang.LoadingMsg;
                    $.get('/Services/Complaints/', data || {}, function (ret) {
                        mvvm.grid1.gridmsg = ret.data.RecordTotal > 0 ? "" : lang.NoListData;
                        mvvm.entityList = ret.data.Source;
                        mvvm.ADD = ret.data.ADD;
                        mvvm.DELETE = ret.data.DELETE;
                        avalon.vmodels.upaing.total = ret.data.RecordTotal //分页总数
                    });
                }
                //副列表
                function GetComplaintsGroup(data) {
                    $.get('/Services/ComplaintsGroup/', data || {}, function (ret) {
                        mvvm.groupList = ret.data;
                    });
                }
                function titleFocus(d) {
                    $("#title", d.content()).focus().select();
                }
                //新增
                function FormSubmit(title) {
                    CBCRM.loadView('/Services/ComplaintsAdd.html', function (tmpl) {
                        var button=[{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                var model = mvvm.entity.$model;
                                model['DisposeDetail.Id'] = 0;
                                model['DisposeDetail.Process'] = mvvm.entityDisposeDetail.Process;
                                model['DisposeDetail.InformOrFeedback'] = mvvm.entityDisposeDetail.InformOrFeedback;
                                model['DisposeDetail.DisposeTime'] = mvvm.entityDisposeDetail.DisposeTime;
                                model['DisposeDetail.ElapsedTime'] = mvvm.entityDisposeDetail.ElapsedTime;
                                model['DisposeDetail.CreateTime'] = mvvm.entityDisposeDetail.CreateTime;
                                model['DisposeDetail.Remarks'] = mvvm.entityDisposeDetail.Remarks;
                                model['DisposeDetail.TypeId'] = mvvm.entityDisposeDetail.TypeId;
                                model['DisposeDetail.EmployeeId'] = mvvm.entityDisposeDetail.EmployeeId;
                                model['DisposeDetail.EmployeeName'] = mvvm.entityDisposeDetail.EmployeeName;
                                model['DisposeDetail.Result'] = mvvm.entityDisposeDetail.Result;
                                model['DisposeDetail.CreateEmpId'] = mvvm.entityDisposeDetail.CreateEmpId;
                                model['DisposeDetail.CreateEmpName'] = mvvm.entityDisposeDetail.CreateEmpName;
                                model.Static = mvvm.entityDisposeDetail.Result;

                                //如果是从来电管理过来
                                if (action == "addfromcallcenter") {
                                    model.callid = paramid;
                                }
                                if (!model.CustomerName) {
                                    messageBox.warning('请选择客户');
                                    return false;
                                }
                                if (model.Ttirle) {
                                    $.post("/Services/ComplaintsAdd/" + model.Id, model, function (ret) {
                                        if (ret.result) {
                                            messageBox.ok(ret.message, function () {
                                                mvvm.tab = 'tab1';
                                                if (request.params.id) {
                                                    mvvm.showItem.customerId = request.params.id;
                                                }
                                                GetDataList(mvvm.showItem.$model);
                                                dialog.close();
                                            });
                                        }
                                        else {
                                            messageBox.fail(ret.message, function () { messageBox.close(); });
                                        }
                                    })
                                }
                                else messageBox.warning('请填写投诉主题');

                                return false;
                            }
                        }];
                        var dialog = openTmpl({
                            vm: mvvm, title: title, w: 800, h: 460,
                            tmplId: tmpl, isContent: true, button: button,
                            onScan: function () { titleFocus(dialog); }
                        });
                    })
                }
                //编辑
                function EditSubmit(title) {
                    CBCRM.loadView('/Services/ComplaintsEdit.html', function (tmpl) {
                        var button=[{
                            name: '提交',
                            focus: true,
                            callback: function () {
                                if (mvvm.tabshow == 'servAdd') {//新增服务
                                    var model = mvvm.entity.$model;
                                    if (!model.CustomerName) {
                                        messageBox.warning('请选择客户');
                                        return false;
                                    }
                                    // 检查是否所有分派人都处理完成了本次投诉
                                    if (!checkComplaintStatus()) {
                                        messageBox.warning('所有分派人必须完成投诉处理，才能将处理结果改为‘处理完成’！');
                                        return false;
                                    }

                                    if (model.Ttirle) {
                                        $.post("/Services/ComplaintsEdit/" + model.Id, model, function (ret) {
                                            if (ret.result) {
                                                messageBox.ok(ret.message, function () {
                                                    if (request.params.id) {
                                                        mvvm.showItem.customerId = request.params.id;
                                                    }
                                                    GetDataList(mvvm.showItem.$model);
                                                    dialog.close(); mvvm.tab = 'tab1';
                                                });
                                            }
                                            else messageBox.fail(ret.message, function () { messageBox.close(); });
                                        })
                                    }
                                    else {
                                        messageBox.error('请填写投诉主题');
                                        return false;
                                    }
                                }
                       
                                return false;
                            }
                        },
                        {
                            name: '关闭',
                            callback: function () {
                                switch (mvvm.tabshow) {
                                    case "servAdd":
                                        return true;
                                        break;
                                    case "dispAdd":
                                        mvvm.tab = 'tab2'; //切换
                                        mvvm.tabshow = 'servAdd';
                                        return false;
                                        break;
                                }
                            }
                        }
                        ];
                        var dialog = openTmpl({
                            vm: mvvm, title: title, w: 800, h: 460,
                            tmplId: tmpl, isContent: true, button: button,
                            onScan: function () { titleFocus(dialog); }
                        });
                    })
                }
                //查看
                function ViewSubmit(title) {
                    CBCRM.loadView('/Services/ComplaintsView.html', function (tmpl) {
                        var dialog = openTmpl({
                            vm: mvvm, title: title, w: 800, h: 300,
                            tmplId:tmpl,isContent:true
                        });
                    })
                }

                function setShowComplate() {
                    //如果发现有未处理完成的4
                    //改成只要没有无需处理的就可以修改总的处理状态1
                    mvvm.showComplate = mvvm.entity.DetailList.length > 0 ? false : true;
                    mvvm.entity.DetailList.forEach(function (item) {
                        if (item.Result != "1") {
                            mvvm.showComplate = true;
                        }
                    })
                }

                function checkComplaintStatus() {
                    if (mvvm.entity.Static != "4") //投诉状态非‘处理完成’
                        return true;
                    for (var i = 0; i < mvvm.entity.DetailList.$model.length; i++)
                    {
                        var item = mvvm.entity.DetailList.$model[i];
                        var result = item.Result;
                        if (result != "1" && result != "4")
                            return false;
                    }
                    return true;
                }

                //自定义过滤器
                avalon.filters.servicesUrgency = function (val) {
                    var result;
                    mvvm.urgency.forEach(function (item) {
                        if (item.value == val)
                            result = item.key;
                    });
                    return result;
                }
                avalon.filters.statusx = function (val) {
                    var result;
                    mvvm.status.forEach(function (item) {
                        if (item.value == val)
                            result = item.key
                    });
                    return result;
                }
                avalon.filters.servicesMode = function (val) {
                    var result;
                    mvvm.mode.forEach(function (item) {
                        if (item.Id == val)
                            result = item.Data
                    });
                    return result;
                }
                avalon.filters.servicesCategory = function (val) {
                    var result;
                    mvvm.category.forEach(function (item) {
                        if (item.Id == val)
                            result = item.Data
                    });
                    return result;
                }

                //客户信息中，合同订单调用
                switch (action) {
                    case "view":
                        mvvm.doview(paramid);
                        break;
                    case "key":
                        mvvm.showItem.key = paramid;
                        fill();
                        break;
                    case "addfromcallcenter":
                        addFromCallCenter();
                        break;
                    case "customer":
                        mvvm.showItem.customerId = paramid;
                        /*隐藏其它，只显示列表块*/
                        mvvm.showOnlyList = true
                        $('#complaints').css({ width: '100%', 'margin-top': '0px', });
                        mvvm.customer.Id = request.params.id;
                        mvvm.customer.Name = paramData.entity.Name;
                        mvvm.showCustomer = false;
                        paramData.viewOther(tmpl, mvvm);
                        break;
                    default:
                        fill();
                        break;
                }
                function addFromCallCenter() {
                    mvvm.doadd();
                    var callvm = avalon.vmodels.Calls;
                    var customer = callvm.customerEntity, callEntity = callvm.callCenterEntity;
                    if (callEntity.Cid) {
                        mvvm.entity.CustomerId = callEntity.Cid;
                        mvvm.entity.CustomerName = callEntity.CustomerName
                        mvvm.entity.ContactsId = callEntity.ContactsId;
                        mvvm.entity.ContactsName = callEntity.CallsName;
                        mvvm.children = [];
                    }
                }
                function fill() {
                    CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                }

                require('commonui', function () {
                    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);
                        mvvm.showItem.date = date;
                        mvvm.showItem.dateName = date;
                        GetDataList(mvvm.showItem.$model);
                    }); //大日历
                })
                //选择员工
                var setting = {
                    async: {
                        enable: true,
                        url: function () {
                            var url
                            if (mvvm.empKey)
                                url = '/Settings/GetGroupPostUser/3050001/?empName=' + mvvm.empKey
                            else
                                url = '/Settings/GetGroupPostUser/3050001'
                            return url
                        },
                        type: 'get',
                        dataFilter: groupPostFilter
                    },
                    callback: {
                        onClick: function (e, treeId, treeNode) {
                            var ids = getNodeIds(treeNode, "emp").join(",");
                            if (!ids) ids = "0";
                            //先清空
                            mvvm.showItem.emp = mvvm.showItem.empName = '';
                            if (treeNode.ParentId == null || treeNode.ParentId == 0)
                                GetComplaintsGroup();
                            else {
                                mvvm.showItem.emp = ids
                                mvvm.showItem.empName = treeNode.Name
                                GetComplaintsGroup({ eid: ids });
                            }
                            GetDataList(mvvm.showItem.$model);
                        }
                    },
                    data: {
                        simpleData: { enable: true, idKey: 'Id', pIdKey: 'ParentId' },
                        key: { name: 'Name' }
                    }
                }
                $.fn.zTree.init($('#empTree'), setting);
            }
        }

        return Services;
    });