'use strict';

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) {
	return typeof obj;
} : function(obj) {
	return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
};

var _createClass = function() {
	function defineProperties(target, props) {
		for(var i = 0; i < props.length; i++) {
			var descriptor = props[i];
			descriptor.enumerable = descriptor.enumerable || false;
			descriptor.configurable = true;
			if("value" in descriptor) descriptor.writable = true;
			Object.defineProperty(target, descriptor.key, descriptor);
		}
	}
	return function(Constructor, protoProps, staticProps) {
		if(protoProps) defineProperties(Constructor.prototype, protoProps);
		if(staticProps) defineProperties(Constructor, staticProps);
		return Constructor;
	};
}();

function _classCallCheck(instance, Constructor) {
	if(!(instance instanceof Constructor)) {
		throw new TypeError("Cannot call a class as a function");
	}
}


 


var SimpleCalendar = function() {
	//构造函数

	function SimpleCalendar(query, options) {
		_classCallCheck(this, SimpleCalendar);

		//默认配置
		this._defaultOptions = {
			width: '500px',
			height: '50px',
			language: 'CH', //语言
			showLunarCalendar: true, //阴历
			showHoliday: true, //休假
			showFestival: true, //节日
			showLunarFestival: true, //农历节日
			showSolarTerm: true, //节气
			showMark: false, //标记
			timeRange: {
				startYear: 1900,
				endYear: 2049
			},
			timeZone: "", //时区
			mark: {
				'2019-7-1': '启明星',
				'2019-8-15': 'dotnetcms.org'
			},

			theme: {
				changeAble: false,
				weeks: {
					backgroundColor: '#FBEC9C',
					fontColor: '#4A4A4A',
					fontSize: '20px'
				},
				days: {
					backgroundColor: '#ffffff',
					fontColor: '#565555',
					fontSize: '24px'
				},
				todaycolor: 'orange',
				activeSelectColor: 'orange',
				invalidDays: '#C1C0C0'
			}
		};

		//容器
		this.container = document.querySelector(query);

		this._defaultOptions.width = this.container.style.offsetWidth;
		this._defaultOptions.height = this.container.style.offsetHeight;


		//得到最终配置
		this._options = this.optionAssign(this._defaultOptions, options);

		this.create();
	}


	//用B的属性覆盖A的属性。例如A定义宽度为100，B定义宽度为200，则最终宽度是200

	_createClass(SimpleCalendar, [{
		key: 'optionAssign',
		value: function optionAssign(optionsA, optionsB) {
			for(var key in optionsB) {
			    if(_typeof(optionsA[key]) !== 'object') 
			        optionsA[key] = optionsB[key];
				else {
					optionsA[key] = this.optionAssign(optionsA[key], optionsB[key]);
				}
			}
			return optionsA;
		}

		//生成日历样式

	}, {
		key: 'create',
		value: function create() {
			var root = this.container;
			root.style.width = this._options.width;
			root.style.height = this._options.height;
			var title = root.querySelector('.sc-title');
			var scbody = root.querySelector('.sc-body');
			var days = scbody.querySelector('.sc-days');
			var week = root.querySelector('.sc-week');
			for(var i = 0; i < 7; i++) {
				week.innerHTML = week.innerHTML + ' <div class="sc-week-item"></div>';
			}
			for(var i = 0; i < 42; i++) { 
			    days.innerHTML = days.innerHTML + '<div class="sc-item">  <div class=daybox > <div class="day"></div> <div class="lunar-day"></div> </div>       <div class="event"></div>            </div>';
			}
			 
			 
			//添加下拉框数据
			this.updateSelect(this.tyear, this.tmonth);
			//刷新日历
			this.update();
			 
		}

		//刷新日历

	}, {
		key: 'update',
		value: function update() {
			var month = arguments.length <= 0 || arguments[0] === undefined ? this.tmonth : arguments[0];
			var year = arguments.length <= 1 || arguments[1] === undefined ? this.tyear : arguments[1];
			var length = this._defaultOptions.mark.length;
			this.updateWeek();
			this.addData(year, month);		 
			this.updateEvent();
		
		}
		//刷新下拉框 只有在初始化和设置语言后才会更新
	}, {
		key: 'updateSelect',
		value: function updateSelect(year, month) {
			//下拉框
			var selectYear = this.container.querySelector('.sc-select-year');
			var selectMonth = this.container.querySelector('.sc-select-month');
			selectYear.innerText = year;
			selectMonth.innerText = SimpleCalendar.prototype.languageData.months_CH[month-1];
		}

	}, {//刷新星期
		key: 'updateWeek',
		value: function updateWeek() {
			var weeks = this.arrayfrom(this.container.querySelectorAll('.sc-week-item'));
			var data = this.languageData['days_' + this._options.language];
			if(!data) {
				console.error('language error!');
			}
			weeks.forEach(function(v, i) {
				v.innerHTML = data[i];
			});
		}

	}, {
	    //添加阳历阴历数据
		key: 'addData',
		value: function addData(year, month) {
			var daysElement = this.arrayfrom(this.container.querySelectorAll('.sc-item'));
			var day = new Date(year, month - 1, 1);
			var week = day.getDay();
			if(week == 0) week = 7;
			var container = this.container;
			
			if((week==7&&(month==1||month==3||month==5||month==7||month==8||month==10||month==12))
				||(week==6&&(month==1||month==3||month==5||month==7||month==8||month==10||month==12))
				||(week==7&&(month==4||month==6||month==9||month==11))){
				container.querySelector('.sc-body').classList.remove('showmonth5');
				container.querySelector('.sc-body').classList.add('showmonth6');
			}else{
				container.querySelector('.sc-body').classList.add('showmonth5');
				container.querySelector('.sc-body').classList.remove('showmonth6');
			}

			//计算得到第一个格子的日期
			var thispageStart = new Date(Date.parse(day) - (week - 1) * 24 * 3600 * 1000);
		    //对每一个格子遍历

			var  icon1=SimpleCalendar.prototype.languageData.feativals_CH;
		 
			var  icon3=SimpleCalendar.prototype.languageData.solarTerm;

			for(var i = 0; i < 42; i++) {
			    daysElement[i].className = 'sc-item';

			    //日历上天数   Thu Jul 18 2019 20:42:30 GMT+0800
			    var theday = new Date(Date.parse(thispageStart) + i * 24 * 3600 * 1000);


			    var dtday =theday.getFullYear() + '-' + (theday.getMonth() + 1) + '-' + theday.getDate();// theday.toLocaleDateString(); //2019-7-18			   
			    daysElement[i].querySelector(".day").setAttribute("data-fullday",dtday);


				var writeyear = theday.getFullYear();
				var writeday = theday.getDate();
				var writemonth = theday.getMonth() + 1;

				if (writemonth > month) {
					daysElement[i].classList.add('sc-nextmonth');
				}else if(writemonth < month){
					daysElement[i].classList.add('sc-premonth');
				}else{
					daysElement[i].classList.add('sc-month');
				}
			  
                //添加阳历和阴历
				daysElement[i].querySelector('.day').innerHTML = writeday; 


                // fix by dream
				var nongli= calendar.solar2lunar(writeyear, writemonth, writeday).IDayCn;
				var _key=writemonth+'-'+writeday;

				if(icon1[_key] != undefined)
				{
				    nongli=icon1[_key] ;
				}
			 
			 

				if(icon3[_key] != undefined)
				{
				    nongli=icon3[_key] ;
				}


				daysElement[i].querySelector('.lunar-day').innerHTML =nongli;

               
				//添加today样式
				if (this.tyear == writeyear && this.tday == writeday && this.tmonth == writemonth) { 
				    //this.selectDay = daysElement[i];
				    daysElement[i].querySelector(".daybox").classList.add("daybox-today");
				    $('.sc-week-item:nth-child(' + this.tweek + ')').addClass('sc-week-today');
				}
				else {
				    daysElement[i].querySelector(".daybox").classList.remove("daybox-today");
				}
			}
		}
	},



     {
         //添加事件预览
         key: 'updateRemark',
         value: function updateRemark(year, month, k) {
 
             var daysElement = this.arrayfrom(this.container.querySelectorAll('.sc-item'));

                 jsonData = [{}]; 
                 var _t=new Date();  
                 setTimeout(function()
                 { 

                     $.ajax({
                         url: "js_cal/data.aspx",
                         data: {  year: year, month: month,k:k  },   
                         type:"get",
                         cache: false,
                         async:true, 
                         dataType:"json",
                         success: function (json) {  
                             
                             jsonData = json.map(x => (  {  name:x.name,  date: x.date } )); 
                           
                             for (var j = 0; j < 42; j++) { 
                                 var _inttime =daysElement[j].querySelector(".day").getAttribute("data-fullday");                                  
                                 var _ele = daysElement[j].querySelector('.event'); 
                                 setdata(_inttime,_ele, jsonData); 

                             }
                              

                         },
                         error: function (err) {
                             
                         }
                     });
                 },500);

              


       

             /*jsonData  [{name:'吃饭',date:'2019-7-23'},   {name:'吃饭',date:'2019-7-24'}, {name:'lalala',date:'2019-7-25'}, {name:'555',date:'2019-7-25'}   ] */
             //_dttime 2019-12-4 
             // _ele div
                 function setdata(_dttime, _ele, jsonData) {
                 var _x = "";               
                 var j = jsonData.length;


                 for (var k = 0; k < j; k++)
                 {
                     var _event= jsonData[k].name;
                     var _dt = jsonData[k].date;
                  
                     if (_dttime==_dt)
                     { 
                        _x += "<div class=_i><span class='label label-red'>" + _event+ "</span> </div>";
                     }

                 }
                      
                  $(_ele).html(_x);
             };

              
              
         }


     },


    {
        //刷新事件
		key: 'updateEvent',
		value: function updateEvent() {

		   



		    var daysElement = this.arrayfrom(this.container.querySelectorAll('.daybox'));

		   

			var container = this.container;
			var calendar = this;
			daysElement.forEach(function (v, i) {

				  

			    v.onclick = function () {
			        $('.daybox').removeClass('daybox-active');
				    this.classList.add('daybox-active');
					calendar.selectDay = v;
					var pre = container.querySelector('.sc-selected');
					if(pre) pre.classList.remove('sc-selected');
					this.classList.add('sc-selected');
					if(v.classList.contains('sc-premonth')){
						this.parentNode.querySelector('.sc-month').classList.add('sc-selected');
						var currentmonth = selectMonth.innerText;
						var currentyear = selectYear.innerText;
						var month;
						for(var i=0;i<SimpleCalendar.prototype.languageData.months_CH.length;i++){
							if(currentmonth==SimpleCalendar.prototype.languageData.months_CH[i]){
								month=i+1;
								break;
							}
						}
						if(month > 1) month--;
						else {
							month = 12;
							selectYear.innerText = --currentyear;
						}
						calendar.update(month, currentyear);
						selectMonth.innerText = SimpleCalendar.prototype.languageData.months_CH[month-1];
					}else if(v.classList.contains('sc-nextmonth')){
						var currentmonth = selectMonth.innerText;
						var currentyear = selectYear.innerText;
						var month;
						for(var i=0;i<SimpleCalendar.prototype.languageData.months_CH.length;i++){
							if(currentmonth==SimpleCalendar.prototype.languageData.months_CH[i]){
								month=i+1;
								break;
							}
						}
						if(month < 12){
							month++;
						}else {
							month = 1;
							selectYear.innerText = ++currentyear;
						};
						calendar.update(month, currentyear);
						selectMonth.innerText = SimpleCalendar.prototype.languageData.months_CH[month-1];
					}
				};


			});

			var selectYear = container.querySelector('.sc-select-year');
			var selectMonth = container.querySelector('.sc-select-month');
			selectYear.onchange = function() {
				var m = selectMonth.innerText;
				var y = this.value;
				calendar.update(m, y);
			};

			selectMonth.onchange = function() {
				var y = selectYear.innerText;
				var m = this.value;
				calendar.update(m, y);
			};

		}
    }, {

        //加月份事件
		key:'addMonth',
		value:function addMonth(){
			var container = this.container;
			var calendar = this;
			var selectYear = container.querySelector('.sc-select-year');
			var selectMonth = container.querySelector('.sc-select-month');
			var currentmonth = selectMonth.innerText;
			var currentyear = selectYear.innerText;
			var month;
			for(var i=0;i<SimpleCalendar.prototype.languageData.months_CH.length;i++){
				if(currentmonth==SimpleCalendar.prototype.languageData.months_CH[i]){
					month=i+1;
					break;
				}
			}
			if(month < 12){
				month++;
			}else {
				month = 1;
				selectYear.innerText = ++currentyear;
			};
			calendar.update(month, currentyear);
			selectMonth.innerText = SimpleCalendar.prototype.languageData.months_CH[month-1];
		}
		
	},{//减月份事件
		key:'subMonth',
		value:function subMonth(){
			var container = this.container;
			var calendar = this;
			var selectYear = container.querySelector('.sc-select-year');
			var selectMonth = container.querySelector('.sc-select-month');
			 
			var currentmonth = selectMonth.innerText;
			var currentyear = selectYear.innerText;
			var month;
			for(var i=0;i<SimpleCalendar.prototype.languageData.months_CH.length;i++){
				if(currentmonth==SimpleCalendar.prototype.languageData.months_CH[i]){
					month=i+1;
					break;
				}
			}
			if(month > 1) month--;
			else {
				month = 12;
				selectYear.innerText = --currentyear;
			}
			calendar.update(month, currentyear);
			selectMonth.innerText = SimpleCalendar.prototype.languageData.months_CH[month-1];
		}

	}, {//添加标记
		key: 'addMark',
		value: function addMark(day, info) {
			this._options.mark[day] = info;
			this.update();
		}

		//获取用户点击的日期

	}, {
		key: 'getSelectedDay',
		value: function getSelectedDay() {
			var selectYear = this.container.querySelector('.sc-select-year').innerText;
			var selectMonth = this.container.querySelector('.sc-select-month').innerText;
			var selectDay = this.selectDay.querySelector('.day').innerHTML;
			return new Date(selectYear, selectMonth - 1, selectDay);
		}

		//设置语言

	}, {
		key: 'setLenguage',
		value: function setLenguage(language) {
			this._options.language = language;
			var selectYear = this.container.querySelector('.sc-select-year');
			var selectMonth = this.container.querySelector('.sc-select-month');
			this.updateSelect(selectYear.innerText, selectMonth.innerText);
			this.update();
		}

		//设置是否显示阴历日期
	}, {
		key: 'showLunarCalendar',
		value: function showLunarCalendar(s) {
			this._options.showLunarCalendar = s;
			this.update();
		}

		//设置是否显示标记日期
	}, {
		key: 'showMark',
		value: function showMark(s) {
			this._options.showMark = s;
			this.update();
		}

		//将nodelist转为数组
	}, {
		key: 'arrayfrom',
		value: function arrayfrom(nidelist) {
			var array = [];
			[].forEach.call(nidelist, function(v) {
				array.push(v);
			});
			return array;
		}

	}]);

	return SimpleCalendar;
}();
 





//国际化，和一些节日数据，标记数据
SimpleCalendar.prototype.languageData = {
	feativals_CH: {
		'1-1': '元旦',
		'2-14': '情人节',
		'3-8': '妇女节',
		'3-12': '植树节',
		'4-1': '愚人节',
		'4-22': '地球日',
		'5-1': '劳动节',
		'5-4': '青年节',
		'6-1': '儿童节',
		'7-1': '建党节',
		'8-1': '建军节',
		'9-10': '教师节',
		'10-1': '国庆节',
		'12-25': '圣诞节'
	}, 
	lunarFeatival_CH: {
		'1-1': '春节',
		'2-2': '龙抬头',
		'1-15': '元宵节',
		'4-4': '寒食节',
		'4-5': '清明节',
		'5-5': '端午节',
		'8-15': '中秋节',
		'9-9': '重阳节',
		'12-30': '除夕'
	},
	//节气
	solarTerm: {
		'2-3': '立春',
		'5-5': '立夏',
		'8-7': '立秋',
		'11-7': '立冬',
		'2-18': '雨水',
		'5-20': '小满',
		'8-22': '处暑',
		'11-22': '小雪',
		'3-5': '惊蛰',
		'6-5': '芒种',
		'9-7': '白露',
		'12-6': '大雪',
		'3-20': '春分',
		'6-21': '夏至',
		'9-22': '秋分',
		'12-21': '冬至',
		'4-4': '清明',
		'7-6': '小暑',
		'10-8': '寒露',
		'1-5': '小寒',
		'4-19': '谷雨',
		'7-22': '大暑',
		'10-23': '霜降',
		'1-20': '大寒'

	},
	days_EN: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
	days_CH: ["一", "二", "三", "四", "五", "六", "日"],
	months_EN: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
	months_CH: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
	vocation: {
		data_2016: ['1-1', '1-2', '1-3', '2-7', '2-8', '2-9', '2-10', '2-11', '2-12', '2-13', '4-2', '4-3', '4-4', '4-30', '5-1', '5-2', '6-9', '6-10', '6-11', '9-15', '9-16', '9-17', , '10-1', '10-2', '10-3', '10-4', '10-5', '10-6', '10-7']
	}
};

SimpleCalendar.prototype.tyear = new Date().getFullYear();
SimpleCalendar.prototype.tmonth = new Date().getMonth() + 1;
SimpleCalendar.prototype.tday = new Date().getDate();
SimpleCalendar.prototype.tweek = new Date().getDay();






