<template>

  <van-field
    ref="input"
    v-model="inputValue"
    :label="label"
    :name="name"
    :size="size"
    :placeholder="placeholder"
    :border="border"
    :disabled="disabled"
    :required="required"
    :clearable="clearable"
    :clickable="clickable"
    :is-link="isLink"
    :error="error"
    :error-message="errorMessage"

    :arrow-direction="arrowDirection"
    :label-class="labelClass"
    :label-width="labelWidth"
    :label-align="labelAlign"
    :input-align="inputAlign"
    :error-message-align="errorMessageAlign"
    :autosize="autosize"
    :left-icon="leftIcon"
    :right-icon="rightIcon"
    :icon-prefix="iconPrefix"
    :rules="editable?rules:null"
    readonly
    @click-input="onClick"
  >
    <template #label>
      {{ label }}<van-icon v-if="desc && descPosition==='lableIcon'" name="warning" class="ibps-dialog-icon" @click="$action.descDialog({ title:label, message:desc })" />
    </template>
    <template v-if="editable" #right-icon>
      <van-icon
        v-if="showClear"
        name="clear"
        class="van-field__clear"
        @click.native.stop="onRightIconClick"
      />
      <!-- <van-icon
        v-else
        :name="showPopup?'arrow-up':'arrow-down'"
        @click.native.stop="onClick"
      /> -->
      <van-icon
        v-else
        class-prefix="ibps-icon"
        :name="rightIcon"
        @click.native.stop="onClick"
      />
      <van-popup
        v-model="showPopup"
        get-container="body"
        position="bottom"
      >
        <date-picker
          v-if="showPopup"
          ref="datePicker"
          :title="title"
          :type="type"
          :custom-types="customTypes"
          :min-date="minDate"
          :max-date="maxDate"
          :default-date="defaultDate"
          :minute-step="minuteStep"
          :unit-text="unitText"
          :today-text="todayText"
          @confirm="onDatePickerConfirm"
          @cancel="onDatePickerCancel"
        />
      </van-popup>
    </template>
  </van-field>
</template>
<script>
import { isDef } from 'vant/lib/utils'
import FieldMixin from '@/mixins/field'
import fecha from '@/utils/fecha'
import DatePicker from './date-picker'

export default {
  name: 'ibps-date-picker',
  components: {
    DatePicker
  },
  mixins: [FieldMixin],
  props: {
    title: {
      type: String
      // default: '选择时间'
    },
    type: { // date, time, datetime,custom
      type: String,
      default: 'custom'
    },
    format: {
      type: String,
      default: 'yyyy-MM-dd HH:mm:ss'
    },
    minDate: {
      type: Date
    },
    maxDate: {
      type: Date
    },
    defaultValue: {
      type: [String, Date],
      default: () => {
        return new Date()
      }
    },
    minuteStep: {
      type: Number
    },
    unitText: {
      type: Array
    },
    todayText: {
      type: String
    },
    rightIcon: {
      type: String,
      default: 'calendar' // 日期：calendar  时间：clock-o
    },
    desc: String
  },
  data() {
    return {
      selectedOptions: [],
      showPopup: false
    }
  },
  computed: {
    showClear() {
      return this.clearable && this.$utils.isNotEmpty(this.value) && isDef(this.value) && this.editable
    },
    customTypes() {
      return this.getCustomTypes()
    },
    datePickerValue() {
      if (this.$utils.isEmpty(this.value)) {
        return ''
      }
      if (this.value instanceof Date) {
        return fecha.format(this.value, this.format)
      } else {
        try {
          return fecha.format(this.parseFormatDate(this.value, this.format), this.format)
        } catch (error) {
          return this.value
        }
      }
    },
    defaultDate() { // 默认日期值
      if (this.$utils.isNotEmpty(this.value)) {
        if (this.value instanceof Date) {
          return this.value
        } else {
          return fecha.parse(this.value, this.format)
        }
      }
      if (this.defaultValue instanceof Date) {
        return this.defaultValue
      } else {
        return fecha.parse(this.defaultValue, this.format)
      }
    }
  },
  watch: {
    value: {
      handler(val, oldVal) {
        this._setInputValue()
      },
      immediate: true
    }
  },
  methods: {
    onClick() {
      if (!this.editable) { return }
      this.showPopup = true
    },
    onRightIconClick() {
      this.showClear ? this.onClear() : this.onClick()
    },
    onClear() {
      this.$emit('input', '')
    },
    onDatePickerConfirm(columnsValue) {
      this.showPopup = false
      this.$emit('input', this.$refs.datePicker.getFormatDate(this.format))
    },
    onDatePickerCancel() {
      this.showPopup = false
    },
    parseFormatDate(time, cFormat) {
      let d = fecha.parse(time, cFormat || 'yyyy-MM-dd')
      if (d) return d
      const dateFormat = ['yyyy-MM-dd HH:mm:ss', 'yyyy-MM-dd', 'HH:mm:ss', 'HH:mm']
      for (let i = 0; i < dateFormat.length; i++) {
        d = fecha.parse(time, dateFormat[i])
        if (d) return d
      }
      return time
    },
    getCustomTypes() {
      if (this.type !== 'custom') {
        return
      }
      // 自定义日期类型
      // 匹配的字符串
      const tokenRe = /yyyy|yyy|yy|y|MMMM|MMM|MM|M|dd|d|%ld|HH|H|mm|m|ss|s|DD|D|WW|W|w|hd/g
      return this.format.match(tokenRe)
    },
    getRightIcon() {
      const dateFormat = ['HH:mm:ss', 'HH:mm']
      if (dateFormat.includes(this.format)) return true
      return false
    }
  }
}
</script>

