<template>
    <div class="custom-date-picker">
        <el-button @click="showPicker = !showPicker" :size="size" class="date-picker-button">
            {{ displayDate }}
        </el-button>
        <el-date-picker
            v-model="selectedDate"
            :type="pickerType"
            :placeholder="placeholder"
            :format="format"
            :value-format="valueFormat"
            :style="{ visibility: 'hidden' }"
            @change="handleDateChange"
            style="margin-top: -100px"
            ref="datePicker"
        />
    </div>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue'
import { ElDatePicker, ElButton } from 'element-plus'

const props = defineProps({
    modelValue: {
        type: [Date, String, Array],
        default: [],
    },
    type: {
        type: String,
        default: 'primary',
    },
    size: {
        type: String,
        default: 'small',
    },
    pickerType: {
        type: String,
        default: 'daterange',
    },
    placeholder: {
        type: String,
        default: '选择日期',
    },
    format: {
        type: String,
        default: 'YYYY-MM-DD',
    },
    valueFormat: {
        type: String,
        default: 'YYYY-MM-DD',
    },
    companyIndex: {
        type: Number,
        default: 0,
    },
    goodsIndex: {
        type: Number,
        default: 0,
    },
})

const emit = defineEmits(['update:modelValue', 'onLeaseDateChange'])

const selectedDate = ref(props.modelValue)
const showPicker = ref(false)
const datePicker = ref(null)

const displayDate = computed(() => {
    return selectedDate.value ? '修改租期' : '请选择租期'
})

const handleDateChange = (value) => {
    emit('update:modelValue', value, props.companyIndex, props.goodsIndex)
    emit('onLeaseDateChange', value, props.companyIndex, props.goodsIndex)
    showPicker.value = false
}

// const onVisibleChange = () => {
//     console.log('关闭')
//     showPicker.value = false
// }

watch(
    showPicker,
    (newValue) => {
        if (newValue) {
            nextTick(() => {
                datePicker.value.handleOpen()
            })
        } else {
            nextTick(() => {
                datePicker.value.handleClose()
            })
        }
    },
    { deep: true, immediate: true },
)

watch(
    () => props.modelValue,
    (newValue) => {
        selectedDate.value = newValue
    },
)
</script>

<style scoped>
.custom-date-picker {
    display: inline-block;
}

.date-picker-button {
    /* min-width: 120px; */
    background-color: #1abc9c;
    color: #fff;
    height: 30px;
    border: none;
}
</style>
