<template>
    <div class="dhcYearPicker" ref="yearPicker">
        <div v-popover:popover @mouseenter="showClear = true" @mouseleave="showClear = false">
            <i class="dateIcon el-icon-date"></i>
            <input class="_inner" ref="inputLeft" v-model="startShowYear" type="text" name="yearInput"
                @keyup="checkStartInput($event)" placeholder="开始年份" />
            <span>{{ sp }}</span>
            <input class="_inner" ref="inputRight" v-model="endShowYear" type="text" name="yearInput"
                @keyup="checkEndInput($event)" placeholder="结束年份" />
            <i v-show="startShowYear && endShowYear && showClear" @click="clearInput"
                class="dhc-close-icon el-icon-circle-close"></i>
        </div>
        <a-popover ref="popover" popper-class="dhc-yearPicker-popover" placement="bottom-start" v-model="showPanel"
            trigger="click">
            <div class="_inner floatPanel" v-clickoutside="() => { showPanel = false }">
                <div class="_inner leftPanel">
                    <div class="_inner panelHead">
                        <i class="_inner el-icon-d-arrow-left" @click="onClickLeft"></i>
                        {{ leftYearList[0] + "-" + leftYearList[9] }}
                    </div>
                    <div class="_inner panelContent">
                        <div :class="{
            oneSelected: item === startYear && oneSelected,
            startSelected: item === startYear,
            endSelected: item === endYear,
            betweenSelected: item > startYear && item < endYear,
        }" v-for="item in leftYearList" :key="item">
                            <a :class="{ cell: true, _inner: true, selected: item === startYear || item === endYear, }"
                                @click="onClickItem(item)" @mouseover="onHoverItem(item)"> {{ item }} </a>
                        </div>
                    </div>
                </div>
                <div class="_inner rightPanel">
                    <div class="_inner panelHead">
                        <i class="_inner el-icon-d-arrow-right" @click="onClickRight"></i>
                        {{ rightYearList[0] + "-" + rightYearList[9] }}
                    </div>
                    <div class="_inner panelContent">
                        <div :class="{
            startSelected: item === startYear,
            endSelected: item === endYear,
            betweenSelected: item > startYear && item < endYear,
        }" v-for="item in rightYearList" :key="item">
                            <a :class="{
            cell: true,
            _inner: true,
            selected: item === endYear || item === startYear,
        }" @click="onClickItem(item)" @mouseover="onHoverItem(item)"> {{ item }} </a>
                        </div>
                    </div>
                </div>
            </div>
        </a-popover>
    </div>
</template>

<script>
import moment from "moment";
import { isEmpty } from '@/utils/validate';
const SELECT_STATE = {
    unselect: 0,
    selecting: 1,
    selected: 2,
};
export default {
    name: "yearPicker",
    watch: {
        value () {
            if (this.value?.length == 2) {
                this.startShowYear = this.value[0]
                this.startYear = this.value[0]
                this.endShowYear = this.value[1]
                this.endYear = this.value[1]
            } else {
                this.startShowYear = null
                this.endShowYear = null
                this.startYear = null
                this.endYear = null
            }
        },
        startShowYear (val) {
            this.$emit("input", [val, this.endShowYear])
        },
        endShowYear (val) {
            this.$emit("input", [this.startShowYear, val])
        }

    },
    computed: {
        oneSelected () {
            return (
                this.curState === SELECT_STATE.selecting &&
                (this.startYear === this.endYear || this.endYear == null)
            );
        },
        startDate () {
            return this.startYear;
        },
        leftYearList () {
            return this.yearList.slice(0, 10);
        },
        rightYearList () {
            return this.yearList.slice(10, 20);
        },
    },
    props: {
        labelWidth: {
            default: 80,
        },
        sp: {
            default: "至",
        },
        value: Array,
        readIgnore: {
            type: String,
            default: null
        }
    },
    data () {
        let startShowYear = null;
        let endShowYear = null;
        let startYear = null;
        let endYear = null;
        if (this.value?.length == 2) {
            startShowYear = this.value[0]
            startYear = this.value[0]
            endShowYear = this.value[1]
            endYear = this.value[1]
        }
        return {
            itemBg: {},
            startShowYear,
            endShowYear,
            yearList: [],
            showPanel: false,
            startYear,
            endYear,
            curYear: 0,
            curSelectedYear: 0,
            curState: SELECT_STATE.unselect,
            showClear: false,    //清除按钮展示标志
            timeoutId: "",       //节流函数定时器timer
        };
    },
    methods: {
        clearInput () {
            this.startYear = null
            this.endYear = null
            this.$emit("input", [this.startYear, this.endYear]);
        },
        checkStartInput (event) {
            if (isNaN(this.startShowYear)) {
                this.startShowYear = this.startYear;
            } else {
                this.startYear = this.startShowYear * 1;
                //使用节流函数触发交换函数，防止用户还未输入完全就交换
                this.throttle(this.changeYear, 1000)();
            }
        },

        checkEndInput () {
            if (isNaN(this.endShowYear)) {
                this.endShowYear = this.endYear;
            } else {
                this.endYear = this.endShowYear * 1;
                //使用节流函数触发交换函数，防止用户还未输入完全就交换
                this.throttle(this.changeYear, 1000)();
            }
        },
        changeYear () {
            if (!isEmpty(this.startYear) && !isEmpty(this.endYear) && this.startYear > this.endYear) {
                let tmp = this.endYear;
                this.endYear = this.startYear;
                this.startYear = tmp;
                this.startShowYear = this.startYear;
                this.endShowYear = this.endYear;
            }
            if (this.startYear && this.endYear) {
                this.$emit("input", [this.startYear, this.endYear]);
            } else {
                console.warn("WARN:年份不合法", this.startYear, this.endYear);
            }
        },
        //节流函数
        throttle (func, delay) {
            let that = this
            return function () {
                const context = this;
                const args = arguments;

                // 清除之前的定时器
                clearTimeout(that.timeoutId);

                // 创建新的定时器
                that.timeoutId = setTimeout(function () {
                    func.apply(context, args);
                }, delay);
            };
        },
        onHoverItem (iYear) {
            if (this.curState === SELECT_STATE.selecting) {
                let tmpStart = this.curSelectedYear;
                this.endYear = Math.max(tmpStart, iYear);
                this.startYear = Math.min(tmpStart, iYear);
            }
        },
        onClickItem (iYear) {
            if (
                this.curState === SELECT_STATE.unselect ||
                this.curState === SELECT_STATE.selected
            ) {
                this.startYear = iYear;
                this.curSelectedYear = iYear;
                this.endYear = null;
                this.curState = SELECT_STATE.selecting;
            } else if (this.curState === SELECT_STATE.selecting) {
                this.endShowYear = this.endYear;
                this.startShowYear = this.startYear;
                this.curState = SELECT_STATE.selected;
                this.$emit("input", [this.startYear, this.endYear]);
                setTimeout(() => {
                    //为动画留的时间，可优化
                    this.showPanel = false;
                }, 300);
            }
        },
        updateYearList () {
            let iStart = Math.floor(this.curYear / 10) * 10 - 10;
            iStart = iStart < 0 ? 0 : iStart;
            this.yearList = [];
            for (let index = 0; index < 20; index++) {
                this.yearList.push(iStart + index);
            }
        },
        closePanel (e) {
            if (!this.showPanel) {
                return;
            }
            if (typeof e.target.className !== "string") {
                this.$nextTick(() => {
                    this.showPanel = false;
                });
                return;
            }
            if (
                e.target.className.indexOf("_inner") === -1 ||
                (e.target.name === "yearInput" &&
                    e.target !== this.$refs.inputLeft &&
                    e.target !== this.$refs.inputRight)
            ) {
                this.$nextTick(() => {
                    this.showPanel = false;
                });
            }

            e.stopPropagation();
            return false;
        },
        onClickLeft () {
            this.curYear = this.curYear * 1 - 10;
            this.updateYearList();
        },
        onClickRight () {
            this.curYear = this.curYear * 1 + 10;
            this.updateYearList();
        },

        //------------------对外接口------------------------
        //直接传时间戳
        setYear (startYearStamp, endYearStamp) {
            if (!isNaN(startYearStamp) && !isNaN(endYearStamp)) {
                //   let startYear = moment(startYearStamp).format("yyyy");
                //   let endYear = moment(endYearStamp).format("yyyy");
                let startYear = startYearStamp;
                let endYear = endYearStamp;
                this.startYear = startYear * 1;
                this.endYear = endYear * 1;
                this.endShowYear = endYear * 1;
                this.startShowYear = startYear * 1;
            }
        },
    },

    created () {
        this.curYear = moment().format("yyyy");
        this.updateYearList();
    },
    beforeUnmount () {
        document.removeEventListener("click", this.closePanel.bind(this));
    },

    mounted () {
        this.$refs.yearPicker.style = "padding-left:" + this.labelWidth + "px";
        document.addEventListener("click", this.closePanel.bind(this));
    },
};
</script>
<style lang="scss">
.dhcYearPicker {
    font-size: 12px;
    display: inline-flex;
    align-items: center;
    position: relative;
    transition: all 0.3s;
    border: 1px solid #DCDFE6;
    height: 34px;
    line-height: 34px;
    border-radius: 2px;
    padding: 3px 10px;
    box-sizing: border-box;
    background-color: #fff;
    padding-left: 15px !important;

    input:first-child {
        text-align: right;
    }

    //修改占位符颜色
    input::-webkit-input-placeholder {
        /* WebKit, Blink, Edge */
        color: rgb(192, 196, 204);
    }

    input:-moz-placeholder {
        /* Mozilla Firefox 4 to 18 */
        color: rgb(192, 196, 204);
    }

    input::-moz-placeholder {
        /* Mozilla Firefox 19+ */
        color: rgb(192, 196, 204);
    }

    input:-ms-input-placeholder {
        /* Internet Explorer 10-11 */
        color: rgb(192, 196, 204);
    }

    input::-ms-input-placeholder {
        /* Microsoft Edge */
        color: rgb(192, 196, 204);
    }

    //年份输入框
    input {
        appearance: none;
        outline: none;
        display: inline-block;
        height: 100%;
        margin: 0;
        padding: 0;
        width: 100%;
        text-align: center;
        font-size: 12px;
        color: #606266;
    }

    //至
    span {
        height: 32px;
        line-height: 32px;
    }

    .el-popover__reference {
        display: inline-flex;
        -webkit-box-align: center;
        align-items: center;
        padding: 3px 10px;
    }

    //清空按钮
    .dhc-close-icon {
        font-size: 14px;
        color: #C0C4CC;
        display: inline-block;
    }

    .dhc-close-icon:hover {
        cursor: pointer;
    }
}

.dhc-yearPicker-popover {
    padding: 0px;
    left: 0px;

    .floatPanel {
        >div {
            width: 50%;
        }

        padding: 0 16px;
        // position: absolute;
        display: flex;
        background-color: #fff;
        z-index: 2000;
        border-radius: 4px;
        width: 650px;
        height: 250px;
        // top: 40px;
        // left: -50px;
        box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);

        .panelContent {
            display: flex;
            flex-wrap: wrap;
            width: 100%;
            height: calc(100% - 70px);

            .oneSelected {
                border-top-right-radius: 24px;
                border-bottom-right-radius: 24px;
            }

            .startSelected {
                background-color: #f6f6f7;
                border-top-left-radius: 24px;
                border-bottom-left-radius: 24px;
            }

            .endSelected {
                background-color: #f6f6f7;
                border-top-right-radius: 24px;
                border-bottom-right-radius: 24px;
            }

            .betweenSelected {
                background-color: #f6f6f7;
            }

            >div {
                width: 75px;
                height: 48px;
                line-height: 48px;
                margin: 3px 0;
                // border-radius: 24px;
                text-align: center;

                a {
                    display: inline-block;
                    width: 60px;
                    height: 36px;
                    cursor: pointer;
                    line-height: 36px;
                    border-radius: 18px;
                }

                .selected {
                    background-color: #3e77fc;
                    color: #fff;
                }
            }
        }

        .panelHead {
            position: relative;
            height: 46px;
            line-height: 46px;
            text-align: center;

            i {
                position: absolute;
                cursor: pointer;

                &:hover {
                    color: #3e77fc;
                }
            }
        }

        .rightPanel {
            padding-left: 8px;
        }

        .leftPanel .panelHead i {
            left: 20px;
            top: 17px;
        }

        .rightPanel .panelHead i {
            right: 20px;
            top: 17px;
        }
    }

    .floatPanel::before {
        content: "";
        height: 100%;
        position: absolute;
        left: 50%;
        width: 1px;
        border-left: 1px solid #e4e4e4;
    }
}

input {
    width: 60px;
    border: none;
    height: 32px;
    line-height: 32px;
    box-sizing: border-box;
    background-color: transparent;
}

input:focus {
    outline: none;
    background-color: transparent;
}

.dhcYearPicker:hover {
    border-color: #3e77fc;
}

.dateIcon {
    position: absolute;
    left: 10px;
    top: 9px;
    color: #adb2bc;
}
</style>

​
