<template>
  <div class="realData" ref="chart">
    <div class="optionLine">
        <span>应用：</span>
            <a-select default-value="0" style="width: 150px" @change="APPChange">
                    <a-select-option value="0">全部</a-select-option>
                    <a-select-option v-for="(item,index) in optionArr" :key='index' :value='item.id'>{{item.name}}</a-select-option>                  
            </a-select>
            
    </div>
    <div class="tabchange">
      <a-tabs default-active-key="click" @change="callback">
        <a-tab-pane key="click" tab="点击数"></a-tab-pane>
        <a-tab-pane key="active" tab="激活" force-render></a-tab-pane>
        <a-tab-pane key="rate" tab="激活率"></a-tab-pane>
      </a-tabs>
    </div>
    <div id="echart" style="width:100%;height:400px"></div>
    <div class="duibishiduan">
      <p>
        <a-button type="primary" @click="openDate" v-clickoutside="handleClose" >对比时段</a-button>
      </p>
      <div class="dateDiv">
        <a-date-picker @change="dateChange" v-show="dateOpen" :open='dateOpen' :disabled-date="disabledDate"  />
      </div>
    </div>

    <a-table
      :columns="columns"
      :data-source="dataSource"
      tableLayout="auto"
      bordered
      :pagination="false"
    ></a-table>
  </div>
</template>

<script>
import moment from 'moment'
import { getAction, postAction, downFile, downFilePost } from '@/api/manage'
// 引入基本模板
var echarts = require('echarts')
// 引入柱状图组件
require('echarts/lib/chart/bar')
require('echarts/lib/chart/pie')
require('echarts/lib/chart/line')
// 引入提示框和title组件
require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')
require('echarts/lib/component/graphic')
require('echarts/lib/component/toolbox')
require('echarts/lib/component/legend')

const clickoutside = {
  // 初始化指令
  bind(el, binding, vnode) {
    function documentHandler(e) {
      // 这里判断点击的元素是否是本身，是本身，则返回
      if (el.contains(e.target)) {
        return false
      }
      // 判断指令中是否绑定了函数
      if (binding.expression) {
        // 如果绑定了函数 则调用那个函数，此处binding.value就是handleClose方法
        binding.value(e)
      }
    }
    // 给当前元素绑定个私有变量，方便在unbind中可以解除事件监听
    el.__vueClickOutside__ = documentHandler
    document.addEventListener('click', documentHandler)
  },
  update() {},
  unbind(el, binding) {
    // 解除事件监听
    document.removeEventListener('click', el.__vueClickOutside__)
    delete el.__vueClickOutside__
  }
}


let columns = [
  {
    title: '',
    dataIndex: 'hour',
    // scopedSlots: { customRender: 'date' },
    width:200,
    align: 'center'
  },
  {
    title: '今天',
    key: 'today',
    dataIndex: 'today',
    // scopedSlots: { customRender: 'date' },
    align: 'center'
  },
  {
    title: '昨天',
    key: 'yesterday',
    dataIndex: 'yesterday',
    // scopedSlots: { customRender: 'date' },
    align: 'center'
  },
  {
    title: '7天前',
    key: 'sevendaysAgo',
    dataIndex: 'sevendaysAgo',
    // scopedSlots: { customRender: 'date' },
    align: 'center'
  }
]
let option = {
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['今天', '昨天', '七天前']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },

  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00','07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00','19:00', '20:00', '21:00', '22:00', '23:00']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '今天',
      type: 'line',
    //   stack: '总量',//可以显示成堆叠图
      data: []
    },
    {
      name: '昨天',
      type: 'line',
      data: []
    },
    {
      name: '七天前',
      type: 'line',
      data: []
    },
    {
      name: '',
      type: 'line',
      data: []
    },
    {
      name: '',
      type: 'line',
      data: []
    }
  ]
}
export default {
    directives: { clickoutside },
  data() {
    return {
 
        //应用下拉选择框的
        optionArr:[],
        APPID:'', 
      //表格参数
      dataSource: [],
      loading: false,
      columns,
      //下拉选择框的参数
      selectValue: 'all',
      //时间选择器的显示隐藏按钮
      dateOpen: false,

      dateStr: [] ,//字符串类型的日期
      //tab切换的参数、
      tabKey:'click',

      //echart的参数
      option,
    }
  },
  methods: {
    moment,
    disabledDate(current) {
      // console.log(current)

      return current && current > moment().subtract(1, 'day')
    },
    //应用选择
        APPChange(value){
            this.APPID=value;
            this.HttpPost().then(item=>{
                this.getEchartData()
            })
        },

    //tab切换的事件
    callback(key) {
        console.log(key)
        this.tabKey=key;
        this.HttpPost().then(item=>{
            this.getEchartData()
        })
    },

    
    //打开对比时间的按钮
    openDate() {
      this.dateOpen = true
    },
    //点击其他地方关闭
    handleClose(){
        this.dateOpen = false
    },
    //日期发生变化时
    dateChange(date, dateString) {
      this.dateOpen = false;
      if(this.dateStr.length<2){
          this.dateStr.push(dateString)
      }else{
          this.dateStr.splice(0,1)
          this.dateStr.push(dateString)
      }
      let addCol=[]
     addCol =  this.dateStr.map((item,index)=>{
         return {               
            title: `${item}`,
            key: `${item}`,
            dataIndex:`${item}`,
            // scopedSlots: { customRender: 'date' },
            align: 'center' 
          }
      })
        this.columns=[...columns,...addCol]
        //修改echart的数据项
        this.option.legend.data=[...option.legend.data,...this.dateStr]
        console.log(this.dateStr)
        this.HttpPost().then(item=>{
            this.getEchartData()
        })
    },
    //获取echart的值
    getEchartData() {
        console.log('echart')
      const chart = this.$refs.chart
      if (chart) {
        const myChart = echarts.init(document.getElementById('echart'))

        myChart.setOption(this.option)
        window.addEventListener('resize', function() {
          myChart.resize()
        })
      }
    },
    //处理echart的数据
    echartHandle(res){
        if(this.dateStr.length>0){
              this.dateStr.map((item,index)=>{
                  this.option.series[index+3].name=item
              })
        }  

        this.option.series.map((item)=>{
            item.data=[]
        })
        //处理this.option.series.data数据
        
        res.map((item,index)=>{
            this.option.series[0].data.push(item.today)
            this.option.series[1].data.push(item.yesterday)
            this.option.series[2].data.push(item.sevendaysAgo);
            if(this.dateStr.length==1){
                this.option.series[3].data.push(item[this.dateStr[0]]);
            }else if(this.dateStr.length==2){
               this.option.series[3].data.push(item[this.dateStr[0]]);
               this.option.series[4].data.push(item[this.dateStr[1]]);
            }
        })
        
        console.log(this.option.series)
    },
    HttpPost(){
    return new Promise((resolve,reject)=>{
     postAction('/pangolin/api/realtime', {       
        
        type:this.tabKey,
        compareTime1:this.dateStr[0],
        compareTime2:this.dateStr[1],
        appId:this.APPID
      }).then(res => {
        console.log(res)
        if (res.success) {
          this.loading = false
          let total={
              key:'zongji',
              today:0,
              yesterday:0,
              sevendaysAgo:0,
              hour:'总计'
          }
          if(this.dateStr.length>0){
              this.dateStr.map((item,index)=>{
                  total[item]=0
              })
          }
          res.data.map((item, index) => {
            item.key = index;
            total.today+=item.today;
            total.yesterday+=item.yesterday;
            total.sevenDaysAgo+=item.sevenDaysAgo;
            if(this.dateStr.length==1){
                total[this.dateStr[0]] += item[this.dateStr[0]]
            }else if(this.dateStr.length==2){
                total[this.dateStr[0]] += item[this.dateStr[0]]
                total[this.dateStr[1]] += item[this.dateStr[1]]
            } 
            

            if(item.hour<10){
                item.hour=`0${item.hour}:00~0${item.hour+1}:00`
            }else{
                item.hour=`${item.hour}:00~${item.hour+1}:00`
            } 
          })
            console.log(total)
            this.dataSource =[total,...res.data] ;
            this.echartHandle(res.data);
           
            resolve(res)
        }
      })
})
    },
  
  },
  mounted() {
    //   this.HttpPost()
    
    console.log(this.dateStr)
    this.option.legend.data=[...option.legend.data,...this.dateStr];
    console.log(this.option.legend.data)
    postAction('/pangolin/api/app/list').then(res=>{
            console.log(res)
            if(res.success){
                this.optionArr=res.data
            }
    })
    this.HttpPost().then(item=>{
         this.getEchartData()
    })
  }
}
</script>

<style lang="scss" scoped>
body,
html {
  width: 100%;
  height: 100%;
}
.realData {
  width: 100%;
  height: 100%;
  background: #fff;
  padding: 10px 15px;
}
.optionLine {
  padding: 30px 5px;
  position: relative;
  margin-top: 20px;
  margin-bottom: 15px;
  border: 1px solid #ccc;
  span {
    display: inline-block;
    padding: 0 3px;
  }
 
  .btn {
    position: absolute;
    right: 10px;
    top: 30px;
  }
}
.optionLine:hover {
  border-color: rgb(24, 144, 255);
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.3);
}
.tabchange {
  margin: 20px 5px;
}
.duibishiduan {
  position: relative;
  height: 50px;
  overflow: hidden;
  p {
    position: absolute;
    right: 10px;
    top: 2px;
  }
  .dateDiv {
    position: absolute;
    right: 10px;
    top: 2px;
  }
}
</style>