define('Home', ['modelFactory',
    'json',
    'dialog',
    'common',
    'leftMenu',
    'jscal2',
    'kindedit',
    'upload',
    'jqPlot','jqBar','jqPointLabels','jqCategory','jqCanvasText','jqCanvasAxisLabel','jqPointLabel','jqEnhancedLegend',
    'slides', 'jcal', 'jqselect','jqueryui'],
    function (modelFactory) {
        var Home = {
            /// <summary>
            /// 首页工作台
            /// </summary>
            Index: function (tmpl, lang, contentId, module)
            {
                var CBCRM = avalon.vmodels.CBCRM
                var mvvm = CBCRM.define('IndexController', function (vm) {
                    vm.mycount = {}
                    vm.keyword = ''
                    vm.search = function () {
                        var url = $('#sb').val()
                        if (mvvm.keyword) {
                            url += mvvm.keyword
                            goto(url)
                        }
                    }
                    vm.enterToSearch = function (e) {
                        if (e.keyCode === 13) {
                            mvvm.search()
                        }
                    }
                    vm.qmenuShow = []
                    vm.desktopShow = []
                    vm.menuOpen = CBCRM.menuOpen
                    vm.customerTable = []
                    vm.chartCookie = { leftId: 1001, leftName: '客户分布情况(所辖)', rightId: 1003, rightName: '客户成长曲线(所辖)' }
                    vm.chartLeft = []
                    vm.leftChange = function (item) {
                        mvvm.chartCookie.leftId = item.id
                        mvvm.chartCookie.leftName = item.name
                    }
                    vm.chartRight = []
                    vm.rightChange = function (item) {
                        mvvm.chartCookie.rightId = item.id
                        mvvm.chartCookie.rightName = item.name
                    }
                    vm.jumpTo = function () {
                        var url = $(this).data()['goto']
                        var iden = $(this).attr('val')
                        if (iden == "4001")
                            goto(url + '/view')
                        else
                            goto(url)
                    }
                    vm.goTo = function (row,t) {
                        var url = t.url;
                        var a = url.split("/").filter(function (item) { return item.indexOf(":") != -1 });
                        if (a.length == 0) return;
                        var field = a[0].replace(":", "");
                        url = url.replace(a[0], row[field]);
                        goto(url, true);
                    }
                    vm.vfilter = function (val,t) {
                        if (!t.filter) return val;
                        var act = t.filter.split("|");
                        var args = [val].concat(act[1].split(","));
                        return avalon.filters[act[0]].apply(avalon.filters, args);
                    }
                    //移除自定义桌面
                    vm.tableRemove = function () {
                        var index = parseInt($(this).attr('index'))
                        CBCRM.desktopShow.removeAt(index);
                        CBCRM.desktopList[index].status = 0;
                        mvvm.customerTable.removeAt(index) //移除选中项目

                        var li = $('#sortable li')
                        if (li.length > 0) {
                            CBCRM.desktopTo = []
                            li.each(function (i) { //重新排序一次
                                if (i != index) 
                                    CBCRM.desktopTo.push(parseInt($(this).attr('identity')))
                            })
                            $.cookie('desktopId', CBCRM.desktopTo.$model.toString()) //并保存到cookie
                        }
                    }
                    //自定义统计
                    vm.openCount = function () {
                        CBCRM.loadView('/Home/Counts.html', function (tmpl) {
                            var dialog = messageBox.openHtml('自定义统计', '500px', '0px', tmpl, [{
                                name: '保存',
                                focus: true,
                                callback: function () {
                                    var countId = []
                                    mvvm.countShow.forEach(function (item) {
                                        countId.push(item.id)
                                    })
                                    //写入Cookie来保存
                                    $.cookie('countId', countId.toString());
                                    location.reload()
                                }
                            }]);
                            avalon.scan(dialog.content(), mvvm)
                        });
                    }
                    //自定义图表
                    vm.openChart = function () {
                        CBCRM.loadView('/Home/Charts.html', function (tmpl) {
                            var dialog = messageBox.openHtml('自定义图表', '700px', '0px', tmpl, [{
                                name: '保存',
                                focus: true,
                                callback: function () {
                                    $.cookie('mycharts', mvvm.chartCookie.leftId + ',' + mvvm.chartCookie.rightId, { path: '/' })
                                    location.reload()
                                }
                            }]);
                            avalon.scan(dialog.content(), mvvm)
                        });
                    }
                    vm.countShow = []
                    vm.countList = []
                    vm.countId = 0
                    vm.countCut = function () {
                        if (mvvm.countShow.length > 1) {
                            var id = parseInt($(this).attr('val'));
                            var index = parseInt($(this).attr('index'))
                            mvvm.countShow.removeAt(index);
                            mvvm.countList.forEach(function (item, i) {
                                if (item.id == id) {
                                    mvvm.countList[i].status = 0
                                }
                            })
                        }
                    }
                    vm.countPlus = function () {
                        if (mvvm.countShow.length < 6) {
                            var id = parseInt($(this).attr('val'))
                            var index = parseInt($(this).attr('index'))
                            countSource.forEach(function (item, i) {
                                if (item.status == 0 && item.id == id) {
                                    var model = item;
                                    model.status = 1;
                                    mvvm.countShow.push(model)
                                }
                            })
                            mvvm.countList[index].status = 2
                        }
                    }
                })

                mvvm.chartLeft = [
                    { id: 1001, name: '客户分布情况(所辖)' },
                    { id: 1002, name: '客户分布情况(个人)' },
                    { id: 2001, name: '产品销售情况(所辖)' },
                    { id: 2002, name: '产品销售情况(个人)' },
                    { id: 3001, name: '来电分布(所辖)' },
                    { id: 3002, name: '来电分布(个人)' },
                    { id: 4001, name: '收入构成图(所辖)' },
                    { id: 4002, name: '收入构成图(个人)' }
                ]
                mvvm.chartRight = [
                    { id: 1003, name: '客户成长曲线(所辖)' },
                    { id: 1004, name: '客户成长曲线(个人)' },
                    { id: 2003, name: '年销售业绩(所辖)' },
                    { id: 2004, name: '年销售业绩(个人)' },
                    { id: 3003, name: '服务曲线(所辖)' },
                    { id: 3004, name: '服务曲线(个人)' },
                    { id: 4003, name: '收支走势图(所辖)' },
                    { id: 4004, name: '收支走势图(个人)' }
                ]

                function initWithData() {
                    mvvm.qmenuShow = CBCRM.menuShow.$model;
                    //if ($.cookie('desktopId') != null)
                    //    mvvm.desktop = $.cookie('desktopId').split(',')
                    //else
                    //    mvvm.desktop = CBCRM.desktopTo
                    mvvm.desktop = CBCRM.desktopTo.$model;
                    //mvvm.desktopShow = CBCRM.desktopShow.$model;

                    if ($.cookie('mycharts') != null) {
                        var c = $.cookie('mycharts').split(',')
                        if (c[0]) {
                            var leftId = parseInt(c[0])
                            mvvm.chartCookie.leftId = leftId;
                            mvvm.chartLeft.forEach(function (item) {
                                if (item.id == leftId)
                                    mvvm.chartCookie.leftName = item.name
                            });
                        }
                        if (c[1]) {
                            var rightId = parseInt(c[1]);
                            mvvm.chartCookie.rightId = rightId;
                            mvvm.chartRight.forEach(function (item) {
                                if (item.id == rightId)
                                    mvvm.chartCookie.rightName = item.name
                            });
                        }
                    }

                    $.get('/Home/MyCharts/', { leftId: mvvm.chartCookie.leftId, rightId: mvvm.chartCookie.rightId }, function (ret) {
                        var left = ret.data.leftCharts
                        var right = ret.data.rightCharts
                        //左边图表
                        commonCharts(left);
                        //右边图表
                        createLineChart(right)
                    })
                }
                

                avalon.nextTick(function ()
                {
                    initWithData()
                    initWithCount()
                    //表格拖动
                    $('#sortable').sortable({
                        handle: '.t_top',
                        //延迟500毫秒后开始排序
                        delay: 100,
                        //占位样式
                        placeholder: 'holderCss',
                        //开启复位动画
                        revert: true,
                        //鼠标指针重叠式时排序
                        tolerance: 'pointer',
                        //开始排序
                        start: function (event, ui) {

                        }
                    })
                    var action = true;
                    //表格拖动排序完成时执行
                    $('#sortable').bind('sortupdate', function (event, ui) {
                        if (action) { //用于识别是否第一次执行
                            var li = $('#sortable li')
                            if (li.length > 0) {
                                CBCRM.desktopTo = []
                                var newSort = []
                                li.each(function () { //重新排序一次
                                    var identity = parseInt($(this).attr('identity'))
                                    CBCRM.desktopTo.push(identity)

                                    CBCRM.desktopShow.forEach(function (item, i) {
                                        if (item.id == identity)
                                            newSort.push(item)
                                    })
                                })
                                $.cookie('desktopId', CBCRM.desktopTo.$model.toString()) //并保存到cookie
                                CBCRM.desktopShow = newSort
                                action = false;
                            }
                        }
                        else action = true;
                    })

                    $('.defaultMenu li').live({
                        mouseover: function () {
                            $(this).find('div').show()
                        },
                        mouseout: function () {
                            $(this).find('div').hide()
                        }
                    });

                    //请求自定义桌面的列表数据
                    var array = {};
                    mvvm.desktop.forEach(function (item, i) {
                        array['array[' + i + ']'] = item
                    })
                    $.get('/Home/MyTables/', array, function (ret) {
                        mvvm.customerTable = ret.data
                    })

                    //请求自定义统计数据
                    var arrayCount = where(mvvm.countShow.$model, true, "id");
                    $.get('/Home/MyCounts/', {mids:arrayCount.join(",")}, function (ret) {
                        mvvm.mycount = ret.data
                    })

                    $("#stest").slider();
                    
                })

                var countDefault = [1001, 2001, 2002, 3001, 3002, 4001]
                var countSource = [
                    //客户
                    { id: 1001, name: "客户量", status: 0, parentId: 1 },
                    { id: 1002, name: "潜在客户", status: 0, parentId: 1 },
                    { id: 1003, name: "成交客户", status: 0, parentId: 1 },
                    //市场
                    { id: 2001, name: "销售机会", status: 0, parentId: 2 },
                    { id: 2002, name: "订单额", status: 0, parentId: 2 },
                    //财务
                    { id: 3001, name: "收入", status: 0, parentId: 3 },
                    { id: 3002, name: "支出", status: 0, parentId: 3 },
                    //服务
                    { id: 4001, name: "来电", status: 0, parentId: 4 },
                    { id: 4002, name: "回访", status: 0, parentId: 4 },
                    { id: 4003, name: "投诉", status: 0, parentId: 4 },
                    { id: 4004, name: "服务", status: 0, parentId: 4 },
                ]
                //初始化自定义统计
                function initWithCount(isDefault) {
                    var countArray
                    if ($.cookie('countId') != null)
                        countArray = $.cookie('countId').split(',')
                    else
                        countArray = countDefault
                    if (isDefault)
                        countArray = countDefault
                    mvvm.countShow = []
                    var source = countSource
                    for (var i = 0; i < countArray.length; i++) {
                        source.forEach(function (item) {
                            var v = avalon.mix({}, item);
                            if (v.id == parseInt(countArray[i])) {
                                v.status = 1
                                mvvm.countShow.push(v)
                                item.status = 2
                            }
                        })
                    }
                    mvvm.countList = source
                }
                
                //柱状图
                function commonCharts(result) {
                    var data = [];
                    result.source.forEach(function (item) {
                        var a = [item.label, item.value];
                        data.push(a);
                    })
                    var ops = {
                        title: result.option.caption,
                        series: [
                            {
                                label:result.option.caption,
                                renderer: $.jqplot.BarRenderer
                            }
                        ],
                        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
                        },
                        axes: {
                            xaxis: {
                                renderer: $.jqplot.CategoryAxisRenderer
                            }
                        }
                    };
                    try{
                        $("#chartLeft").jqplot([data], ops);
                    }catch(ex){
                        $("#chartLeft").html("<p class='nodata'>"+ex.message+"</p>")
                    }
                }
                //折线图
                function createLineChart(result)
                {
                    var data = [], series=[],index;
                    result.source.forEach(function (item) {
                        var arr = [];
                        series.push({
                            color: item.color? "#"+item.color:null,
                            label: item.seriesname
                        });
                        index = 0;
                        item.data.forEach(function (d) {
                            index++;
                            var a = [index + "月", d.value];
                            arr.push(a);
                        });
                        data.push(arr);
                    })
                    var ops = {
                        title: result.option.caption,
                        series: series,
                        seriesDefaults: {
                            rendererOptions: { fillToZero: true },
                            // Rotate the bar shadow as if bar is lit from top right.
                            shadowAngle: 135
                        },
                        legend: {
                            show: true,
                            placement: 'outsideGrid'
                        },
                        axes: {
                            xaxis: {
                                renderer: $.jqplot.CategoryAxisRenderer
                            }
                        }
                    };
                    try {
                        $("#chartRight").jqplot(data, ops);
                    } catch (ex) {
                        $("#chartRight").html("<p class='nodata'>" + ex.message + "</p>")
                    }
                }
                CBCRM.fillContent(tmpl, lang, contentId, module, mvvm)
                if (!$("#sb_container").length) {
                    $('#sb').selectbox()
                    $('#sb_input').removeAttr('readonly')
                }
            }
        }
        return Home;
    })