<template>
  <div class="d-form-field d-datetime-picker">
    <van-field
      readonly
      :value="displayValue"
      :name="name"
      :label="label"
      :class="{
        'field-border': border,
        'field-large': size == 'large',
        'field-small': size == 'small',
      }"
      :placeholder="placeholder"
      right-icon="arrow"
      :required="_required"
      :disabled="disabled"
      :rules="rules"
      @click="showPicker = !disabled && true"
    />
    <van-popup round position="bottom" v-model="showPicker">
      <van-datetime-picker show-toolbar v-model="dateValue" :min-date="startDate" :title="'选择' + label" :type="type" @confirm="onConfirm" @cancel="showPicker = false" />
    </van-popup>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from "vue-property-decorator";
import { formUtilService } from "@/services/form-util.service";
/**
 * @Description 时间日期选择器
 * @Author ZPFly
 * @Date 2021/11/3 10:19
 */
@Component({
  name: "DDatetimePicker",
})
export default class DDatetimePicker extends Vue {
  @Prop({ default: "" }) value: string | undefined; // 当前选择器的值
  @Prop({ default: "" }) label: string | undefined; // 输入框左侧文本
  @Prop({ default: "" }) placeholder: string | undefined; // 输入框占位提示文字
  @Prop({ default: "" }) name: string | undefined; // 名称，提交表单的标识符
  @Prop({ default: "" }) size: string | undefined; // 大小，可选值为 large
  @Prop({ default: false }) disabled: boolean | undefined; //是否禁用输入框
  @Prop({ default: false }) required: boolean | undefined; //是否显示表单必填星号
  @Prop({ default: "date" }) type: string | undefined; //时间类型，可选值为 date time year-month month-day datehour
  @Prop({ default: "yyyy-MM-dd" }) format: string | undefined; // 日期格式
  @Prop({ default: false }) border: false | undefined; // 显示边框
  @Prop({ default: () => [] }) rules: any[] | undefined; // 校验规则
  @Prop({ default: () => {return new Date(new Date().getFullYear()-10,new Date().getMonth(),new Date().getDay()) }}) startDate: Date | undefined; //初始时间

  displayValue: any = ""; // 显示的日期
  dateValue: any = ""; // 选中的日期
  showPicker = false; // 显示选择器
  // 是否必输项
  get _required() {
    const rules = this.rules || [];
    let required = this.required || false;
    for (const item in rules) {
      required = required || rules[item].required;
    }
    return required;
  }

  mounted() {
    console.log("jtewe", this.value);
    const val = this.value;
    if (val != "") {
      this.displayValue = val;
    }
    this.displayValue = this.value || "";
    this.dateValue = val && val != "" ? new Date(val) : new Date();
  }

  onConfirm(value: any) {
    this.displayValue = formUtilService.formatDate(value);
    this.$emit("input", this.displayValue);
    console.log(this.displayValue);
    this.showPicker = false;
  }
}
</script>
<style scoped lang="scss">
::v-deep .van-field__label {
  font-size: 14px;
}
::v-deep .van-cell::after {
  border: 0;
}
::v-deep .van-field__body {
  padding: 4px 0 !important;
}
</style>
