<template>
    <div class="wj-calendar-box">
        <!--左边-->
        <div class="calendar-left">
            <!--菜单标题栏-->
            <div class="calendar-title">
                <!-- <span>{{initCurrentMonth}}</span> -->
                <Button class="ivu-btn-blue btn-back-today mr10" @click="onBackToday">返回今天</Button>
                <Select v-model="currentYear" @on-change="onChangeYear" class="sel-calendar">
                    <Option v-for="item in years" :value="item.value" :key="item.value">{{ item.label }}</Option>
                </Select>
                <Icon type="ios-arrow-back" class="ml10 mr5 cursor-pointer" color="#008080" @click.native="onPreMonth" />
                <Select v-model="currentMonth" @on-change="onChangeMonth"  class="sel-calendar">
                    <Option v-for="item in months" :value="item.value" :key="item.value">{{ item.label }}</Option>
                </Select>
                <Icon type="ios-arrow-forward" class="ml5 cursor-pointer" color="#008080" @click.native="onNextMonth" />
            </div>
            <!--日历表格-->
            <div class="left-body">
                <table class="calendar-table">
                    <thead>
                    <tr>
                        <th v-for="val in weekdays" :key="val">{{val}}</th>
                    </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(week,index) in calendars" :key="index">
                            <td v-for="(day,i) in week" :key="i" :class="{'other-month':!day.is_currentMonth,'work-day':day.work_type === '99',
                            'rest-day':day.work_type === '2' || day.work_type === '4','holiday':day.work_type === '3','today':day.is_currentMonth && day.day === new Date().getDate()&&
                            (day.month === new Date().getMonth() + 1) && day.year === new Date().getFullYear()}">
                                <div @click="onCheckDate(day.day,$event,day.is_currentMonth,!day.is_currentMonth)" :class="{'active':day.is_currentMonth && day.day === currentDay}">
                                    <!-- {{day.day}}
                                    <Checkbox v-model="day.checked" style="position:absolute;top:0;right:10px" :disabled="!day.is_currentMonth"></Checkbox> -->                                   
                                    <Tooltip placement="top-end" transfer v-if="day.isNew">
                                        <span style="background:pink">{{day.day}}</span>
                                        <div slot="content">
                                            <div v-for="detail in day.detailArr" :key="detail.lineId">
                                                <p>{{detail.lineId+'号线' }}</p>
                                                <p>{{'首班：' + detail.firstTime }}</p>
                                                <p>{{'末班：' + detail.lastTime}}</p>
                                            </div>
                                        </div>    
                                    </Tooltip>
                                    <span v-else>{{day.day}}</span>
                            </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <!--右边-->
        <!-- <div class="calendar-right">
            <div class="calendar-title text-center">
                {{currentDate}}
            </div>
            <div class="right-day">
                {{currentDay}}
            </div>
            <div class="mt20 mb20 ml10">
              设置为：
            </div>
            <Select v-model="work_type" style="width:128px" class="ml10 mb20">
                <template v-if="method === 1">
                    <Option :value="1">上班</Option>
                    <Option :value="2">公休</Option>
                </template>
                <template v-else>
                     <Option :value="0">删除</Option>
                     <Option :value="99">上班</Option>
                     <Option :value="3">节假日</Option>
                     <Option :value="4">公休日</Option>
                </template>

            </Select>
            <Button class="ivu-btn-blue mt10 ml10" style="width: 128px" @click="onSubmitWorkType">保存</Button>
        </div> -->
    </div>
</template>

<script>
    export default {
      name: "CalendarSetting",
        props: {
            // url_data:String,   //请求数据接口url
            // url_set: String,   //设置状态接口url
            show_other_month: {  //是否显示非本月日期
                type: Boolean,
                default: true
            },
            method: {
                type: Number,
                default: 0
            },
            initCurrentYear:{
                type: Number,
                default: 0
            },
            initCurrentMonth:{
                type: String,
                default: ''
            },
            currentMonthNum: {
                type: Number,
                default: 1
            },
            // calendarData: {
            //     type: Object,
            //     default: () => {}
            // },
            calendarData: {
                type: Array,
                default: () => []
            }
        },
        data() {
            return {
                // currentYear: 0,    //当前年
                // currentMonth: 0,   //当前月
                currentYear: new Date().getFullYear(),    //当前年
                currentMonth: new Date().getMonth() + 1,   //当前月
                weekdays: ['一','二','三','四','五','六','日'],
                calendars:[],  //日历数据
                currentDate: '',   //右边标题栏显示日期
                currentDay: new Date().getDate(),     //右边大字日期
                work_type: 1,  //作息状态
                is_year_eve: false,   //是否跨年
            }
        },
        computed: {
            years() {
                let arr = [];
                for(let i = 1970; i<=2050; i++) {
                    let obj = {};
                    obj.value = i;
                    obj.label = i + '年';
                    arr.push(obj);
                }
                return arr;
            },
            months() {
                let arr = [];
                for (let i = 1; i <= 12; i++) {
                    let obj = {};
                    obj.value = i;
                    obj.label = i + '月';
                    arr.push(obj);
                }
                return arr;
            }
        },
        created() {
            // this.currentYear = this.initCurrentYear
            // this.currentMonth = this.initCurrentMonth
            const weekday = new Date().getDay() === 0 ? 7 : new Date().getDay();
            this.currentDate = new Date().getFullYear() + '-' + (new Date().getMonth() < 9 ? '0' + (new Date().getMonth() + 1) : new Date().getMonth() + 1)
                + '-' + (new Date().getDate() < 10 ? '0' + new Date().getDate() : new Date().getDate()) + ' 星期' + this.weekdays[weekday - 1];
            this.onGetCalendarData();
        },
        mounted() {
            // $('.ivu-select .ivu-icon-arrow-down-b').addClass('icon-arrow-down').removeClass('ivu-icon-arrow-down-b').addClass('arrow-mini');
        },
        methods: {
            /**
             * 获取后台日历数据
             */
            onGetCalendarData() {
                this.onCalendarInit()
                // this.$axios.ajax.post(this.url_data, {month:this.currentYear+ '' + (this.currentMonth < 10 ? '0' + this.currentMonth : this.currentMonth)}).then(res => {
                //     if(res.data.code===0) {
                //         this.onCalendarInit(res.data.data.calwork ? res.data.data.calwork : res.data.data);
                //         this.$emit('callback',res.data.data);
                //     }else if(res.data.code===2) {
                //         this.onCalendarInit();
                //     } else {
                //         console.error(res.data.msg);
                //     }
                // })
            },
            /**
             * 日历初始化
             * @param val 后台日历数据
             */
            onCalendarInit(cuyear) {
                console.log(this.currentMonth)
                // if (cuyear) {
                //     this.currentYear = cuyear 
                // }
                let first_day = this.currentYear + '-' + this.currentMonth + '-01';  //取出当月第一天
                let year = this.currentYear;  //当前年
                let month = this.currentMonth;  //当前月
                let last_day = new Date(year,month,0).getDate() ;   //当前月最后一天
                let currentMonthDays = [];   //当前月份数据
                //构造本月数组
                for(let i = 1; i <= last_day; i++) {
                    let obj = {};
                    obj.is_currentMonth = true;
                    obj.day = i;
                    // obj.month = month;
                    obj.month = this.currentMonthNum
                    obj.year = year;
                    obj.detailArr = []
                    // if(val && !!val[i-1]){
                    //     obj.work_type = val[i-1].work_type;
                    // }
                    currentMonthDays.push(obj);
                }
                let first_weekday = new Date(first_day).getDay() === 0 ? 7 : new Date(first_day).getDay(); //计算出第一天是周几
                const week_length = Math.ceil((last_day + first_weekday - 8)/7 + 1);
                let first_week = currentMonthDays.splice(0,8 - first_weekday);    //取出第一周数据
                let weeks = [];   //日历按周分组
                let pre_last_day = new Date(year,month - 1,0).getDate() ;   //前一个月的最后一天
                let pre_length = pre_last_day - first_weekday + 2;  //前一个月需要补充的天数
                let n = new Date()
                let date = new Date(n.getFullYear() - 1, n.getMonth(), n.getDate(), n.getHours(), n.getMinutes(), n.getSeconds(), n.getMilliseconds());
                let endDate = new Date(date.getFullYear(), date.getMonth() + 1, 0)
                let dayEnd = endDate.getDate()
                //补全第一周数据
                for(let i = pre_last_day; i >= pre_length; i--) {
                    if(this.show_other_month){
                        first_week.unshift({day: i,is_currentMonth: false});
                    }else {
                        first_week.unshift({});
                    }
                }
                weeks.push(first_week);
                //将剩下数据按7等分
                let day_last = '';
                for(let i = 0; i <= week_length - 2; i++) {
                    let currentWeek = currentMonthDays.splice(0,7);  //每次截取7天
                    //补全最后一周数据
                    if( i === week_length - 2 && this.show_other_month) {
                        let length = currentWeek.length;
                        day_last = 8 - length;
                        for(let j = 1; j <= 7 - length; j++) {
                            currentWeek.push({day: j,is_currentMonth: false});
                        }
                    }
                    weeks.push(currentWeek);
                }
                //如果少于6周，再补一周
                if(weeks.length < 6) {
                    let currentWeek = [];
                    for(let i = day_last; i < day_last + 7; i++) {
                        currentWeek.push({day: this.show_other_month ? i : '', is_currentMonth: false});
                    }
                    weeks.push(currentWeek);
                }
                // function flatten(arr) { return [].concat( ...arr.map(x => Array.isArray(x) ? flatten(x) : x) ) } //二维数组转变为一维数组
                var arr2 = this.flatten(weeks); // arr2 [0, 1, 2, 3, 4, 5]
                // console.log('arr2',arr2)
                let newArr = this.calendarData
                // console.log('newArr',newArr)
                for(let m = 0; m < arr2.length ; m++) {
                    for(let n = 0; n <= newArr.length; n++) {
                       if (arr2[m].is_currentMonth) {
                           if(newArr[n]  && (arr2[m].month == newArr[n].currentMonth) && (arr2[m].day == newArr[n].currentDay)) {
                              arr2[m].isNew = true
                              arr2[m].detailArr.push({lineId : newArr[n].lineId,firstTime: newArr[n].firstTime,lastTime: newArr[n].lastTime})
                            //   arr2[m].lineId =  newArr[n].lineId
                            //   arr2[m].firstTime = newArr[n].firstTime
                            //   arr2[m].lastTime = newArr[n].lastTime
                           }
                       }
                    } 
                }

                let newArr2 = []; //一维数组转变为二维数组 一个二维数组里有7个值
                let len = 7;//数量
                for (let i = 0; i < Math.ceil(arr2.length / len); i++) {
                    let start = i * len
                    let end = start + len
                    newArr2.push(arr2.slice(start, end))
                }
                this.calendars = newArr2
                console.log('45454',this.calendars)
                // console.log('last Array',this.calendars)
                // this.calendars = weeks;
            },
            flatten (arr) { //二维数组转变为一维数组
             return [].concat( ...arr.map(x => Array.isArray(x) ? this.flatten(x) : x) )
            },
            /**
             * 改变年份
             */
            onChangeYear() {
                if(!this.is_year_eve) {
                    this.onGetCalendarData();
                }else {
                    this.is_year_eve = false;
                }
            },
            /**
             * 改变月份
             */
            onChangeMonth() {
                this.onGetCalendarData();
            },
            /**
             * 前一个月
             */
            onPreMonth() {
                this.currentMonth --;
                if(this.currentMonth <= 0) {
                    this.currentMonth = 12;
                    this.is_year_eve = true;
                    this.currentYear --;
                }else {
                    this.is_year_eve = false;
                }
            },
            /**
             * 后一个月
             */
            onNextMonth() {
                this.currentMonth ++;
                if(this.currentMonth > 12) {
                    this.currentMonth = 1;
                    this.is_year_eve = true;
                    this.currentYear ++;
                }else {
                    this.is_year_eve = false;
                }
            },
            /**
             * 点击日期
             * @param val 点击的日期的日数
             * @param e 点击的dom节点
             * @param val2 点击的日期是否是本月
             */
            onCheckDate(val,e,val2,val3) {
                if (val3) return;
                if(!val2) {
                    if(val > 15) {
                        this.onPreMonth();
                    }else {
                        this.onNextMonth();
                    }
                }
                this.currentDay = val;
                const date = this.currentYear + '-' + (this.currentMonth <10 ? '0' + this.currentMonth :this.currentMonth) + '-' + (val <10 ? '0' + val : val);
                const weekday = new Date(date).getDay() === 0 ? 7 : new Date(date).getDay();
                this.currentDate = date + ' 星期' + this.weekdays[weekday - 1];

            },
            /**
             * 返回今天
             */
            onBackToday() {
                //获取当前时间
                const year = new Date().getFullYear();
                const month = new Date().getMonth() + 1;
                const day = new Date().getDate();
                const weekday = new Date().getDay();
                //给变量重新赋值
                this.currentYear= year;
                this.currentMonth = month;
                this.currentDate = year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day) + ' 星期' + this.weekdays[weekday - 1];
                this.currentDay = day;
            },
            /**
             * 提交状态修改
             */
            onSubmitWorkType() {
                this.$axios.ajax.post(this.url_set, {date:this.currentDate.split(' ')[0],work_type:this.work_type}).then(res => {
                    if(res.data.code===0) {
                        this.$Message.success('设置成功');
                        this.onGetCalendarData();
                    }else {
                        this.$Message.error('只能设置今天之后的日期，请检查');
                    }
                })
            }
        }
    }
</script>

<style scoped lang="stylus">
    .wj-calendar-box {
        // width: 540px;
        width: 100%;
        height: 100%;
        .calendar-title {
            width: 100%;
            height: 26px;
            line-height: 26px;
            background-color: #a5e4fe;

            .btn-back-today {
                width: 90px;
                height: 32px;
                margin-left: 25px;
                border-radius: 32px;
            }

            .sel-calendar {
                width: 90px;

                .ivu-select-selection {
                    border-radius: 30px;
                }
            }
        }

        .calendar-left {
            height: 100%;
            // width: 380px;
            // float: left;
            border: 1px solid #e6e6e6;

            .left-body {
                width: 100%;
                height: 100%;;
                .calendar-table {
                    width: 100%;
                    text-align: center;

                    thead {
                        width: 100%;
                        background-color: #f5fdff;
                        height: 38px;
                        line-height: 38px;
                        color: #2484cf;
                        font-size: 16px;
                        
                    }
                    caption, th {
                     text-align: center;
                    }
                    tbody {
                        background-color: #fff;

                        tr {
                            font-size: 18px;
                            color: #222222;

                            td {
                                position: relative;
                                cursor: pointer;
                                height: 54px;
                            }
                            td div {
                                border-radius:50%;
                                border: 1px solid white;
                                width: 40px;
                                height: 40px;
                                line-height: 40px;
                                margin: auto;
                            }
                            td div:hover,td div.active {
                                border: 1px solid #e6e6e6;
                            }
                            td:before {
                                content: '';
                                display: none;
                                position: absolute;
                                top: 5px;
                                right: 5px;
                                font-size: 13px;
                                text-align: center;
                                line-height: 15px;
                                text-indent: 1px;
                                width: 15px;
                                background: rgb(0,195,150);
                                height: 15px;
                                color: #fff;
                                overflow: hidden;
                                border-radius: 15px;
                            }

                            td.work-day:before {
                                content: '班';
                                display: block;
                            }

                            td.rest-day:before {
                                content: '休';
                                display: block;
                            }

                            td.holiday:before {
                                content: '节';
                                display: block;
                            }
                            td.other-month {
                                color: rgb(191, 191, 197);
                                cursor: not-allowed;
                            }
                            td.today div {
                                background: #47baef;
                                color: #FFFFFF;
                            }
                        }
                    }
                }
            }

        }

        .calendar-right {
            width: 150px;
            height: 410px;
            float: left;
            margin-left: 10px;
            border: 1px solid #e6e6e6;
            background-color: #fff;

            .right-day {
                width: 130px;
                height: 130px;
                line-height: 130px;
                margin: 20px auto;
                text-align: center;
                background-color: #e4f5ff;
                font-size: 60px;
                color: #1698d6;
                border-radius: 7px;
                font-weight: 700;
            }
        }
    }
</style>