<template>
    <view
        class="calendar"
    >
        <!-- 标题 -->
        <view class="fix-tag-head">
            <view class="date-head">
                <view v-show="showTitle">日期</view>
                <view class="year-month">
                    <view
                        class="left c-gap-right-middle"
                        :class="[
                            visLeft ? 'left-disable' : 'left-able',
                        ]"
                        @tap="handlePreviousMonthTap"
                    />
                    <view class="c-font-normal secect-month">
                        {{ calendarData && calendarData[currSelect] && calendarData[currSelect].mounth }}
                    </view>
                    <view
                        class="right c-gap-left-middle"
                        :class="[
                            visRight ? 'right-disable' : 'right-able',
                        ]"
                        @tap="handleNextMonthTap"
                    />
                </view>
            </view>
            <!-- week -->
            <view class="week">
                <view
                    v-for="(item, index) in weekStrArr"
                    :key="index"
                    :style="{
                        color: '#858585',
                    }"
                    class="week-item c-font-normal"
                >
                    {{ item }}
                </view>
            </view>
        </view>
        <!-- body -->
        <view
            v-if="calendarData[currSelect] && calendarData[currSelect].days"
            class="day c-gap-inner-left-boundary c-gap-inner-right-boundary"
        >
            <scroll-view
                scroll-y
                scroll-with-animation
                :style="{'max-height': maxHeight + 'px'}"
                :scroll-top="scrollTop"
                class="scroll-view"
            >
                <view
                    v-for="(day, dayIndex) in calendarData[currSelect].days"
                    :id="'day-' + day.datetime"
                    :key="calendarData[currSelect].mounth + '-' + dayIndex"
                    class="day-item c-gap-bottom-large"
                    @tap.stop="onTapDate(day)"
                >
                    <view
                        class="day-item-wrap c-color-normal"
                        :class="{'day-item-wrap-selected': day && day.datetime === selected}"
                        :style="{
                            color: (day && day.datetime === selected)
                                ? '#FD503E'
                                : (day && day.status === 1 ? primaryColor : ''),
                        }"
                    >
                        <view
                            v-if="day.day"
                            class="font-15 day-font"
                        >{{ day.day }}</view>
                        <view v-if="day.status === 1" class="c-font-small status">剩{{ day.surplus }}</view>
                        <view v-if="day.status === 2" class="c-font-small status">{{ day.btnText }}</view>
                    </view>
                </view>
            </scroll-view>
        </view>
    </view>
</template>

<script>
/**
 * @file 时间选择
 * @author zhangqian51
 */
import {getSystemInfo} from '@baidu/med-utils/lib/Mars/system';

export default {
    config: {
        component: true
    },
    props: {

        /**
         * 主颜色
         */
        primaryColor: {
            type: String,
            default: '#489af6'
        },

        /**
         * 类型；'default' 单选，'range' 范围选择
         */
        type: {
            type: String
        },
        /**
         * 日期
         */
        dateGroup: {
            type: Array,
            default: () => []
        },
        showTitle: {
            type: Boolean,
            default: true
        },
        isTap: {
            type: Boolean,
            default: true
        }
    },
    data() {
        return {
            env: 'swan',
            weekStrArr: ['日', '一', '二', '三', '四', '五', '六'],
            calendarData: null,
            // 当前选择的calendarData项
            currSelect: 0,
            // 当前选中的日期
            selected: '',
            visLeft: true,
            visRight: false,
            screenHeight: 0,
            scrollTop: 0,
            maxHeight: 0
        };
    },
    created() {
        const systemInfoSync = getSystemInfo();
        this.screenHeight = systemInfoSync.screenHeight;
        const num = this.showTitle ? 50 : 38;
        if (process.env.MARS_ENV === 'h5') {
            // if ((this.screenHeight - 74) * 0.8 > 522) {
            //     this.maxHeight = 224;
            // } else {
            this.maxHeight = (this.screenHeight - 74) * 0.8 - 244 + num;
            // }
        } else {
            // if (this.screenHeight * 0.7 > 522) {
            //     this.maxHeight = 290;
            // } else {
            this.maxHeight = this.screenHeight * 0.8 - 244 + num;
            // }
        }
        this.initCalendar();
    },
    onReady() {
        this.env = process.env.MARS_ENV;
    },
    watch: {
        dateGroup(newVal, oldVal) {
            this.dateGroup = newVal;
            this.initCalendar();
        },
        calendarData(newVal) {
            this.calendarData = newVal;
        }
    },
    methods: {
        // 初始化日历数据
        initCalendar() {
            this.currSelect = 0;
            let dateGroup = this.dateGroup || [];
            let monthArr = [];
            let result = [];
            dateGroup.forEach((item, itemIndex) => {
                if (item.selected) {
                    this.selected = item.datetime;
                }
                let date = item.datetime.replace(/-/g, '');
                let year = date.slice(0, 4);
                let month = date.slice(4, 6);
                let yearMonth = date.slice(0, 6);
                let day = date.slice(6);
                let week = (new Date(`${year}/${month}/${day}`)).getDay();
                let dayData = Object.assign({},
                                            item,
                                            {day},
                                            {weekNum: week}
                );
                // 月份计算
                if (monthArr.indexOf(yearMonth) > -1) {
                    result[monthArr.indexOf(yearMonth)].days.push(dayData);
                }
                else {
                    // 产生空格，保证日期和星期对应上
                    let dayArr = [];
                    for (let i = 0; i < week; i++) {
                        dayArr.push({});
                    }
                    // 新增加一个月份
                    monthArr.push(yearMonth);
                    result.push({
                        mounth: `${year}年${month}月`,
                        mounthNum: month,
                        days: dayArr.concat(dayData)
                    });
                }
            });
            // 处理日期间空格
            result && result.forEach((item, index) => {
                let curYearMonth = `${new Date().getFullYear()}年${Number(new Date().getMonth()) + 1}月`;
                if (curYearMonth === item.mounth) {
                    this.currSelect = index;
                }
                const {days} = item;
                let daysArr = [];
                for (let i = 0; i < days.length; i++) {
                    if (days[i].weekNum === undefined) {
                        daysArr.push({});
                    } else {
                        daysArr.push(days[i]);
                        if (days[i + 1]) {
                            let j = days[i + 1].weekNum === 0 ? 7 : days[i + 1].weekNum;
                            let sub = j - days[i].weekNum;
                            for (let q = 1; q < sub; q++) {
                                /* eslint-disable max-len */
                                let day = Number(days[i].day) + 1 < 10 ? `0${Number(days[i].day) + 1}` : Number(days[i].day) + 1;
                                /* eslint-enable max-len */
                                let datetime = `${days[i].datetime.slice(0, 8)}${day}`;
                                daysArr.push({
                                    datetime: datetime,
                                    status: 2,
                                    day: day,
                                    btnText: '约满'
                                });
                            }
                        }
                    }
                }
                result[index].days = daysArr;
            });
            // 初始化月份切换
            if (result.length === 1) {
                this.visLeft = true;
                this.visRight = true;
            } else {
                this.visLeft = false;
                this.visRight = false;
                if (this.currSelect === 0) {
                    this.visLeft = true;
                }
                if (this.currSelect === result.length - 1) {
                    this.visRight = true;
                }
            }
            this.calendarData = result;
        },

        // 点击某个日期
        onTapDate(day) {
            if (!this.isTap) {
                return;
            }
            if (day && day.status === 1) {
                this.selected = day.datetime;
                this.$emit('changeDate', day.datetime);
            }
        },

        // 前一个月点击
        handlePreviousMonthTap() {
            if (this.visLeft) {
                return;
            }
            this.visRight = false;
            if (this.currSelect < 2) {
                this.visLeft = true;
            }
            --this.currSelect;
            this.scrollTop = 0;

        },

        // 下一个月点击
        handleNextMonthTap() {
            if (this.visRight) {
                return;
            }
            this.visLeft = false;
            if (this.currSelect > this.calendarData.length - 3) {
                this.visRight = true;
            }
            ++this.currSelect;
            this.scrollTop = 0;

        }
    }
};
</script>

<style lang="less" scoped>
.calendar {
    background-color: #fff;
    padding-bottom: 60px;
    // padding-top: 64px;
}

.fix-tag-head {
    top: 0;
    width: 100%;
    z-index: 922;
}

.date-head {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    position: relative;
    color: #555;
    line-height: 40px;
    height: 28px;
    padding-left: 17px;
}

.year-month {
    background-color: #f5f5f5;
    border-radius: 100px;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: .07rem;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);

    .left-able {
        border-top: .05rem solid transparent;
        border-bottom: .05rem solid transparent;
        border-right: .05rem solid #999;
    }

    .right-able {
        border-top: .05rem solid transparent;
        border-bottom: .05rem solid transparent;
        border-left: .05rem solid #999;
    }

    .left-disable {
        border-top: .05rem solid transparent;
        border-bottom: .05rem solid transparent;
        border-right: .05rem solid #dfdfdf;
    }

    .right-disable {
        border-top: .05rem solid transparent;
        border-bottom: .05rem solid transparent;
        border-left: .05rem solid #dfdfdf;
    }

    .left::after,
    .right::after {
        content: '';
        display: block;
        width: .4rem;
        height: .4rem;
        position: absolute;
        top: -1px;
    }

    .left::after {
        left: -20px;
    }

    .right::after {
        right: -20px;
    }
}

.icon {
    padding: 10px;
}

.week {
    display: flex;
    padding-left: 17px;
    padding-right: 17px;
    align-items: center;
    height: 46px;
    border-bottom: 1px solid #f1f1f1;
}

.week-item {
    flex: 1;
    text-align: center;
    font-size: 14px;
}

.day {
    padding-top: 17px;

    &-item {
        display: inline-block;
        vertical-align: top;
        text-align: center;
        width: 14.2%;
    }

    &-item-wrap {
        width: 48px;
        height: 48px;
        border-radius: 50%;
        padding: 2px;
        margin: 0 auto;
        color: #858585;
        display: flex;
        flex-direction: column;
        justify-content: center;
        box-sizing: border-box;

        &-selected {
            background: #fff5f4;
            border: 1px solid #fd503e;
            border-radius: 8px;
            // box-sizing: border-box;
        }

        .status {
            margin-top: -4px;
            // font-size: 14px;
        }

        .font-15 {
            font-size: 15px;
            line-height: 18px;
            color: #1f1f1f;
            margin-bottom: 8px;
        }

        .day-status-01 {
            color: #489af6;
        }

        .day-status-02 {
            color: #999;
        }
    }

    &-status {
        margin-top: -8px;
    }

    .c-gap-bottom-large {
        margin-bottom: 30px;
    }
}

.time-wrap {
    .title {
        color: #555;
        line-height: 40px;
    }
}

.scroll-view::-webkit-scrollbar {
    width: 0;
    height: 0;
    color: transparent;
}

.day-font {
    font-size: 16px;
}

.secect-month {
    line-height: 14px;
    color: #1f1f1f;
}
</style>
