/**
 *  自定义控件书写模板
 */
(function(KDApi, $){
    // 构造函数，变量名随意，与最后一句代码的KDApi.register的第二个参数一致即可
    function WorkSchdule (model) {
        this._setModel(model)
    }

    // 原型中封装生命周期函数，固定格式
    WorkSchdule.prototype = {
        _setModel: function(model) {
            this.model = model
        },
        init: function(props){
            this.model.themeNum = props.themeNum;
            initFunc(this.model, props);
        },
        update: function(props){
            if('init' !=props.data.event){
                updateDom(this.model, props);
            }
           
        },
        destoryed: function(){
        }
    }

    // Other Code
    var initFunc = function(model, props) {
        KDApi.loadFile(['./css/index.css','./js/index.js'], model, function () {
            updateDom(model, props);
        })
    }

    //渲染页面
    var shiftInfo = function(model, items,props){ 
        if(items.mode == 'd'){
            items.heads = ['1','2','3','4','5','6','7']   
        }else{
            items.heads = ['周一','周二','周三','周四','周五','周六','周日']   
        }
		console.log("渲染页面"+items);
		
        KDApi.getTemplateStringByFilePath('./html/index.art', model,{items}).then(function (result) {
            model.dom.innerHTML = result;			
			
            for(let i=0;i<items.cells.length;i++){
                classInfo(i,items.cells[i]);
            }

			
			//重置页码、总页数
			var currPageNo = props.data.currPageNo;
			var totalPage = props.data.totalPage;
			
			
			if(!isNaN(parseInt(currPageNo))&& !isNaN(parseInt(totalPage))){		
				$("#pageNo",model.dom).val(currPageNo);
				$("#totalPage",model.dom).text(totalPage);
			}			
            initEvent(model);
        })
           
    }
    //渲染班次信息
    var classInfo = function(index,item){
		
		var shiftNumber = item.shiftNumber;
		if(!shiftNumber){
			shiftNumber = "";
		}
		var shiftcolor = item.shiftcolor;
		if(!shiftcolor){
			shiftcolor = "";
		}
        var holidayTag = item.holidayTagList;
        // holidayTag = ['元旦节','重阳节重阳','国庆节国情','中秋节']
        var holidayTagDiv = '';
		if(holidayTag.length > 0){
            if(holidayTag.length >2){
                for(var i = 0;i<2;i++){
                    holidayTagDiv += '<div class="custom-holiday-style" title='+holidayTag[i]+'>'+holidayTag[i]+'</div>';
                }
                holidayTagDiv += '<div class="custom-holiday-ellipsis" holiday_ellipsis= '+holidayTag+'>...</div>' 	
            }else{
                for(var i = 0;i<holidayTag.length;i++){
                    holidayTagDiv += '<div class="custom-holiday-style" title='+holidayTag[i]+'>'+holidayTag[i]+'</div>';
                }	
            } 
		}
		
		var startEndTime  = item.startEndTime;
		if(!startEndTime){
			startEndTime = "";
		}
		
		var emodifierName = item.emodifierName;
		if(!emodifierName){
			emodifierName = "";
        }
        
        var editContent = "";
        if(emodifierName){
            editContent = {
                emodifierName:  emodifierName,
                emodifytimestr: item.emodifytimestr   
            } 
            editContent = JSON.stringify(editContent)
        }

        var className = item.enable ? 'custom-able-div' : 'custom-disable-div';
	
        $("div[index='"+index+"']").html('<div class='+className+'>'+
        '<div class="custom-top-part">'+
			'<div class="custom-holidayTag">'+holidayTagDiv+'</div>'+
            '<div class="custom-workDateStr" workDateStr='+item.workDateStr+'>'+item.day+'</div>'+
            '</div><div class="custom-center-part">'+
			'<div class="custom-box-color" style="background-color:'+shiftcolor+'"></div>'+
			'<div class="custom-shiftNumber" title= '+shiftNumber+'>'+shiftNumber+'</div>'+			
            '<div class="custom-startEndTime"title= '+startEndTime+'>'+startEndTime+'</div>'+
            '</div>'+
			'<div class="custom-editusername"><div class="custom-emodifierName" editContent='+editContent+'>'+emodifierName+'</div></div>'+
		  '</div>');
    }
	
	
    var updateDom = function(model,props){
       var event = '';
       var items = {};
       if(props && props.data){
           event = props.data.event;
           items = props.data.args;
       }else{
          items.mode = 'w'; //默认为周模式
          items.rows = 0;
          items.startindex = 0;
          items.endindex = 0;
          items.cells = [];
          shiftInfo(model,items,props);
          return;
       }
       if('init'==event){
        shiftInfo(model,items,props);
        removeBorderColor();
       }
        if('set'==event){
            for(let i=0;i<items.cells.length;i++){
                classInfo(i,items.cells[i]);
            }
            if(!isNaN(parseInt(props.data.currPageNo))&& !isNaN(parseInt(props.data.currPageNo))){
                $('#pageNo',model.dom).val(props.data.currPageNo);
                $('#totalPage',model.dom).text(props.data.totalPage);
            }
        initEvent(model)
        }
        if('clear'==event){//清空选中的单元格
				console.log("清除单元格");
                var selected = items;
                if(items && items.length){	
                    for(var i=0;i<items.length;i++){
                      var $workdatestr = $(".custom-workDateStr[workdatestr="+items[i]+"]").parent();
                      $workdatestr.next().empty();
                      $workdatestr.next().next().empty();
                      $workdatestr.parent().css('border','none');  //清楚单元格选中状态
                    }
										
					}					
        }
		if('reset'==event){//单个新增时覆盖
				
                if(items && items.length){	

					console.log("单个新增时覆盖items: "+items);				
                 								
						$("#custom-body-click", model.dom).find('.custom-able-border').each(function(){
                            $(this).find('.custom-center-part').html(
                                '<div class="custom-box-color" style="background-color:'+items[0].shiftcolor+'"></div>'+
                                '<div class="custom-shiftNumber" title= '+items[0].shiftNumber+'>'+items[0].shiftNumber+'</div>'+			
                                '<div class="custom-startEndTime"title= '+items[0].startEndTime+'>'+items[0].startEndTime+'</div>'
                            );
                            var editContent = "";
                            if(items[0].emodifierName){
                                editContent = {
                                    emodifierName:  items[0].emodifierName,
                                    emodifytimestr: items[0].emodifytimestr   
                                } 
                                editContent = JSON.stringify(editContent)
                            }
                    
                            $(this).find('.custom-editusername').html(
                                '<div class="custom-emodifierName" editContent='+editContent+'>'+items[0].emodifierName+'</div>'
                            );
                        })
                        emodifierNameHoverEvent(model);			
                }
                //removeBorderColor();
            return;
		}
		
		
    }
    //数据更新后取消边框颜色
    var removeBorderColor = function(){
        $(".custom-able-td").removeClass("custom-able-border");
    }
    //绑定事件
    var initEvent = function (model) {
        //是否按住ctrl键的标识
        var isCtrl = false;
        //按住ctrl键进行多选
        $(window).keydown(function(e){
            if(e.ctrlKey){
                isCtrl = true;
            }
        }).keyup(function(){
            isCtrl = false;
        })      
        $("#custom-body-click",model.dom).click(function (e) {
            var target = e.target;
            if($(target).parents().hasClass('custom-able-div')){
                target = $(target).parents('.custom-able-div');
            }
            if($(target).hasClass('custom-able-div')){
                if(isCtrl){
                    var select = [];
                    $(target).toggleClass("custom-able-border");
                    if( $(target).hasClass('custom-able-border')){
                        $(target).css('border','1px solid '+model.themeNum)
                    }else{
                        $(target).css('border','none') 
                    }
                   $("#custom-body-click",model.dom).find(".custom-able-border").each(function(){
					   var workDateStr = $(this).children().find(".custom-workDateStr").attr('workDateStr');
					  console.log("选中的日期"+workDateStr);
					  
                      select.push(workDateStr);
                   })
                   console.log(select);
                   model.invoke("select", JSON.stringify({selected:select}));
                }else{
					
                    $(".custom-able-td", model.dom).find('.custom-able-div').removeClass("custom-able-border");
                    $(".custom-able-td", model.dom).find('.custom-able-div').css('border','none');
					 console.log("选中的单个日期");					 
					var workDateStr = $(target).children().find(".custom-workDateStr").attr('workDateStr');
                    $(target).addClass("custom-able-border");
                    $(target).css("border", '1px solid '+model.themeNum);
                    model.invoke("select", JSON.stringify({selected:[workDateStr]}));
                }
      
			}            
		});
		
		//注册分页按钮事件
		$('.pageleft', model.dom).click(function(){//上一页    
			var pageNo = $("#pageNo").val();
			var totalPage = $("#totalPage").text();
			console.log("pageleft"+pageNo);
			if(!pageNo || pageNo == 1 || (Number(pageNo) - 1) < 1 || !totalPage || (Number(totalPage)) < 1){				
				return;
			}
			var currPageNo = Number(pageNo) - 1;
			console.log("去往页"+currPageNo);
			model.invoke('changePage', currPageNo);
		});
		
		$('.pageright', model.dom).click(function(){//下一页    
			var pageNo = $("#pageNo").val();
			var totalPage = $("#totalPage").text();
			
			console.log("pageright"+pageNo);
			console.log("totalPage"+totalPage);
			
			if(!pageNo){
				return;
			}
			var currPageNo = Number(pageNo) + 1;
			
			if(currPageNo > totalPage){				
				return;
			}
			console.log("去往页"+currPageNo);
			model.invoke('changePage', currPageNo);
		});
		
		$('.pagetop', model.dom).click(function(){//头页    
			var totalPage = $("#totalPage").text();			
			console.log("pagetop"+totalPage);
			if(totalPage && (Number(totalPage)) > 0){
				model.invoke('changePage', 1);
			}			
		});
		
		$('.pagebottom', model.dom).click(function(){//尾页    
			var totalPage = $("#totalPage").text();
			console.log("pagebottom"+totalPage);
			if(totalPage && (Number(totalPage)) > 0){
				model.invoke('changePage', totalPage);
			}
        });
        //input离焦事件
        $('#pageNo',model.dom).on('blur',function(e){
            var inputVal = parseInt($('#pageNo',model.dom).val());
            if(!isNaN(inputVal) && inputVal> 0 && inputVal <= parseInt($("#totalPage",model.dom).text())){
                model.invoke('changePage', inputVal);
            }else{
                $('#pageNo',model.dom).val('') 
            }
        })
        emodifierNameHoverEvent(model);
        holidayHoverEvent(model);
    }
      //修改人鼠标悬浮事件
    var emodifierNameHoverEvent = function(model){  
        $(model.dom).on('mouseenter mouseleave', '.custom-emodifierName',  function(e){
            if(e.type == 'mouseenter'){
                var top = $(e.target).offset().top - 20;
                var left = $(e.target).offset().left + 70;
                var editContent = JSON.parse($(e.target).attr('editContent')); 
                $('body').append(
                  '<div class="custom-workschdule-tips" id="custom-workschdule-tips">'+
                  '<div class="custom-workschdule-arrow"></div><div class="custom-workschdule-tips-title">修改记录</div>'+
                  '<div class="custom-workschdule-tips-edituser"></div><div class="custom-workschdule-tips-edittime"></div></div>'
              )
             
                $('#custom-workschdule-tips').css('top', top+'px');
                $('#custom-workschdule-tips').css('left', left+'px');
                $('#custom-workschdule-tips').find('.custom-workschdule-tips-edituser').text('上次修改人：'+ editContent.emodifierName);
                $('#custom-workschdule-tips').find('.custom-workschdule-tips-edittime').text('上次修改时间 : '+ editContent.emodifytimestr);
                }else if(e.type == 'mouseleave'){
                    $('body').find('#custom-workschdule-tips').remove() 
                }
                })
    }
    //节假日标签鼠标悬浮事件
    var holidayHoverEvent = function(model){  
        $(model.dom).on('mouseenter mouseleave', '.custom-holiday-ellipsis',  function(e){
            if(e.type == 'mouseenter'){
                  var top = $(e.target).offset().top + 26;
                  var left = $(e.target).offset().left -10;
                  var holiday_ellipsis = $(e.target).attr('holiday_ellipsis').split(','); 
                  var holidayDom = '';
                  for(var i=0;i<holiday_ellipsis.length;i++){
                    holidayDom +='<div class="custom-holiday-all">'+holiday_ellipsis[i]+'</div>'
                  }
                  $('body').append(
                    '<div class="custom-holiday-tips" id="custom-holiday-tips">'+
                    '<div class="custom-holiday-arrow"></div>'+
                    '<div class="custom-holiday-content"></div>'+
                    '</div>'
                )
                 
                  $('#custom-holiday-tips').css('top', top+'px');
                  $('#custom-holiday-tips').css('left', left+'px');
                  $('#custom-holiday-tips').find('.custom-holiday-content').html(holidayDom);
                }else if(e.type == 'mouseleave'){
                    $('#custom-holiday-tips').remove(); 
                }
                })
    }
    // 你只需知道第一个参数是你接下来要新增控件方案时填的方案id，第二个参数是上面声明的构造函数
    KDApi.register('wtcworkschdule', WorkSchdule)
})(window.KDApi, jQuery) // 这里的jQuery不是必须要传进去的，可移除，要用到的时候才传，PC端系统默认会有jQuery对象，版本是1.12.4
