<template>
  <q-page class="q-pa-md">
    <div class="q-pa-md" style="padding-left: 0">
      层数: <input v-model="count" style="border-radius: 0;height: 31px;" type="number" :max="100"/>
      <q-btn @click="enterConfig" stretch dense style="margin-left: 20px" square color="primary" icon="download"
             label="确认 "/>
    </div>
    <h6 class="h4" style="margin: 0; color: green;font-size: 2em">当前时间: {{ hourDate }}</h6>
    <div id="table"></div>
  </q-page>
</template>

<script>

import { TabulatorFull } from 'tabulator-tables'

export default {
  name: 'Connection',
  data () {
    return {
      table: null,
      ovens: [],
      count: 10,
      // time
      nowDate: null,
      hourDate: null,
      nowtimer: '',
      logger: null,
      intervals: []
    }
  },
  watch: {
    count (v) {
      if (v > 100) {
        this.count = 100
      } else {
        this.count = Math.abs(v)
      }
    }
  },
  created () {
    this.getTime() // 如果不先调用一次的话，页面显示一秒后，时间才会显示
    this.nowtimer = setInterval(this.getTime, 1000)
    this.logger = require('electron-log')
    this.logger.transports.file.resolvePath = () => ('./logs-' + this.getDate() + '.log')
    this.logger.info('Application Running!')
    this.enterConfig()
  },
  mounted () {
    this.initTable(this.ovens)
  },
  methods: {
    // UpdateS () {
    //   this.table.updateData([{
    //     id: 1,
    //     remainingTime: 'a'
    //   }])
    // },
    getDate () {
      const myDate = new Date()
      const myYear = myDate.getFullYear() // 获取完整的年份(4位,1970-????)
      const myMonth = myDate.getMonth() + 1 // 获取当前月份(0-11,0代表1月)
      const myToday = myDate.getDate() // 获取当前日(1-31)
      return String(myYear + '/' + myMonth + '/' + myToday)
    },
    getTime () {
      this.nowDate = new Date().toLocaleString('zh', {
        year: 'numeric',
        month: 'numeric',
        day: 'numeric'
      })
      this.hourDate = new Date().toLocaleString('zh', {
        hour: 'numeric',
        minute: 'numeric',
        second: 'numeric'
      })
    },
    enterConfig () {
      this.intervals.forEach((item, i) => {
        clearInterval(item.invObj)
      })
      this.ovens = []
      for (let i = 0; i < this.count; i++) {
        this.ovens.push({
          id: i + 1,
          oven: `第 ${i + 1} 层`,
          normalTime: 0,
          startTime: '未开始',
          remainingTime: '未开始'
        })
      }
      if (this.table) {
        this.table.setData(this.ovens)
      }
    },
    startTimer (duration, id, cell) {
      const btn = document.getElementById(id + '_btn')
      btn.innerHTML = '取出'
      btn.setAttribute('flag', 1)
      btn.style = 'border-radius: 0;width: 100%; background-color: red;color: white'
      const table = this.table

      table.updateData([{
        id,
        startTime: this.hourDate
      }])
      let timer = duration, minutes, seconds
      const interval = setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10)
        if (timer >= 0) {
          minutes = minutes < 10 ? '0' + minutes : minutes
          seconds = seconds < 10 ? '0' + seconds : seconds
        } else {
          minutes = Math.abs(minutes) < 10 ? '-0' + Math.abs(minutes) : '-0' + Math.abs(minutes)
          seconds = Math.abs(seconds) < 10 ? '0' + Math.abs(seconds) : Math.abs(seconds)
        }
        table.updateData([{
          id,
          remainingTime: minutes + ':' + seconds,
          timer
        }])
        if (--timer < 0) {
          cell.getRow().getCell('remainingTime').getElement().style.backgroundColor = 'yellow'
        }
      }, 1000)
      const idx = this.intervals.findIndex((item) => item.id === id)
      if (idx > -1) {
        this.intervals[idx].invObj = interval
      } else {
        this.intervals.push({
          id,
          invObj: interval
        })
      }
    },
    getTimeByS (time) {
      // 转换为式分秒
      let h = parseInt(time / 60 / 60 % 24)
      h = h < 10 ? '0' + h : h
      let m = parseInt(time / 60 % 60)
      m = m < 10 ? '0' + m : m
      let s = parseInt(time % 60)
      s = s < 10 ? '0' + s : s
      // 作为返回值返回
      return [h, m, s]
    },

    handleClick (ev, cell) {
      // eslint-disable-next-line no-unused-vars
      const rowData = cell.getRow().getData()
      if (rowData.normalTime <= 0) {
        this.$q.notify({
          type: 'warning',
          message: '请设置时间'
        })
        return
      }
      const btn = document.getElementById(rowData.id + '_btn')
      const opFlag = btn.getAttribute('flag')
      if (opFlag === '0') {
        this.logger.info(`  ${rowData.oven}  开始放入 放入时间: ${this.nowDate + ' ' + this.hourDate}`)
        cell.getRow().getCell('remainingTime').getElement().style.backgroundColor = ''
        this.startTimer(rowData.normalTime * 60, rowData.id, cell)
      } else {
        cell.getRow().getCell('remainingTime').getElement().style.backgroundColor = ''
        const remainingTime = rowData.remainingTime
        this.table.updateData([{
          id: rowData.id,
          remainingTime: '未开始'
        }])
        btn.style = 'border-radius: 0;width: 100%; background-color: #1D68CD;color: white'
        btn.setAttribute('flag', 0)
        btn.innerHTML = '放入'
        const idx = this.intervals.findIndex((item) => item.id === rowData.id)
        clearInterval(this.intervals[idx].invObj)
        if (rowData.timer > 0) {
          const res = this.getTimeByS(rowData.timer)
          const res1 = this.getTimeByS((rowData.normalTime * 60) - rowData.timer)
          this.logger.info(`  ${rowData.oven}  取出 放入时间: ${rowData.startTime} 取出时间 ${this.nowDate + ' ' + this.hourDate} 提前: ${res[1]}分${res[2]} 秒取出 合计: ${res1[1]}分${res1[2]} 秒`)
        } else {
          const s = Math.abs(parseInt(rowData.timer)) + parseInt(rowData.normalTime) * 60
          const res = this.getTimeByS(s)
          this.logger.info(`  ${rowData.oven}  取出 放入时间: ${rowData.startTime} 取出时间 ${this.nowDate + ' ' + this.hourDate} 超时: ${remainingTime} 秒取出 合计: ${res[1]}分${res[2]} 秒`)
        }
      }
      // this.startTimer(rowData.normalTime, rowData.id)
    },
    initTable (data) {
      const timeEditor = function (cell, onRendered, success, cancel) {
        const cellValue = cell.getValue()
        const input = document.createElement('input')
        // const rowData = cell.getRow().getData()
        input.setAttribute('type', 'number')
        input.style.padding = '4px'
        input.style.width = '100%'
        input.style.boxSizing = 'border-box'

        input.value = cellValue

        onRendered(function () {
          input.focus()
          input.style.height = '100%'
        })

        function onChange () {
          if (!isNaN(input.value)) {
            success(Number(input.value))
          } else {
            cancel()
          }
        }

        // submit new value on blur or change
        input.addEventListener('blur', onChange)

        // submit new value on enter
        input.addEventListener('keydown', function (e) {
          if (e.keyCode === 13) {
            onChange()
          }

          if (e.keyCode === 27) {
            cancel()
          }
        })

        return input
      }
      // eslint-disable-next-line camelcase
      const that = this
      this.table = new TabulatorFull('#table', {
        layout: 'fitColumns',
        movableRows: true,
        data,
        index: 'id',
        selectable: 1,
        rowFormatter: function (row) {
          const element = row.getElement()
          // const data = row.getData()
          element.style = 'font-size: 1.5em'
        },
        columns: [
          {
            title: 'id',
            field: 'id',
            visible: false
          },
          {
            title: 'timer',
            field: 'timer',
            visible: false
          },
          {
            title: '烤箱',
            field: 'oven'
          },
          {
            title: '标准时长(分钟)',
            field: 'normalTime',
            editor: timeEditor
          },
          {
            title: '开始时间',
            field: 'startTime'
          },
          {
            title: '剩余时长',
            field: 'remainingTime'
          },
          {
            title: '操作',
            field: 'option',
            // eslint-disable-next-line camelcase
            formatter: function (cell, formatterParams) {
              const view = document.createElement('button')
              view.style = 'border-radius: 0;width: 100%; background-color: #1D68CD;color: white'
              view.id = cell.getRow().getData().id + '_btn'
              view.setAttribute('flag', 0)
              view.innerHTML = '放入'
              view.addEventListener('click', ev => {
                that.handleClick(ev, cell)
              })
              return view
            },
            width: 100,
            align: 'center'
          }
        ]
      })
    }
  }
}
</script>

<style scoped>
@import "./tabulator.css";

body {
  font-size: 1.5em;
}
</style>
