<template>
  <picker mode="date" :value="date" @change="bindDateChange">
    <text>{{ date }}</text>
  </picker>
</template>
<script>
export default {
  props: {
    value: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      date: this.value ? this.getTime(this.value) : this.getDate(),
    };
  },
  watch: {
    value() {
      this.date = this.getTime(this.value);
    },
  },
  mounted() {
    this.$emit('input', this.date);
  },
  methods: {
    getDate(type) {
      const date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      if (type === 'start') {
        year = year - 60;
      } else if (type === 'end') {
        year = year + 2;
      }
      month = month > 9 ? month : '0' + month;
      day = day > 9 ? day : '0' + day;
      return `${year}-${month}-${day}`;
    },
    getTime(val) {
      const date = new Date(val);
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      month = month > 9 ? month : '0' + month;
      day = day > 9 ? day : '0' + day;
      return `${year}-${month}-${day}`;
    },
    bindDateChange: function (e) {
      this.date = e.detail.value;
      this.$emit('input', this.date);
    },
  },
};
</script>
<style lang="scss" scoped>
picker {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
