$(function () {
    Array.prototype.indexOf = function (val) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == val) return i
        }
        return -1
    }
    Array.prototype.remove = function (val) {
        var index = this.indexOf(val)
        if (index > -1) {
            this.splice(index, 1)
        }
    }
    
    function renderGraph1(graphData) {
        // 基于准备好的dom，初始化echarts实例
        var graph1 = echarts.init(document.getElementById('fold_line_diagram1'))
        // 指定图表的配置项和数据
        var option = {
            title: {
                text: '分时数据图'
            },
            tooltip: {
                enterable: true,
                trigger: 'axis',
                formatter: function (params) { //数据格式
                    var colorRecord = [
                        {
                            name: '总量',
                            color: '#5798d7'
                        }
                    ]
                    // 把数据按颜色整理出来
                    $('.body .selection-item[currentColor]').each(function (index, item) {
                        var ele = {
                            name: $(item).parent().siblings('.list-item')[1].innerHTML,
                            color: $(item).attr('currentColor')
                        }
                        colorRecord.push(ele)
                    })
                    function findColor(name) {
                        for (var i = 0; i < colorRecord.length; i++) {
                            if (name == colorRecord[i].name) {
                                return colorRecord[i].color
                            }
                        }
                    }
                    // 组织当前的数据类型（5个维度）
                    var lineType = []
                    $('.data_item_i.active') && $('.data_item_i.active').each(function (index, item) {
                        lineType.push($(item).attr('line-type'))
                    })
                    var relVal = ''
                    for (var i = 0; i < params.length; i++) {
                        if ($('.data_num .active').length > 0) {
                            relVal += "<p class='pHoverStyle' style='position: relative; background-color: " + findColor(params[i].seriesName) + "'>" +
                                "<span style='margin-right: 0;display: inline-block;width: 10px; color: transparent'>" + i + "</span>" +
                                "<span style='display: inline-block;'>" + params[i].seriesName + "</span>" +
                                "<span style='display: inline-block;width: 40px;position: relative;top: -4px; margin: 0 60px 0 4px; border-top: 2px " + lineType[Math.floor(i / ($('.body .selection-item[currentColor]').length + 1))] + " #fff'></span>" +
                                "<span style='padding-left: 30px; position: absolute; right: 10px; top: 2px;'>" + params[i].value + "次</span>" +
                                "</p>";
                        } else if ($('.data_rate .active').length > 0) {
                            relVal += "<p class='pHoverStyle' style='position: relative; background-color: " + findColor(params[i].seriesName) + "'>" +
                                "<span style='margin-right: 0;display: inline-block;width: 10px; color: transparent'>" + i + "</span>" +
                                "<span style='display: inline-block;'>" + params[i].seriesName + "</span>" +
                                "<span style='display: inline-block;width: 40px;position: relative;top: -4px; margin: 0 60px 0 4px; border-top: 2px " + lineType[Math.floor(i / ($('.body .selection-item[currentColor]').length + 1))] + " #fff'></span>" +
                                "<span style='padding-left: 30px; position: absolute; right: 10px; top: 2px;'>" + params[i].value + "%</span>" +
                                "</p>";
                        } else if ($('.data_yuan .active').length > 0) {
                            relVal += "<p class='pHoverStyle' style='position: relative; background-color: " + findColor(params[i].seriesName) + "'>" +
                                "<span style='margin-right: 0;display: inline-block;width: 10px; color: transparent'>" + i + "</span>" +
                                "<span style='display: inline-block;'>" + params[i].seriesName + "</span>" +
                                "<span style='display: inline-block;width: 40px;position: relative;top: -4px; margin: 0 60px 0 4px; border-top: 2px " + lineType[Math.floor(i / ($('.body .selection-item[currentColor]').length + 1))] + " #fff'></span>" +
                                "<span style='padding-left: 30px; position: absolute; right: 10px; top: 2px;'>" + params[i].value + "元</span>" +
                                "</p>";
                        }
                       
                    }
                    relVal += "<div class='simulation-parent'></div>";
                    return relVal;
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            toolbox: {
                feature: {
                    //saveAsImage: {}
                }
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                axisLine: {
                    lineStyle: {
                        color: '#999'
                    }
                },
                data: ['0时', '1时', '2时', '3时', '4时', '5时', '6时', '7时', '8时', '9时', '10时', '11时', '12时', '13时', '14时', '15时', '16时', '17时', '18时', '19时', '20时', '21时', '22时', '23时', '24时']
            },
            yAxis: {
                type: 'value',
                axisLine: {
                    lineStyle: {
                        color: '#999'
                    }
                },
            },
            series: []
        }
        graph1.setOption(option, true)
        if ($('.data_num .active').length > 0) {
            graph1.setOption({
                title: {
                    text: '分时数据图（次）'
                }
            })
        } else if ($('.data_rate .active').length > 0) {
            graph1.setOption({
                title: {
                    text: '分时数据图（%）'
                }
            })
        } else if ($('.data_yuan .active').length > 0) {
            graph1.setOption({
                title: {
                    text: '分时数据图（元）'
                }
            })
        } else {
            graph1.setOption({
                title: {
                    text: '分时数据图'
                }
            })
        }
        graph1.setOption({
            series: graphData
        })
    }

    function renderGraph2(graphData) {
        // 基于准备好的dom，初始化echarts实例
        var graph2 = echarts.init(document.getElementById('fold_line_diagram2'));

        // 指定图表的配置项和数据
        var option = {
            title: {
                text: '总'
            },
            tooltip: {
                enterable: true,
                trigger: 'axis'
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            toolbox: {
                feature: {
                    //saveAsImage: {}
                }
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                axisLine: {
                    lineStyle: {
                        color: '#999'
                    }
                },
                data: ['0时', '1时', '2时', '3时', '4时', '5时', '6时', '7时', '8时', '9时', '10时', '11时', '12时', '13时', '14时', '15时', '16时', '17时', '18时', '19时', '20时', '21时', '22时', '23时', '24时']
            },
            yAxis: {
                type: 'value',
                axisLine: {
                    lineStyle: {
                        color: '#999'
                    }
                },
            },
            series: []
        }
        graph2.setOption(option, true)
        graph2.setOption({
            series: graphData
        })
    }

    // 数据列表的相关数据和方法（上部）
    window.DataGraph1 = {
        // 线条数量
        lineNum: 3,
        // 所有颜色
        allColors: ['#ffbc34', '#36bea6', '#f62d51', '#5898d7', '#b855d8', '#da2b92', '#9acf5b', '#ce8238', '#4cd6e6', '#d1ef28'],
        // 选中（占用）了的颜色
        selectedColors: [],
        // 数据图表1
        graphData1: {
            adExposure: [],
            clickCharge: [],
            transformPV: [],
            clickRate: [],
            transformRate: [],
            inCome: []
        },
        // 数据类型：总(0)-分(1)
        total_branch: '0',
        // 交互事件1：选择显示的数据类型（广告主，投放，计划）
        handleDataSwitch1: function () {
            var _this = this
            $('.data-type').click(function () {
                $(this).addClass('btn-primary').siblings().removeClass('btn-primary')
                var dataType = $(this).attr('data-type')
                if (dataType == '1') {
                    $('.data-search .search-s.data-type-name').html('广告主列表')
                } else if (dataType == '2') {
                    $('.data-search .search-s.data-type-name').html('投放列表')
                } else if (dataType == '3') {
                    $('.data-search .search-s.data-type-name').html('计划列表')
                } 
                DataGraph2._getData1()
            })
        },
        // 交互事件2：选择显示的数据类型（次数：广告曝光，计费点击，转化PV； 率：点击率，转化率， 元：消耗）
        handleDataSwitch2: function () {
            var _this = this
            $('.data_num').on('click', '.data_item_i', function () {
                $('.data-graph1 .line-type .line-type-i.line-rate').hide()
                $('.data-graph1 .line-type .line-type-i.line-yuan').hide()
                $('.data_rate .data_item_i').removeClass('active')
                $('.data_yuan .data_item_i').removeClass('active')
                $(this).toggleClass('active')
                if ($('.data_num .data_item_i.active').length > 0) {
                    $('.data-graph1 .line-type .line-type-i.line-num').show()
                } else {
                    $('.data-graph1 .line-type .line-type-i.line-num').hide()
                }
                _this._reorganizeDataToRender(_this.graphData1, _this._filterData2())
                DataGraph2._getData3()
            })
            $('.data_rate').on('click', '.data_item_i', function () {
                $('.data-graph1 .line-type .line-type-i.line-num').hide()
                $('.data-graph1 .line-type .line-type-i.line-yuan').hide()
                $('.data_num .data_item_i').removeClass('active')
                $('.data_yuan .data_item_i').removeClass('active')
                $(this).toggleClass('active')
                if ($('.data_rate .data_item_i.active').length > 0) {
                    $('.data-graph1 .line-type .line-type-i.line-rate').show()
                } else {
                    $('.data-graph1 .line-type .line-type-i.line-rate').hide()
                }
                _this._reorganizeDataToRender(_this.graphData1, _this._filterData2())
                DataGraph2._getData3()
            })
            $('.data_yuan').on('click', '.data_item_i', function () {
                $('.data-graph1 .line-type .line-type-i.line-num').hide()
                $('.data-graph1 .line-type .line-type-i.line-rate').hide()
                $('.data_num .data_item_i').removeClass('active')
                $('.data_rate .data_item_i').removeClass('active')
                $(this).toggleClass('active')
                if ($('.data_yuan .data_item_i.active').length > 0) {
                    $('.data-graph1 .line-type .line-type-i.line-yuan').show()
                } else {
                    $('.data-graph1 .line-type .line-type-i.line-yuan').hide()
                }
                _this._reorganizeDataToRender(_this.graphData1, _this._filterData2())
                DataGraph2._getData3()
            })
        },
        // 交互事件3：选择显示的数据类型（媒体。。。  广告位。。。）
        handleDataSwitch3: function () {
            var allColors = this.allColors
            var _this = this
            $('.body').on('click', '.selection-item', function (e) {
                var lineNum = _this.lineNum
                if (_this.selectedColors.length === lineNum && !$(this).attr('currentColor')) {
                    alert('广告位最多可选择3个')
                    return
                }
                if ($(this).attr('currentColor')) {
                    _this.selectedColors.remove($(this).attr('currentColor'))
                    $(this).css('backgroundColor', '#eaeaea')
                    $(this).parent().parent().css('color', '#666')
                    $(this).removeAttr('currentColor')
                } else {
                    var nextColor = ''
                    for (var i = 0; i < allColors.length; i++) {
                        if (_this.selectedColors.indexOf(allColors[i]) == -1) {
                            nextColor = allColors[i]
                            break
                        }
                    }
                    _this.selectedColors.push(nextColor)
                    $(this).css('backgroundColor', nextColor)
                    $(this).parent().parent().css('color', nextColor)
                    $(this).attr('currentColor', nextColor)
                }
                _this._reorganizeDataToSend()
            })
            $('.medias-ads.select-all').on('click', function () {
                var unselectedColors = []
                if ($(this).hasClass('active') || _this.selectedColors.length == _this.lineNum) {
                    $(this).removeClass('active')
                    _this.selectedColors = []
                    $('.body .selection-item').css('background-color', '#eaeaea')
                    $('.body .media_ads-item').css('color', '#666')
                    $('.body .selection-item').removeAttr('currentColor')
                } else {
                    $(this).addClass('active')
                    for (var i = 0; i < allColors.length; i++) {
                        if (_this.selectedColors.indexOf(allColors[i]) == -1 && unselectedColors.length < (_this.lineNum - _this.selectedColors.length)) {
                            unselectedColors.push(allColors[i])
                        }
                    }
                    var sLength = _this.selectedColors.length
                    unselectedColors.forEach(function (item, i) {
                        $('.body .selection-item').each(function (eIndex, eItem) {
                            if (!$(eItem).attr('currentColor')) {
                                $(eItem).css('background-color', item)
                                $(eItem).attr('currentColor', item)
                                $(eItem).parent().parent().css('color', item)
                                return false
                            }
                        })
                        _this.selectedColors.unshift(item)
                    })
                    unselectedColors = []
                }
                _this._reorganizeDataToSend()
            })
        },
        // 交互事件4：选择显示的数据类型（总，分）
        handleDataSwitch4: function () {
            var _this = this
            $('.total-branch').on('click', '.total-branch-item .glyphicon-ok', function () {
                if ($(this).parent().hasClass('selected')) {
                    return
                } else {
                    $(this).parent().addClass('selected').siblings('.total-branch-item').removeClass('selected')
                    _this.total_branch = $(this).attr('total-branch')
                    _this._reorganizeDataToRender(_this.graphData1, _this._filterData2())
                }
            })
        },
        // 筛选数据2：次数，率
        _filterData2: function () {
            var data_to_show = []
            $('.data_item_i.active').each(function (index, item) {
                data_to_show.push($(item).attr('data-type2'))
            })
            return data_to_show
        },
        // 渲染媒体和广告主列表
        _renderMediaAds: function () {
            var id = $('.data-graph2 .left-part .tBody .select-btn.selected').attr('data-id')
            DataGraph2._getData2(id)
        },
        // 整理请求数据需要的参数
        _reorganizeDataToSend: function (datatype) {
            var dataToSend = {
                mediaIds: '',
                adsIds: '',
                dataType: parseInt(datatype) || 1
            }
            var _this = this
            var mediaArr = []
            var adsArr = []
            $('.body .selection-item[data-type=0][currentColor]').each(function (index, item) {
                mediaArr.push($(item).attr('data-id'))
            })
            $('.body .selection-item[data-type=1][currentColor]').each(function (index, item) {
                adsArr.push($(item).attr('data-id'))
            })
            dataToSend.mediaIds = mediaArr.join(',')
            dataToSend.adsIds = adsArr.join(',')

            _this._getData(dataToSend)  // 向接口请求数据
        },
        // 按需获取数据
        _getDataByNeed: function (sourceArr, type) {
            var ret = []
            var daypartingDataAmount = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
            (sourceArr && sourceArr.length > 0 && sourceArr[0] && sourceArr[0].length > 0) && sourceArr.forEach(function (sItem, sIndex) {
                var dataItem = {
                    name: sItem[0].SourceName,
                    ID: sItem[0].SourceId,
                    daypartingData: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                }
                sItem.forEach(function (tItem, tIndex) {
                    dataItem.daypartingData[tItem.Hour] = tItem[type]
                    daypartingDataAmount[tItem.Hour] += tItem[type]
                    daypartingDataAmount[tItem.Hour] = Number(daypartingDataAmount[tItem.Hour].toFixed(2))
                })
                ret.push(dataItem)
            })
            ret.push({
                name: '总量',
                ID: 0,
                daypartingData: daypartingDataAmount
            })
            return ret
        },
        // 请求左上角折线图数据数据
        _getData: function (params) {
            var _this = this
            var data = {
                PutOnSourceId: params.adsIds,
                date: $('.date-time').val(),
                DataType: parseInt($('.data-type.btn-primary').attr('data-type')),
                Id: parseInt($('.select-btn.selected').attr('data-id'))
            }
            $.post('/IAD_DataGraph/GetIadHourDataAPI', data, function (res) {
                var adsSelected = []
                var userInfoApiModel1 = JSON.parse(JSON.stringify(res.userInfoApiModel))
                $('.media_ads-item .medias-ads[currentColor]').each(function (index, item) {
                    adsSelected.push({
                        id: parseInt($(item).attr('data-id')),
                        name: $(item).parent().siblings('.media-or-ads-name').html()
                    })
                })
                userInfoApiModel1.forEach(function (item, index) {
                    adsSelected.forEach(function (adsIitem, adsIndex) {
                        if (item.SourceId == adsIitem.id) {
                            adsSelected.splice(adsIndex, 1)
                        }
                    })
                })
                if (adsSelected.length > 0) {
                    adsSelected.forEach(function (item, index) {
                        userInfoApiModel1.push({
                            CTR: 0,
                            CVR: 0,
                            ClickPvCount: 0,
                            ExposureCount: 0,
                            SourceId: item.id,
                            InCome: 0,
                            SourceName: item.name,
                            TransferPvCount: 0
                        })
                    })
                }
                var medias_ads_arr = []
                var prev_id = 0
                var medias_ads_i = -1
                userInfoApiModel1.forEach(function (item, index) {
                    if (prev_id == item.SourceId) {
                        medias_ads_arr[medias_ads_i].push(item)
                    } else {
                        prev_id = item.SourceId
                        medias_ads_i++
                        medias_ads_arr[medias_ads_i] = []
                        medias_ads_arr[medias_ads_i].push(item)
                    }
                })

                _this.graphData1 = {
                    adExposure: _this._getDataByNeed(medias_ads_arr, 'ExposureCount'),
                    clickCharge: _this._getDataByNeed(medias_ads_arr, 'ClickPvCount'),
                    transformPV: _this._getDataByNeed(medias_ads_arr, 'TransferPvCount'),
                    clickRate: _this._getDataByNeed(medias_ads_arr, 'CTR'),
                    transformRate: _this._getDataByNeed(medias_ads_arr, 'CVR'),
                    inCome: _this._getDataByNeed(medias_ads_arr, 'InCome')
                }
                _this._reorganizeDataToRender(_this.graphData1, _this._filterData2())
            })
           
        },
        // 重组要渲染的数据
        _reorganizeDataToRender: function (params, dataType) {   // 整理要渲染的数据
            var colorRecord = []
            // 把数据按颜色整理出来
            $('.body .selection-item[currentColor]').each(function (index, item) {
                var ele = {
                    id: $(item).attr('data-id'),
                    color: $(item).attr('currentColor')
                }
                colorRecord.push(ele)
            })
            function findColor(id) {
                for (var i = 0; i < colorRecord.length; i++) {
                    if (id == colorRecord[i].id) {
                        return colorRecord[i].color
                    }
                }
            }
            var graphData = []
            dataType = dataType || []

            if (this.total_branch == '0') {
                if (dataType.indexOf('0') > -1) {
                    params.adExposure.forEach(function (item, index) {
                        var color = findColor(item.ID)
                        var dataItem = {
                            name: item.name,
                            smonth: 0.3,
                            type: 'line',
                            stack: color + 0 || '#5798d7' + 0,
                            data: item.daypartingData,
                            itemStyle: {
                                normal: {
                                    color: item.name == '总量' ? '#5798d7' : 'transparent',
                                    lineStyle: {
                                        color: item.name == '总量' ? '#5798d7' : 'transparent',
                                        type: 'solid'
                                    }
                                }
                            }
                        }
                        graphData.push(dataItem)
                    })
                }
                if (dataType.indexOf('1') > -1) {
                    params.clickCharge.forEach(function (item, index) {
                        var color = findColor(item.ID)
                        var dataItem = {
                            name: item.name,
                            type: 'line',
                            stack: color + 1 || '#5798d7' + 1,
                            data: item.daypartingData,
                            itemStyle: {
                                normal: {
                                    color: item.name == '总量' ? '#5798d7' : 'transparent',
                                    color1: color || '#5798d7',
                                    lineStyle: {
                                        color: item.name == '总量' ? '#5798d7' : 'transparent',
                                        type: 'dashed'
                                    }
                                }
                            }
                        }
                        graphData.push(dataItem)
                    })

                }
                if (dataType.indexOf('2') > -1) {
                    params.transformPV.forEach(function (item, index) {
                        var color = findColor(item.ID)
                        var dataItem = {
                            name: item.name,
                            type: 'line',
                            stack: color + 2 || '#5798d7' + 2,
                            data: item.daypartingData,
                            itemStyle: {
                                normal: {
                                    color: item.name == '总量' ? '#5798d7' : 'transparent',
                                    color1: color || '#5798d7',
                                    lineStyle: {
                                        color: item.name == '总量' ? '#5798d7' : 'transparent',
                                        type: 'dotted'
                                    }
                                }
                            }
                        }
                        graphData.push(dataItem)
                    })
                }
                if (dataType.indexOf('3') > -1) {
                    params.clickRate.forEach(function (item, index) {
                        var color = findColor(item.ID)
                        var dataItem = {
                            name: item.name,
                            type: 'line',
                            stack: color + 3 || '#5798d7' + 3,
                            data: item.daypartingData,
                            itemStyle: {
                                normal: {
                                    color: item.name == '总量' ? '#5798d7' : 'transparent',
                                    color1: color || '#5798d7',
                                    lineStyle: {
                                        color: item.name == '总量' ? '#5798d7' : 'transparent',
                                        type: 'solid'
                                    }
                                }
                            }
                        }
                        graphData.push(dataItem)
                    })
                }
                if (dataType.indexOf('4') > -1) {
                    params.transformRate.forEach(function (item, index) {
                        var color = findColor(item.ID)
                        var dataItem = {
                            name: item.name,
                            type: 'line',
                            stack: color + 4 || '#5798d7' + 4,
                            data: item.daypartingData,
                            itemStyle: {
                                normal: {
                                    color: item.name == '总量' ? '#5798d7' : 'transparent',
                                    color1: color || '#5798d7',
                                    lineStyle: {
                                        color: item.name == '总量' ? '#5798d7' : 'transparent',
                                        type: 'dashed'
                                    }
                                }
                            }
                        }
                        graphData.push(dataItem)
                    })
                }
                if (dataType.indexOf('5') > -1) {
                    params.inCome.forEach(function (item, index) {
                        var color = findColor(item.ID)
                        var dataItem = {
                            name: item.name,
                            type: 'line',
                            stack: color + 5 || '#5798d7' + 5,
                            data: item.daypartingData,
                            itemStyle: {
                                normal: {
                                    color: item.name == '总量' ? '#5798d7' : 'transparent',
                                    color1: color || '#5798d7',
                                    lineStyle: {
                                        color: item.name == '总量' ? '#5798d7' : 'transparent',
                                        type: 'solid'
                                    }
                                }
                            }
                        }
                        graphData.push(dataItem)
                    })
                }
            } else {
                if (dataType.indexOf('0') > -1) {
                    params.adExposure.forEach(function (item, index) {
                        var color = findColor(item.ID)
                        var dataItem = {
                            name: item.name,
                            type: 'line',
                            stack: color + 0 || '#5798d7' + 0,
                            data: item.daypartingData,
                            itemStyle: {
                                normal: {
                                    color: item.name == '总量' ? 'transparent' : color,
                                    lineStyle: {
                                        color: item.name == '总量' ? 'transparent' : color,
                                        type: 'solid'
                                    }
                                }
                            }
                        }
                        graphData.push(dataItem)
                    })
                }
                if (dataType.indexOf('1') > -1) {
                    params.clickCharge.forEach(function (item, index) {
                        var color = findColor(item.ID)
                        var dataItem = {
                            name: item.name,
                            type: 'line',
                            stack: color + 1 || '#5798d7' + 1,
                            data: item.daypartingData,
                            itemStyle: {
                                normal: {
                                    color: item.name == '总量' ? 'transparent' : color,
                                    lineStyle: {
                                        color: item.name == '总量' ? 'transparent' : color,
                                        type: 'dashed'
                                    }
                                }
                            }
                        }
                        graphData.push(dataItem)
                    })

                }
                if (dataType.indexOf('2') > -1) {
                    params.transformPV.forEach(function (item, index) {
                        var color = findColor(item.ID)
                        var dataItem = {
                            name: item.name,
                            type: 'line',
                            stack: color + 2 || '#5798d7' + 2,
                            data: item.daypartingData,
                            itemStyle: {
                                normal: {
                                    color: item.name == '总量' ? 'transparent' : color,
                                    lineStyle: {
                                        color: item.name == '总量' ? 'transparent' : color,
                                        type: 'dotted'
                                    }
                                }
                            }
                        }
                        graphData.push(dataItem)
                    })
                }
                if (dataType.indexOf('3') > -1) {
                    params.clickRate.forEach(function (item, index) {
                        var color = findColor(item.ID)
                        var dataItem = {
                            name: item.name,
                            type: 'line',
                            stack: color + 3 || '#5798d7' + 3,
                            data: item.daypartingData,
                            itemStyle: {
                                normal: {
                                    color: item.name == '总量' ? 'transparent' : color,
                                    lineStyle: {
                                        color: item.name == '总量' ? 'transparent' : color,
                                        type: 'solid'
                                    }
                                }
                            }
                        }
                        graphData.push(dataItem)
                    })
                }
                if (dataType.indexOf('4') > -1) {
                    params.transformRate.forEach(function (item, index) {
                        var color = findColor(item.ID)
                        var dataItem = {
                            name: item.name,
                            type: 'line',
                            stack: color + 4 || '#5798d7' + 4,
                            data: item.daypartingData,
                            itemStyle: {
                                normal: {
                                    color: item.name == '总量' ? 'transparent' : color,
                                    lineStyle: {
                                        color: item.name == '总量' ? 'transparent' : color,
                                        type: 'dashed'
                                    }
                                }
                            }
                        }
                        graphData.push(dataItem)
                    })
                }
                if (dataType.indexOf('5') > -1) {
                    params.inCome.forEach(function (item, index) {
                        var color = findColor(item.ID)
                        var dataItem = {
                            name: item.name,
                            type: 'line',
                            stack: color + 5 || '#5798d7' + 5,
                            data: item.daypartingData,
                            itemStyle: {
                                normal: {
                                    color: item.name == '总量' ? 'transparent' : color,
                                    lineStyle: {
                                        color: item.name == '总量' ? 'transparent' : color,
                                        type: 'solid'
                                    }
                                }
                            }
                        }
                        graphData.push(dataItem)
                    })
                }
            }
            renderGraph1(graphData)
        },
        // 初始化图表的各种事件
        _init: function () {
            this.handleDataSwitch1()
            this.handleDataSwitch2()
            this.handleDataSwitch3()
            this.handleDataSwitch4()
            this._reorganizeDataToSend($('.data-type.btn.btn-primary').attr('data-type'))
        }
    }
    DataGraph1._init()

    // 数据列表的相关数据和方法（下部）
    window.DataGraph2 = {
        // 折线图2的数据
        graphData: {
            adExposure: [],
            clickCharge: [],
            transformPV: [],
            clickRate: [],
            transformRate: [],
            inCome: []
        },
        // 处理数据类型变化
        handleDataTypeChange: function () {
            var _this = this
            $('.data-graph2 .tBody tbody').on('click', '.select-btn', function () {
                if ($(this).hasClass('selected')) {
                    return
                } else {
                    $('.data-graph2 .tBody tbody .select-btn').removeClass('selected')
                    $(this).addClass('selected')
                    _this._getData2($(this).attr('data-id'))
                    _this._getData3()
                }
            })
        },
        // 处理数据搜索
        handleDataSearch: function () {
            var _this = this
            $('.data-search .search-s.glyphicon-search').click(function () {
                _this._getData1()
            })
            $('.search-s.search-frame').keypress(function (e) {
                if (e.keyCode == "13") {
                    _this._getData1()
                }
            })
        },
        // 处理数据导出
        handleDataExport: function () {
            $('#exportDataOfCurrent').click(function () {
                var DataType = $('.data-type.btn-primary').attr('data-type')
                var Date = $('.search-s.date-time').val()
                var Id = $('.select-btn.selected').attr('data-id')
                window.location.href = '/IAD_DataGraph/ExportCurrentAPI?DataType=' + DataType + '&Date=' + Date + '&Id=' + Id
                $('.shield-box').fadeOut(300)
            })
            $('#exportDataOfAll').click(function () {
                var DataType = $('.data-type.btn-primary').attr('data-type')
                var Date = $('.search-s.date-time').val()
                window.location.href = '/IAD_DataGraph/ExportAllAPI?DataType=' + DataType + '&Date=' + Date + '&SearchId=0&Name='
                $('.shield-box').fadeOut(300)
            })
        },
        // 渲染列表数据
        _renderListData: function (dataList) {
            var htmlStr = template('table_data', { list: dataList})
            $('.data-graph2 .tBody tbody').html(htmlStr)
            DataGraph1._renderMediaAds()
            this._getData3()
        },
        // 渲染媒体和广告位列表
        _renderMediaAdsContent: function (dataList) {
            var medias_ads = template('medias_ads', { list: dataList })
            $('.data-graph1 .right-part .body').html(medias_ads)
            var ele = $('.medias-ads.selection-item')[0]
            $(ele).css('backgroundColor', '#ffbc34')
            $(ele).parent().parent().css('color', '#ffbc34')
            $(ele).attr('currentColor', '#ffbc34')
            DataGraph1.selectedColors = ['#ffbc34']
            DataGraph1._reorganizeDataToSend()
        },
        // 重组需要折线图2渲染的数据
        _reorganizeDataToRender: function (params) {
            var dataType = []
            $('.data_item_i.active').each(function (index, item) {
                dataType.push($(item).attr('data-type2'))
            })
            var graphData = []
            if (dataType.indexOf('0') > -1) {
                var dataItem = {
                    name: '广告曝光',
                    type: 'line',
                    stack: '#5798d7' + 0,
                    data: params.adExposure[1] ? params.adExposure[1].daypartingData : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                    itemStyle: {
                        normal: {
                            color: '#5798d7',
                            lineStyle: {
                                color: '#5798d7',
                                type: 'solid'
                            }
                        }
                    }
                }
                graphData.push(dataItem)
            }
            if (dataType.indexOf('1') > -1) {
                var dataItem = {
                    name: '计费点击',
                    type: 'line',
                    stack: '#5798d7' + 1,
                    data: params.clickCharge[1] ? params.clickCharge[1].daypartingData : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                    itemStyle: {
                        normal: {
                            color: '#5798d7',
                            lineStyle: {
                                color: '#5798d7',
                                type: 'dashed'
                            }
                        }
                    }
                }
                graphData.push(dataItem)
            }
            if (dataType.indexOf('2') > -1) {
                var dataItem = {
                    name: '转化PV',
                    type: 'line',
                    stack: '#5798d7' + 2,
                    data: params.transformPV[1] ? params.transformPV[1].daypartingData : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                    itemStyle: {
                        normal: {
                            color: '#5798d7',
                            lineStyle: {
                                color: '#5798d7',
                                type: 'dotted'
                            }
                        }
                    }
                }
                graphData.push(dataItem)
            }
            if (dataType.indexOf('3') > -1) {
                var dataItem = {
                    name: '点击率',
                    type: 'line',
                    stack: '#5798d7' + 3,
                    data: params.clickRate[1] ? params.clickRate[1].daypartingData : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                    itemStyle: {
                        normal: {
                            color: '#5798d7',
                            lineStyle: {
                                color: '#5798d7',
                                type: 'solid'
                            }
                        }
                    }
                }
                graphData.push(dataItem)
            }
            if (dataType.indexOf('4') > -1) {
                var dataItem = {
                    name: '转化率',
                    type: 'line',
                    stack: '#5798d7' + 4,
                    data: params.transformRate[1] ? params.transformRate[1].daypartingData : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                    itemStyle: {
                        normal: {
                            color: '#5798d7',
                            lineStyle: {
                                color: '#5798d7',
                                type: 'dashed'
                            }
                        }
                    }
                }
                graphData.push(dataItem)
            }
            if (dataType.indexOf('5') > -1) {
                var dataItem = {
                    name: '消耗',
                    type: 'line',
                    stack: '#5798d7' + 5,
                    data: params.inCome[1] ? params.inCome[1].daypartingData : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                    itemStyle: {
                        normal: {
                            color: '#5798d7',
                            lineStyle: {
                                color: '#5798d7',
                                type: 'solid'
                            }
                        }
                    }
                }
                graphData.push(dataItem)
            }
            if (dataType.length === 0) {
                var dataItem = {
                    name: '点击率*70% + 转化率*30%',
                    type: 'line',
                    stack: '#5798d7' + 5,
                    data: params.ctrCvrSum[1] ? params.ctrCvrSum[1].daypartingData : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                    itemStyle: {
                        normal: {
                            color: '#5798d7',
                            lineStyle: {
                                color: '#5798d7',
                                type: 'solid'
                            }
                        }
                    }
                }
                graphData = dataItem
            }
            renderGraph2(graphData)
        },
        // 请求数据1
        _getData1: function () {
            var _this = this
            var params = {
                DataType: parseInt($('.data-type.btn-primary').attr('data-type')),
                Date: $('.date-time').val(),
                SearchId: 0,
                Name: ''
            }
            var keyWords = $('.search-s.search-frame').val()
            if (/^\d+$/.test(keyWords)) {
                params.SearchId = parseInt(keyWords)
            } else {
                params.Name = keyWords
            }
            $.post('/IAD_DataGraph/PutOnAPI ', params, function (res) {
                _this._renderListData(res.putOnIdApiModel)
            })
        },
        // 请求数据2
        _getData2: function (id) {
            var _this = this
            var params = {
                DataType: parseInt($('.form-group .btn.btn-primary').attr('data-type')),
                Id: parseInt(id),
                Date: $('.date-time').val()
            }
            $.post('/IAD_DataGraph/GetUserListAPI', params, function (res) {
                _this._renderMediaAdsContent(res.userInfoApiModel)
            })
        },
        // 获取数据3（右下角折线图数据）
        _getData3: function () {
            var type = $('.data_item_i.active').attr('data2')
            var _this = this
            var params = {
                DataType: parseInt($('.form-group .btn.btn-primary').attr('data-type')),
                Id: parseInt($('.select-btn.selected').attr('data-id')),
                Date: $('.date-time').val()
            }
            $.post('/IAD_DataGraph/putOnIadHourAPI', params, function (res) {
                if (res) {
                    _this.graphData = {
                        adExposure: DataGraph1._getDataByNeed([res.putOnIdModel], 'ExposureCount'),
                        clickCharge: DataGraph1._getDataByNeed([res.putOnIdModel], 'ClickPvCount'),
                        transformPV: DataGraph1._getDataByNeed([res.putOnIdModel], 'TransferPvCount'),
                        clickRate: DataGraph1._getDataByNeed([res.putOnIdModel], 'CTR'),
                        transformRate: DataGraph1._getDataByNeed([res.putOnIdModel], 'CVR'),
                        inCome: DataGraph1._getDataByNeed([res.putOnIdModel], 'InCome'),
                        ctrCvrSum: DataGraph1._getDataByNeed([res.putOnIdModel], 'CtrCvrSum')
                    }
                } else {
                    _this.graphData = {
                        adExposure: [],
                        clickCharge: [],
                        transformPV: [],
                        clickRate: [],
                        transformRate: [],
                        inCome: [],
                        ctrCvrSum: []
                    }
                }
                _this._reorganizeDataToRender(_this.graphData)
            })
        },
        // 初始化下半部分的事件
        _init: function () {
            this._getData1(1)
            this.handleDataTypeChange()
            this.handleDataSearch()
            this.handleDataExport()
        }
    }
    DataGraph2._init()
})