<template>
  <div
    class="c-time"
    :style="styles"
  >{{ time }}</div>
</template>

<script>
import { WidgetType } from '../constant'

export default {
  name: WidgetType.TIME,
  props: {
    node: {
      type: Object,
      default: null
    }
  },
  data () {
    return {
      time: ''
    }
  },
  computed: {
    styles () {
      const {
        width,
        height,
        color,
        fontSize,
        fontWeight,
        textAlign
      } = this.node
      return {
        width: `${width}px`,
        height: `${height}px`,
        color,
        'font-size': `${fontSize}px`,
        'font-weight': fontWeight,
        'justify-content': ({
          left: 'flex-start',
          center: 'center',
          right: 'flex-end'
        })[textAlign]
      }
    },
    format () {
      return this.node ? this.node.format : ''
    }
  },
  watch: {
    format () {
      this.getTime()
    }
  },
  mounted () {
    this.$timer = setInterval(this.getTime, 1000)
    this.getTime()
  },
  beforeDestroy () {
    clearInterval(this.$timer)
  },
  methods: {
    getTime () {
      const now = new Date()
      const o = {
        'y+': `${now.getFullYear()}`.padStart(2, '0'),
        'M+': `${now.getMonth() + 1}`.padStart(2, '0'),
        'd+': `${now.getDate()}`.padStart(2, '0'),
        'H+': `${now.getHours()}`.padStart(2, '0'),
        'm+': `${now.getMinutes()}`.padStart(2, '0'),
        's+': `${now.getSeconds()}`.padStart(2, '0'),
        'w+': ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][now.getDay()]
      }
      let format = this.format
      Object.keys(o).forEach(k => {
        format = format.replace(
          new RegExp(k),
          o[k]
        )
      })
      this.time = format
    }
  }
}
</script>

<style lang="scss" scoped>
.c-time {
  position: relative;
  display: inline-flex;
  align-items: center;
  white-space: nowrap;
  overflow: hidden;
}
</style>
