<template>
  <div class="l-flex--col c-device-grid-item has-border radius">
    <div class="l-flex__none l-flex--row c-sibling-item--v">
      <i class="l-flex__none c-sibling-item o-icon" />
      <span class="l-flex__fill c-sibling-item near u-color--info u-ellipsis">在线总时长</span>
      <div class="u-color--info u-font-size--xs">{{ timestamp }}</div>
      <!-- <i
        class="el-icon-date"
        @click="open()"
      /> -->
      <!-- <el-dialog
        title="历史在线时长"
        custom-class="c-dialog xl"
        :visible.sync="dialogVisible"
        width="30%"
        close-on-press-escape="true"
      >
        <div class="picker_top">
          <el-date-picker
            v-model="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="getTime()"
          />
        </div>
        <div
          id="chart"
          class="content"
          style="width:1250px;height:1000px "
        />
      </el-dialog> -->
    </div>
    <div class="l-flex__fill l-flex--row center u-color--black u-text--center">
      <div
        v-if="duration"
        class="u-font-size--lg"
      >
        {{ duration }}
      </div>
      <i
        v-else
        class="el-icon-loading"
      />
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getOnlineDurationByIds } from '@/api/platform'

export default {
  name: 'OnlineDuration',
  props: {
    device: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      duration: '',
      timestamp: '',
      datearr: [],
      publication: [],
      date: [],
      dialogVisible: false
    }
  },
  created () {
    this.$running = true
    this.$timer = -1
    this.startRun()
  },
  mounted () {
    this.datearr = this.getDayAll(this.getDay(-1), this.getDay(0))
  },
  beforeDestroy () {
    this.$running = false
    clearTimeout(this.$timer)
  },
  methods: {
    startRun () {
      if (!this.$running) {
        return
      }
      getOnlineDurationByIds([this.device.id], { custom: true }).then(({ data }) => {
        if (data?.[0]) {
          if (data[0].powerSeconds === '0') {
            this.duration = this.transformDuration(data[0].onlineSeconds)
            this.timestamp = data[0].onlineSecondsUpdateTime
          } else {
            this.duration = this.transformDuration(data[0].powerSeconds)
            this.timestamp = data[0].powerSecondsUpdateTime
          }
          if (!this.duration) {
            this.duration = '暂无统计数据'
          }
        } else {
          this.duration = '暂无统计数据'
          this.timestamp = ''
        }
      }).finally(() => {
        if (this.$running) {
          this.$timer = setTimeout(this.startRun, 60000)
        }
      })
    },
    transformDuration (duration) {
      duration = Number(duration)
      return [
        { value: duration / (24 * 3600) | 0, unit: '天' },
        { value: (duration % (24 * 3600)) / 3600 | 0, unit: '小时' },
        { value: (duration / 3600) / 60 | 0, unit: '分' },
        { value: duration % 60, unit: '秒' }
      ].reduce((curr, { value, unit }) => value ? `${curr}${value}${unit}` : curr, '')
    },
    getDayAll (starDay, endDay) {
      const arr = []
      const dates = []
      const db = new Date(starDay)
      const de = new Date(endDay)
      const s = db.getTime() - 24 * 60 * 60 * 1000
      const d = de.getTime() - 24 * 60 * 60 * 1000
      for (let i = s; i <= d;) {
        i += 24 * 60 * 60 * 1000
        arr.push(parseInt(i))
      }
      for (const j in arr) {
        if (arr[j] !== null) {
          const time = new Date(arr[j])
          const year = time.getFullYear(time)
          const mouth = (time.getMonth() + 1) >= 10 ? (time.getMonth() + 1) : (`0${time.getMonth() + 1}`)
          const day = time.getDate() >= 10 ? time.getDate() : (`0${time.getDate()}`)
          const YYMMDD = `${year}-${mouth}-${day}`
          dates.push(YYMMDD)
        }
      }

      return dates
    },
    getDay (setmonth) {
      const date = new Date()
      const seperator1 = '-'
      const year = date.getFullYear()
      let month = date.getMonth() + 1 + setmonth
      let strDate = date.getDate()
      if (month >= 1 && month <= 9) {
        month = `0${month}`
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = `0${strDate}`
      }
      const currentdate = year + seperator1 + month + seperator1 + strDate
      return currentdate
    },
    getTime () {
      this.datearr = this.getDayAll(this.date[0], this.date[1])
      this.setChart()
    },
    open () {
      this.dialogVisible = true
      this.setChart()
    },
    setChart () {
      setTimeout(() => {
        const option = {
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['设备1', '设备2', '设备3', '设备4', '设备5']
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: this.datearr
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '设备1',
              type: 'line',
              stack: 'Total',
              data: [120, 132, 101, 134, 90, 230, 210]
            },
            {
              name: '设备2',
              type: 'line',
              stack: 'Total',
              data: [220, 182, 191, 234, 290, 330, 310]
            },
            {
              name: '设备3',
              type: 'line',
              stack: 'Total',
              data: [150, 232, 201, 154, 190, 330, 410]
            },
            {
              name: '设备4',
              type: 'line',
              stack: 'Total',
              data: [320, 332, 301, 334, 390, 330, 320]
            },
            {
              name: '设备5',
              type: 'line',
              stack: 'Total',
              data: [820, 932, 901, 934, 1290, 1330, 1320]
            }
          ]
        }
        const chartDom = document.getElementById('chart')
        console.log('chart', document.getElementById('chart'))
        const myChart = echarts.init(chartDom)
        myChart.setOption(option)
      }, 100)
    }
  }
}
</script>

<style lang="scss" scoped>
.picker_top {
  margin-left: 30px;
}

.o-icon {
  background-image: url("~@/assets/icon_online.png");
}
</style>
