<template>
    <div class="hc-date-year-select hc-flex">
        <el-date-picker ref="startYearRef" v-model="startYears" type="year" value-format="YYYY" placeholder="计划开工年" :disabled="disabled" :clearable="false" @change="startYearChange" />
        <div class="to ml-2 mr-2 text-[14px]">至</div>
        <el-date-picker ref="endYearRef" v-model="endYears" type="year" value-format="YYYY" placeholder="计划完工年" :clearable="clearable" :disabled="disabled" @change="endYearChange" @blur="endYearBlur" />
    </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { isNullES } from 'js-fast-way'

defineProps({
    disabled: {
        type: Boolean,
        default: false,
    },
    clearable: {
        type: Boolean,
        default: true,
    },
})

defineOptions({
    name: 'HcDateYear',
})

//双向绑定
const startYear = defineModel('modelValue', {
    type: [String, Number],
    default: '',
})
const endYear = defineModel('end', {
    type: [String, Number],
    default: '',
})

//监听数据改变
const startYears = ref('')
const endYears = ref('')
watch(() => [startYear.value, endYear.value], ([start, end]) => {
    startYears.value = start ? start + '' : ''
    endYears.value = end ? end + '' : ''
}, { deep: true, immediate:true })

//日期选择框ref
const startYearRef = ref(null)
const endYearRef = ref(null)

//开始年
const startYearChange = (val) => {
    startYear.value = val
    endYearRef.value?.focus()
    endYearRef.value?.handleOpen()
    startYearRef.value?.handleClose()
}

//结束年
const endYearChange = (val) => {
    if (isNullES(val)) {
        startYear.value = ''
    }
    endYear.value = val
    if (val < startYear.value) {
        window.$message.warning('完工年不能小于开工年')
        endYear.value = ''
        endYearRef.value?.handleOpen()
    } else {
        endYearRef.value?.handleClose()
    }
}

//失去焦点
const endYearBlur = () => {
    if (isNullES(startYear.value) || isNullES(endYear.value)) {
        startYear.value = ''
        endYear.value = ''
        window.$message.warning('请重新选择完整的范围年份')
    } else if (endYear.value < startYear.value) {
        startYear.value = ''
        endYear.value = ''
        window.$message.warning('完工年不能小于开工年')
    }
    console.log(startYear.value, endYear.value)
}
</script>

<style lang="scss">
.hc-date-year-select {
    .el-input.el-date-editor,
    .el-date-editor.el-input__wrapper {
        width: 124px;
    }
}
</style>
