<template>
  <div class="date-cell van-hairline--bottom" >
    <van-cell v-if="disabled" :title="title" :label="selected" />
    <van-cell v-else :title="title" is-link :label="selected" @click="clickItem">
      <template #right-icon>
        <van-icon name="underway-o" class="date-icon"/>
      </template>
    </van-cell>
    <van-popup v-model="showPicker" round  position="bottom" :close-on-popstate="true" get-container="#app">
      <van-datetime-picker
        v-bind="$attrs"
        show-toolbar
        :type="dateType"
        :columns="columns"
        @cancel="cancelPicker"
        @confirm="pickerConfirm"
      />
    </van-popup>
  </div>
</template>

<script>

import dayjs from "dayjs";
import {formatDate} from "@/filters/filter";

export default {
  props:{
    disabled:{
      type: [Boolean,String],
      default: false,
    },
    //默认值
    value:{
      type: String,
      default: null,
    },
    //标题
    title:{
      type: String,
      default: null,
    },
    //时间类型，见van-datetime-picker
    dateType:{
      type: String,
      default: 'time',
    },
  },
  data(){
    return{
      showPicker:false,
      selected:null,
      columns: [],
      type: {
        'date': {value: 'YYYY-MM-DD'},
        'time': {value: 'mm:ss'},
        'year-month':{ value: 'YYYY-MM'},
        'month-day': {value: 'MM-DD'},
        'datetime':{ value: 'YYYY-MM-DD HH:mm:ss'},
      }
    }
  },
  watch:{
    value:{
      handler (val) {
        if(!val){
          this.selected = null
        }else{
          if(this.dateType === 'time'){
            this.selected = val
          }else {
            this.selected =  formatDate(val,this.type[this.dateType].value);
          }
        }
      },
      immediate: true
    }
  },
  methods:{
    cancelPicker(){
      this.showPicker = false;
    },
    pickerConfirm(val){
      this.selected = formatDate(val,this.type[this.dateType].value);
      this.showPicker = false;
      this.$emit('change',this.selected)
    },
    clickItem(){
      this.showPicker = true;
    },
  },
  model:{
    prop: 'value',
    event: 'change',
  }
}
</script>

<style lang="scss">
.date-icon{
  font-weight: 500;
  line-height: inherit;
  width: 42px;
  height: 42px;
  color: #008cd6;
  font-size: 42px;
}
</style>
