<template lang="html">
  <div class="detailedDataVue">
    <div class="title">
      选择时间段：
      <input type="text" name="" class="dateInput" placeholder="2017-12-12" id="detailedDataStartTime" readonly>
      <select class="" name="" v-model="startHours" @change="echartsUpdate()">
        <option v-for="n,i in 24" :value="i">{{ i < 10 ? '0' + i : i }}</option>
      </select> 小时 ——
      <input type="text" name="" class="dateInput" placeholder="2017-12-12" id="detailedDataEndTime" readonly>
      <select class="" name="" v-model="endHours" @change="echartsUpdate()">
        <option v-for="n,i in 24" :value="i">{{ i < 10 ? '0' + i : i }}</option>
      </select> 小时
      <select class="" name="" class="method" v-model="method">
        <option value="source">来源</option>
        <option value="tempName">模板</option>
        <option value="type">type</option>
      </select> ：
      <input type="text" name=""
          v-model="methodValue"
          class="channel"
          spellcheck="false"
          @blur="toggle.matchingList = false"
          @focus="searchValue(), toggle.matchingList = true"
          @keyup="searchValue()"
          @keydown.enter="echartsUpdate()">
      <!-- <button type="button" class="btn2" @click="echartsUpdate()">搜索</button> -->
      <ul class="matchingList" v-show="toggle.matchingList">
        <li v-for="n,i in matchingWord" @mousedown="inputToSearch(n)">{{ n }}</li>
      </ul>
    </div>
    <div class="table">
      <div id="myECharts"></div>
      <div class="select">
        单位：
        <select class="" name="" v-model="timeType" @change="echartsUpdate()">
          <option value="day">天</option>
          <option value="hour">小时</option>
        </select>
      </div>
    </div>
  </div>
</template>

<script>
import echarts from 'echarts'
import moment from 'moment'
import _ from 'lodash'
import { bus, requestGetDataByTempName, requestGetSource } from '@/vuex/request.js'

export default {
  data () {
    return {
      myChart: null,
      option: {},
      startTime: (new Date(moment().format('YYYY-MM-DD'))).getTime() - 1000 * 60 * 60 * 24 * 7,
      endTime: (new Date(moment().format('YYYY-MM-DD'))).getTime(),
      startHours: 0,
      endHours: 0,
      colorList: ['#4FCF94', '#F8656B', '#ffbb22', '#4CB1F5', '', '', '', '', '', ''],
      data: [],
      timeType: 'day',
      methodValue: 'IT时报',
      method: 'tempName',
      matchingWord: [],
      toggle: {
        matchingList: false
      }
    }
  },
  mounted () {
    // 自定义日历插件
    let self = this
    setTimeout(() => {
      // startTime
      window.$('#detailedDataStartTime').val(moment(self.startTime).format('YYYY-MM-DD'))
      window.$('#detailedDataStartTime').DatePicker({
        format: 'Y-m-d',
        date: window.$('#detailedDataStartTime').val(),
        current: window.$('#detailedDataStartTime').val(),
        starts: 1,
        position: 'bottom',
        onBeforeShow: function () {
          window.$('#detailedDataStartTime').DatePickerSetDate(window.$('#detailedDataStartTime').val(), true)
        },
        onChange: function (formated, dates) {
          console.log(formated, dates)
          self.startTime = dates.getTime()
          self.echartsUpdate()
          window.$('#detailedDataStartTime').val(formated)
          window.$('#detailedDataStartTime').DatePickerHide()
        }
      })
      // endTime
      window.$('#detailedDataEndTime').val(moment(self.endTime).format('YYYY-MM-DD'))
      window.$('#detailedDataEndTime').DatePicker({
        format: 'Y-m-d',
        date: window.$('#detailedDataEndTime').val(),
        current: window.$('#detailedDataEndTime').val(),
        starts: 1,
        position: 'bottom',
        onBeforeShow: function () {
          window.$('#detailedDataEndTime').DatePickerSetDate(window.$('#detailedDataEndTime').val(), true)
        },
        onChange: function (formated, dates) {
          console.log(formated, dates)
          self.endTime = dates.getTime()
          self.echartsUpdate()
          window.$('#detailedDataEndTime').val(formated)
          window.$('#detailedDataEndTime').DatePickerHide()
        }
      })
    })

    // 初始化 ECharts

    // 基于准备好的dom，初始化echarts实例
    this.myChart = echarts.init(document.getElementById('myECharts'))
    // 指定图表的配置项和数据
    this.option = {
      title: {
        text: '渠道信息数量折线图',
        textStyle: {
          color: '#fff'
        },
        left: 'center',
        top: 10
      },
      tooltip: {},
      toolbox: {
        feature: {
          dataView: {},
          saveAsImage: {
            pixelRatio: 2
          },
          restore: {}
        }
      },
      grid: {
        show: true,
        borderColor: '#515B65',
        left: 60,
        right: 60,
        top: 100
      },
      axisPointer: {
        show: true,
        snap: true,
        triggerTooltip: false,
        lineStyle: {
          type: 'dashed'
        }
      },
      xAxis: {
        type: 'time',
        axisLine: {
          lineStyle: {
            color: '#515B65'
          }
        },
        splitLine: {
          lineStyle: {
            color: '#515B65'
          }
        },
        maxInterval: 3600 * 24 * 1000,
        axisLabel: {
          formatter: () => {}
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          lineStyle: {
            color: '#515B65'
          }
        },
        splitLine: {
          lineStyle: {
            color: '#515B65'
          }
        }
      },
      legend: {
        // data: ['微博', '微信', '网媒'],
        x: 60,
        y: '10%',
        textStyle: {
          color: '#ccc'
        }
        // selected: {
        //   '微博': true,
        //   '微信': true,
        //   '网媒': true
        // }
      },
      series: []
    }
    // 使用刚指定的配置项和数据显示图表。
    setTimeout(() => {
      window.$(window).on('resize', () => { this.myChart.resize() })
    })
    this.echartsUpdate()
  },
  methods: {
    inputToSearch (str) {
      this.methodValue = str
      this.matchingWord = []
      this.echartsUpdate()
    },
    searchValue () {
      let data = {
        method: this.method,
        value: this.methodValue
      }
      requestGetSource({}, data, (response) => {
        if (response.data) {
          if (response.data.state) {
            this.matchingWord = response.data.data
            this.toggle.matchingList = true
          } else {
            // bus.$emit('alert', response.data.message)
            console.log(response.data.message)
          }
        } else {
          // bus.$emit('alert', response + '.')
          console.log(response + '.')
        }
      })
    },
    echartsUpdate () {
      let params = {
        start: 0,
        end: 0,
        timeType: this.timeType,
        method: this.method
      }
      params[this.method] = this.methodValue
      if (this.timeType === 'day') {
        params.start = this.startTime
        params.end = this.endTime
        this.option.xAxis.maxInterval = 1000 * 60 * 60 * 24
        this.option.xAxis.axisLabel.formatter = (n, i) => { return moment(n).format('MM-DD') }
      } else if (this.timeType === 'hour') {
        params.start = this.startTime + this.startHours * 1000 * 60 * 60
        params.end = this.endTime + this.endHours * 1000 * 60 * 60
        this.option.xAxis.maxInterval = 1000 * 60 * 24 * 2
        this.option.xAxis.axisLabel.formatter = (n, i) => { return moment(n).format('HH:00') }
        if (Math.abs(params.start - params.end) > 1000 * 60 * 60 * 24) {
          bus.$emit('alert', '单位为小时则时间段不可超过一天(即：1000 * 60 * 60 * 24 = ' + (1000 * 60 * 60 * 24) + 'ms)(current: ' + (Math.abs(params.start - params.end)) + ')')
          this.timeType = 'day'
          this.option.xAxis.maxInterval = 1000 * 60 * 60 * 24
          this.option.xAxis.axisLabel.formatter = (n, i) => { return moment(n).format('MM-DD') }
          return false
        }
      } else {
        bus.$emit('alert', '选择时间段错误！(Error code: 159)')
        return false
      }
      let data = params
      requestGetDataByTempName(params, data, (response) => {
        if (response.data) {
          if (response.data.state) {
            // 清空
            this.option.legend.data = []
            this.option.legend.selected = {}
            this.option.series = []
            // 赋值
            this.data = response.data.data
            this.option.legend.data.push(this.data.value)
            this.option.legend.selected[this.data.value] = true
            this.option.series.push({
              name: this.data.value,
              type: 'line',
              smooth: true,
              symbolSize: 10,
              itemStyle: {
                normal: {
                  borderWidth: 3,
                  color: this.colorList[0]
                }
              },
              lineStyle: {
                normal: {
                  width: 3,
                  color: this.colorList[0]
                }
              },
              data: _.sortBy(this.data.list, (n) => {
                return moment(n.time)
              }).map((n, i) => {
                return [n.time, n.count]
              })
            })
            this.myChart.setOption(this.option)
          } else {
            bus.$emit('alert', response.data.message)
          }
        } else {
          bus.$emit('alert', response + '.')
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.detailedDataVue{
  padding: 0 50px;
  max-width: 1600px;
  margin: auto;
  .title{
    padding: 15px 0;
    color: #868D93;
    position: relative;
    z-index: 10;
    input, select{
      max-width: 130px;
      height: 33px;
      background-color: #282D33;
      border: 1px solid #525A65;
      color: #4F5762;
      text-align: center;
      background-image: url('~static/img/select_01.png');
      background-repeat: no-repeat;
      background-size: contain;
      background-position: right;
      padding-right: 33px;
      margin-right: 20px;
      &.dateInput{
        margin-right: 0;
        &+select{
          margin-right: 0;
          cursor: pointer;
        }
      }
      &.channel{
        background-image: none;
        text-align: left;
        padding: 3px 6px;
      }
      &.method{
        margin-right: 0;
        margin-left: 40px;
        color: #868D93;
      }
    }
    select{
      position: relative;
      top: -1px;
    }
    &>button{
      letter-spacing: 5px;
    }
    .matchingList{
      position: absolute;
      left: 753px;
      top: 47px;
      background-color: #282D33;
      border: 1px solid #525A65;
      max-height: 500px;
      overflow-y: auto;
      li{
        padding: 5px;
        cursor: pointer;
        transition: all .5s ease;
        max-width: 300px;
        overflow: hidden;
        text-overflow:ellipsis;
        white-space: nowrap;
        &:hover{
          color: #4CB1F5;
          background-color: #525A65;
        }
      }
    }
  }
  .table{
    position: relative;
    .select{
      position: absolute;
      right: 10%;
      top: 60px;
      color: #fff;
      select{
        height: 31px;
        background-color: #000;
        border: 1px solid #394048;
        background-image: url('~static/img/select_02.png');
      }
    }
  }
  #myECharts{
    width: 100%;
    height: 620px;
  }
}
</style>
