<template>
    <div :class="classStr" @touchstart="fnTouchStart" @touchmove="fnTouchEnd">
        <div class="yDate_month">
            <div class="yDate_month_wrap">
                <div class="yDate_part" v-for="(month,monthIndex) in months" :key="monthIndex">
                    <div class="yDate_month_title">{{month}}</div>
                    <div class="yDate_month_row yDate_month_header">
                        <div v-for="(item,index) in header" :key="index">{{item}}</div>
                    </div>
                    <div class="yDate_month_row" v-for="(week,weekIndex) in cache[month]" :key="week.key">
                        <div v-for="(day,dayIndex) in week.list" :class="day.classStr">
                            <div @click.stop="fnClick(day)" :key="day.dayKey">{{day.value}}</div>
                        </div>

                    </div>
                </div>
            </div>

        </div>
        <div class="yDate_Time" v-if="withTime" :style="(selectStart && selectEnd) ? 'transform:translateY(0);' : ''">
            <div class="yDate_Time_box">
                <div class="yDate_Time_start">
                    <div>{{tipsPickUpTime}}</div>
                    <div>{{selectStart}}</div>
                </div>
                <div class="yDate_Time_to">
                    <div>{{selectDuration}} {{tipsDay}}</div>
                </div>
                <div class="yDate_Time_start">
                    <div>{{tipsDropOffTime}}</div>
                    <div>{{selectEnd}}</div>
                </div>
            </div>
            <div class="yDate_Time_picker">
                <div class="yDate_Time_startHours">
                    <y-picker :columns="hoursStart"
                              font-size="14px"
                              check-color="#49c6d8"
                              item-size="small"
                              :value-key="hourStart"
                              @update:valueKey="val=>hourStart=val"></y-picker>
                </div>
                <div class="yDate_Time_sy">:</div>
                <div class="yDate_Time_startMinute">
                    <y-picker :columns="minute"
                              font-size="14px"
                              check-color="#49c6d8"
                              item-size="small"
                              :value-key="minutestart"
                              @update:valueKey="val=>minutestart=val"
                              ></y-picker>
                </div>
                <div class="yDate_Time_pickerTo">
                </div>
                <div class="yDate_Time_endHours">
                    <y-picker :columns="hoursEnd"
                              font-size="14px"
                              check-color="#49c6d8"
                              item-size="small"
                              :value-key="hourEnd"
                              @update:valueKey="val=>hourEnd=val"
                              ></y-picker>
                </div>
                <div class="yDate_Time_sy">:</div>
                <div class="yDate_Time_endMinute">
                    <y-picker :columns="minute"
                              font-size="14px"
                              check-color="#49c6d8"
                              item-size="small"
                              :value-key="minuteEnd"
                              @update:valueKey="val=>minuteEnd=val"
                              ></y-picker>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import {getTime, newDate} from "../utils/utils";
    import yPicker from "./yPicker";
    import Vue from "vue";
    import {each, isArray} from "../utils/utils"

    export default {
        name: "yDate",
        components: {
            yPicker
        },
        computed: {

            classStr() {
                return "yDate" + (this.customClass ? " " + this.customClass : "") +
                    (this.noAbsolute ? 'yDate_noAbsolute' : '') +
                    (this.withTime ? " yDate_withDate" : "");
            },
            header() {
                return this.langPackage.yDate && this.langPackage.yDate.header && this.langPackage.yDate.header.length == 7 ? this.langPackage.yDate.header : [];
            },
            hoursEnd() {
                let ret = [];
                let max = 24;
                let min = 0;
                let selectEnd = newDate(this.selectEnd).getTime();
                //判断选择的开始时间是否和能选择的时间最小为同一天,如果是同一天，则最小值设定为开始的那个小时
                if (!isNaN(selectEnd) && getTime(selectEnd, "YYYY-mm-dd") == getTime(newDate(this.startDate).getTime(), "YYYY-mm-dd")) {
                    min = parseInt(getTime(newDate(this.startDate).getTime(), "hh"));
                }
                //判断选择的开始时间是否和能选择的最大时间为同一天,如果是同一天，则最大值设定为开始的那个小时
                if (!isNaN(selectEnd) && getTime(selectEnd, "YYYY-mm-dd") == getTime(newDate(this.endDate).getTime(), "YYYY-mm-dd")) {
                    max = parseInt(getTime(newDate(this.startDate).getTime(), "hh"));
                }
                for (var n = min; n < max; n++) {
                    ret.push(n < 10 ? ("0" + n) : n);
                }
                return ret;
            },
            hoursStart() {
                let ret = [];
                let max = 24;
                let min = 0;
                let selectStart = newDate(this.selectStart).getTime();
                //判断选择的开始时间是否和能选择的时间最小为同一天,如果是同一天，则最小值设定为开始的那个小时
                if (!isNaN(selectStart) && getTime(selectStart, "YYYY-mm-dd") == getTime(newDate(this.startDate).getTime(), "YYYY-mm-dd")) {
                    min = parseInt(getTime(newDate(this.startDate).getTime(), "hh"));
                }
                //判断选择的开始时间是否和能选择的最大时间为同一天,如果是同一天，则最大值设定为开始的那个小时
                if (!isNaN(selectStart) && getTime(selectStart, "YYYY-mm-dd") == getTime(newDate(this.endDate).getTime(), "YYYY-mm-dd")) {
                    max = parseInt(getTime(newDate(this.startDate).getTime(), "hh"));
                }
                for (var n = min; n < max; n++) {
                    ret.push(n < 10 ? ("0" + n) : n);
                }
                return ret;
            },
            minute() {
                let ret = ["00", "30"];
                /*for (var n = 0; n < 60; n++) {
                    ret.push(n < 10 ? ("0" + n) : n);
                }*/
                return ret;
            },
            selectStartDay() {
                let ret = "";
                ret = newDate(this.selectStart);
                ret.setHours(0, 0, 0, 0);
                if (isNaN(ret)) {
                    ret = "";
                } else {
                    ret = ret.getTime();
                }
                return ret;
            },
            selectEndDay() {
                let ret = "";
                ret = newDate(this.selectEnd);
                ret.setHours(0, 0, 0, 0);
                if (isNaN(ret)) {
                    ret = "";
                } else {
                    ret = ret.getTime();
                }
                return ret;
            },
            selectDuration() {
                let ret = 0;
                if (this.selectStart && this.selectEnd) {
                    let startMount = newDate(this.selectStart).setHours(parseInt(this.hourStart), parseInt(this.minutestart), 0, 0);
                    let endMount = newDate(this.selectEnd).setHours(parseInt(this.hourEnd), parseInt(this.minuteEnd), 0, 0);
                    ret = Math.ceil((endMount - startMount) / (24 * 60 * 60 * 1000));
                }
                return ret;
            },
            startDateDayTime() {
                return newDate(this.startDate).setHours(0, 0, 0, 0);
            },
            tipsPickUpTime() {
                return this.langPackage.yDate.pickUpTime || "取车时间";
            },
            tipsDropOffTime() {
                return this.langPackage.yDate.dropOffTime || "还车时间";
            },
            tipsDay() {
                return this.langPackage.yDate.day || "天";
            },
            endDateDayTime() {
                return newDate(this.endDate).setHours(0, 0, 0, 0);
            }
        },
        data() {
            return {
                cache: {},
                hourStart: "",
                hourEnd: "",
                splitStr: "-",
                minutestart: "",
                minuteEnd: "",
                months: [],
                selectStart: "",
                selectEnd: "",
                selectTimeStart: "00:00",
                selectTimeEnd: "00:00",
                todayTime: new Date().setHours(0, 0, 0, 0),
            }
        },
        methods: {
            fnClick(item) {
                const self = this;
                if (!item || !item.dayTime || self.getClass(item.dayTime).indexOf("yDate_disable") > -1) return;
                let ccTime = getTime(item.dayTime, "YYYY-mm-dd");
                if (self.selectStart && self.selectEnd) {
                    self.selectStart = ccTime;
                    self.selectEnd = "";
                } else if (self.selectStart) {
                    if (ccTime > self.selectStart) {
                        self.selectEnd = ccTime;
                    } else {
                        self.selectEnd = self.selectStart;
                        self.selectStart = ccTime;
                    }
                } else {
                    self.selectStart = ccTime;
                }
            },
            fnCountClassStr() {
                const self = this;
                each(self.cache, (month, monthKey) => {
                    if (isArray(month)) {
                        month.forEach((week, weekKey) => {
                            week.list.forEach((day, dayKey) => {
                                if (day && day.dayTime) {
                                    day.classStr = self.getClass(day.dayTime);
                                    //Vue.set(self.cache[monthKey][weekKey][dayKey], "classStr", self.getClass(day.dayTime));
                                }
                            })
                        })
                    }
                })
                self.$forceUpdate();


            },
            foramtTime(year, month, day) {
                return newDate(year + "-" + month + "-" + day + " 00:00:00");
            },
            getMonth(time, isDouble) {
                let ccDate = newDate(time);
                let ret = ccDate.getMonth();
                ret = isNaN(ret) ? false : ret + 1;
                if (ret < 10 && isDouble) {
                    ret = "0" + ret;
                }
                return ret;
            },
            getClass(thisDay) {
                const self = this;
                let ret = "";
                if (thisDay) {
                    let startDay = self.selectStartDay;
                    let endDay = self.selectEndDay;
                    if (thisDay == startDay) {
                        ret += "yDate_start ";
                        if (endDay - startDay > 0) {
                            ret += "yDate_select "
                        }
                    }
                    if (thisDay == endDay) {
                        ret += "yDate_end ";
                        if (endDay - startDay > 0) {
                            ret += "yDate_select "
                        }
                    }
                    if (thisDay > self.selectStartDay && thisDay < self.selectEndDay) {
                        ret += "yDate_select "
                    }
                    if (self.disSelectOver && (thisDay < self.startDateDayTime || thisDay > self.endDateDayTime)) {
                        ret += "yDate_disable"
                    }
                }
                return ret;
            },
            getYear(time) {
                return newDate(time).getFullYear();
            },
            getLastDay(year, month) {
                var new_year = year; //取当前的年份
                var new_month = month++;//取下一个月的第一天，方便计算（最后一天不固定）
                if (month > 12) {
                    new_month -= 12; //月份减
                    new_year++; //年份增
                }
                var new_date = new Date(new_year, new_month, 1); //取当年当月中的第一天
                return (new Date(new_date.getTime() - 1000 * 60 * 60 * 24)).getDate();//获取当月最后一天日期
            },
            setProps() {
                if (this.selectStart && !isNaN(parseInt(this.hourStart)) && !isNaN(parseInt(this.minutestart))) {
                    let str = getTime(newDate(this.selectStart).setHours(this.hourStart, this.minutestart, 0, 0), "YYYY-mm-dd hh:ii:00");
                    this.$emit("update:selectStartTime", str)
                } else {
                    this.$emit("update:selectStartTime", "")
                }
                console.log("hourEnd1",this.hourEnd)
                if (this.selectEnd && !isNaN(parseInt(this.hourEnd)) && !isNaN(parseInt(this.minuteEnd))) {
                    let str = getTime(newDate(this.selectEnd).setHours(this.hourEnd, this.minuteEnd, 0, 0), "YYYY-mm-dd hh:ii:00");
                    this.$emit("update:selectEndTime", str)
                } else {
                    this.$emit("update:selectEndTime", "")
                }
            },
            setMonthDate(year, month, index) {
                const self = this;
                if (self.cache[year + "-" + month]) return;
                let firstDate = newDate(year + "-" + month + "-" + "01");
                let firstDay = firstDate.getDay();
                let source = [];
                let lastDateNumber = self.getLastDay(year, month);
                for (var n = 1; n <= lastDateNumber; n++) {
                    if (!source[0] || source[source.length - 1].list.length >= 7) {
                        source.push({
                            key:index + "_"+source.length,
                            list:[]
                        });
                    }
                    let ccItem = source[source.length - 1].list;
                    let thisDay = self.foramtTime(year, month, n).getTime();
                    let ccKey = "date:"+year + "_" + month + "_" +n

                    //1号之前
                    if (n == 1) {
                        for (let t = 0; t < firstDay; t++) {
                            ccItem.push({
                                value: "",
                                dayTime: "",
                                dayKey: ccKey+t,
                                classStr: ""
                            });
                        }
                    }
                    //今天
                    if (thisDay == self.todayTime && self.today) {
                        ccItem.push({
                            value: self.today,
                            dayTime: thisDay,
                            dayKey: ccKey,
                            classStr: self.getClass(thisDay)
                        });
                    }
                    //有日子的时间
                    else {
                        ccItem.push({
                            value: n,
                            dayTime: thisDay,
                            dayKey: ccKey,
                            classStr: self.getClass(thisDay)
                        });
                    }
                    //最后一个礼拜
                    if (n == lastDateNumber) {
                        for (let t = ccItem.length; t < 7; t++) {
                            ccItem.push({
                                value: "",
                                dayTime: "",
                                dayKey: ccKey+t,
                                classStr: ""
                            });
                        }
                    }
                }
                self.cache[index] = source;
            },
            initMonths() {
                const self = this;
                let startMonth = self.getMonth(self.startDate);
                let startYear = self.getYear(self.startDate);
                let endMonth = self.getMonth(self.endDate);
                let endYear = self.getYear(self.endDate);
                console.log("initMonthsStart",self.startDate,startMonth,startYear)
                console.log("initMonthsEnd",self.endDate,endMonth,endYear)
                if (startMonth && startYear && endMonth && endYear) {
                    let countMonth = startMonth;
                    let countYear = startYear;
                    let loop = 0;
                    let maxLoop = 500;
                    while (!((countMonth > endMonth && countYear >= endYear) || countYear > endYear) && loop++ < maxLoop) {
                        let index = countYear + self.splitStr + (countMonth < 10 ? ("0" + countMonth) : countMonth);

                        self.months.push(index)
                        self.setMonthDate(countYear, countMonth, index)
                        countMonth++;
                        if (countMonth > 12) {
                            countMonth = 1;
                            countYear++;
                        }
                    }
                }

            },
            initTime() {
                let selectStartTime = newDate(this.selectStartTime).getTime();
                let selectEndTime = newDate(this.selectEndTime).getTime();

                //如果开始时间大于结束时间，则置换时间
                if (selectStartTime && selectEndTime && selectEndTime < selectStartTime) {
                    let a = selectStartTime;
                    selectStartTime = selectEndTime;
                    selectEndTime = a;
                }
                if (selectStartTime) {
                    this.selectStart = getTime(selectStartTime, "YYYY-mm-dd");
                    this.hourStart = getTime(selectStartTime, "hh");

                    this.minutestart = getTime(selectStartTime, "ii");
                    this.minutestart = this.minutestart >= 30 ? "30" : "00"
                }
                if (selectEndTime) {
                    this.selectEnd = getTime(selectEndTime, "YYYY-mm-dd");
                    this.hourEnd = getTime(selectEndTime, "hh");
                    this.minuteEnd = getTime(selectEndTime, "ii");
                    this.minuteEnd = this.minuteEnd >= 30 ? "30" : "00"
                }


            },
            fnTouchStart(e) {
                e.stopPropagation();
            },
            fnTouchEnd(e) {

                e.stopPropagation();
            }
        },
        props: {
            //允许选择的开始时间
            startDate: {
                default: "2019-11-15"
            },
            //允许选择的结束时间
            endDate: {
                default: "2020-11-01"
            },
            today: {
                default: "今天"
            },
            format: {
                default: "YYYY-mm-dd"
            },
            disSelectOver: {
                type: Boolean,
                default: true
            },
            langPackage: {
                type: Object,
                default() {
                    return {
                        yDate: {
                            header: ["日", "一", "二", "三", "四", "五", "六"],
                            pickUpTime: "取车时间",
                            dropOffTime: "还车时间",
                            day: "天"
                        }
                    }
                }
            },
            withTime: {
                type: Boolean,
                default: true
            },
            noAbsolute: {
                type: Boolean
            },
            selectStartTime: "",
            selectEndTime: "",

        },
        watch: {
            selectStartTime() {
                this.initTime();
            },
            selectEndTime() {
                this.initTime();
            },
            selectStart() {
                const self = this;
                setTimeout(tick => {
                    self.fnCountClassStr();
                }, 100)
                this.setProps();
            },
            selectEnd() {
                const self = this;
                setTimeout(tick => {
                    self.fnCountClassStr();
                }, 100)
                this.setProps();
            },
            hourStart() {
                console.log(1);
                this.setProps();
            },
            hourEnd() {
                console.log(2);
                this.setProps();
            },
            minutestart() {
                console.log(3);
                this.setProps();
            },
            minuteEnd() {
                console.log(4);
                this.setProps();
            }
        },
        beforeMount() {
            this.initTime();
            this.initMonths()
        }
    }
</script>

<style lang="scss">
    @import "../css/var.scss";

    $yDate_main_color: #49c6d8;
    $yDate_select_color: #e7f9fd;
    $yDate_width: 34px;
    $yDate_Time_height: 225px;
    .yDate {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: hidden;

        &.yDate_withDate {

            .yDate_month {
                padding-bottom: $yDate_Time_height + 20px;

                .yDate_month_wrap {
                    overflow: auto;
                }
            }
        }

        &.yDate_noAbsolute {
            position: relative;
        }

    }

    .yDate_month {
        position: relative;
        height: 100%;
        box-sizing: border-box;
        overflow: auto;
        -webkit-overflow-scrolling: touch;
    }

    .yDate_part {
        margin-bottom: 20px;
    }

    .yDate_month_title {
        height: 48px;
        text-align: center;
        font-size: $font-size_t2;
        line-height: 48px;
        border-bottom: 1px solid $color_border_default;
    }

    .yDate_month_row {
        height: $yDate_width;
        line-height: $yDate_width;
        margin-top: 7px;
        display: flex;

        & > div {
            flex: 1;
            overflow: hidden;
            text-align: center;
            position: relative;
            transition: all .3s;

            & > div {
                display: inline-block;
                width: $yDate_width;
                height: $yDate_width;
                font-size: $font_size_t4;
                border-radius: 50%;
                transition: all .3s;
            }

            &:before, &:after {

                transition: all .3s ease-in-out 2s;
            }
        }
    }

    .yDate_month_header {

        margin-top: 0px;
    }

    .yDate_select {
        background: $yDate_select_color;
    }

    .yDate_disable {
        color: #a2a2a2;
    }

    .yDate_start, .yDate_end {
        background: none;

        & > div {
            display: inline-block;
            width: $yDate_width;
            height: $yDate_width;
            border-radius: 50%;
            background: $yDate_main_color;
            position: relative;
            z-index: 2;
            color: #fff;
        }
    }

    .yDate_start {
        &:after {
            content: " ";
            display: block;
            width: 50%;
            position: absolute;
            background: $yDate_select_color;
            right: 0;
            top: 0;
            height: $yDate_width;
        }
    }

    .yDate_end {
        &:before {
            content: " ";
            display: block;
            width: 50%;
            position: absolute;
            background: $yDate_select_color;
            left: 0;
            top: 0;
            height: $yDate_width;
        }
    }


    .yDate_Time {
        box-sizing: border-box;
        height: $yDate_Time_height +30px;
        background: #fff;
        border-top: 10px solid #f7f7f7;
        padding-top: 15px;
        transition: all .3s;
        transform: translateY(100%);
        position: absolute;
        width: 100%;
        bottom: 0;
        z-index: 2;
        left: 0;
    }

    .yDate_Time_box {
        width: 280px;
        border-radius: 5px;
        background: $yDate_main_color;
        display: flex;
        margin: 0 auto;
        padding: 8px 35px;
        font-size: $font_size_t5;
        color: #fff;
        box-sizing: border-box;
    }

    .yDate_Time_start {
        flex: 1;

        & > div:first-child {
            margin-bottom: 5px;

        }
    }

    .yDate_Time_to {
        align-self: center;
        background: #fff;
        color: $yDate_main_color;
        padding: 0 8px;
        border-radius: 50px;
        margin: 0 15px;

        & > div {
            transform: scale(.8);
            transform-origin: center center;
        }
    }

    .yDate_Time_picker {
        display: flex;
        width: 220px;
        margin: 0 auto;

        & > div {
            flex: 1;
        }

        .y_picker_columnChecked {
            color: $yDate_main_color;


        }

        .y_picker_column {
            font-size: $font_size_t4;
        }
    }

    .yDate_Time_sy {
        color: $yDate_main_color;
        align-self: center;
        font-weight: bold;
        width: 15px;
        flex: none !important;
    }

    .yDate_Time_pickerTo {
        align-self: center;

        &:before {
            content: "\e727";
            color: $yDate_main_color;
            font-family: "yesaway_ui";
        }
    }
</style>
