<template>
    <div ref="mainRef" style="min-width: 400px;">
        <div class="calendar-tools">
            <div class="calendar-tools-title">
                <span style="float: left">
                    <i class="el-icon-d-arrow-left calendar-tools-btn" v-show="showSwitchYearBtn" @click="handleSwitchDate('prevYear')"/>
                    <i class="el-icon-arrow-left calendar-tools-btn" v-show="showSwitchMonthBtn" @click="handleSwitchDate('prevMonth')"/>
                </span>
                {{formatDateTimeText}}
                <span style="float: right">
                    <span style="color: #4CAAFF; cursor: pointer;" v-show="showBakcTodayBtn" @click="handleSwitchDate('today')">{{bakcTodayText}}</span>
                    <i class="el-icon-arrow-right calendar-tools-btn"  v-show="showSwitchMonthBtn" @click="handleSwitchDate('nextMonth')"/>
                    <i class="el-icon-d-arrow-right calendar-tools-btn" v-show="showSwitchYearBtn" @click="handleSwitchDate('prevYear')"/>
                </span>
            </div>
        </div>
        <div class="calendar-main">
            <ul style="display: flex">
                <li style="flex: 1; text-align: center; padding: 5px 0px;" v-for="(item, index) in cells" :key="index">
                    {{item}}
                </li>
            </ul>
            <ul class="calendar-box">
                <li class="calendar-box-row" v-for="(item, index) in dateList" :key="index">
                    <div class="calendar-box-item" :style="{height: wh}" :class="{'calendar-box-item-today': isSameDate(child.stampTime, todayDate), 'calendar-box-item-other': !child.status, 'calendar-box-item-disbaled': child.disabled, [selectedItemClass]: child.checked }" v-for="(child, i) in item" :key="i" @click="handleClickChooseDate(child)" @dblclick="handleDblclickChooseDate(child)">
                        <slot :data="child">{{child.day}}</slot>
                        <slot v-bind="child" name="checked">
                            <i class="el-icon-check calendar-box-item-checked" v-show="child.checked" />
                        </slot>
                    </div>
                </li>
            </ul>
        </div>
    </div>
</template>
<script>
import dateExtend from '../common/datetimeExtend';
export default {
    extends: dateExtend,
    props: {
        disabled: {
            type: Boolean,
            default: false
        },
        pickerOptions: {
            type: Object,
            default() {
                return {};
            }
        },
        format: {
            type: String,
            default: 'yyyy年MM月'
        },
        valueFormat: {
            type: String,
            default: 'yyyy-MM-dd'
        },
        value: {
            type: [Array, String],
            // required: true,
            default() {
                if (this.multiple) {
                    return [];
                } else {
                    return '';
                }
            }
        },
        multiple: {
            type: Boolean,
            default: false
        },
        showSwitchYearBtn: {
            type: Boolean,
            default: true
        },
        showSwitchMonthBtn: {
            type: Boolean,
            default: true
        },
        showBakcTodayBtn: {
            type: Boolean,
            default: false
        },
        bakcTodayText: {
            type: String,
            default: '返回今天'
        },
        isDblclick: {
            type: Boolean,
            default: false
        },
        selectedItemClass: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            operationInstruction: '',
            todayDate: new Date(),
            dateList: [],
            date: new Date(),
            dateData: {},
            cells: ['日', '一', '二', '三', '四', '五', '六'],
            formatDateTimeText: '',
            wh: 'auto'
        };
    },
    created() {
        const date = new Date();
        this.initShowDate(date);
    },
    mounted() {
        this.onResize(this.$refs.mainRef);
    },
    watch: {
        multiple: {
            immediate: true,
            handler(value) {
                if (value && !(this.value instanceof Array)) {
                    throw new Error('In multi-select mode, the value must be an array');
                } else if(value === false && typeof this.value !== 'string') {
                    throw new Error('In radio mode, the value must be a string');
                }
            }
        },
        value: {
            immediate: true,
            handler(value) {
                this.resetDateListChecked(value);
                this.setChecked(value);
            }
        },
        dateList: {
            immediate: true,
            handler() {
                this.setChecked(this.value);
            }
        }
    },
    methods: {
        handleClickChooseDate(data) {
            if (this.isDblclick) {
                return;
            }
           this.chooseDate(data);
        },
        handleDblclickChooseDate(data) {
            if (!this.isDblclick) {
                return false;
            }
           this.chooseDate(data);
        },
        handleSwitchDate(value) {
            switch(value) {
                case 'prevMonth':
                    const prevMonthDate = this.getDateByMonth(this.date, -1);
                    this.initShowDate(prevMonthDate);
                    this.$emit('changeMonth', prevMonthDate);
                    break;
                case 'nextMonth':
                    const nextMonthDate = this.getDateByMonth(this.date, +1);
                    this.initShowDate(nextMonthDate);
                    this.$emit('changeMonth', nextMonthDate);
                    break;
                case 'prevYear':
                    const prevYearDate = this.getDateByMonth(this.date, +12);
                    this.initShowDate(prevYearDate);
                    this.$emit('changeYear', prevYearDate);
                    break;
                case 'nextYear':
                    const nextYearDate = this.getDateByMonth(this.date, -12);
                    this.initShowDate(nextYearDate);
                    this.$emit('changeYear', nextYearDate);
                    break;
                case 'today':
                    this.initShowDate(new Date());
                    break;
            }
            this.operationInstruction = value;
        },
        chooseDate(data) {
            this.$emit('onClick', data);
            if (data.disabled) {
                return false;
            }
            this.$set(data, 'checked', !data.checked);
            const formatDate = this.formatDateTime(data, this.valueFormat);
            const date = new Date(data.stampTime);
            this.$emit('onChoose', date);
            if (data.checked) {
                this.$emit('onSelected', date);
            } else {
                this.$emit('onCancel', date);
            }
            if (data.checked) {
                if (this.multiple) {
                    this.value.push(formatDate);
                    this.$emit('input', this.value);
                    this.$emit('change', this.value);
                } else {
                    this.$emit('input', formatDate);
                    this.$emit('change', formatDate);
                }
            } else {
                if (this.multiple) {
                    const res = this.removeDateItem(this.value, formatDate);
                    this.$emit('input', res);
                    this.$emit('change', res);
                } else {
                    this.$emit('input', '');
                    this.$emit('change', '');
                }
            }
        },
        setChecked(data) {
            if (data === '' || data.length === 0) {
                return false;
            }
            this.dateList.forEach(arr => {
                arr.forEach(item => {
                    if (!item.formatDateTime) {
                        item.formatDate = this.formatDateTime(item, this.valueFormat);
                    }
                    if (data instanceof Array) {
                        if (this.value.indexOf(item.formatDate) > -1) {
                            this.$set(item, 'checked', true);
                        } else {
                            this.$set(item, 'checked', false);
                        }
                    } else {
                        if (this.value === item.formatDate) {
                            this.$set(item, 'checked', true);
                        } else {
                            this.$set(item, 'checked', false);
                        }
                    }
                });
            });
        },
        resetDateListChecked(value) {
            this.dateList.forEach(item => {
                item.checked = false;
            });
        },
        removeDateItem(list, dateStr) {
            const newArr = [];
            list.forEach(item => {
                if (dateStr !== item) {
                    newArr.push(item);
                }
            });
            return newArr;
        },
        getDateData(date) {
            if (!(date instanceof Date)) {
                date = new Date(date);
            }
            this.dateData = this.getDateTimeInfo(date);
            this.formatDateTimeText = this.formatDateTime(this.dateData, this.format)
        },
        initShowDate(date) {
            this.date = date;
            this.getDateData(date);
            this.dateList = this.createdDaysData(date);
        },
        onResize(element) {
            let timer = null;
            this.wh = this.getWh(element.offsetWidth);
            window.onresize = () => {
                if (timer) {
                    return false;
                }
                timer = setTimeout(() => {
                    this.wh = this.getWh(element.offsetWidth);
                    clearTimeout(timer);
                    timer = null;
                }, 100);
            };
        },
        getWh(width) {
            let wh = (width)/7-0.5;
            wh += 'px';
            return wh;
        }
    }

}
</script>
<style lang="scss" scoped>
.calendar-tools {
    overflow: hidden;
    padding: 5px 0px;
    border-bottom: 1px solid #eee;
    margin-bottom: 5px;
    &-title {
        text-align: center;
        overflow: hidden;
    }
    &-btn {
        cursor: pointer;
    }
    &-btns {
        float: right;
        a {
            color: $themeColor;
        }
        padding-right: 12px;
    }
}
.calendar-main {
    padding: 0px 0px;
}
.calendar-box {
    border-bottom: 1px solid #ddd;
    border-right:1px solid #ddd;
    &-row {
        display: flex;
    }
    &-item:hover {
        background-color: $hoverBackgroundColor;
    }
    &-item {
        cursor: pointer;
        flex: 1;
        box-sizing: border-box;
        width: 60px;
        padding: 8px;
        height: 60px;
        border-top: 1px solid #ddd;
        border-left: 1px solid #ddd;
        &-checked {
            color: $themeColor;
        }
        &-other {
            color: #999;
        }
        &-disabled {
            color: #999;
            cursor: not-allowed;
        }
        &-today {
            color: $themeColor
        }
    }
}
</style>