<template>
  <div class="realData" ref="chart">
    <div class="optionLine">
        <span>项目选择：</span>
         <a-tree-select
                    v-model="treeValue"
                    style="width: 50%"
                    :tree-data="treeData"
                    tree-checkable
                    :show-checked-strategy="SHOW_PARENT"
                    searchPlaceholder="请选择项目和账户"
                    :allowClear=true
                    @change="treeChange"
                />
            <span>应用选择：</span>
            <a-select v-model="defalutAPP" 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 class="btn">
                <a-button type='primary'  @click="getData">查询</a-button>
            </div>
            
    </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" size="small"  />
      </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'
import { TreeSelect } from 'ant-design-vue';
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
// 引入基本模板
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:'', 
        defalutAPP:'0',
      //表格参数
      dataSource: [],
      loading: false,
      columns,
      //下拉选择框的参数
      selectValue: 'all',
      //时间选择器的显示隐藏按钮
      dateOpen: false,

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

      //echart的参数
      option:JSON.parse(JSON.stringify(option)),

      //treeselect的参数
            treeValue:[],
            treeData:[],
            SHOW_PARENT,
    }
  },

  methods: {
    moment,
    //项目改变后的事件
        treeChange(val){
            this.projectId=[];
            this.accountName=[];
            console.log(val,this.treeValue);
            this.treeValue.forEach((item,index)=>{
                if(parseInt(item)){
                     this.projectId.push(item)
                }else{
                    this.accountName.push(item)
                }
            })
            this.APPID=''
            this.defalutAPP='0'
            this.selectValue='all'
            this.optionArr=[]
            if(this.treeValue.length==0){
                this.optionArr=[]
            }
           postAction('/pangolin/api/app/list',{
                projectId:this.projectId,
                accountName:this.accountName
            }).then(res=>{
                console.log(res)
                if(res.success){
                    this.optionArr=res.data
                }
            })
        },
    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]]);
            }
        })
        this.getEchartData()
        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,
        projectId:this.projectId,
        accountName:this.accountName
      }).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)
            if(this.tabKey!='rate'){
              this.dataSource =[total,...res.data] ;
            }else{
              this.dataSource =[...res.data] ;
            }
            
            this.echartHandle(res.data);
           
            resolve(res)
        }
      })
})
    },
     //项目请求
        accountHttp(){
            postAction('/pangolin/api/memberList',{
                projectId:this.projectId,
                accountName:this.accountName
            }).then(res => {
                
                console.log(res)
                if(res.success){
                    res.data.forEach((element,index) => {
                        this.treeData.push({});
                        this.treeData[index].title=element.projectName;
                        this.treeData[index].value=element.projectId;
                        this.treeData[index].key=element.projectId;
                        this.treeData[index].children=[];
                        element.accountList.forEach((ele,i)=>{
                            this.treeData[index].children.push({});
                             this.treeData[index].children[i].title=ele.accountName;
                             this.treeData[index].children[i].value=ele.accountName;
                             this.treeData[index].children[i].key=ele.accountName;
                        })  
                    }); 
                }
                console.log(this.treeData)
            })
        },
        
        //确定按钮的事件
        getData(){
           
            console.log(this.monthStr,this.selectValue);
            this.loading=true;
            this.HttpPost()
            
        },
  
  },
  
  mounted() {
    //   this.HttpPost()
    
    // console.log(this.dateStr)
    this.option=JSON.parse(JSON.stringify(option))
    // console.log(this.option.legend.data,option,'------------------------------')
    // postAction('/pangolin/api/app/list',{
    //    projectId:this.projectId,
    //   accountName:this.accountName
    // }).then(res=>{
    //         // console.log(res)
    //         if(res.success){
    //             this.optionArr=res.data
    //         }
    // })
    this.HttpPost().then(item=>{
         this.getEchartData()
    })
    this.accountHttp()
  }
}
</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>