<template>
    <el-date-picker v-model="betweenDate" :clearable="isClearable" :type="isType" :value-format="isFormat"
                    class="hc-date-picker" end-placeholder="结束日期" range-separator="至"
                    start-placeholder="开始日期" @change="betweenDateUpdate"/>
</template>

<script setup>
import {ref, watch} from "vue";
import {ElDatePicker} from 'element-plus'

const props = defineProps({
    dates: {
        type: Array,
        default: () => ([])
    },
    clearable: {
        type: Boolean,
        default: false
    },
    type: {
        type: String,
        default: 'daterange'
    },
    format: {
        type: String,
        default: 'YYYY-MM-DD'
    },
})

//初始变量
const betweenDate = ref(props.dates)
const isType = ref(props.type)
const isFormat = ref(props.format)
const isClearable = ref(props.clearable)

//监听
watch(() => [
    props.dates,
    props.type,
    props.format,
    props.clearable,
], ([dates, type, format, clearable]) => {
    betweenDate.value = dates
    isType.value = type
    isFormat.value = format
    isClearable.value = clearable
})

//事件
const emit = defineEmits(['change'])
const betweenDateUpdate = (arr) => {
    let res = arr ?? [], query = '';
    let obj = {start: null, end: null}
    if (res.length > 0) {
        obj = {start: res[0], end: res[1]}
    }
    if (obj['start'] && obj['end']) {
        query = `${obj['start']}~${obj['end']}`
    }
    emit('change', {val: obj, arr: res, query})
}
</script>

<style lang="scss">
.hc-date-picker.el-range-editor.el-input__wrapper {
    width: 100%;
}
</style>
