<template>
  <div class="picker-wrap">
    <div class="picker-wrap-txt" @click="show = true">
      <input type="text" readonly :value="pickerValShow" :placeholder="placeholder" />
      <svg-icon icon-class="triangle-right" slot="button" />
    </div>
    <cr-popup v-model="show" position="bottom" get-container="body">
      <date-picker
        v-model="pickerVal"
        type="date"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="onConfirm"
        @cancel="onCancel"
      />
    </cr-popup>
  </div>
</template>

<script>
import DatePicker from "vant/lib/datetime-picker";
import "vant/lib/datetime-picker/style";
import { format as dateFormat } from "date-fns";
const currentYear = new Date().getFullYear();
const VALUE_CHANGE_EVENT = "input";
export default {
  name: "PopupDatePicker",
  components: {
    DatePicker
  },
  props: {
    value: null,
    placeholder: {
      type: String,
      default: "请选择"
    },
    pickerData: {
      type: Array,
      default() {
        return [];
      }
    },
    minDate: {
      type: Date,
      default: () => new Date(currentYear - 10, 0, 1),
      validator: isDate
    },
    maxDate: {
      type: Date,
      default: () => new Date(currentYear + 10, 11, 31),
      validator: isDate
    }
  },
  data() {
    return {
      show: false,
      pickerVal: "",
      refreshed: false,
      refName: "datepicker",
      pickerValShow: ""
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        if (val) {
          this.pickerValShow = val;
          this.pickerVal = new Date(val);
        }
      }
    }
  },

  methods: {
    handleResult(res) {
      if (res) {
        this.pickerValShow = dateFormat(res, "yyyy-MM-dd");
        this.pickerVal = new Date(res);
      }
    },
    onCancel() {
      this.show = false;
    },
    onConfirm() {
      this.handleResult(this.pickerVal);
      this.$emit(VALUE_CHANGE_EVENT, this.pickerValShow);
      this.onCancel();
    }
  }
};

function isDate(val) {
  return Object.prototype.toString.call(val) === "[object Date]" && !isNaN(val.getTime());
}
</script>
<style lang="less">
.picker-wrap {
  width: 100%;
  &-txt {
    height: 24px;
    color: #333;
    font-size: 14px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  input {
    color: #333;
    width: 90%;
  }
  .svg-icon {
    height: 16px;
    width: 16px;
  }
}
</style>
