//过滤方法，如果这个方法返回false，则该card不显示
var Filter = function(cardinfo){
	return true;//cardinfo.title.indexOf('城战')!=-1;
}

function setFilter(fun){
	Filter = fun;
	listInit();
}

var filterList = {
	_lastFiler : 'null',
	"my" : function(){
		this._lastFiler='my';
		setFilter(function(cardinfo){
			return cardinfo.members.indexOf(MYID)!=-1;
		})
	},
	"null" : function(){
		this._lastFiler='null';
		setFilter(function(cardinfo){
			return true;
		})
	},
	"key" : function(v){
		this._lastFiler='key';
		setFilter(function(cardinfo){
			return cardinfo.title.indexOf(v)!=-1;
		})
	},
	"hasLabel" : function(v){
		this._lastFiler='hasLabel';
		setFilter(function(cardinfo){
			return cardinfo.labelIds.indexOf(v)!=-1;
		})
	},
	"hasqaLabel" : function(v){
		this._lastFiler='hasqaLabel';
		setFilter(function(cardinfo){
			console.log('fun=== ',cardinfo);
			if(cardinfo.qalabelIds){
				return cardinfo.qalabelIds.indexOf(v)!=-1;
			}else {
				return false
			}
		})
	},
	// 根据部门的人员设置的时间来过滤
	"hasTodayDone4DeptLabel" : function(v){
		this._lastFiler='hasTodayDone4DeptLabel';
		console.log('filter v',v);
		setFilter(function(cardinfo){
			console.log('fun=== ',cardinfo);
			var userList = DATA.yanqidepartmentuser[v];
			var todayZeroTime = new Date(new Date().toLocaleDateString()).getTime()*0.001;

			if(cardinfo.mem_time){
				var memTimeList = Object.keys(cardinfo.mem_time);
				for (let i = 0; i < memTimeList.length; i++) {
					var userid = memTimeList[i];
					if(cardinfo.mem_time[userid]['end']==todayZeroTime && userList.user.indexOf(userid)>0){
						return true
					}
				}
				return false;
			}else {
				return false
			}
		})
	},
	"hasTodayDone" : function(v){
		this._lastFiler='hasTodayDone';
		console.log('filter v',v);
		setFilter(function(cardinfo){
			console.log('fun=== ',cardinfo);
			var userList = DATA.yanqidepartmentuser[v];
			var todayZeroTime = new Date(new Date().toLocaleDateString()).getTime()*0.001;

			if(cardinfo.mem_time){
				var memTimeList = Object.keys(cardinfo.mem_time);
				for (let i = 0; i < memTimeList.length; i++) {
					var userid = memTimeList[i];
					if(cardinfo.mem_time[userid]['end']==todayZeroTime){
						return true
					}
				}
				return false;
			}else {
				return false
			}
		})
	}
}


//事件处理
function emitEventByJSON(json,sendOther){
	var act = json.act;
	if(act=='addcomment'){
		if(DATA.card_comments)DATA.card_comments[ json.data._id ] = json.data;
	}else if(act=='setdescription' || act=='settitle' || act=='addcard' || act=='memberchange' || act=='memtimechange' || act=='labelchange' || act=='attachmentschange' || act=='changesort'){
		if(DATA.cards){
			var oldListId;
			if(DATA.cards[ json.data._id ]){
				oldListId = DATA.cards[ json.data._id ].listId;
			}
			DATA.cards[ json.data._id ] = json.data;
			DATA.cards[ json.data._id ].oldListId = oldListId;
		}
	}else if(act=='setlisttitle' || act=='addlist' || act=='archivedlist'){
		if(DATA.lists)DATA.lists[ json.data._id ] = json.data;
	}else if(act=='addboard' || act=='boardtitlechange' || act=='modifylabel'){
		if(DATA.boards)DATA.boards[ json.data._id ] = json.data;
	}else if(act=='addchecklist' || act=='setchecklistfinish'){
		if(!DATA.card_checklists)DATA.card_checklists={};
		DATA.card_checklists[ json.data._id ] = json.data;
	}else if(act=='delchecklist'){
		if(!DATA.card_checklists)DATA.card_checklists={};
		delete DATA.card_checklists[ json.data._id ];
	}else if(act=='delcard'){
		// if(DATA.lists)DATA.lists[ json.data._id ] = {};
		delete DATA.cards[ json.data._id ];
	}
	EVENT.emit( json.act , json.data );

	if(sendOther!==false){
		WS.sendToOther( JSON.stringify(json) );
	}
}

EVENT.on('settitle',function(data){
	fmtCardTitle(data._id);
	freshList( data.listId );
});
EVENT.on('setlisttitle',function(data){
	if($('#list_'+ data._id).length==0)return;
	$('#list_'+ data._id +' .tasktitle_cont').html(data.title);
	createListTags();
});

EVENT.on('addcard',function(data){
	if(data.boardId != DATA.boardid && DATA.boardid!=null)return;
	if($('#list_'+ data.listId).length==0)return;
	freshList( data.listId );
	$('#list_'+ data.listId +' .tasklist').sortable('refresh');
});

// 删除卡片
EVENT.on('delcard',function(data){
	if(data.boardId != DATA.boardid && DATA.boardid!=null)return;
	if($('#list_'+ data.listId).length==0)return;
	freshList( data.listId );
	$('#list_'+ data.listId +' .tasklist').sortable('refresh');
});

EVENT.on('addlist',function(data){
	if(data.boardId != DATA.boardid && DATA.boardid!=null)return;
	freshLists();
	$('#centerpanel').sortable('refresh');
	bindTasklistsort();
	createListTags();
});

EVENT.on('boardtitlechange',function(data){
	if(data._id != DATA.boardid && DATA.boardid!=null)return;
	$('.projectheader h1').html(data.title);
});

EVENT.on('memberchange',function(data){
	if(data.boardId != DATA.boardid && DATA.boardid!=null)return;
	if($('#card_'+ data._id).length==0)return;
	fmtMembersByCardID( data._id );
});

EVENT.on('memtimechange',function(data){
	if(data.boardId != DATA.boardid && DATA.boardid!=null)return;
	if($('#card_'+ data._id).length==0)return;
	fmtMembersByCardID( data._id );
});

EVENT.on('labelchange',function(data){
	if(data.boardId != DATA.boardid && DATA.boardid!=null)return;
	if($('#card_'+ data._id).length==0)return;
	fmtLabelsByCardID( data._id );
});

EVENT.on('changesort',function(data){
	if(data.boardId != DATA.boardid)return;
	if($('#card_'+ data._id).length==0)return;

	if(data.oldListId){
		freshList( data.oldListId );
	}
	$('#card_'+ data._id).remove();
	freshList( data.listId );
});

EVENT.on('archivedlist',function(data){
	if(data.boardId != DATA.boardid)return;
	if($('#list_'+ data._id).length==0)return;
	$('#list_'+ data._id).remove();

	freshLists();
	$('#centerpanel').sortable('refresh');
	bindTasklistsort();
	createListTags();
});

EVENT.on('archivedcards',function(data){
	if($('#list_'+ data.listId).length==0)return;
	for(var i=0;i<data.cards.length;i++){
		var _id = data.cards[i];
		if(DATA.cards[ _id ] )DATA.cards[ _id ].archived = true;
		$('#card_'+ _id ).remove();
	}
	freshList( data.listId );
});



setInterval(function(){
	$.get('./?app=api&apiact=ping',function(text){

	});
},30000);

//================


//初始化列表
function listInit(){
	var lists = [];
	var hashCardid = '';
	if( window['HASH'] && HASH()['cardid']){
		hashCardid = HASH()['cardid'];
	}

	for(var listid in DATA.lists){
		if(DATA.lists[listid].boardId != DATA.boardid)continue;
		if(DATA.lists[listid].archived)continue;

		if(TITLEKEY!=""){
			if( DATA.lists[listid].title.indexOf( '【'+TITLEKEY+'】' ) != -1 ){
				lists.push( DATA.lists[listid] );
			}
		}else{
			lists.push( DATA.lists[listid] );
		}
	}
	lists.sort(function(a,b){
		return (a.sort||0) - (b.sort||0);
	});
	fill('#tmpl-lists',lists ,'#centerpanel');

	$('#centerpanel').append( $('#tmpl-list-add').html() );

	for(var listid in DATA.lists){
		freshList(listid);
	}
	$('.tasklist').height( $('#main').height() - 150 );
	$('#list_add_panel .tasklist').height( $('#main').height() - 100 );
	bindTasklistsort();
}

function bindTasklistsort(){
	try{
		$('.tasklist').sortable('destory');
	}catch(e){}

	var lastSortCard;
	$('.tasklist').sortable({
		connectWith: [".tasklist"],
		placeholder: "drop-area",
		distance: 15,
		tolerance:'pointer',
		opacity:0.8,
		revert:100,
		helper:'clone',
		appendTo:'body',
		start : function(event, ui){
			lastSortCard = ui.helper.context;
			//$(ui.placeholder.context).css('height',$(ui.helper.context).clientHeight);
			//alert($(ui.helper.context).clientHeight);
			$('.drop-area').height( $(ui.helper).height()+13 +'px' );
			//event.preventDefault();
			//event.stopPropagation();
			//console.log('xxxx',event,ui);
		},
		stop: function(event, ui){
			var cardid = $(lastSortCard).data('id');
			var listid = $(lastSortCard).parents('.panel').data('id');
			var newOrder = $(lastSortCard).parents('.tasklist').sortable('serialize');
			doSubmitChangeListID(cardid,listid,newOrder);
		},

	}).disableSelection();
}


//遍历新增列表
function freshLists(){
	var lists = [];
	if(window.rebuild==null)rebuild=false;
	for(var listid in DATA.lists){
		if(DATA.lists[listid].boardId != DATA.boardid)continue;
		if(DATA.lists[listid].archived)continue;
		if($('#list_'+listid).length>0)continue;
		lists.push( DATA.lists[listid] );
	}
	lists.sort(function(a,b){
		return a.sort||0 - b.sort||0;
	});

	fill('#tmpl-lists',lists ,'#centerpanel','prepend');
	$('.tasklist').height( $('#main').height() - 150 );
}

//刷新列表
function freshList(listid){
	var cards = [];
	for(var cardid in DATA.cards){
		if(DATA.cards[cardid].listId != listid)continue;
		if(DATA.cards[cardid].archived ) continue;
		if(!Filter(DATA.cards[cardid]))continue;
		cards.push( DATA.cards[cardid] );
	}
	cards.sort(function(a,b){
		var as = a.sort||0;
		var bs = b.sort||0;
		if(as==bs){
			return a.createdAt.sec - b.createdAt.sec;
		}else{
			return as-bs;
		}

	});
	fill('#tmpl-card',cards ,'#list_'+ listid+' .tasklist');

	var _all = cards.length;
	var _over = 0;
	for(var i=0;i<cards.length;i++){
		if(cards[i].title.indexOf('~~')!=-1)_over++;

		fmtCardTitle( cards[i]._id );
		fmtLabelsByCardID(cards[i]._id);
		fmtRiskLabelsByCardID(cards[i]._id);
		//tIssueTagsByCardID(cards[i]._id);
		fmtMembersByCardID(cards[i]._id);
		fmtQALabelsByCardIDInListCard(cards[i]._id);
	}
	//console.log('freshList',listid,_over,_all)
	$('#list_'+ listid +' .tasklistcount').html(_over + '/' + _all);

	if(_all == 0 && filterList._lastFiler != 'null'){
		//有筛选条件，且当列1个卡片都没有，直接隐藏
		$('#list_'+ listid).hide();
	}else{
		$('#list_'+ listid).show();
	}
}


function getboards(callback){
	$.get('./?app=api&apiact=boards&orgid='+rqorgid,function(txt){
		var json = JSON.parse(txt);
		DATA['boards'] = json;
		callback && callback( json );
	});
}

function getlists(boardid,callback){
	$.get('./?app=api&apiact=lists&boardid='+ boardid ,function(txt){
		var json = JSON.parse(txt);
		DATA['lists'] = json;
		callback && callback( json );
	});
}

function getUserInfo(_id){
	if(!DATA.users || !DATA.users[_id])return null;
	return DATA.users[_id];
}

function getAllRiskLabels(callback){
	$.get('./?app=api&apiact=boards',function(txt){
		var json = JSON.parse(txt);
		DATA['boards'] = json;
		callback && callback( json );
	});
}

function getLabelInfo(boardid,labelid){
	if(DATA.boards && DATA.boards[boardid]){
		for(var i=0;i<DATA.boards[boardid].labels.length;i++){
			if( DATA.boards[boardid].labels[i]._id == labelid){
				return DATA.boards[boardid].labels[i];
			}
		}
	}
}

function getQALabelInfo(boardid,labelid){
	if(DATA.boards && DATA.boards[boardid]){
		if (!DATA.boards[boardid].qalabels) return ;
		for(var i=0;i<DATA.boards[boardid].qalabels.length;i++){
			if( DATA.boards[boardid].qalabels[i]._id == labelid){
				return DATA.boards[boardid].qalabels[i];
			}
		}
	}
}

function getRiskLabelInfo(_id){
	if(!DATA.risklabels || !DATA.risklabels[_id])return null;
	return DATA.risklabels[_id];
}

//按模板填充HTML
function fill(tmplid,data,fillTo,appendType){
	var tmpl = $(tmplid ).html();
	var html = [];
	for(var bid in data){
		html.push( T( tmpl, data[bid] ) );
	}
	if('prepend' == appendType){
		$(fillTo).prepend( html.join('') );
	}else if(!appendType){
		$(fillTo).html( html.join('') );
	}
}

//刷新指定card的title
function fmtCardTitle(cardid){
	if($('#card_'+ cardid).length == 0){
		return;
	}
	var title = DATA.cards[cardid].title;

	if($('#card_'+ cardid).length==0)return;

	var _preTitle="";
	/*
	//与我有关 界面中，加上list前缀
	if(DATA.boardid==null){
		_preTitle = (DATA.boards[DATA.cards[cardid].boardId] || {title:""}).title;
		if(_preTitle!=""){
			_preTitle = "<span style='font-size: 6px;color:#aaa'>"+ _preTitle +"</span>";
		}
	}
	*/

	$('#card_'+ cardid).find('.list_card_title').html(marked(title) );
	if(_preTitle){
		$('#card_'+ cardid).find('.list_card_title p').prepend(_preTitle);
	}

	var ckv = (title.indexOf('~~')==-1?false:true);
	$('#card_'+ cardid).find('.finishcheck').prop('checked',ckv);
}

function _formatDate(time) {
	var now = new Date(time);
     var year=now.getFullYear();
     var month= ("0"+ (now.getMonth()+1)).substr(-2);
     var date= ("0"+ now.getDate()).substr(-2);
     var hour=now.getHours();
     var minute=now.getMinutes();
     var second=now.getSeconds();
     return month+""+date;
}

//刷新指定cardid的标签
function fmtLabelsByCardID(cardid,callback){
	if(!DATA.cards[cardid] || !$('#card_'+cardid) )return;
	var board = DATA.boards[DATA.cards[cardid].boardId];
	if(!board)return;

	var html = [];
	for(var i=0;i < DATA.cards[cardid].labelIds.length;i++){
		var lid = DATA.cards[cardid].labelIds[i];
		for(var l=0;l<board.labels.length;l++){
			if( board.labels[l]._id == lid ){
				var linfo  = board.labels[l];

				var timeto = "";
				if(DATA.cards[cardid].labels_time && DATA.cards[cardid].labels_time[lid] && DATA.cards[cardid].labels_time[lid]['need']){
					//有设定到期时间
					var now = (new Date()).getTime();
					var need = DATA.cards[cardid].labels_time[lid]['need'];
					var blinkcss = "";

					if(now>=need*1000)blinkcss="blink";
					timeto = '<i class="timetospan '+ blinkcss +'">'+_formatDate(need*1000) + '</i>';
				}
				html.push(' <span data-id="'+ linfo._id +'" class="minicard-label card-label-'+ linfo.color +'" title="'+ linfo.name +'">'+ linfo.name + timeto +'</span> ');
			}
		}
	}
	if(callback){
		callback && callback( html.join('') );
	}else{
		$('#card_'+cardid).find('.minicard-labels').html( html.join(''));
	}
}

//刷新指定cardid的标签
function fmtQALabelsByCardID(cardid,callback){
	if(!DATA.cards[cardid] || !$('#card_'+cardid) )return;
	var board = DATA.boards[DATA.cards[cardid].boardId];
	if(!board)return;

	var html = [];

	if(DATA.cards[cardid].qalabelIds) {
		for(var i=0;i < DATA.cards[cardid].qalabelIds.length;i++){
			var lid = DATA.cards[cardid].qalabelIds[i];
			for(var l=0;l<board.qalabels.length;l++){
				if( board.qalabels[l] && board.qalabels[l]._id == lid ){
					var linfo  = board.qalabels[l];

					// 判断是否完成 完成加删除线
					if(DATA.cards[cardid].title.indexOf('~~')!=-1){
						$('#card_'+ cardid).find('.list_card_title_qalabel_name').html('<del style="color:#bbb">【'+linfo.name+'】</del>' ||'【没有类型】');
					}else {
						$('#card_'+ cardid).find('.list_card_title_qalabel_name').html('【'+linfo.name+'】' ||'【没有类型】');
					}

					$('.cardinfo_title_qalabel_name').html( '【'+linfo.name+'】' ||'【没有类型】' );
					// $('#card_'+ cardid).find('.list_card_title_qalabel_name').html('【'+linfo.name+'】' ||'【没有类型】');
					html.push(' <span data-id="'+ linfo._id +'" class="minicard-label card-label-'+ linfo.color +'" title="'+ linfo.name +'">'+ linfo.name +'</span> ');
				}

			}
		}
	}

	if(callback){
		callback && callback( html.join('') );
	}else{
		$('#card_'+cardid).find('.minicard-labels').html( html.join(''));
	}
}

//刷新指定cardid的风险标签
function fmtRiskLabelsByCardID(cardid,callback){
	if(!DATA.cards[cardid] || !$('#card_'+cardid) )return;
	var board = DATA.boards[DATA.cards[cardid].boardId];
	if(!board)return;

	var html = [];
	if(DATA.cards[cardid].risklabelIds) {
		for(var i=0;i < DATA.cards[cardid].risklabelIds.length;i++){
			var lid = DATA.cards[cardid].risklabelIds[i];
			var linfo  = DATA.risklabels[lid];
			html.push(' <span data-id="'+ linfo._id +'" class="minicard-label card-label-'+ linfo.color +'" title="'+ linfo.name +'">'+ linfo.name  +'</span> ');
		}
	}

	// 刷新指定card的风险标签数量
	if(DATA.cards[cardid].risklabelIds){
		var num = DATA.cards[cardid].risklabelIds.length;
		if(num >=1){
			$('#card_'+cardid).find('.card-corner-mark').html('<span>'+ num +'</span>').show();
		}else{
			$('#card_'+cardid).find('.card-corner-mark').hide();
		}
	}else{
		$('#card_'+cardid).find('.card-corner-mark').hide();
	}


	if(callback){
		callback && callback( html.join('') );
	}else{
		//$('#card_'+cardid).find('.minicard-labels').html( html.join(''));
	}
}

//刷新指定cardid风险标签相关事件列表
function fmtIssueTagsByCardID(cardid,callback){
    if(!DATA.cards[cardid] || !$('#card_'+cardid) )return;
    var board = DATA.boards[DATA.cards[cardid].boardId];
    if(!board)return;

    var html = [];
    DATA.riskdept = [];
    DATA.riskIssueId = [];

    //console.trace();

    if(DATA.cards[cardid].risklabelIds) {
	    for(var i=0;i < DATA.cards[cardid].risklabelIds.length;i++){
	        var lid = DATA.cards[cardid].risklabelIds[i];

            var lb = DATA.allrisklabels[lid];

            for(var c=0;c< lb.length;c++){
				var linfo = lb[c];
				DATA.riskIssueId.push( linfo.issueId );
			}
		}

		var newurl = 'http://10.0.0.5'
		var issueIdStr = DATA.riskIssueId.join(',');
		var requrlObj = new URL('/bughistory/?app=api&act=hascont&bugids='+issueIdStr, newurl);

		var riskIssueId = $.getJSON(requrlObj, function(data) {

			DATA.riskIssueIdAPIs = [];
			for(bid in data){
				var riskIssueIdAPI = bid
				console.log('bid', bid)
				DATA.riskIssueIdAPIs.push( riskIssueIdAPI );
			}

			for(var i=0;i < DATA.cards[cardid].risklabelIds.length;i++){
		        var lid = DATA.cards[cardid].risklabelIds[i];

	            var lb = DATA.allrisklabels[lid];

	            for(var c=0;c< lb.length;c++){
					var linfo = lb[c];

					var issueColor;
					switch(linfo.issueColor){
						case "1":
							issueColor="#c22b34";
							break;
						case "2":
							issueColor="#0099FF";
							break;
						case "3":
							issueColor="#8f4ccf";
							// issueColor="#000000";
							break;
					}

					DATA.riskdept.push( linfo.department );

					res = new Set(DATA.riskIssueIdAPIs);

					var newurl = 'http://10.0.0.5';
					var newurlObjEdit = new URL('/bughistory/?app=view&bugid='+linfo.issueId+'&urltitle='+ encodeURIComponent(linfo.description), newurl);

					if(res.has(linfo.issueId) == 1){
						console.log('linfo issueID', DATA.riskIssueIdAPIs);

						var newurlObj = new URL('/bughistory/?app=view&bugid='+linfo.issueId, newurl);

						// html.push('<li style="color:'+issueColor+'">【'+linfo.reasonTag+'】<a href="http://www.baidu.com" target="_blank">' + linfo.description + '</a><br/>' + '问题原因：'+linfo.reason+ '></li>' );
						// html.push('<li style="color:'+issueColor+'">【'+linfo.reasonTag+'】<a href="' + newurlObj +'"target="_blank">' + linfo.description + '</a><br/>' + '问题原因：'+linfo.reason+ '</li>' );
						html.push('<li style="color:'+issueColor+'">【'+linfo.reasonTag+'】<a href="' + newurlObj +'"target="_blank">' + linfo.description + '</a>' + '<a href="' + newurlObjEdit +'"target="_blank"><i class="fa fa-pencil fa-fw"></i></a><br/>' + '问题原因：'+linfo.reason+ '</li>' );
					}else{
						html.push('<li style="color:'+issueColor+'">【'+linfo.reasonTag+'】' + linfo.description + '<a href="' + newurlObjEdit +'"target="_blank"><i class="fa fa-pencil fa-fw"></i></a><br/>' + '问题原因：'+linfo.reason+ '</li>' );
				    }
		        }
		    }

		    if(callback){
				callback && callback( html.join('') );
			}else{
				console.log( $('#cardinfoIssueTags') );
				$('#cardinfoIssueTags').html( html.join(''));
			}
		});
	}
}

// 列表中的卡片初始化的时候设置qa标签
function fmtQALabelsByCardIDInListCard(cardid,callback){
	if(!DATA.cards[cardid] || !$('#card_'+cardid) )return;
	var board = DATA.boards[DATA.cards[cardid].boardId];
	if(!board)return;

	var html = [];

	if(DATA.cards[cardid].qalabelIds) {
		for(var i=0;i < DATA.cards[cardid].qalabelIds.length;i++){
			var lid = DATA.cards[cardid].qalabelIds[i];
			for(var l=0;l<board.qalabels.length;l++){
				if( board.qalabels[l] && board.qalabels[l]._id == lid ){
					var linfo  = board.qalabels[l];

					// 判断是否完成 完成加删除线
					if(DATA.cards[cardid].title.indexOf('~~')!=-1){
						$('#card_'+ cardid).find('.list_card_title_qalabel_name').html('<del style="color:#bbb">【'+linfo.name+'】</del>' ||'【没有类型】');
					}else {
						$('#card_'+ cardid).find('.list_card_title_qalabel_name').html('【'+linfo.name+'】' ||'【没有类型】');
					}
					$('.cardinfo_title_qalabel_name').html( '【'+linfo.name+'】' ||'【没有类型】' );

				}

			}
		}
	}

	if(callback){
		callback && callback( html.join('') );
	}else{
		// $('#card_'+cardid).find('.minicard-labels').html( html.join(''));
	}
}


//刷新指定cardid的评论数
function fmtCommentsNumByCardID(cardid){
	var num = getCommentsNumByCardID(cardid);
	if($('#card_'+cardid).length==0 )return;
	if(num == 0){
		$('#card_'+cardid).find('.commonts_num').empty();
	}else{
		$('#card_'+cardid).find('.commonts_num').html('<span class="badge-icon fa fa-comment-o badge-comment"> '+ num +'</span>');
	}
}

function getCommentsNumByCardID(cardid){
	var num = 0;
	for(var k in DATA.card_comments){
		if(DATA.card_comments[k].cardId == cardid){
			num++;
		}
	}
	return num;
}

//刷新指定cardid的参与者
function fmtMembersByCardID(cardid,callback){
	if(!DATA.cards[cardid] || !$('#card_'+cardid) )return;
	var board = DATA.boards[DATA.cards[cardid].boardId];
	if(!board)return;

	var html = [];
	for(var i=0;i < DATA.cards[cardid].members.length;i++){

		var _uid = DATA.cards[cardid].members[i];
		if( DATA.users[_uid] ){
			var uinfo  = DATA.users[_uid];

			var timeto = "";
			var timestr = "";
			if(DATA.cards[cardid].mem_time && DATA.cards[cardid].mem_time[_uid] && DATA.cards[cardid].mem_time[_uid]['end']){
				//有设定到期时间
				//var now = (new Date()).getTime();
				var start = DATA.cards[cardid].mem_time[_uid]['start'];
				var end = DATA.cards[cardid].mem_time[_uid]['end'];

				timestr = _formatDate(start*1000) +"~"+ _formatDate(end*1000) ;//DATA.cards[cardid].mem_time[_uid]['timestr'];
				var blinkcss = "";
				//if(now>=need*1000)blinkcss="blink";
				timeto = '<i  data-timestr="'+ timestr +'" class="timetospan memtimeto '+ blinkcss +'">'+ _formatDate(start*1000) +"/"+_formatDate(end*1000) + '</i>';
			}

			html.push(' <span data-id="'+ _uid +'" title="'+ timestr +'" data-timestr="'+ timestr +'" class="member js-member '+ (MYID==_uid?" myuid":"") +'">'+  uinfo.profile.fullname.substr(-2) + timeto  +'</span>');
		}
	}
	if(callback){
		callback && callback( html.join('') );
	}else{
		$('#card_'+cardid).find('.js-minicard-members').html( html.join('') );
	}
}

//刷新指定cardid的参与者
function fmtYanQiMembersByCardID(cardid,callback){
	if(!DATA.cards[cardid] || !$('#card_'+cardid) )return;
	var board = DATA.boards[DATA.cards[cardid].boardId];
	if(!board)return;

	var html = [];
	for(var i=0;i < DATA.cards[cardid].members.length;i++){

		var _uid = DATA.cards[cardid].members[i];
		if( DATA.users[_uid] ){
			var uinfo  = DATA.users[_uid];

			var timeto = "";
			var timestr = "";
			if(DATA.cards[cardid].mem_time && DATA.cards[cardid].mem_time[_uid] && DATA.cards[cardid].mem_time[_uid]['isyanqi']){
				html.push(' <span data-id="'+ _uid +'" title="'+ timestr +'" data-timestr="'+ timestr +'" class="member js-member '+ (MYID==_uid?" myuid":"") +'">'+  uinfo.profile.fullname.substr(-2) + timeto  +'</span>');
			}

			// html.push(' <span data-id="'+ _uid +'" title="'+ timestr +'" data-timestr="'+ timestr +'" class="member js-member '+ (MYID==_uid?" myuid":"") +'">'+  uinfo.profile.fullname.substr(-2) + timeto  +'</span>');
		}
	}
	if(callback){
		callback && callback( html.join('') );
	}else{
		$('#card_'+cardid).find('.js-minicard-members').html( html.join('') );
	}
}


/*
//增加或删除标签
$(document).on('mouseover','.member',function(e){
	var timestr = $(this).find('.memtimeto').data('timestr');
	var ov = $(this).find('.memtimeto').text();
	if(timestr){
		//console.log('timestr',timestr);
		$(this).find('.memtimeto').data('oldtmeto',ov).html(timestr);
	}
}).on('mouseout','.member',function(e){
	var oldtmeto = $(this).find('.memtimeto').data('oldtmeto');
	if(oldtmeto){
		$(this).find('.memtimeto').html(oldtmeto);
	}
});
*/

//增加卡片
function doSubmitAddCard(text,boardid,listid,callback){
	$.get('./?app=api&apiact=add_card&listid='+listid+"&boardid="+boardid+"&text="+ encodeURIComponent(text),function(text){
		var json = JSON.parse( text );
		emitEventByJSON(json);
		callback && callback(json);
	});
}

// 新的添加卡片方法
function doSubmitAddCard2(text,boardid,listid,callback){
	$.get('./?app=api&apiact=add_card2&listid='+listid+"&boardid="+boardid+"&text="+ encodeURIComponent(text),function(text){
		var json = JSON.parse( text );
		emitEventByJSON(json);
		callback && callback(json);
	});
}


//增加卡片设置内容
function doSubmitAddCardAndDesc(text,desc,boardid,listid,callback){
	$.get('./?app=api&apiact=add_card&listid='+listid+"&boardid="+boardid+"&text="+ encodeURIComponent(text)+"&description="+ encodeURIComponent(desc),function(text){
		var json = JSON.parse( text );
		emitEventByJSON(json);
		callback && callback(json);
	});
}

//设置栏目标题
function doSubmitSetListTitle(text,boardid,listid,callback){
	$.get('./?app=api&apiact=set_list_title&listid='+listid+"&boardid="+boardid+"&text="+ encodeURIComponent(text),function(text){
		var json = JSON.parse( text );
		emitEventByJSON(json);
		callback && callback(json);
	});
}

//增加栏目
function doSubmitAddList(text,boardid,callback){
	$.get('./?app=api&apiact=add_list&boardid='+boardid+"&text="+ encodeURIComponent(text),function(text){
		var json = JSON.parse( text );
		emitEventByJSON(json);
		callback && callback(json);
	});
}

//增加看板
function doSubmitAddboard(text,callback){
	$.get('./?app=api&apiact=add_board&text='+ encodeURIComponent(text),function(text){
		var json = JSON.parse( text );
		emitEventByJSON(json);
		callback && callback(json);
	});
}

//归档看板
function doArchivedboard(boardid,callback){

	$.get('./?app=api&apiact=archived_board&boardid='+ boardid , function(text){
		var json = JSON.parse( text );
		emitEventByJSON(json);
		callback && callback(json);
	});
}

//移动card并设定新排序
function doSubmitChangeListID(cardid,listid,newOrder,callback){
	if (!listid){
		alert('错误操作，bug就是你引起的，请进行归档操作！');
		return
	}
	$.post('./?app=api&apiact=set_card_listid&cardid='+cardid+"&listid="+listid ,newOrder,function(text){
		var json = JSON.parse( text );
		emitEventByJSON(json);
		callback && callback(json);
	});
}

//重新排序列表
function doSubmitSortList(boardid,newOrder,callback){
	$.get('./?app=api&apiact=sort_list&boardid='+boardid+"&"+ newOrder ,function(text){
		var json = JSON.parse( text );
		emitEventByJSON(json);
		callback && callback(json);
	});
}
//修改看板标题
function doSubmitMidifyBoardTitle(boardid,text,callback){
	if(text.length==0)return;

	$.get('./?app=api&apiact=modify_board_title&boardid='+boardid+"&text="+ text ,function(text){
		var json = JSON.parse( text );
		emitEventByJSON(json);
		callback && callback(json);
	});
}
//归档列表
function doSubmitArchivedList(listid,callback){
	$.get('./?app=api&apiact=archived_list&listid='+listid,function(text){
		var json = JSON.parse( text );
		emitEventByJSON(json);
		callback && callback(json);
	});
}

//归档已完成项目
function doSubmitArchivedOveredCards(listid,callback){
	$.get('./?app=api&apiact=archived_overedcards&listid='+listid,function(text){
		var json = JSON.parse( text );
		emitEventByJSON(json);
		callback && callback(json);
	});
}

// 删除卡片
function doSubmitDeleteCards(cid,callback){
	$.get('./?app=api&apiact=del_card&cardid='+cid,function(text){
		var json = JSON.parse( text );
		if(json.msg){
			alert(json.msg);
			return
		}
		emitEventByJSON(json);
		callback && callback(json);
	});
}

function HASH(){
	var res = {};
	var hash = location.hash.replace('#','');
	if(hash.length > 0){
		var hashArr = hash.split('&');
		for(var i=0;i<hashArr.length;i++){
			var _ = hashArr[i].split('=');
			res[ _[0] ] = _[1];
		}
	}
	return res;
}

//显示修改看板标题栏
function showMidiTitle(e){
	if($('#modifyTitle').length>0){
		$('#modifyTitle').remove();
		return;
	}

	$('#modifyTitle').remove();

	var html = T( $('#tmpl-modifyTitle').html() , DATA );
	$('body').append( html );

	$('#modifyTitle').css({
		'left':$(document).scrollLeft()+e.clientX+5,
		'top':e.clientY+10
	});

	var board = DATA.boards[ DATA.boardid ];
	$('.modifyTitle_text').val( board.title );
}

function showListMenu(e,obj){
	if($('#listmenu').length>0){
		$('#listmenu').remove();
		return;
	}

	$('#listmenu').remove();
	var listid = $(obj).parents('.panel').data('id');
	var html = T( $('#tmpl-listmenu').html() , DATA.lists[ listid ] );
	$('body').append( html );

	$('#listmenu').css({
		'left':$(document).scrollLeft() + e.clientX-155,
		'top':e.clientY+15
	});

	$("#listmenu").menu();
//	var board = DATA.boards[ DATA.boardid ];
//	$('.modifyTitle_text').val( board.title );
}

//发送dingding消息
function sendDDMSG(toname,text,url,dduserid){
	//if(!window.MYINFO)return;
	$.post('http://'+ HOSTANDPORT +'/dtalk/?app=senddmsgbyappid',{
		appid:(DTALK_APPID||""),
		content:text,
		name:toname,
		dduserid:(dduserid||""),
		url:url
	});
}
