<template>
  <div style="display: flex" :style="boxSize">
    <div v-if="showLogo">
      <img src="../assets/thyylogo.png" alt="" :style="boxSize" />
    </div>
    <div style="width: 30px"></div>
    <div class="clock" :style="[fontSize, boxSize]">{{ date }}&nbsp;&nbsp;&nbsp;&nbsp;{{ time }}</div>
  </div>
</template>

<script>
import { ref } from '@vue/reactivity'
import { getServerDateApi } from '@/api/public-api'
import { onMounted, onUnmounted } from 'vue'
export default {
  props: {
    size: {
      type: String,
      default: 'large',
    },
    showLogo: {
      type: Boolean,
      defaut: true,
    },
  },
  setup(props) {
    const mInterval = ref(null)
    const date = ref('')
    const time = ref('')
    const week = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']

    let nowtime = ''
    const updateTime = () => {
      nowtime += 1000
      let cd = new Date(nowtime)
      time.value = zeroPadding(cd.getHours(), 2) + ':' + zeroPadding(cd.getMinutes(), 2) + ':' + zeroPadding(cd.getSeconds(), 2)
      date.value = zeroPadding(cd.getFullYear(), 4) + '-' + zeroPadding(cd.getMonth() + 1, 2) + '-' + zeroPadding(cd.getDate(), 2) + ' ' + week[cd.getDay()]
    }
    const zeroPadding = (num, digit) => {
      let zero = ''
      for (let i = 0; i < digit; i++) {
        zero += '0'
      }
      return (zero + num).slice(-digit)
    }

    const boxSize = {
      height: props.size === 'large' ? '60px' : '',
      lineHeight: props.size === 'large' ? '60px' : '',
    }

    const fontSize = {
      fontSize: props.size === 'large' ? '26px' : '20px',
    }

    onMounted(() => {
      getServerDateApi().then((res) => {
        nowtime = new Date(res).getTime()
        mInterval.value = setInterval(() => {
          updateTime()
        }, 1000)
      })
    })

    onUnmounted(() => {
      clearInterval(mInterval.value)
    })

    return {
      date,
      time,
      boxSize,
      fontSize,
    }
  },
}
</script>

<style scoped>
.clock {
  float: right;
  width: max-content;
  color: #09555b;
  font-weight: 600;
}
</style>
