<template>
    <div id="DatePicker">
        <!-- 选择年份 -->
        <el-date-picker
            v-if="type === 'year' || type === 'month' || type === 'date' || type === 'dates' || type === 'datetime'"
            v-model="dateValue"
            :type="type"
            placeholder="选择时间"
            :picker-options="pickerOptions || tempPickerOptions"
            :value-format="valueFormat"
            :default-time="defaultTime"
            @change="datePickerChange"
        />
        <el-time-select
            v-else-if="type === 'time'"
            v-model="dateValue"
            :picker-options="pickerOptions"
            placeholder="选择时间"
            @change="datePickerChange"
        />
        <div v-else-if="type === 'datetimerange' || type === 'daterange' || type==='monthrange'">
            <el-date-picker
                ref="datePickerRef"
                v-model="dateRangeArr"
                :type="type"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                unlink-panels
                :picker-options="pickerOptions || tempPickerOptions"
                :value-format="valueFormat"
                :default-time="defaultTime"
                @input="immediUpdate"
            />
        </div>
    </div>
</template>

<script>
import { datePickerOptions, dayPickerOptions, monthPickerOptions } from '@/tool/pickerOptions';
export default {
    name: 'DatePicker',
    components: { },
    props: {
        dateRange: {
            type: Array,
            default: () => []
        },
        // 可选的时间间隔，默认七天范围（中间隔6天）
        selectDateRange: {
            type: Number,
            default: 3600 * 1000 * 24 * 6
        },
        // 总共的时间范围
        totalDateRange: {
            type: Number,
            default: 3600 * 1000 * 24 * 30
        },
        type: {
            type: String,
            default: 'daterange'
        },
        hasDatePicker: {
            type: Boolean,
            default: false
        },
        // 是否限制可选范围
        isLimitDateRange: {
            type: Boolean,
            default: false
        },
        // 是否带快捷项
        hasQuickItem: {
            type: Boolean,
            default: false
        },
        defaultTime: {
            type: [Array, String],
            default: ''
            // default: () => ['00:00:00', '23:59:59']
        },
        valueFormat: {
            type: String,
            default: 'yyyy-MM-dd HH:mm:ss'
        },
        initialValue: {
            type: Number,
            default: 0
        },
        pickerOptions: {
            type: Object,
            default: () => { }
        }
    },
    data() {
        return {
            dateRangeArr: [],
            maxToolTipWidth: '',
            // 默认30天范围
            // timeDefaultShow: new Date(new Date().getTime() - 30 * 24 * 60 * 60),
            minDate: '',
            maxDate: '',
            dateValue: '',
            tempPickerOptions: {}
        };
    },
    watch: {
        dateRange(val) {
            this.dateRangeArr = JSON.parse(JSON.stringify(val));
        },
        totalDateRange() {
            this.getPickerData();
        }
    },
    mounted() {
        this.dateRangeArr = JSON.parse(JSON.stringify(this.dateRange));
        if (this.initialValue) {
            const startTime = this.$dayjs().subtract(this.initialValue, 'day').format('YYYY-MM-DD HH:mm:ss');
            const endTime = this.$dayjs().format('YYYY-MM-DD HH:mm:ss');
            this.dateRangeArr.push(startTime, endTime);
        }
        this.getPickerData();
    },
    methods: {
        datePickerChange() {
            console.log('this.dateValue', this.dateValue);
            this.$emit('getDateRange', this.dateValue);
        },
        getPickerData() {
            this.timeDefaultShow = new Date(new Date().getTime() - this.totalDateRange);
            if ((this.type === 'datetimerange' || this.type === 'monthrange' || this.type === 'daterange') && this.isLimitDateRange) {
                // isLimitDateRange 和 hasQuickItem互斥，因为limitDateRange是限制时间的，目前是默认限制7天,hasQuickItem是快捷选择时间的，默认是一周，一个月，三个月
                this.tempPickerOptions = {
                    onPick: ({ maxDate, minDate }) => {
                        this.minDate = minDate;
                        this.maxDate = maxDate;
                    },
                    disabledDate: time => {
                        if (this.$refs.datePickerRef.picker) {
                            this.minDate = this.$refs.datePickerRef.picker.minDate;
                            this.maxDate = this.$refs.datePickerRef.picker.maxDate;
                        }
                        const todayStamp = this.getStamp();
                        // 大于今天23:59:59
                        const compareWithNow = time.getTime() > todayStamp;
                        // 限制了总共可选择的范围
                        const rangeDisabled =
                        time.getTime() < todayStamp - this.todayDateRange;
                        if (this.minDate) {
                            const range = this.selectDateRange;
                            let compareWithSum = false;
                            let compareWithSub = false;
                            if (this.type === 'monthrange') {
                                compareWithSum = time.getTime() > this.minDate.getTime() + range;
                                compareWithSub = time.getTime() < this.getMonthStamp(this.minDate) - range;
                            } else {
                                // 大于（minDate-1)23:59:59 + 时间段
                                compareWithSum = time.getTime() > this.getStamp(this.minDate) + range;
                                // 小于minDate0:00:00 - 时间段
                                compareWithSub = time.getTime() < this.minDate.getTime() - range;
                            }
                            const commonCompare = compareWithNow || compareWithSum || compareWithSub;
                            return this.isLimitDateRange ? (commonCompare || rangeDisabled) : commonCompare;
                        }
                        return this.isLimitDateRange
                            ? compareWithNow || rangeDisabled
                            : compareWithNow;
                    }
                };
            } else if (this.hasQuickItem) {
                if (this.type === 'daterange' || this.type === 'datetimerange') {
                    this.tempPickerOptions = datePickerOptions;
                } else if (this.type === 'datetime') {
                    this.tempPickerOptions = dayPickerOptions;
                } else if (this.type === 'monthrange') {
                    this.tempPickerOptions = monthPickerOptions;
                }
            }
        },
        clear() {
            this.minDate = '';
            this.maxDate = '';
            this.dateRangeArr = [];
        },
        // 清除组件子代清除按钮的可选范围
        immediUpdate(val) {
            if (val === null) {
                this.minDate = '';
                this.maxDate = '';
            }
            console.log('immediUpdate222', val);
            this.$emit('getDateRange', val);
        },
        getStamp(date) {
            const newDate = date ? new Date(date) : new Date();
            return newDate.setHours(0, 0, 0, 0) + 3600 * 1000 * 24 - 1;
        },
        getMonthStamp(date) {
            const newDate = date ? newDate(date) : new Date();
            return newDate.getMonth(newDate.getMonth() + 1) - 1;
        },
        handlePicker(picker, timeDate) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - timeDate);
            picker.$emit('pick', [start, end]);
        }
    }
};
</script>

<style lang="less" scoped>
</style>
