<template>
    <view class="calendar-wrapper">
       <view class="header" v-if="headerBar">
           <view :class="{pre: !is_future_month(-1),
						  pre_unable: is_future_month(-1)}" @click="changeMonth('pre')">
				<label class="iconfont icon-left-circle"></label>
				上月</view>
            <view>{{y+'年'+formatNum(m)+'月'}}</view>
			
            <view :class="{next: !is_future_month(1),
						   next_unable: is_future_month(1)}" @click="changeMonth('next')">下月
			<label class="iconfont icon-right-circle"></label>
			</view>
        </view> 
        <view class="week">
            <view class="week-day border_dates" v-for="(item, index) in weekDay" :key="index">{{ item }}</view>
        </view>	
		<view class='weeks'>
			<view class="week-row border_dates" v-for="(item1, index1) in group_dates" :key="index1">
				<view class="week-day border_dates" v-for="(item2, index2) in item1" :key="index2" @click="selectOne(item2, $event)">
					<label class="content">{{Number(items[index1*7+index2].date)}}</label>
					
					<view  class="status" 
					:class="{
							status1: items[index1*7+index2].status==0,
							status2: items[index1*7+index2].status==1,
							status3: items[index1*7+index2].status==2,
							status4: items[index1*7+index2].status==3
						}"></view>
				</view>
			</view>
		</view>
	 
    </view>
</template>

<script>
export default {
    name: 'ren-calendar',
    props: {
        // 星期几为第一天(0为星期日)
        weekstart: {
            type: Number,
            default: 0
        },		 
        // 标记的日期
        markDays: {
            type: Array,
            default: ()=>{
                return [];
            }
        },
        //是否展示月份切换按钮
        headerBar:{
            type: Boolean,
            default: true
        },
        // 是否展开
        open: {
            type: Boolean,
            default: true
        },
        //是否可收缩
        collapsible:{
            type: Boolean,
            default: true
        },
        //未来日期是否不可点击
        disabledAfter: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
			//kpi_url:'',
			//employeeNumber:'',
			//datas:[],
			//workMonth:'',
            weektext: [ '一', '二', '三', '四', '五', '六','日'],
            y: new Date().getFullYear(), // 年
            m: new Date().getMonth() + 1, // 月
            dates: [], // 当前月的日期数据
			group_dates:[],
			prev_dates:[],//上一月数据
			next_dates:[],//下一月数据
            positionTop: 0,
            monthOpen: true,
            choose: '',
			items:[
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'01'},
				{day:2,year:2021,month:10,status:3,isCurM:false,date:'02'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'03'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'04'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'05'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'06'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'07'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'08'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'09'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'10'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'11'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'12'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'13'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'14'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'15'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'16'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'17'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'18'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'19'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'20'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'21'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'22'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'23'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'24'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'25'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'26'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'27'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'28'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'29'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'30'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'31'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'32'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'33'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'34'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'35'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'36'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'37'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'38'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'39'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'40'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'41'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'42'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'43'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'44'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'45'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'46'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'47'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'48'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'49'},
				{day:1,year:2021,month:10,status:3,isCurM:false,date:'50'},
			]
        };
    },
    created() {
		 
		this.dates = this.monthDay(this.y, this.m);
		 this.group_dates = [];
		 for(let i = 0;i<this.dates.length/7;i++)
		 {
			 this.group_dates.push(this.dates.slice(i*7,i*7+7)); 
		 } 
		 for(let i = 0;i<this.dates.length;i++)
		 {
			 this.items[i] = this.dates[i];
		 }
		
		!this.open && this.toggle();
		 
         
    },
    mounted() {
        this.choose = this.getToday().date;
    },
    computed: {
        // 顶部星期栏
        weekDay() {
            return this.weektext.slice(this.weekstart).concat(this.weektext.slice(0, this.weekstart));
        },
        height() {
            return (this.dates.length / 7) * 80 + 'rpx';
        }
    },
    methods: {
        formatNum(num) {
            let res = Number(num);
            return res < 10 ? '0' + res : res;
        },
		addMonth(date, months) {
		    let y = date.getFullYear();
		    let m = date.getMonth();
		    var d = date.getDate();
		
	//		console.log('add month y' + y + ' m:' + m + ' d: ' + d + ' month: ' + months);
		    y += Math.floor((m + 1 + months) / 12); //计算年
		    m = Math.floor((m + 1 + months) % 12) - 1; //计算月
			let _date = new Date(y,m,d);
	//		console.log('result y:' + y + ' m: ' + m + '_date:' + _date);
			return _date;
		},
		 set_status_by_datestr(date,status)
		 {
			 for(let i = 0;i< this.items.length;i++)
			 {
			    let date1 = this.items[i].year.toString()+this.items[i].month.toString()+this.items[i].date;
				if(date1 == date)
				{					
					this.items[i].status = status;
					
					//if(status == 0)
					//	console.log('zero alarm');
					console.log('find '+date1);
					return;
				}  
				 
			 }
		 },
		 set_status_by_datestr1(date,status)
		{ 
			 for(let i = 0;i< this.items.length;i++)
			 {
				let date1 = this.items[i].year.toString()+'-'+this.items[i].month.toString()+'-'+this.items[i].date;
				if(date1 == date)
				{					
					if(status == 3)
					{
						if(this.items[i].status== 1)
							this.items[i].status = status;
						
					}else{
						this.items[i].status = status;
						
					}
					//console.log('find '+date1);
					return;
				}  
				 
			 }
		 },
		set_status(index,status)
		{
			this.items[index].status = status;
		},
		is_future_month(increment)
		{
			let date = new Date();
			let page_date = new Date(this.y,this.m-1,1);
			page_date = this.addMonth(page_date,increment)
			let _y = date.getFullYear();//当前年
			let _m = date.getMonth();//当前月
			let _y1 = page_date.getFullYear();
			let _m1 = page_date.getMonth();
			//console.log('计算 y:' +_y1 + 'm:' + _m1);
			//console.log('当前 y:'+_y +' m:' + _m);
			if(_y1>_y)
				return true;
			if(_y1<_y)
				return false;
			if(_m1 > _m)
				return true;
			return false;
		},
        getToday() {
            let date = new Date();
            let y = date.getFullYear();
            let m = date.getMonth();
            let d = date.getDate();
            let week = new Date().getDay();
            let weekText = ['日', '一', '二', '三', '四', '五', '六'];
            let formatWeek = '星期' + weekText[week];
            let today = {
                date: y + '-' + this.formatNum(m + 1) + '-' + this.formatNum(d),
                week: formatWeek
            };
            return today;
        },
		is_fill_logs(_year,_month,_date)
		{
			
			//console.log('res'+JSON.stringify(this.datas));
			let workDate = _year + '-' + this.formatNum(_month) + '-' + this.formatNum(_date);
 			return false;
			if(!this.datas.length)
				return false;
			console.log('datas:' +JSON.stringify(this.datas))
				
			for(let i = 0;i< this.datas.length;i++)
			{
				//console.log('logs:'+ JSON.stringify(this.datas[i]))
				//continue;
				if(workDate==this.datas[i].workDate)
				{
					if(this.datas[i].summary.length>0)
					{
						console.log('work logs filled'+this.datas[i].summary);	
						return true;
					}
					console.log('work logs is not filled');
					return false;
				}
			}
			return false;
		},
		 
        // 获取当前月份数据
        monthDay(y, month) {
            let dates = [];
            let m = Number(month);
            let firstDayOfMonth = new Date(y, m - 1, 1).getDay(); // 当月第一天星期几
			let prevDays = firstDayOfMonth-1;//前面有几天
			if(prevDays<0)
				prevDays = 6;				
			let lastDayOfMonth = new Date(y,m,0).getDay();
			let nextDays = 7- lastDateOfMonth;
			/*for(let i = 1;i< prevDays;i++)
			{
				dates.push({
				    date: this.formatNum(lastDayOfLastMonth - startDay + i),
				    day: weekstart + i - 1 || 7,
				    month: m - 2 >= 0 ? this.formatNum(m - 1) : 12,
				    year: m - 2 >= 0 ? y : y - 1
				});
				
			}
			for(let i = 1;i<nextDays;i++)
			{
				
			}*/
            let lastDateOfMonth = new Date(y, m, 0).getDate(); // 当月最后一天
            let lastDayOfLastMonth = new Date(y, m - 1, 0).getDate(); // 上一月的最后一天 
            let weekstart = this.weekstart == 7 ? 0 : this.weekstart;
            let startDay = (() => {
                // 周初有几天是上个月的
				let prevDays = firstDayOfMonth -1;
				if(prevDays<0)
					prevDays = 6;
				return prevDays;
                /*
				if (firstDayOfMonth == weekstart) {
                    return 0;//
                } else if (firstDayOfMonth > weekstart) {
                    return firstDayOfMonth - weekstart;
                } else {
                    return 7 - weekstart + firstDayOfMonth;
                }*/
            })();
            let endDay = 7 - ((startDay + lastDateOfMonth) % 7); // 结束还有几天是下个月的
			if(endDay>=7)
				endDay = 0;
				
			//console.log('endDay'+endDay);
            for (let i = 1; i <= startDay; i++) {
                dates.push({
                    date: this.formatNum(lastDayOfLastMonth - startDay + i),
                    day: weekstart + i - 1 || 7,
                    month: m - 1 >= 0 ? this.formatNum(m - 1) : 12,
                    year: m - 1 >= 0 ? y : y - 1,
					status:0,
					isCurM:false
                });
            }
            for (let j = 1; j <= lastDateOfMonth; j++) {
				let _status = 3;
				let _date = this.formatNum(j);
				let _day = (j % 7) + firstDayOfMonth - 1 || 7;
				let _month = this.formatNum(m);
				let _year = y;
				
				/*if(!this.isWorkDay(_year,_month,_date))
					_status = 2;
				else if(!this.is_fill_logs(_year,_month,_date))
				{
					//_status = Math.floor(Math.random() * 4);	
					_status = 2;
				}*/
                dates.push({
                    date: _date,
                    day: _day,
                    month: _month,
                    year: _year,
					status: _status,
                    isCurM: true //是否当前月份
                });
            }
            for (let k = 1; k <= endDay; k++) {
				//console.log(' date ' + k);
                dates.push({
                    date: this.formatNum(k),
                    day: (lastDateOfMonth + startDay + weekstart + k - 1) % 7 || 7,
                    month: m + 1 <= 11 ? this.formatNum(m + 1) : 0,
                    year: m + 1 <= 11 ? y : y + 1,
					status:0,
					isCurM:false
                });
            }
            // console.log(dates);
            return dates;
        },
        isWorkDay(y, m, d) {
            //是否工作日
            let ymd = `${y}/${m}/${d}`;
            let formatDY = new Date(ymd.replace(/-/g, '/'));
            let week = formatDY.getDay();
            if (week == 0 ) {//|| week == 6
                return false;
            } else {
                return true;
            }
        },
        isFutureDay(y, m, d) {
            //是否未来日期
            let ymd = `${y}/${m}/${d}`;
            let formatDY = new Date(ymd.replace(/-/g, '/'));
            let showTime = formatDY.getTime();
            let curTime = new Date().getTime();
            if (showTime > curTime) {
                return true;
            } else {
                return false;
            }
        },
        // 标记日期
        isMarkDay(y, m, d) {
            let flag = false;
            for (let i = 0; i < this.markDays.length; i++) {
                let dy = `${y}-${m}-${d}`;
                if (this.markDays[i] == dy) {
                    flag = true;
                    break;
                }
            }
            return flag;
        },
        isToday(y, m, d) {
            let checkD = y + '-' + m + '-' + d;
            let today = this.getToday().date;
            if (checkD == today) {
                return true;
            } else {
                return false;
            }
        },
        // 展开收起
        toggle() {
            this.monthOpen = !this.monthOpen;
            if (this.monthOpen) {
                this.positionTop = 0;
            } else {
                let index = -1;
                this.dates.forEach((i, x) => {
                    this.isToday(i.year, i.month, i.date) && (index = x);
                });
                this.positionTop = -((Math.ceil((index + 1) / 7) || 1) - 1) * 80;
            }
        },
        // 点击回调
        selectOne(i, event) {
            let date = `${i.year}-${i.month}-${i.date}`;
            let selectD = new Date(date).getTime();
            let curTime = new Date().getTime();
            let week = new Date(date).getDay();
            let weekText = ['日', '一', '二', '三', '四', '五', '六'];
            let formatWeek = '星期' + weekText[week];
            let response = {
                date: date,
                week: formatWeek
            };
			
			if(i.status ==2)
				return false;
            if (!i.isCurM) {
                // console.log('不在当前月范围内');
                return false;
            }
			/*
            if (selectD > curTime) {
                if (this.disabledAfter) {
                    console.log('未来日期不可选');
                    return false;
                } else {
                    this.choose = date;
                    this.$emit('onDayClick', response);
                }
            } else {
				*/
             this.choose = date;
             this.$emit('onDayClick', response);
            //}
            //console.log(response);
        },
        //改变年月
        changYearMonth(y, m) {
            this.dates = this.monthDay(y, m);
            this.y = y;
            this.m = m;
        }, 
        changeMonth(type){
            if(type=='pre'){
               
			   if (this.m + 1 == 2) {
                   this.m = 12;
                   this.y = this.y - 1;
               } else {
                   this.m = this.m - 1;
               } 
			   
			   let _year = this.y;
			   let _month = this.m; 
			   let response = {
			       year: _year,
			       month: _month
			   };
			   
			   this.dates = this.monthDay(this.y, this.m);
			   this.group_dates =[];
			   for(let i = 0;i<this.dates.length/7;i++)
			   {
			   	this.group_dates.push(this.dates.slice(i*7,i*7+7));  
			   }
			   for(let i = 0;i<this.dates.length;i++)
			   {
			   	 this.items[i] = this.dates[i];
			   }
			   
			   this.$emit('onPreviousMonth',response);
			    
            }else{
                if (this.m + 1 == 13) {
                    this.m = 1;
                    this.y = this.y + 1;
                } else {
                    this.m = this.m + 1;
                }
				let _year = this.y;
				let _month = this.m; 
				let response = {
				    year: _year,
				    month: _month
				};
				
				this.dates = this.monthDay(this.y, this.m);
				this.group_dates =[];
				for(let i = 0;i<this.dates.length/7;i++)
				{
					this.group_dates.push(this.dates.slice(i*7,i*7+7));  
				}
				for(let i = 0;i<this.dates.length;i++)
				{
					 this.items[i] = this.dates[i];
				}
				
				this.$emit('onNextMonth',response);
				 
            }
			

			//console.log('xxxx');
        }
    }
};
</script>

<style lang="scss" scoped>
	@import url("/static/font/iconfont.css");
	.border_dates{
		border-style: solid; 
		border-width: 1rpx;
		border-right-style: none;
		border-bottom-style:none; 
		border-color: #E6E6E6;
		
	}
.calendar-wrapper {
    color: #bbb7b7;
    font-size: 28rpx;
    text-align: center;
    background-color: #fff;
    padding-bottom: 10rpx;
	display: flex;
	flex-direction: column;
    
    .header{
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 88rpx;
        color: #42464A;
        font-size: 32rpx;
        font-weight: bold;
        border-bottom: 2rpx solid #f2f2f2;
        .pre,.next{
              color: #4d7df9;
              font-size: 28rpx;
              font-weight: normal;
              padding: 8rpx 15rpx;
              //border-radius: 10rpx;
              //border: 2rpx solid #dcdfe6;
        }
		.pre_unable,.next_unable
		{
			color: #B5B5B5;
			font-size: 28rpx;
			font-weight: normal;
			padding: 8rpx 15rpx;
		}
        .pre{
            margin-right: 30rpx;
        }
        .next{
            margin-left: 30rpx;
        }
    }
	.weeks{
		display: flex;
		flex-direction: column;
		.week-row{
			display: flex;
			flex-direction: row;
			width: 100%;
			height: 100rpx;
			.week-day
			{
				display: flex;
				flex-direction: column;
				height: 100rpx;
				line-height: 50rpx;	
				align-items: center;
				justify-content: center;
				
				width:calc(100%/7);
				.content{
					height: 50%;
					padding-bottom: 0rpx;
					margin-bottom: 0rpx;
				}
				.status{
				    font-style: normal;	 
				    width: 20rpx;
				    height: 20rpx;
				    border-radius: 20rpx;
					
				}
				.status1{
					
				}
				.status2{
				    background: #34C758;
					
				}
				.status3{
				    background: #B5B5B5;
					
				}
				.status4{
				    background: #FF6666;
					
				}
			}
		}
	}
    .week {
        display: flex;
        align-items: center;
        height: 80rpx;
        line-height: 80rpx;
        border-bottom: 1rpx solid rgba(255, 255, 255, 0.2);
		.week-day
		{
			background-color: #ECEEF0;
		}
        view {
            flex: 1;
        }
    }

    .content {
        position: relative;
        overflow: hidden;
        transition: height 0.4s ease;

        .days {
            transition: top 0.3s;
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            position: relative;
			
			
            .item {
                position: relative;
                display: block;
                height: 80rpx;
                line-height: 80rpx;	
                width: calc(100% / 7);
               .day {
					
                    font-style: normal;
                    display: inline-block;
                    vertical-align: middle;
                    width: 60rpx;
                    height: 60rpx;
                    line-height: 60rpx;
                    overflow: hidden;
                    border-radius: 60rpx;

                    &.choose {
                        background-color: #4d7df9;
                        color: #fff;
                    }

                    &.nolm {
                        color: #666666;
                        opacity: 0.3;
                    }
                }
                .isWorkDay {
                    color: #42464a;
                }

                .notSigned {
                    font-style: normal;
                    width: 8rpx;
                    height: 8rpx;
                    background: #fa7268;
                    border-radius: 10rpx;
                    position: absolute;
                    left: 50%;
                    bottom: 0;
                    pointer-events: none;
                }
                .today {
                    color: #fff;
                    background-color: #a8c0ff;
                }
                .workDay {
                    font-style: normal;
                    width: 8rpx;
                    height: 8rpx;
                    background: #4d7df9;
                    border-radius: 10rpx;
                    position: absolute;
                    left: 50%;
                    bottom: 0;
                    pointer-events: none;
                }
                .markDay{
                    font-style: normal;
                    width: 8rpx;
                    height: 8rpx;
                    background: #fc7a64;
                    border-radius: 10rpx;
                    position: absolute;
                    left: 50%;
                    bottom: 0;
                    pointer-events: none;
                }
            }
        }
    }

    .hide {
        height: 80rpx !important;
    }

    .weektoggle {
        width: 85rpx;
        height: 32rpx;
        position: relative;
        bottom: -42rpx;
        &.down {
            transform: rotate(180deg);
            bottom: 0;
        }
    }
}
</style>
