<template>
  <u-dropdown-item :title="label">
    <view class="bg-white">
      <view
        class="p-30rpx flex items-center text-28rpx"
        @click.stop="openCalendar"
      >
        <u-icon name="calendar" color="#333" size="32"></u-icon>
        <text style="margin-left: 6rpx">选择日期：</text>
        <template v-if="isRange">
          <view class="flex flex-1 items-center">
            <u-input
              :value="status[0]"
              :placeholder="placeholderStr[0]"
              class="flex-1 !pointer-events-none"
              disabled
              input-align="center"
            />
            <view class="px-10rpx">至</view>
            <u-input
              :value="status[1]"
              :placeholder="placeholderStr[1]"
              class="flex-1 !pointer-events-none"
              disabled
              input-align="center"
            />
          </view>
        </template>
        <template v-else>
          <u-input
              :value="status"
              :placeholder="placeholderStr"
              class="flex-1 !pointer-events-none"
              disabled
              input-align="left"
            />
        </template>
      </view>
      <u-line></u-line>
      <portal to="calendar-portal">
        <u-calendar
          v-model="show"
          :mode="mode"
          @change="handleChange"
        ></u-calendar>
      </portal>
    </view>
  </u-dropdown-item>
</template>
<script>
export default {
  props: {
    label: {
      type: String,
      default: '',
    },
    value: {
      type: [Array, Object, String, Number],
    },
    placeholder: {
      type: [Array, String],
      default: '请选择日期',
    },
    params: {
      type: Object,
      default: () => ({}),
    },
    mode: {
      type: String,
      default: 'date',
    },
  },
  computed: {
    isRange() {
      return this.mode === 'range'
    },
    placeholderStr() {
      if (this.isRange) {
        return [this.placeholder?.[0] ?? '', this.placeholder?.[1] ?? '']
      }
      return this.placeholder
    },
    status() {
      if (this.isRange) {
        return [this.date?.[0] ?? '', this.date?.[1] ?? '']
      }
      return this.date
    },
  },
  data() {
    return {
      show: false,
      date: null,
    }
  },
  methods: {
    openCalendar() {
      this.show = true
    },
    handleChange(e) {
      let value
      if (this.isRange) {
        const { startDate, endDate } = e
        value = [startDate, endDate]
      } else {
        value = e.result
      }
      this.$emit('change', value)
      this.$emit('input', value)
      this.date = value
      this.$emit('close-dropdown',value)
    },
  },
  watch:{
    value:{
      handler(val){
        this.date = val
      },
      immediate:true,
      deep:true
    }
  }
}
</script>
<style lang="scss" scoped>
.inp {
  @apply border rounded-4rpx flex-1 h-60rpx px-10px leading-60rpx;
}
</style>
