<template>
  <view class="calendar">
    <uv-calendar 
      ref="calendar" 
      title="出行日期"
      mode="single" 
      rowHeight="110"
      :defaultDate="defaultDate"
      @confirm="confirm"
    ></uv-calendar>
  </view>
</template>

<script>
  export default {
    props: {
      value: {
        type: String,
        default: null
      },
      options: {
        type: Array,
        default() {
          return []
        }
      },
    },
    data() {
      return {
        defaultDate: null,
      }
    },
    computed: {
      selected: {
        set(val) {
          this.$emit('input', val)
        },
        get() {
          return this.value
        }
      },
      startDateList() {
        return this.options.map(item => {
          const { startDate } = item

          return this.$dayjs(`2025/${startDate}`).format('YYYY-MM-DD')
        })
      },
    },
		onReady() {
			this.$refs.calendar.setFormatter(this.formatter);
		},
		methods: {
			formatter(day) {
        const dateStr = this.$dayjs(day.date).format('YYYY-MM-DD')
	
        const index = this.startDateList.findIndex(startDate => startDate === dateStr) 

        if (index === -1) {
          day.disabled = true

          return day;
        }

        const { startDate, endDate, priceDiscount } = this.options[index]

        // day.topInfo = `${startDate}-${endDate}`
        day.topInfo = `~${endDate}`
        day.bottomInfo = `¥${priceDiscount}`
        return day
			},
			open() {
        if (this.selected) {
          const index = this.options.findIndex(option => option.id === this.selected)
          this.defaultDate = this.startDateList[index]
        }

				this.$refs.calendar.open();
			},
			confirm(e) {
        const dateStr = e[0]
        const index = this.startDateList.findIndex(startDate => startDate === dateStr) 

        this.selected = this.options[index].id
			},
		}
  }
</script>

<style lang="scss" scoped>
</style>