<template>
   <div>
    <span class='ks-dateSelect-title' v-text='title'></span>
    <ButtonGroup class='ks-dateSelect-btns' checkType="radio" v-model="currentValue" >
      <Button v-for='item in dateList' :key='item.value' :value="item.value" @click="onBtnChange"><span v-text='item.label'></span></Button>
    </ButtonGroup>
    <Datepicker 
      class='ks-dateSelect-picker'
      v-model="date" range type="datetime"  
      :placeholder="placeholder" 
      clearable 
      @changeValue='onPickerChange'  
      @selecting='onSelecting'
    />
   </div>
</template>
<script setup>
import { computed, onMounted, ref } from 'vue';
import { Button, ButtonGroup,Datepicker } from '@king-design/vue';
import dayjs from 'dayjs';
const props = defineProps({
    title: {
      type: String,
      default: '时间范围'
    },
    dateList: {
      type: Array,
      default: [
        {
            value: 'hour_0.5',
            label: '0.5小时'
        },
        {
            value: 'hour_1',
            label: '1小时'
        },
        {
            value: 'hour_3',
            label: '3小时'
        },
        {
            value: 'day_1',
            label: '1天'
        },
        {
            value: 'day_7',  
            label: '7天'
        },
        {
            value: 'month_1',
            label: '30天'
        }
      ]
    },
    placeholder: String,
});
// 接收父组件声明的方法
const emit = defineEmits(['onChangeDate'])
const placeholder = computed(()=>{
  return props.placeholder || '请选则开始日期 - 请选择结束日期'
});

const date = ref([])
const isOperateDate = ref(false) // 是否手动操作时间，而不是通过button按钮点击时间
const currentValue = ref(props.dateList[0].value)

const getDateValue = () => {
  const startTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  const unit = currentValue.value && currentValue.value?.split('_')[0]
  const time = currentValue.value && currentValue.value?.split('_')[1]
  const endTime = dayjs().add(time, unit).format('YYYY-MM-DD HH:mm:ss')
  date.value = [startTime, endTime]
  emit('onChangeDate',date.value)
}

const onBtnChange = () => {
  isOperateDate.value = false
  getDateValue()
}

const onPickerChange = (time) => {
  if(!isOperateDate.value) return
  currentValue.value = ''
  const pcikerDate = !time ? [] : time
  date.value = pcikerDate
  emit('onChangeDate',pcikerDate)
}

const onSelecting = (time) => {
  isOperateDate.value = true
}

onMounted(()=>{
   getDateValue()
})

defineExpose({
  getDateValue,
})

</script>

<style scoped lang="less">
.ks-dateSelect-title {
  margin-right: 16px;
}
.ks-dateSelect-picker {
  left: -2px;
  border-top-left-radius: 0px;
  border-bottom-left-radius: 0px;
}
.ks-dateSelect-btns button:last-child{
  border-top-right-radius: 0px;
  border-bottom-right-radius: 0px;
}
</style>
