<template>
  <view class="calender-popup">
    <view class="open-btn" @click="openCalender">
      <slot>
        <view class="default-btn">
          <view>日历</view>
          <wd-icon name="calendar" size="35rpx"></wd-icon>
        </view>
      </slot>
    </view>
    <wd-popup
      v-model="showCalenderPopup"
      position="bottom"
      custom-style="border-radius: 30rpx 30rpx 0 0;"
    >
      <student-calender v-model:value="currentDate"></student-calender>
      <view class="calender-popup-footer">
        <wd-button :round="false" class="cancel" @click="closeCalender">取消</wd-button>
        <wd-button :round="false" class="confirm" @click="confirm">确定</wd-button>
      </view>
    </wd-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import StudentCalender from '@/components/student-calendar/index.vue'
import dayjs from 'dayjs'

const props = defineProps({
  value: {
    type: [String, dayjs],
  },
})

const emit = defineEmits(['update:value', 'change'])

const showCalenderPopup = ref(false)

const currentDate = ref('')

const openCalender = () => {
  showCalenderPopup.value = true
}

const closeCalender = () => {
  showCalenderPopup.value = false
}

watch(
  () => props.value,
  value => {
    if (value) {
      currentDate.value = typeof value === 'string' ? value : value.format('YYYY-MM-DD')
    } else {
      currentDate.value = dayjs().format('YYYY-MM-DD')
    }
  },
  { immediate: true, deep: true },
)

const confirm = () => {
  emit('update:value', dayjs(currentDate.value))
  emit('change', dayjs(currentDate.value))
  closeCalender()
}
</script>

<style scoped lang="scss">
.calender-popup {
  display: inline-block;
  .open-btn {
    display: inline-block;
    .default-btn {
      display: inline-flex;
      align-items: center;
      gap: 10rpx;
      color: #666;
      user-select: none;
    }
  }
}
.calender-popup-footer {
  height: 122rpx;
  box-sizing: border-box;
  padding: 16rpx 30rpx;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .cancel {
    width: 230rpx;
    height: 90rpx;
    border-radius: 20rpx;
    background-color: #efefff;
    color: #615dff;
    font-size: 30rpx;
    font-weight: 500;
  }
  .confirm {
    width: 440rpx;
    height: 90rpx;
    border-radius: 20rpx;
    background-color: #615dff;
    color: #fff;
    font-size: 30rpx;
    font-weight: 500;
  }
}
</style>
