<template>
  <div>
    <div class='flex justify-between'>
      <div>{{ title }}</div>
      <div class='flex items-center'>        
        <span class="mr-2 text-xs">{{ date }}</span>
        <div @click="showStart = true">
          <app-icon customize type='icon-rili' size='20px'></app-icon>
        </div>
        <van-calendar
          class="text-black"
          v-model="showStart"
          :default-date="new Date(date)"
          :min-date="minDate"
          :max-date="maxDate"
          :show-confirm="false"
          @select="onConfirm"/>
      </div>
    </div>
    <input
      type="number"
      :placeholder="placeholder + blockHeight"
      class="w-full text-sm py-2 px-3 mt-2 rounded text-app-blue-1"
      :value="value"
      @input="handleChange($event)"
      @blur="getDateTime"
      >
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { Calendar } from 'vant'
import { getPreDay } from '@/utils/date'
Vue.use(Calendar)
export default Vue.extend({
  props: {
    title: {
      type: String,
      default: '投票开始时间'
    },
    placeholder: {
      type: String,
      default: '请输入开始区块               当前区块'
    },
    blockHeight: {
      type: String
    },
    blockTime: {
      type: String
    },
    value: {
      type: String
    }
  },
  data() {
    return {
      date: getPreDay('YYYY-MM-DD'),
      showStart: false,
      minDate: new Date(2019, 0, 1),
      maxDate: new Date(2023, 0, 1),
    }
  },
  components: {
    'app-icon':()=>import('@/components/common/Icon.vue'),
  },
  methods: {
    handleChange(v: any) {
      this.$emit('update:value', v.target.value)
    },
    onConfirm(v: any) {
      const r = new Date(v).getFullYear() + '-' + 
          (new Date(v).getMonth() + 1 < 10 ? '0' + (new Date(v).getMonth() + 1) : new Date(v).getMonth() + 1) + '-' + 
          (new Date(v).getDate() < 10 ? '0' + (new Date(v).getDate()) : new Date(v).getDate())
      this.date = r
      this.showStart = false
      const t = new Date(v).getTime()
      const ra = t - +(this.blockTime + '000')
      this.$emit('update:value', Math.round(+this.blockHeight + ra/5000) + '')
    },
    getDateTime() {
      if (!this.value) return 
      let stamp = 0
      const r = +this.value - +this.blockHeight
      stamp = +(this.blockTime + '000') + r * 5000
      const hour = new Date(stamp).getHours()
      const t = hour === 23 ? 1 : 0
      this.date = new Date(stamp).getFullYear() + '-' + 
          (new Date(stamp).getMonth() + 1 < 10 ? '0' + (new Date(stamp).getMonth() + 1) : new Date(stamp).getMonth() + 1) + '-' + 
          (new Date(stamp).getDate() < 10 ? '0' + (new Date(stamp).getDate() + t) : new Date(stamp).getDate() + t)
    }
  },
  watch: {
    blockHeight() {
      this.getDateTime()
    }
  }
})
</script>