<!-- 日历表单组件 zhao -->
<template>
  <!-- !!!注: 不支持逝去的日子, 以`FieldDatePicker`代替 !!! -->
  <div>
    <van-field
      :readonly="true"
      :clickable="!readonly"
      :name="name"
      :value="visibleValue"
      :label="label"
      :placeholder="placeholder"
      @click="openPopup"
      input-align="right"
      right-icon="arrow-down"
      :rules="rules"
      :required="required"
      :label-width="labelWidth || 'auto'"
    >
<!--      <template #button>
        <van-icon name="notes-o" size="20"/>
      </template>-->
    </van-field>
    <van-calendar
      ref="calender"
      v-model="popupVisible"
      :title="label"
      :default-date="internalValue"
      :readonly="readonly"
      @confirm="onConfirm" />
  </div>
</template>

<script>

import { formatDate } from "element-ui/src/utils/date-util.js"

export default {
  name: "FieldCalender",
  props: [
    'name', 'readonly', 'value', 'label', 'placeholder', 'required', 'rules', 'labelWidth',
    'formatter', // value的格式化 String|Function|undefined 字符串为格式字符串, 函数则必须有返回 undefined则不转换
  ],
  watch: {
    value: function (newVal, oldVal) {
      this.visibleValue = newVal;
      this.internalValue = new Date(newVal);
    },
  },
  created() {
    if(this.value)
    {
      this.visibleValue = this.value;
      this.internalValue = new Date(this.value);
    }
  },
  data() {
    return {
      popupVisible: false,
      internalValue: new Date(this.value || Date.now()),
      visibleValue: this.value,
      loading: false,
    };
  },
  methods: {
    openPopup() {
      if(!this.readonly)
      {
        this.popupVisible = true;
        this.$nextTick(() => {
          this.$refs.calender.scrollToDate(this.internalValue);
        })
      }
    },
    closePopup() {
      this.popupVisible = false;
    },
    onConfirm(data) {
      this.syncValue(data);
      this.$emit('input', this.visibleValue);
      this.$emit('confirm', this.visibleValue, this.internalValue);
      this.closePopup();
    },
    onCancel() {
      this.closePopup();
      this.$emit('cancel');
    },
    getValue(data) {
      let type = typeof(this.formatter);
      if(type === 'function')
        return this.formatter(data);
      else if(type === 'string')
        return formatDate(data, this.formatter);
      else
        return data;
    },
    syncValue(data) {
      this.internalValue = data;
      this.visibleValue = this.getValue(data);
      console.log(this.internalValue, this.visibleValue);
    },
  },
}
</script>

<style scoped>

</style>
