var DC = {};
DC.unfinishedTitle = '【该单子未创建完成】';
DC.permission = {};


//查看详情
function closeCardInfo(){
	$('.isselect').removeClass('isselect');
	$('#cardinfoMask').remove();
	$('#cardinfo').remove();
	$('#memberlist').remove();
	$('#addlabels').remove();
	$('#addQAlabels').remove();
	$('#addRisklabels').remove();
	DATA.lastShowCardID = null;
}
var showCommentsType;
function showCard(cardid,callback){
	showCommentsType='default';
	$.get('./?app=api&apiact=getcardinfo&cardid='+cardid,function(text){
		var json = JSON.parse(text);
		location.hash = "cardid="+cardid;
		
		if( json[cardid] ){
			DATA.cards[ cardid ] = json[cardid];
			closeCardInfo();	
			
			DATA.lastShowCardID = cardid;
			console.log('json',json);
			$('#card_'+cardid).addClass('isselect');
			
			var html = T( $('#tmpl-cardinfo').html() , DATA.cards[ cardid ] );
			$('body').append( html );
			$('#cardinfoMask').fadeIn(100).css('width',$(document).width());
			
			_fmtCardInfoLabelsByCardID();

			_fmtCardInfoQALabelsByCardID();
			_fmtCardInfoRiskLabelsByCardID();
			_fmtCardInfoIssueTagsByCardID();

			_fmtCardInfoMembersByCardID();
			// 延期成员
			//_fmtCardInfoYanQiMembersByCardID();

			setDescription( json[cardid] );
			setCardInfoTitle( json[cardid] );
			
			fmtCommentsByCardID(cardid);
			fmtCheckListByCardID(cardid);
			showAttachmentsByCardID(cardid);
			
			
			$('.cardinfo_addcommets_editor,.cardinfo_description_editor').pasteImageReader(function(results){
				var me = this;
				$.post('base64upload/index.php',{
					"data":results.dataURL
				},function(url){
					var ov = $(me).val();
					$(me).val( ov +"![](base64upload/"+ url +")" );
					console.log('url',url,$(me).val());
				});
			});
			
			var names = [];
			for(var uid in DATA.users){
				names.push( {'name':DATA.users[uid].username,'fullname': DATA.users[uid].profile.fullname } );
			}
    
    		//@功能
    		$('.atwho-container').remove();
			$('.cardinfo_addcommets_editor,.cardinfo_description_editor').atwho({
			    at: "@",
			    data:names,
			    insertTpl: '@${fullname}',
			    displayTpl: "<li>${name} <small>${fullname}</small></li>",
			    limit: 200
			});

			if(MYID != DATA.cards[DATA.lastShowCardID].userId){
				$('#cardinfoDelete').hide();
			}
		}

		callback && callback(json);
	});
}

// 成员
function _fmtCardInfoMembersByCardID(){
	fmtMembersByCardID( DATA.lastShowCardID ,function(html){
		html = '<span class="addjiahao member cardinfo_addmember" title="在该卡片中添加或移除看板成员" href="#" aria-label="在该卡片中添加或移除看板成员"><i class="fa fa-plus"></i></span>' + html;
		$('#cardinfoMembers').html( html );
		
		$('#cardinfoMembers .js-member').attr('title','双击去除该用户').unbind().on('dblclick',function(){
			var uid = $(this).data('id');
			doSubmitSetMember(DATA.boardid,DATA.lastShowCardID,uid,function () {
				// 记录日志
				var uinfo = getUserInfo( uid );
				var myinfo = getUserInfo( MYID );

				var uNmae = uinfo?uinfo.profile.fullname:data.userId;
				var commontText = `${myinfo.profile.fullname}<font color=red>[删除]</font>成员 [${uNmae}]`;
				doSubmitCommonts(commontText,DATA.boardid,DATA.lastShowCardID);

			});
		});
	});
}

// 延期成员
function _fmtCardInfoYanQiMembersByCardID(){
	$('#yanqimembers-h3').hide();
	$('#yanqimembers-div').hide();
	checkPermission('removeYanQi',function (isok) {
		if(isok){
			$('#yanqimembers-h3').show();
			$('#yanqimembers-div').show();
			fmtYanQiMembersByCardID( DATA.lastShowCardID ,function(html){
				// html = '<span class="addjiahao member cardinfo_addmember" title="在该卡片中添加或移除看板成员" href="#" aria-label="在该卡片中添加或移除看板成员"><i class="fa fa-plus"></i></span>' + html;
				$('#cardinfoYanQiMembers').html( html );

				$('#cardinfoYanQiMembers .js-member').attr('title','双击去除该用户').unbind().on('dblclick',function(){
					var uid = $(this).data('id');
					$(this).remove();
					doSubmitRemoveYanQiMember(DATA.boardid,DATA.lastShowCardID,uid);
				});
			});
		}else {

		}

	});


}

// 标签
function _fmtCardInfoLabelsByCardID(){
	fmtLabelsByCardID( DATA.lastShowCardID ,function(html){
		html = '<span class="addjiahao cardinfo_addlabel" title="在该卡片中添加或移除标签" href="#" aria-label="在该卡片中添加或移除看板成员"><i class="fa fa-plus"></i></span>' + html;
		$('#cardinfoLabels').html( html );
		
		$('#cardinfoLabels .minicard-label').attr('title','双击去除该标签').unbind().on('dblclick',function(){

			if(! $(this).data("labelName") ) {
				$(this).data("labelName" ,$(this).text());
			}

			var labelid = $(this).data('id');
			var labelName =$(this).data("labelName");
			var _that = this;
			
			doSubmitSetLabel(DATA.lastShowCardID,labelid);

			/*
			var dept = new Set(DATA.riskdept.join(",").split(","))
			if (dept.has(labelName) == 1){

				if($(_that).data("timeout")){
					console.log('锁定中...');
					return;
				}


				var clicks = $(this).data('clicks');
				if(clicks==null)clicks=0;
				$(this).data('clicks', clicks*1+1);

				if($(_that).data('clicks')*1==1){
					$(".fengxianbiaoqian").html("请阅读风险提示，<span id='clicktimeout'>5</span>秒后再次双击部门标签去标");

					var _times = 5;
					$(_that).data("timeout",setInterval(function(){
						$('#clicktimeout').html( --_times);

						if(_times<=0){
							clearInterval($(_that).data("timeout"));
							$(_that).data("timeout",null);
						}
					},1000))

				}

				window.location.hash = "#fengxianbiaoqian_title";
				var hash = window.location.hash;

				$('#cardinfoRiskLabels').parent().css('background-color', '#fffdc9').css('padding', '10px').animate({
			       backgroundColor: '#00A087'
			     }, 200);
			}



			var isOk = checkMeiShuLabelRemove(labelName);
			if (isOk){
				console.log('isok');
				if( !dept.has(labelName) ||  (dept.has(labelName) == 1 && $(this).data('clicks')*1 >= 2) ){
					doSubmitSetLabel(DATA.lastShowCardID,labelid);
				}
			}
			*/
		});
	});
}

// 风险标签
function _fmtCardInfoRiskLabelsByCardID(){
	return;
	fmtRiskLabelsByCardID( DATA.lastShowCardID ,function(html){
		html = '<span class="addjiahao cardinfo_addRisklabel" title="在该卡片中添加或移除标签" href="#" aria-label="在该卡片中添加或移除看板成员"><i class="fa fa-plus"></i></span>' + html;
		$('#cardinfoRiskLabels').html( html );

		$('#cardinfoRiskLabels .minicard-label').attr('title','双击去除该标签').unbind().on('dblclick',function(){
			var labelid = $(this).data('id');
			var labelName = $(this).text();


			doSubmitSetRiskLabel(DATA.lastShowCardID,labelid);
		});

		//_fmtCardInfoIssueTagsByCardID();
	});
}

// 风险标签相关事件列表
function _fmtCardInfoIssueTagsByCardID(){
	return;
	fmtIssueTagsByCardID( DATA.lastShowCardID)
}

// legulabel 中有 美 UI 的去掉 ui验 美验 判断评论图片
// true 可以执行
function checkMeiShuLabelRemove(labelName) {
	var userLabel = ['UI','美'];
	var checkList = ['美验', '美术验', 'UI验'];
	var imgStr = '.png';
	// 排除描述在评论中
	var commentDesc = '添加了描述';
	// 判断要去掉的标签
	if (checkList.indexOf(labelName) != -1){

		// 各自部门去掉各自部门的验需要评论图片

		var userLeguLabelList = MYINFO.legulabel;
		var isUser = false;
		var labelnotYan = labelName.replace('验', '');
		for (var i of userLeguLabelList){
			// if (userLabel.indexOf(i)!=-1){
			if (labelnotYan == i){
				isUser = true;
				break
			}
		}
		// 用户是美术相关人员
		if(isUser){
			// 评论中有图片
			// ![](http://myip.legu.cc:81/base64upload/files/5ece83286f33e.png)
			var isComment = false;
			var nt = parseInt(new Date().getTime()/1000);

			for(let i in DATA.card_comments){
				let comment = DATA.card_comments[i];
				if (comment.boardId == DATA.boardid &&
					comment.cardId == DATA.lastShowCardID &&
					comment.userId == MYID &&
					comment.text.indexOf(imgStr) != -1 &&
					comment.text.indexOf(commentDesc) == -1 &&
					(nt - comment.createdAt.sec) < 30*60
				){
					isComment = true;
				}
			}
			if (!isComment){
				alert('在评论区添加游戏内验收的效果图 30分钟以内');
				return false;
			}
			return true;

		}
	}
	return true;







}


// QA标签
function _fmtCardInfoQALabelsByCardID(){

	$('#qalabels-h3').hide();
	$('#qalabels-div').hide();
	var pms = 'QAlabels';
	console.log(window.MYINFO);


	// 权限判断 __setting.Permission.QAlabels
	if(window.MYINFO && window.MYINFO.legulabel && window.MYINFO._id){
		var uid = window.MYINFO._id;

		$('#qalabels-h3').show();
		$('#qalabels-div').show();

		fmtQALabelsByCardID( DATA.lastShowCardID ,function(html){
			html = '<span class="addjiahao cardinfo_addQAlabel" title="在该卡片中添加或移除标签" href="#" aria-label="在该卡片中添加或移除看板成员"><i class="fa fa-plus"></i></span>' + html;
			$('#cardinfoQALabels').html( html );

			$('#cardinfoQALabels .minicard-label').attr('title','双击去除该标签').unbind().on('dblclick',function(){
				var labelid = $(this).data('id');
				doSubmitSetQALabel(DATA.lastShowCardID,labelid);
			});
		});


		// $.get('./?app=api&apiact=getWorkPermission&uid=' + uid + '&pms=' + pms,function (txt) {
		// 	var isAllow = JSON.parse(txt);
		// 	if (isAllow){
		// 		$('#qalabels-h3').show();
		// 		$('#qalabels-div').show();
		//
		// 		fmtQALabelsByCardID( DATA.lastShowCardID ,function(html){
		// 			html = '<span class="addjiahao cardinfo_addQAlabel" title="在该卡片中添加或移除标签" href="#" aria-label="在该卡片中添加或移除看板成员"><i class="fa fa-plus"></i></span>' + html;
		// 			$('#cardinfoQALabels').html( html );
		//
		// 			$('#cardinfoQALabels .minicard-label').attr('title','双击去除该标签').unbind().on('dblclick',function(){
		// 				var labelid = $(this).data('id');
		// 				doSubmitSetQALabel(DATA.lastShowCardID,labelid);
		// 			});
		// 		});
		//
		// 	}
		// });



	}
}


function showAttachmentsByCardID(cardid){
	if(cardid!=DATA.lastShowCardID)return;
	if(!DATA.cards[ DATA.lastShowCardID ])return;
	
	var attachments = DATA.cards[ DATA.lastShowCardID ].attachments || [];
	var html = [];
	for(var i=0;i<attachments.length;i++){
		html.push('<span><a class="fa fa-close delfujian" data-id="'+ attachments[i]._id +'" href="javascript:;"></a>&nbsp;&nbsp;<a target="_blank" href="'+ attachments[i].file +'" title="'+ attachments[i].name +'">'+ attachments[i].name +'</a></span>');
	}
	$('.fujianlist').html( html.join(''));
}
			

function fmtCommentsByCardID(cardid){
	$.get('./?app=api&apiact=card_comments&cardid='+cardid,function(text){
		var json = JSON.parse( text );
		DATA.card_comments = DATA.card_comments || {};
		for(var k in json){
			DATA.card_comments[k] = json[k];
		}
		showComments();
	});
}

function isShiJian(title){
	return title.indexOf('</font>')!=-1 && title.indexOf('[')!=-1 && title.indexOf(']')!=-1;
}

//显示评论内容
//var showCommentsType;
//function showComments(){
//	var comments = [];
//	var shijianNum=0;
//	var dongtaiNum=0;
//	
//	if(!DATA.card_comments)return;
//	for(var k in DATA.card_comments){
//		if(DATA.card_comments[k].cardId == DATA.lastShowCardID){
//			comments.push( DATA.card_comments[k] );
//			
//			if(isShiJian(DATA.card_comments[k].text)){
//				shijianNum++;
//			}else{
//				dongtaiNum++;
//			}
//		}
//	}
//	
//	console.log('shijianNum',shijianNum);
//	console.log('dongtaiNum',dongtaiNum);
//	
//	comments.sort(function(a,b){
//		return b.createdAt.sec - a.createdAt.sec;
//	});
//	
//	fill('#tmpl-cardinfo_comments',comments,'#cardinfo_comments_panel');
//	$('#cardinfo_comments_panel').viewer({
//		viewed:function() {
//	        $('#cardinfo').css('overflow-y','visible');
//	    },
//	   hide:function(){
//	   	$('#cardinfo').css('overflow-y','auto');
//	   }
//	});
//}

//格式化检查项
function fmtCheckListByCardID(cardid){
	$.get('./?app=api&apiact=get_checklists&cardid='+cardid,function(text){
		var json = JSON.parse( text );
		DATA.card_checklists = DATA.card_checklists || {};
		for(var k in json){
			DATA.card_checklists[k] = json[k];
		}
		showCheckList();
	});
}

//显示评论内容
function showComments(){
	if(!DATA.card_comments)return;
	var shijian=[];
	var dongtai=[];
	var comments = [];
	for(var k in DATA.card_comments){
		if(DATA.card_comments[k].cardId == DATA.lastShowCardID){
			comments.push( DATA.card_comments[k] );
			if(isShiJian(DATA.card_comments[k].text)){
				shijian.push( DATA.card_comments[k] );
			}else{
				dongtai.push( DATA.card_comments[k] );
			}
		}
	}
	
	
	if(showCommentsType=='all'){
		
	}else if(showCommentsType=='shijian'){
		comments = shijian;
	}else if(showCommentsType=='dongtai' || showCommentsType=='default'){
		comments = dongtai;
		if( dongtai.length==0 && showCommentsType=='default'){
			showCommentsType = 'shijian';
			comments = shijian;
		}else{
			showCommentsType = "dongtai";
		}
	}
	
	$('.detail_lis').removeClass('on');
	$('.detail_lis_'+showCommentsType).addClass('on')
	
	comments.sort(function(a,b){
		return b.createdAt.sec - a.createdAt.sec;
	});
	
	fill('#tmpl-cardinfo_comments',comments,'#cardinfo_comments_panel');
	$('#cardinfo_comments_panel').viewer({
		viewed:function() {
	        $('#cardinfo').css('overflow-y','visible');
	    },
	   hide:function(){
	   	$('#cardinfo').css('overflow-y','auto');
	   }
	});
}

//显示检查项
function showCheckList(){
	var contents = [];
	if(!DATA.card_checklists)return;
	for(var k in DATA.card_checklists){
		if(DATA.card_checklists[k].cardId == DATA.lastShowCardID){
			contents.push( DATA.card_checklists[k] );
		}
	}
	contents.sort(function(a,b){
		if(a.sort != b.sort){
			return a.sort-b.sort;
		}else{
			return a._id > b._id ? -1 : 1;
		}
	});
	
	var html = [];
	for(var i=0;i<contents.length;i++){
		html.push('<li><input class="checklistcheckbox" type="checkbox" data-id="'+ contents[i]._id +'" '+ (contents[i].isFinished?' checked="checked"':"") +' /> '+ (contents[i].isFinished?'<s style="color:#bbb">':"") + contents[i].title + (contents[i].isFinished?'</s>':"") +' <a class="fa fa-close delchecklist" style=" text-decoration: none; color:#999" href="javascript:;"></a></li>');
	}
	
	$('#checklistsol').html( html.join('') );
}

function setDescription( data ){
	$('.cardinfo_description').html( replaceImgURL(marked(data['description']||'点击编辑')) );
	
	$('.cardinfo_description').viewer({
		viewed:function() {
	        $('#cardinfo').css('overflow-y','visible');
	   },
	   hide:function(){
	   		$('#cardinfo').css('overflow-y','auto');
	   }
	});
	
	if(HOST!='10.0.0.5'){
		$('.cardinfo_description a').unbind().each(function(index,o){

			if(o.href.indexOf('url.cn')!=-1){
				//内网文档
				$.get('./?app=short2long&url='+encodeURIComponent(o.href),function(longurl){
					console.log('longurl',longurl);
					if(longurl!="" && longurl.indexOf('10.0.0.5')!=-1){
						o.href = longurl.replace('10.0.0.5','myip.legu.cc:81');
						o.innerHTML += '[已重置为异地办公模式]';
					}
				});
			}
		});
	}
	
}

function timetrans(date) {// 格式化日期
	var date = new Date(date*1000);
	var YY = date.getFullYear() + '-';
	var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
	var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
	var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
	var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
	var ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
	return MM + DD +" "+ hh + mm + ss;
}

function setCardInfoTitle( data ){
	$('.cardinfo_title').html( data['title']||'无' );
	console.log('data',data);
	$('.cardinfo_ctime').html( timetrans(data['createdAt'].sec) ||'' );
}


function checkats(text){
	var ats = text.match(/@(\S*)\s{1}/g);
	var tousers = [];
	if(window.MYINFO && ats && ats.length>0){
		for(var i=0;i<ats.length;i++){
			var touser = ats[i].replace('@','').replace(' ','');
			tousers.push(touser);
		}
		if(tousers.length>0){
			var msgInfo = window.MYINFO.profile.fullname + "在任务["+ DATA.cards[ DATA.lastShowCardID  ].title+']中提到了你：'+ text;
			sendDDMSG(tousers.join(','),msgInfo,location.href);
		}
	}
}

//提交评论
function doSubmitCommonts(text,boardid,cardid,callback){
	if(boardid==null){boardid = DATA.cards[cardid].boardId;} //兼容“与我相关“模式
	checkats(text);
	$.get('./?app=api&apiact=add_card_comments&cardid='+cardid+"&boardid="+boardid+"&text="+ encodeURIComponent(text),function(text){
		var json = JSON.parse( text );
		emitEventByJSON(json);
		callback && callback(json);
	});
}
//修改描述
function doSubmitDescription(text,boardid,cardid,callback){
	if(boardid==null){boardid = DATA.cards[cardid].boardId;} //兼容“与我相关“模式
	checkats(text);
	var newDescription = text;
	var oldDescription = DATA.cards[cardid].description;
	$.get('./?app=api&apiact=set_card_description&cardid='+cardid+"&boardid="+boardid+"&text="+ encodeURIComponent(text),function(text){
		var json = JSON.parse( text );
		if (newDescription != oldDescription){
			var myinfo = getUserInfo( MYID );
			var info = myinfo.profile.fullname || "我";

			// console.log('oldDescription',oldDescription);

			if(oldDescription){
				info += '<font color=red>[修改了描述]</font><br>';
				info += '```'+ oldDescription +'```' + '<br>为<br>```' + newDescription + '```';

			}else {
				info += '<font color=red>[添加了描述]</font> <br>'; 
				info += '```' + newDescription + '```';

			}

			doSubmitCommonts( info, DATA.boardid, cardid );
		}

		emitEventByJSON(json);
		callback && callback(json);
	});
}
//修改标题
function doSubmitTitle(text,boardid,cardid,callback){
	var uid = window.MYINFO._id;
	var newTitle = text;
	var oldTitle = DATA.cards[cardid].title;
	if(boardid==null){boardid = DATA.cards[cardid].boardId;} //兼容“与我相关“模式
	// $.get('./?app=api&apiact=set_card_title&cardid='+cardid+"&boardid="+boardid+"&text="+ encodeURIComponent(text),function(text){
	$.get('./?app=api&apiact=set_card_title&cardid='+cardid+"&boardid="+boardid+"&uid="+uid+"&text="+ encodeURIComponent(text),function(text){
		var json = JSON.parse( text );

		if (newTitle != oldTitle){
			var myinfo = getUserInfo( MYID );
			var info = myinfo.profile.fullname || "我";
			info += '<font color=red>[修改了标题]</font>';
			info += '<font color=blue>'+ oldTitle +'</font>' + ' 为 <font color=red>' + newTitle + '</font>';

			// console.log('aaaa', json);

			doSubmitCommonts( info, DATA.boardid, cardid );
		}


		emitEventByJSON(json);
		callback && callback(json);
	});
}
//删除附件
function doSubmitDelFuJian(cardid,fujianid,callback){
	$.get('./?app=api&apiact=del_fujian&cardid='+cardid+"&fujianid="+fujianid,function(text){
		var json = JSON.parse( text );
		emitEventByJSON(json);
		callback && callback(json);
	});
}

//新增检查项
function doSubmitAddChecklist(text,cardid,callback,sort){
	if(sort==null)sort="";
	$.get('./?app=api&apiact=add_card_checklist&sort='+ sort+'&cardid='+cardid+"&text="+ encodeURIComponent(text),function(text){
		var json = JSON.parse( text );
		emitEventByJSON(json);
		callback && callback(json);
	});
}

function doSubmitSetFickshChecklist(checkid,val,callback){
	$.get('./?app=api&apiact=set_checklist_finish&id='+checkid+"&val="+ val,function(text){
		var json = JSON.parse( text );
		emitEventByJSON(json);
		callback && callback(json);
	});
}

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

function setMemTimer(val,obj,callback){
	var memid = $(obj).data('id');
	var cardid = $(obj).parents('.card,#cardinfo').data('id');

	
	console.log('memid',memid);
	console.log('cardid',cardid);
	if(!memid || !cardid)return;
	
	var times = '',timee='';
	if(val){
		var arr = val.split('~');
		times = arr[0];
		timee = arr[1];
	}
	
	$.get('./?app=api&apiact=set_mem_time&times='+ times +'&timee='+ timee +'&cardid='+cardid+"&memid="+memid,function(text){
		var json = JSON.parse( text );
		emitEventByJSON(json);
		callback && callback(json);
		var setText = '设置了<font color=blue>[时间]</font>卡片' + times + ' / ' + timee;
		doSubmitCommonts(setText,DATA.boardid,cardid);
	});
}


// 是否设置了QA标签
function isSetQALabel(cid){
	var qalabelIds = DATA.cards[cid].qalabelIds;
	if (!qalabelIds || qalabelIds.length <= 0){
		return false;
	}
	return true;

}

// 检查当前用户是否是QA
function isQA(){
	if(window.MYINFO && window.MYINFO.legulabel && window.MYINFO._id){
		var pms = 'QAlabels';
		var uid = window.MYINFO._id;
		$.get('./?app=api&apiact=getWorkPermission&uid=' + uid + '&pms=' + pms,function (txt) {
			var isAllow = JSON.parse(txt);
			console.log('isAQ------'+ isAllow);
			if (isAllow){
				return true;
			}
		});

	}else {
		return false;
	}

}

// 检查是否是QA
function checkQA(callback,uid){
	callback && callback(true);

	/*if(window.MYINFO && window.MYINFO.legulabel && window.MYINFO._id) {
		
		var pms = 'QAlabels';
		var ckuid = uid || window.MYINFO._id;
		$.get('./?app=api&apiact=getWorkPermission&uid=' + ckuid + '&pms=' + pms, function (txt) {
			var isAllow = JSON.parse(txt);
			// console.log('isAQ------' + isAllow);
			if (isAllow) {
				// callback && callback(isAllow);
			}
			callback && callback(isAllow);
		});
	}
	*/
}


function checkPermission(pms,callback){
	var uid = window.MYINFO._id;
	$.get('./?app=api&apiact=getWorkPermission&uid=' + uid + '&pms=' + pms, function (txt) {
		var isAllow = JSON.parse(txt);
		// console.log('isAQ------' + isAllow);
		if (isAllow) {
			// callback && callback(isAllow);
		}
		callback && callback(isAllow);
	});
}

// 未完成的卡片关闭的时候检查状态
function checkUnfinishedCardCanClose(callback){
	callback && callback({});
	var cardid = DATA.lastShowCardID;


	if(DATA.cards[cardid] && DATA.cards[cardid] && DATA.cards[cardid].qalabelIds){
		if(!DATA.cards[cardid].qalabelIds || DATA.cards[cardid].qalabelIds.length == 0){
			alert('请添加【问题类型】');
			return;
		}
	}

	if(DATA.cards[cardid] && DATA.cards[cardid]._status && DATA.cards[cardid]._status == 'unfinished'){
		// 标题
		// if(DATA.cards[cardid].title == DC.unfinishedTitle || DATA.cards[cardid].title == '' || DATA.cards[cardid].title == '无'){
		// 	alert('请修改标题');
		// 	return;
		// }

		// 部分看板
		// 是否检查 《xx》看板要检查
		var isCheck = true;
		var boardTitle = DATA.boards[DATA.boardid].title;
		var isCheckBoardTitle = boardTitle.match(/《(\S*?)》/g);
		if (!isCheckBoardTitle || isCheckBoardTitle.length == 0){
			isCheck = false;
		}


		// var title = DATA.cards[cardid].title.match(/【(\S+?)】/g);
		var title = DATA.cards[cardid].title;
		if(isCheck){
			if ((!title || title.length == 0)){
				alert('请添加【标题】');
				return;
			}

			// qa标签
			if((!DATA.cards[cardid].qalabelIds || DATA.cards[cardid].qalabelIds.length == 0)){
				alert('请对创建的单子添加【问题类型】');
				return;
			}

			// 根据qa标签是否检查描述
			// bug和其他不检查
			board = DATA.boards[DATA.cards[cardid].boardId];
			// var linfo  = board.qalabels[DATA.cards[cardid].qalabelIds[0]];
			// 只有一个qa标签
			var lid = DATA.cards[cardid].qalabelIds[0];
			for(var l=0;l<board.qalabels.length;l++) {
				if (board.qalabels[l] && board.qalabels[l]._id == lid) {
					var linfo = board.qalabels[l];
					if (!(['BUG', '其他'].indexOf(linfo.name) > -1)) {
						// 描述不能为空
						if (!DATA.cards[cardid].description || !DATA.cards[cardid].description.trim()) {
							alert('请添加单子详细【描述】（最好带截图）');
							return;
						}
					}
				}
			}

			// 部门标签
			if((!DATA.cards[cardid].labelIds || DATA.cards[cardid].labelIds.length == 0)){
				alert('请对创建的单子添加【部门标签】');
				return;
			}


		}


		// 验证完了 修改类型
		boardid = '';
		uid = '';
		$.get('./?app=api&apiact=set_card_status&cardid='+cardid+"&boardid="+boardid+"&uid="+uid,function(text){
			//if(cards[cardid].risklabelsId.length>1){
			//	alert('请将风险标签去除后再来打勾勾哦~');
			//}
			var json = JSON.parse( text );
			emitEventByJSON(json);
			callback && callback(json);
		});


		// var title = DATA.cards[cardid].title.match(/【(\S*?)】/g);
		// if (isCheck && (!title || title.length == 0)){
		// 	alert('请修改标题 【模块】标题');
		// 	return;
		// }
		//
		// // qa标签
		// if(isCheck && (!DATA.cards[cardid].qalabelIds || DATA.cards[cardid].qalabelIds.length == 0)){
		// 	alert('请对创建的单子添加问题类型');
		// 	return;
		// }
		// // 验证完了 修改类型
		boardid = '';
		uid = '';
		$.get('./?app=api&apiact=set_card_status&cardid='+cardid+"&boardid="+boardid+"&uid="+uid,function(text){
			var json = JSON.parse( text );
			emitEventByJSON(json);
			callback && callback(json);
		});


	}

	$('#firstAddQaLabels').hide();

	callback && callback();

}

// 检查状态是未完成的单子是否可点开
function checkUnfinishedCardCanClick(cardid, callback){
	// 状态是未完成且不是自己创建的单子不能点开
	// 添加了描述和部门就能点开
	if(DATA.cards[cardid] && DATA.cards[cardid]._status=='show' || DATA.cards[cardid] && DATA.cards[cardid]._status==undefined){

	}
	else if(DATA.cards[cardid] && (DATA.cards[cardid].description==undefined || !DATA.cards[cardid].labelIds.length) && DATA.cards[cardid].userId != window.MYINFO._id){
		alert('该单子未创建完成');
		return;
	}
	callback && callback();
}



$(function(){

	checkQA(function (isAllow) {
		DC.permission.QAlabels = isAllow
	});


	$('body').on("click","#cardinfoClose",function(){
		checkUnfinishedCardCanClose(function () {
			closeCardInfo();
		});
	});

	$('body').on("click","#cardinfoDelete",function(){

		var that = $(this);
		var cid = DATA.lastShowCardID;

		if(MYID!=DATA.cards[cid].userId){
			alert('不是你的单子你删不掉');
			return
		}

		if(confirm("确定删除吗？")){


			// var listid = $(this).parents('.listmenu').data('id');
			// doSubmitArchivedOveredCards(listid,function(){
			// 	$('.close_menu_li').click();
			// });

			doSubmitDeleteCards(cid,function () {
				$('#cardinfoClose').click();
			})
		}



	});


	$('body').on("click","#cardinfoOverd",function(){
		var that = $(this);
		var lid = DATA.lastShowCardID;

		// if (isQA()){
		// 	if (!isSetQALabel(lid)){
		// 		alert('请设置问题类型');
		// 		return;
		// 	}
		// }
		var cardid = lid;

		// ui验 美验
		var card = DATA.cards[ DATA.lastShowCardID ];
		var board = DATA.boards[ card.boardId ];
		var board_id_name = {};
		for (var i of board.labels){
			board_id_name[i['_id']] = i['name'];
		}
		// 已经设置的标签 再次点击是去除标签
		for (var clid of card.labelIds){
			var labelName = board_id_name[clid];
			var isOk = checkMeiShuLabelRemove(labelName);
			if(!isOk){
				return;
			}
		}

		//完成该卡片
		if(confirm('删除所有标签并设为完成?')){
			// var lid = DATA.lastShowCardID;
			// var labels = DATA.cards[lid].labelIds;
			// for(var i=0;i<labels.length;i++){
			// 	doSubmitSetLabel(lid,labels[i]);
			// }
			$('#finishcheck_'+lid).click();
		}
	}); 
	
	$('body').on("click","#cardinfoMask",function(){
		// if($(".cardinfo_description_editor_div").is(":visible"))
		if($('.cardinfo_addcommets_editor').val())
		{
			alert('你有未保存的评论，请评论或清空评论')
		}
		else {
			checkUnfinishedCardCanClose(function () {
				closeCardInfo();
			});
		}

	});

	$('body').on("click","#firstlabelcardinfoMask",function(){
		alert('请先选择【问题类型】')

	});


	$('body').on("mouseover","#cardinfo",function(){
		$('#cardinfoMask').fadeIn(100);
	});
	
	var _mdTimer = null;
	function _clearMdTimer(){
		if(_mdTimer)clearTimeout(_mdTimer);
		_mdTimer = null;
	}
	/*
	$('body').on('mousedown','.member',function(){
		//长按名单
		var me = this;
		var _id = 'mem_'+$(this).attr('data-id')+"_"+(new Date()).getTime();
		$(this).attr('id', _id);

		_mdTimer = setTimeout(function(){
			$(me).addClass('blink');
			jeDate({
				dateCell:"#"+ _id,
				format:"YYYY-MM-DD",
				isinitVal:false,
				shownowtime:true,
				isTime:false,
				festival:true,
				notFillValWhenGet:true,
				okfun : function(val){
					setMemTimer(val,me);
				},
				clearfun : function(val){
					setMemTimer('',me);
				},
				choosefun : function(val){
					setMemTimer(val,me);
				}
			});
		},300);
		
	}).on('mouseup','.member',function(){
		_clearMdTimer();
		$(this).removeClass('blink');
	});
	*/


	$('body').on('mousedown','.member',function(){
		//长按名单
		var me = this;
		var _id = 'mem_'+$(this).attr('data-id')+"_"+(new Date()).getTime();
		$(this).attr('id', _id);

		_mdTimer = setTimeout(function(){
			$(me).addClass('blink');
			$('.date-picker-wrapper').remove();

			$('#'+_id).dateRangePicker({
				showShortcuts: false ,
				separator:"~",
				autoClose:true,
				//getValue: function(){
				//	return $('#'+_id).data('timestr');
				//},
				setValue: function(s){
					setMemTimer(s,$('#'+_id));
					setTimeout(function(){
						$('#'+_id).data('dateRangePicker').destroy();
					},10);
				}
			});

		},300);
		
	}).on('mouseup','.member',function(){
		_clearMdTimer();
		$(this).removeClass('blink');
	});
	
	//评论提交按钮
	$('body').on("click",".cardinfo_addcommets_btnsubmit",function(){
		//发表评论
		var val = $('.cardinfo_addcommets_editor').val();
		if(val.length == 0)return;
		doSubmitCommonts(val, DATA.boardid, DATA.lastShowCardID,function(){
			$('.cardinfo_addcommets_editor').val('');
		});
	});
	//描述内容
	$('body').on('click','.cardinfo_description',function(e){
		if(e && e.toElement && e.toElement.src)return; //图片不触发事件
		if(e && e.toElement && e.toElement.href)return; //链接不触发事件
		$(this).hide();
		$('.cardinfo_description_editor_div').show();
//		var ov = $('.cardinfo_description').text();
//		if(ov=='点击编辑')ov="";
		$('.cardinfo_description_editor').val( DATA.cards[DATA.lastShowCardID].description );
	});
	
	window.modal = function(type){
		$('.cardinfo_description').click();
		if(type=='1'){
			$('.cardinfo_description_editor').val("开发文档：\n\n美术需求文档：\n\nUI需求文档：\n\n简要描述：");
		}else if(type=='2'){
			$('.cardinfo_description_editor').val("现象：\n\n复现步骤：\n\n期望：");
		}else if(type=='3'){
			$('.cardinfo_description_editor').val("现象：\n\n期望：");
		}
	};
	
	//描述内容修改时取消按钮
	$('body').on('click','.cardinfo_description_btncannel',function(){
		$('.cardinfo_description_editor_div').hide();
		$('.cardinfo_description').show();
	});
	//描述内容修改时确定按钮
	$('body').on('click','.cardinfo_description_btnsubmit',function(){
		var val = $('.cardinfo_description_editor').val();
		if(!val.trim()){
			alert("描述不能为空");
			return
		}
		doSubmitDescription(val, DATA.boardid, DATA.lastShowCardID,function(){
			$('.cardinfo_description_btncannel').click();
		});
	});
	//增加或删除成员
	$('body').on('click','.cardinfo_addmember',function(e){
		showMemberList(e);
	});
	//增加或删除标签
	$('body').on('click','.cardinfo_addlabel',function(e){
		showLabels(e);
	});

	$('body').on('click','.cardinfo_addRisklabel',function(e){
		// console.log('e',e);
		showRiskLabels(e);
	});

	$('body').on('click','.cardinfo_addQAlabel',function(e){
		console.log('e',e);
		showQALabels(e);
	});

	
	//title内容
	$('body').on('click','.cardinfo_title',function(){
		$(this).hide();
		$('.cardinfo_title_editor_div').show();
		var ov = $('.cardinfo_title').text();
		$('.cardinfo_title_editor').val( ov );
	});
	//title修改时取消按钮
	$('body').on('click','.cardinfo_title_btncannel',function(){
		$('.cardinfo_title_editor_div').hide();
		$('.cardinfo_title').show();
	});
	//title修改时确定按钮
	$('body').on('click','.cardinfo_title_btnsubmit',function(){
		var val = $('.cardinfo_title_editor').val();
		doSubmitTitle(val, DATA.boardid, DATA.lastShowCardID,function(){
			$('.cardinfo_title_btncannel').click();
		});
	});
	//删除附件
	$('body').on('click','.delfujian',function(){
		var id =$(this).data('id');
		if(confirm('确认要删除该附件吗？')){
			doSubmitDelFuJian(DATA.lastShowCardID,id,function(){
				//$('.cardinfo_title_btncannel').click();
			});
		}
	});

	//新增检查项
	$('body').on('click','.addchecklist_btnsubmit',function(){
		var val = $('.addchecklist_input').val();
		if(val.length==0)return;
		doSubmitAddChecklist(val, DATA.lastShowCardID,function(){
			$('.addchecklist_input').val('');
		});
	});
	window.autochecklist = function(t){
		// console.log('===',t);

		var arr = [
			'策划需求完成',
			'UI设计完成',
			'UI拼接完成',
			'UI验收完成',
			'美术设计完成',
			'美术草图代入',
			'美术成品代入',
			'动效成品代入',
			'开发后端完成',
			'开发前端完成',
			'策划配置完成',
			'流程跑通'
		];
		if(t == '2'){
			arr = [
				'是否有执行脚本',
				'configmongodb.py 和 configmongodb_cross.py 有没有增删改',
				'检测前后端需要更新的文件是否提交',
				'最新文件是否同步到外网svn',
				'configmongodb.py 和 configmongodb_cross.py如有增删改，需要执行文件或清理索引',
				'检测是否有逻辑脚本执行，如果有，需要执行脚本',
				'更新后是否开区',
			];
		}
		
		var index = 0;
		function _add(){
			var v = arr.shift();
			doSubmitAddChecklist(v, DATA.lastShowCardID,function(){
				if(arr.length>0)_add();
			},index);
			index++;
		}	
		_add();
	};
	
	$('body').on('click','.checklistcheckbox',function(){
		var val = $(this).prop('checked');
		var _id = $(this).data('id');
		doSubmitSetFickshChecklist(_id,val,function(){
			
		});
	});
	
	$('body').on('click','.delchecklist',function(){
		var _id = $(this).parent().find('.checklistcheckbox').data('id');
		doSubmitDelChecklist(_id,function(){
			
		});
	});
	
	$('body').on('click','.detail_lis_dongtai',function(){
		//动态
		showCommentsType = 'dongtai';
		showComments();
		
	});
	$('body').on('click','.detail_lis_shijian',function(){
		//事件
		showCommentsType = 'shijian';
		showComments();
	});
	$('body').on('click','.detail_lis_all',function(){
		//全部评论
		showCommentsType = 'all';
		showComments();
	});
	
	
	EVENT.on('addcomment',function(data){
		if(data.cardId != DATA.lastShowCardID && DATA.boardid!=null)return;
		showComments();
	});
	
	EVENT.on('addchecklist',function(data){
		if(data.cardId != DATA.lastShowCardID && DATA.boardid!=null)return;
		showCheckList();
	});
	
	EVENT.on('setchecklistfinish',function(data){
		if(data.cardId != DATA.lastShowCardID && DATA.boardid!=null)return;
		showCheckList();
	});
	
	EVENT.on('delchecklist',function(data){
		if(data.cardId != DATA.lastShowCardID && DATA.boardid!=null)return;
		showCheckList();
	});
	
	EVENT.on('setdescription',function(data){
		if(data._id != DATA.lastShowCardID)return;
		setDescription( data );
	});
	EVENT.on('settitle',function(data){
		if(data._id != DATA.lastShowCardID)return;
		setCardInfoTitle( data );
	});
	
	EVENT.on('memberchange',function(data){
		if(data.boardId != DATA.boardid && DATA.boardid!=null)return;
		if(data._id != DATA.lastShowCardID)return;
		_fmtCardInfoMembersByCardID();
	});

	EVENT.on('memtimechange',function(data){
		if(data.boardId != DATA.boardid && DATA.boardid!=null)return;
		if(data._id != DATA.lastShowCardID)return;
		_fmtCardInfoMembersByCardID();
	});
	
	EVENT.on('labelchange',function(data){
		if(data.boardId != DATA.boardid && DATA.boardid!=null)return;
		if(data._id != DATA.lastShowCardID)return;
		_fmtCardInfoLabelsByCardID();
		_fmtCardInfoQALabelsByCardID();
		_fmtCardInfoRiskLabelsByCardID();
		_fmtCardInfoIssueTagsByCardID();
	});
	
	EVENT.on('attachmentschange',function(data){
		if(data.boardId != DATA.boardid && DATA.boardid!=null)return;
		if(data._id != DATA.lastShowCardID)return;
		
		showAttachmentsByCardID( data._id );
	});
	
	
});


function formatDate(time) {
	var now = new Date(time*1000);
　　var year = now.getFullYear(),
　　month = now.getMonth() + 1,
　　date = now.getDate(),
　　hour = now.getHours(),
　　minute = now.getMinutes(),
　　second = now.getSeconds();
　　return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
}
