<!-- 日期选择表单组件 zhao -->
<template>
  <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'"
      :input-align="inputAlign || 'left'"
      :size="size || ''"
    >
<!--      <template #button>
        <van-icon name="notes-o" size="20"/>
      </template>-->
    </van-field>

    <van-popup v-model="popupVisible" position="bottom" v-if="type === 'year'">
      <van-picker
        ref="picker"
        :title="label"
        show-toolbar
        :columns="yearColumns"
        :readonly="readonly"
        v-model="internalValue"
        @confirm="onConfirm"
        @cancel="onCancel"
        @change="onChanged"
      />
    </van-popup>
    <van-popup v-model="popupVisible" position="bottom" v-else>
      <van-datetime-picker
        ref="picker"
        v-model="internalValue"
        :type="type || 'date'"
        :readonly="readonly"
        :title="label || ''"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="onConfirm"
        @cancel="onCancel"
        @change="onChanged"
      />
    </van-popup>
  </div>
</template>

<script>

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

export default {
  name: "fieldDatePicker",
  props: [
    'name', 'readonly', 'value', 'label', 'placeholder', 'required', 'rules', 'labelWidth', 'inputAlign',
    'type', // 类型, 仅支持 datetime date time year-month month-day datehour, 额外支持year(但formatter必须为yyyy, 可以提供yearRangeLength=<Number>指定年范围)
    'formatter', // value的格式化 String|Function|undefined 字符串为格式字符串, 函数则必须有返回 undefined则不转换
    'clearable', // 点击取消时清空绑定值
    'yearRangeLength', // type === 'year' 时生成的年份数量范围 [YEAR - yearRangeLength, YEAR + yearRangeLength]
      'minDate', 'maxDate',
    'size',
  ],
  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);
    }
    // 默认当前
/*    else {
      this.syncValue(new Date);
    }*/
  },
  data() {
    return {
      popupVisible: false,
      internalValue: new Date(this.value || Date.now()),
      visibleValue: this.value,
      loading: false,
    };
  },
  methods: {
    openPopup() {
      if(!this.readonly)
      {
        //console.log(this.internalValue);
        this.popupVisible = true;
        this.$nextTick(() => {
          try
          {
            if(1)
            {
              let values = (this.visibleValue || this.getValue(new Date)).split(/\D+/); //TODO: 按非数字符号粗略分割解析初始值, 仅对于类似yyyy-MM-dd
              //console.log(values);
              let picker = this.$refs.picker.getPicker ? this.$refs.picker.getPicker() : this.$refs.picker;
              picker.setValues(values);
            }
            else {
              //TODO: 打开时保存初始值, 取消或点击遮罩未确定的时候恢复该初始值到v-model
            }
          }
          catch (e)
          {
            console.error(e);
          }
        })
      }
    },
    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');
      if(this.clearable)
      {
        this.visibleValue = '';
        this.internalValue = null;
        this.$emit('input', this.internalValue);
      }
    },
    onChanged(data) {
      this.$emit('change', this.getValue(data), data);
    },
    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);
    },
    genYearColumns(num) {
      let d;
      try
      {
        if(this.value)
        {
          d = strtotime(this.value, 'yyyy');
        }
        else
          d = new Date;
      }
      catch(e)
      {
        d = new Date;
      }
      let y = d.getFullYear();
      let arr = ['' + y];
      for(let i = 1; i <= num; i++)
      {
        arr.push('' + (y + i));
        arr.splice(0, 0, '' + (y - i));
      }
      return arr;
    },
    strtotime,
  },
  computed: {
    yearColumns() {
      if(this.type !== 'year')
        return [];
      return this.genYearColumns(this.yearRangeLength || 100);
    },
  }
}
</script>

<style scoped>

</style>
