<template>
  <div class="date-cell" >
    <van-cell v-if="disabled" :required="required" :title="title" :label="label" />
    <van-cell v-else :title="title" :required="required" :label="label" @click="clickItem">
      <template #right-icon>
        <van-icon name="notes-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
        v-model="selected"
        :type="dateType"
        :columns="columns"
        @cancel="cancelPicker"
        @confirm="pickerConfirm"
        confirm-button-text="确定"
      />
    </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: 'date',
    },
    required:{
      type: [Boolean,String],
      default: false,
    },
  },
  data(){
    return{
      showPicker:false,
      selected:null,
      columns: [],
      defaultTime:null,
      type: {
        'date': {value: 'YYYY-MM-DD'},
        'year-month':{ value: 'YYYY-MM'},
        'month-day': {value: 'MM-DD'},
        'datetime':{ value: 'YYYY-MM-DD HH:mm:ss'},
      },
      label:'',
    }
  },
  watch:{
    value:{
      handler (val) {
        console.log(val,'valllll')
        if(!val){
          this.selected = null;
          this.label = '';
        }else{
          this.selected = val;
          this.label = formatDate(val,this.type[this.dateType].value);
        }
      },
      immediate: true
    }
  },
  created() {
    //初始化时间
    this.selected = new Date();
  },
  methods:{
    cancelPicker(){
      this.showPicker = false;
    },
    pickerConfirm(val){
      this.selected = val;
      this.label = formatDate(val,this.type[this.dateType].value);
      this.showPicker = false;
      this.$emit('change',this.label)
    },
    clickItem(){
      this.showPicker = true;
    },
  },
  model:{
    prop: 'value',
    event: 'change',
  }
}
</script>

<style lang="scss">
.date-icon{
  font-weight: 500;
  width: 42px;
  height: 6.4vw;
  color: #008cd6;
  font-size: 42px;
  line-height: 6.4vw;
}
.van-cell__label{
  margin: 0;
}
</style>
<style lang="scss" scoped>
.date-cell{
  position: relative;
  box-sizing: border-box;
  width: 100%;
  overflow: hidden;
  color: #323233;
  background-color: #fff;
}
.date-cell::after{
  position: absolute;
  box-sizing: border-box;
  content: ' ';
  pointer-events: none;
  right: 30px;
  bottom: 0;
  left: 30px;
  border-bottom: 1px solid #ebedf0;
  -webkit-transform: scaleY(.5);
  transform: scaleY(.5);
}
</style>
