<template>
  <box
    componentkey="TrafficCamera"
    title="人流量监测"
  >
    <div
      class="wrapper"
      :class="{ full }"
    >
      <div class="o-detail">
        <div class="choosedate">
          <div class="timeBtn">
            <div class="timeType">
              <div
                class="type__hour type"
                :class="{ active: active === 'hour' }"
                @click="timeType('hour')"
              >
                1小时
              </div>
              <div
                class="type__day type"
                :class="{ active: active === 'day' }"
                @click="timeType('day')"
              >
                1天
              </div>
            </div>
            <el-date-picker
              v-model="datevalue"
              class="datePicker"
              type="datetime"
              placeholder="选择日期时间"
              prefix-icon="el-icon-date"
              format="yyyy-MM-dd HH:mm"
              value-format="yyyy-MM-dd HH:mm:ss"
              size="mini"
              :picker-options="pickerOptions"
              @change="onDateTimeChange()"
            />
          </div>
        </div>

        <div
          :id="'main' + key"
          class="charts"
        />
      </div></div></box>
</template>

<script>
import Box from './Box'
import * as echarts from 'echarts'
import { getCameras } from '@/api/external'
import { getStatistic } from '@/api/camera'

export default {
  components: {
    Box
  },
  props: {
    device: {
      type: Object,
      required: true
    },
    full: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      cameraType: 2,
      datevalue: new Date(),
      active: 'hour', // hour是小时，day是天
      imgUrl: {
        setting: require('@/assets/icon_setting.png'),
        stop: require('@/assets/icon_stop.png'),
        start: require('@/assets/icon_start.png'),
        refresh: require('@/assets/icon_refresh.png')
      },
      settingActive: 0,
      setData: ['分辨率', '帧率', '码流'],
      settingData: [[], [], []],
      settingTab: true,
      settingBshow: false,
      echartsData: [],
      player: null,
      availableParam: {},
      infoData: {},
      videoLoading: false,
      settingDatacopy: [],
      camera: {},
      key: this.full ? 1 : 0,
      pickerOptions: {

        disabledDate (time) {
          return time.getTime() > Date.now()
        }

      }

    }
  },
  mounted () {
    this.timeType(this.active)
    // this.getCameras()
  },
  methods: {
    getCameras () {
      const key = Date.now()
      this.$key = key
      getCameras({
        deviceId: this.device.id,
        cameraType: this.cameraType
      }).then(({ data }) => {
        if (!data.length) {
          return
        }
        if (key === this.$key) {
          data = data.map(({ thirdPartyDevice }) => thirdPartyDevice)
        }
        this.camera = data[0] // 取一个
        this.timeType(this.active)
        // this.getStatistic(
        //   this.getStarttime(new Date(), 'now'),
        //   this.getStarttime(new Date())
        // )
      })
    },
    // getxdata (data) {
    //   const arr = []
    //   data.forEach(item => {
    //     const time = item.eventTime.slice(11, 16)
    //     arr.push(time)
    //   })
    //   return arr
    // },
    // getydata (data) {
    //   const arr = []
    //   data.forEach(item => {
    //     arr.push(item.insidePeopleNum)
    //   })
    //   return arr
    // },
    // mock
    getxdata () {
      if (this.active === 'day') {
        return Array.from({ length: 24 }, (item, index) => `${index + 1}:00`)
      }
      const hour = new Date(this.datevalue).getHours()
      return [`${hour}:15`, `${hour}:30`, `${hour}:45`, `${hour + 1}:00`]
    },
    getydata () {
      if (this.active === 'day') {
        return Array.from({ length: 24 }, () => Math.floor(Math.random() * 100))
      }
      return Array.from({ length: 4 }, () => Math.floor(Math.random() * 100))
    },
    getStatistic (endTime, startTime) {
      getStatistic({
        deviceId: this.camera.identifier,
        startTime,
        endTime,
        pageIndex: 1,
        pageSize: 10000
      }).then(({ data }) => {
        this.echartsData = data

        this.initEchart()
      })
    },
    initEchart () {
      const data = this.echartsData.filter(
        item => item.insidePeopleNum !== 0
      )
      const xdata = this.getxdata(data)
      const ydata = this.getydata(data)
      console.log('initEchart')
      const chartDom = document.getElementById(`main${this.key}`)
      const myChart = echarts.init(chartDom)
      myChart.setOption({
        title: {
          text: '',
          textStyle: {
            color: '#fff',
            fontWeight: 'bold'
          }
          // padding: [0, 30],
        },
        xAxis: {
          type: 'category',
          data: xdata,
          splitLine: {
            show: false
          },
          axisLine: {
            lineStyle: {
              color: '#4779BC'
            }
          },
          axisLabel: {
            color: '#A9CEFF'
          }
        },
        yAxis: {
          type: 'value',
          minInterval: 1,
          splitLine: {
            lineStyle: {
              color: '#4779BC',
              type: 'dashed'
            }
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: '#4779BC'
            }
          },
          axisLabel: {
            color: '#A9CEFF'
          }
        },
        grid: {
          left: '30',
          right: '20',
          top: '40',
          bottom: '20'
        },
        series: [
          {
            data: ydata,
            type: 'bar',
            showBackground: true,
            backgroundStyle: {
              color: 'transparent'
            },
            itemStyle: {
              color: '#2956F0'
            },
            select: {
              itemStyle: {
                color: 'rgb(0, 234, 255)'
              }
            }
          }
        ],
        emphasis: {
          itemStyle: {
            color: '#FFCA1A', // hover时改变柱子颜色
            // shadowColor: 'rgba(102,102,102,0.50)',
            // shadowOffsetX: 0,
            // shadowOffsetY: 2,
            // shadowBlur: 6,
            borderWidth: 1,
            borderColor: '#FF2222',
            borderType: 'solid'
          }
        },
        tooltip: {
          formatter: '时间：{b}<br />人流量：{c}'
        }
      })
    },
    timeType (type) {
      this.active = type
      // let startTime
      // if (this.datevalue.length) {
      //   startTime = this.datevalue
      // } else {
      //   this.datevalue = new Date()
      //   startTime = this.getStarttime(new Date(), 'now')
      // }
      // this.getStatistic(startTime, this.getStarttime(startTime, type))
      this.initEchart()
    },
    onDateTimeChange () {
      // if (this.datevalue) {
      //   this.getStatistic(
      //     this.datevalue,
      //     this.getStarttime(this.datevalue, this.active)
      //   )
      // }
      if (this.datevalue.getTime() > Date.now()) {
        this.datevalue = Date.now()
      }
      this.initEchart()
    },
    getStarttime (time, type) {
      let onehour = 60 * 60 * 1000
      if (type === 'day') {
        onehour = 60 * 60 * 1000 * 24
      } else if (type === 'now') {
        onehour = 0
      }
      const startTime = new Date(new Date(time).getTime() - onehour)
        .toLocaleString('zh', { hour12: false })
        .split('/')
        .join('-')
      const arr = startTime.split(' ')[0].split('-')
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].length < 2) {
          arr[i] = `0${arr[i]}`
        }
      }
      return `${arr.join('-')} ${startTime.split(' ')[1]}`
    }
  }
}
</script>

<style lang="scss" scoped>
.wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}
.o-detail {
  width: 100%;
  height: 100%;
}
.timeBtn {
  display: flex;
  align-items: center;
  justify-content: space-around;
  margin-top: 20px;
  .timeType {
    display: flex;
    .type {
      width: 60px;
      height: 24px;
      cursor: pointer;
      font-size: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #2e3756;
      &.active {
        background-color: #2956f0;
      }
    }
  }
  .datePicker {
    width: 170px;
    ::v-deep>.el-input__inner{
      background-color: transparent;
      color: #fff;

    }
  }
}
.charts {
  width: 100%;
  height: 100%;
}
.full {
  .charts {
    width: 750px;
    height: 400px;
    margin-bottom: 30px;
  }
}
</style>
