<?
// 根据部门查看人员的单子

require_once "api.php";
$boardid = r('boardid');
$user = r('user');
$timeType = r('time_type');
$st = r('st');
$et = r('et');

$boards = getboards();
if($user){
    if($timeType=='bj'){
        $cards = getUserCards($user,$st,$et);
    }elseif ($timeType =='wc'){
        $cards = getUserCards4Finish($user,$st,$et);
    }elseif ($timeType =='xz'){
        $cards = getUserCards4New($user,$st,$et);
    }
}else{
//    echo "no data";
    $cards = array();
}

//we($mycards);
//$lists = getlists($boardid);
//$cards = getcards($boardid,array_keys($lists));
$users = getusers();
$risklabels = getRiskLabels();
$allrisklabels = getAllRiskLabels();

$list = array();
foreach($cards as $cid=>$card){
	$borderid = $card['boardId'];
	if($list[$borderid])continue;
	if(!$boards[ $borderid ]['title'])continue;
	$list[ $borderid ] = array(
		"archived"=>false,
		"title"=> $boards[ $borderid ]['title'],
		"_id"=> $borderid
	);
}

/*
$DATA = array(
	'boardid' => $boardid,
	'boards' => $boards,
	'lists' => array("mime"=>array(
		"archived"=>false,
		"title"=>"与我相关",
		"_id"=>'mime'
	)),
	'cards' => $cards,
	'users'=>$users
);
*/

$DATA = array(
	'boardid' => $boardid,
	'boards' => $boards,
	'lists' => $list,
	'cards' => $cards,
	'users'=>$users,
    'risklabels'=>$risklabels,
    'allrisklabels'=>$allrisklabels
);

?>

<!DOCTYPE html>
<html>
	<head>
		<? require_once "header.html"; ?>
		<link type="text/css" href="css/jquery.atwho.css?_<?=filemtime('css/jquery.atwho.css')?>" rel="stylesheet" />
		<link type="text/css" href="scripts/jedate.css?_<?=filemtime('scripts/jedate.css')?>" rel="stylesheet" />
		<script type="text/javascript" src="scripts/jquery.caret.js?_<?=filemtime('scripts/jquery.caret.js')?>"></script>
		<script type="text/javascript" src="scripts/jquery.atwho.js?_<?=filemtime('scripts/jquery.atwho.js')?>"></script>
		<script type="text/javascript" src="scripts/proreport.js?_<?=filemtime('scripts/proreport.js')?>"></script>
		<script type="text/javascript" src="scripts/cardPopover.js?_<?=filemtime('scripts/cardPopover.js')?>"></script>
		<script type="text/javascript" src="scripts/card_list_timeline.js?_<?=filemtime('scripts/card_list_timeline.js')?>"></script>
		<script type="text/javascript" src="scripts/copy_list_to_new.js?_<?=filemtime('scripts/copy_list_to_new.js')?>"></script>
		<script type="text/javascript" src="scripts/echarts.min.js?_<?=filemtime('scripts/echarts.min.js')?>"></script>
		<script type="text/javascript" src="scripts/jedate.js?_<?=filemtime('scripts/jedate.js')?>"></script>

        <script type="text/javascript" src="scripts/md5/md5.js?_<?=filemtime('scripts/md5/md5.js')?>"></script>

	</head>
	<body>
    	<? require_once "leftbar.html"; ?>
    	<? require_once "projectheader.html"; ?>

        <script type="text/tmpl" id="tmpl-cardinfo" >
			<? require_once "cardinfo.html"; ?>
		</script>

        <script type="text/tmpl" id="tmpl-card_timeline" >
			<? require_once "card_list_timeline.html"; ?>
		</script>

		<script type="text/tmpl" id="tmpl-listmenu" >
			<? require_once "listmenu.html"; ?>
		</script>

		<script type="text/tmpl" id="tmpl-cardinfo_comments" >
			<? require_once "cardinfo_comments.html"; ?>
		</script>

		<script type="text/tmpl" id="tmpl-proreport" >
			<? require_once "proreport.html"; ?>
		</script>

        <script type="text/tmpl" id="tmpl-cardpopover" >
			<? require_once "cardpopover.html"; ?>
		</script>

		<script type="text/tmpl" id="tmpl-memberlist" >
			<? require_once "memberlist.html"; ?>
		</script>

        <script type="text/tmpl" id="tmpl-addlabels" >
			<? require_once "labels.html"; ?>
		</script>

        <script type="text/tmpl" id="tmpl-addRisklabels" >
            <? require_once "risklabels.html"; ?>
        </script>


        <script type="text/tmpl" id="tmpl-addQAlabels" >
			<? require_once "qalabels.html"; ?>
		</script>

        <script type="text/tmpl" id="tmpl-firstAddQaLabels" >
			<? require_once "firstAddQaLabels.html"; ?>
		</script>

		<script type="text/tmpl" id="tmpl-modifyTitle" >
			<div class="pop-over" id="modifyTitle">
				<div class="header">
					<span class="header-title">修改看板名</span>
					<a class="headbtn_right close_popover"><i class="fa fa-close"></i></a>
				</div>
				<div class="popcontent">
					<input type="text" class="modifyTitle_text" placeholder="输入看板名"></input>
					<button class="button modifyTitle_btnsubmit" type="button" style=" margin: 4px 0 15px 0;">确定</button>
				</div>
			</div>
		</script>

        <script type="text/tmpl" id="tmpl-lists" >
			<div class="panel" data-id="<%=data['_id']%>" id="list_<%=data['_id']%>">
				<div class="tasktitle">
					<div class="tasklistcount"></div>
					<h2 class="tasktitle_cont"><%=data['title']%></h2>
					<a class="fa fa-bars list_menu" href="javascript:;;;"></a>
					<div class="setlisttile_editor_div" style="display:none ;">
	            		<textarea class="setlisttile_editor js-new-comment-input" data-bindbtn='.setlisttile_btnsubmit' placeholder="输入栏目标题" data-autosize-on="true" style=" word-wrap: break-word; height: 35px;width: 200px;"></textarea><button class="button setlisttile_btnsubmit" type="button" style=" float: right; margin-top: 4px;">确定</button>
	            	</div>

				</div>

				<div class="tasklist">
				</div>

				<div class="" style=" width:94%; clear: both; position:relative;; margin:0 3%;margin-top: 15px; display: ;">
					<a class="js-card-composer add_card_href" href="javascript:;">
						<i class="fa fa-plus"></i>添加卡片
					</a>

	            	<div class="class_addcard_div" style="display: none;">
	            		<textarea class="addcard_editor js-new-comment-input" data-bindbtn='.addcard_btnsubmit' placeholder="输入任务(Ctrl+Enter提交)" data-autosize-on="true" style="word-wrap: break-word; height: 35px;width: 200px;"></textarea><button class="button addcard_btnsubmit" type="button" style=" float: right; margin-top: 4px;">添加</button>
	            	</div>
            	</div>
			</div>
		</script>

		<script type="text/tmpl" id="tmpl-list-add" >
			<div class="panel" id="list_add_panel">
				<div class="tasktitle">
					<h2 class="tasktitle_cont"><i class="fa fa-plus"></i> 新增栏目</h2>
					<div class="setlisttile_editor_div" style="display:none ;">
	            		<textarea class="setlisttile_editor js-new-comment-input"  data-bindbtn='.setlisttile_btnsubmit' placeholder="输入标题(Ctrl+Enter提交)" data-autosize-on="true" style="word-wrap: break-word; height: 35px;width: 200px;"></textarea><button class="button setlisttile_btnsubmit" type="button" style=" float: right; margin-top: 4px;">确定</button>
	            	</div>

				</div>
				<div class="tasklist">
				</div>
			</div>
		</script>

        <script type="text/tmpl" id="tmpl-card" >
			<div class="card" class="card-corner-mark" data-id="<%=data['_id']%>" id="card_<%=data['_id']%>">
				<div><input type="checkbox" id="finishcheck_<%=data['_id']%>" class="finishcheck" style="vertical-align: top;"/> <span class="list_card_title"></span> <span class="commonts_num"></span></div>
				<!--<span class="badge-icon fa fa-comment-o badge-comment"> 4</span> -->
				<div class="badges">
					<div class="minicard-labels"></div>
				</div>
				<div class="minicard-members js-minicard-members"></div>
				<div style="clear:both"></div>
			</div>
		</script>


		<div id="wrap">
			<div id="main">
				<div id="centerpanel" style=" white-space:nowrap;">

				</div>
			</div>
		</div>

		<style>
		/*.panel{width:450px;}
		.list_card_title p, .list_card_title ol{max-width:380px}*/
		</style>


        <script>
		DATA = <?=json_encode($DATA)?>;
		// 不通看板的qalabel id不一样 名字可能相同
		// DATA.all_board_qalabel = {};
		D = {};
		D.qalabel_b64_name = {};
		D.qalabel_name_b64 = {};
		D.all_board_qalabel_id_name = {};

		// 根据qalabel分类的列表
		D.b64cardList = {
		    'noqalabel':[]
        };

		function initUserSelect() {
            $.ajax({
                url: './?app=api&apiact=get_timeline_users',
                dataType: 'json',
                data: {
                },
                success: function (data) {
					data.sort(function(a,b){
						return a.group.charCodeAt(0)-b.group.charCodeAt(0);
					});
                    //console.log('data',data);
                    var options = '';

					/*
                    var kaifagroup = ['服务端','客户端','技术支持','H5','H5组'];
                    data.forEach(function (v,i) {
                        if (kaifagroup.indexOf(v.group)!=-1){
                            options += `<option value='${v.id}'>${v.group}-${v.title}</option>`;
                        }
                    });
					*/
					data.forEach(function (v,i) {
                        options += `<option value='${v.id}'>${v.group}-${v.title}</option>`;
                    });

                    $('#user').append(options);
                    initSearchParm();

                }
            });

        }

		function initAllBoardQALabel() {
		    var name_set = new Set();
            for(var board in DATA.boards){
                if (DATA.boards[board] && DATA.boards[board].qalabels){
                    DATA.boards[board].qalabels.forEach(function (v,i) {
                        D.all_board_qalabel_id_name[board+ '_' + v._id] = v.name;
                        name_set.add(v.name)
                    })
                }
            }

            name_set.forEach(function (v,i) {
                // var b64name = window.btoa(unescape(encodeURIComponent(v)));
                var b64name = md5(v);
                D.qalabel_b64_name[b64name] = v;
                D.qalabel_name_b64[v] = b64name;

            })
        }


		function initSearchParm() {
		    // 浏览器url参数
		    var myURL = new URL(window.location.href);
            var searchParams = new URLSearchParams(myURL.search);
            user = searchParams.get('user');
            st = searchParams.get('st');
            et = searchParams.get('et');
            department = searchParams.get('department');
            time_type = searchParams.get('time_type');
            $('#user').val(user);
            $('#date').val(st + '~' + et);
            $('#department').val(department);
            $('#time_type').val(time_type);

        }

		function listInit(){
		    // qalabelIds 列表
			var lists = [];
            var qalabelid_list = [];

			// for(var listid in DATA.lists){
			// 	lists.push( DATA.lists[listid] );
			// }

            console.log('=====DATA.cards=====');
            console.log(DATA.cards);

            var labelNameSet = new Set();

            for(var card in DATA.cards){
                // 设置了qalabel
                if(DATA.cards[card].qalabelIds){
                    // allQaLabelSet.add(card.qalabelIds);
                    var board = DATA.cards[card].boardId;
                    DATA.cards[card].qalabelIds.forEach(function (v,i) {
                        // lists.push( v );

                        labName = D.all_board_qalabel_id_name[board+ '_' + v];
                        labelNameSet.add(labName);
                        b64 = D.qalabel_name_b64[labName];

                        if(D.b64cardList[b64]){
                            D.b64cardList[b64].push(DATA.cards[card]);
                        }else{
                            D.b64cardList[b64] = [DATA.cards[card]];
                        }
                    })
                }else{
                    D.b64cardList['noqalabel'].push(DATA.cards[card])
                }

            }


            console.log('====D.b64cardList====');
            console.log(D.b64cardList);

            console.log('====D.qalabel_b64_name====');
            console.log(D.qalabel_b64_name);

            console.log('====D.qalabel_name_b64====');
            console.log(D.qalabel_name_b64);



            labelNameSet.forEach(function (v,i) {
                b64 = D.qalabel_name_b64[v];
                lists.push({
                    _id: b64,
                    title: v,
                })
            });

            lists.push({
                _id:'noqalabel',
                title:"没有设置QA标签的",
            });

			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 list in lists){
			// 	freshList(list._id);
			// }
            // lists.forEach(function (v,i) {
            //     freshList(v._id);
            // });

            for (var b64 in D.b64cardList){
                freshList({
                    'b64':b64,
                    'cardlist':D.b64cardList[b64]
                });
            }

			$('.tasklist').height( $('#main').height() - 80 );
			$('#list_add_panel .tasklist').height( $('#main').height() - 0 );
		}

		function freshList(data){
			var cards = data.cardlist;
			var listid = data.b64;

			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);
                fmtIssueTagsByCardID(cards[i]._id);
				fmtMembersByCardID(cards[i]._id);
			}
			//console.log('freshList',listid,_over,_all)
			$('#list_'+ listid +' .tasklistcount').html(_over + '/' + _all);

			// if( (_all == 0 && filterList._lastFiler != 'null') || _all == _over ){  //所有单子都已完成的列表不显示
			// 	//有筛选条件，且当列1个卡片都没有，直接隐藏
			// 	$('#list_'+ listid).hide();
			// }else{
			// 	$('#list_'+ listid).show();
			// }

            $('#list_'+ listid).show();

		}

		$(function(){
		    var title = "人员看板";
            document.title = title;
            $('.projectheader h1').html(title);


            // initSearchParm();
            initUserSelect();

            initAllBoardQALabel();

            $('input[name="daterange"]').dateRangePicker({
                showShortcuts: false ,
                separator:"~",
                autoClose:true,
                format: 'YYYY-MM-DD HH:mm:ss',
                time: {
                    enabled: true
                },
                // ranges:{
                //     'Today':[moment(),moment()]
                // },
                //getValue: function(){
                //	return $('#'+_id).data('timestr');
                //},
                setValue: function(s){
                    console.log(s);
                    if ($('input[name="daterange"]').val() != s){
                        var arr = s.split('~');
                        st = arr[0];
                        et = arr[1];

                        // getQAChart2(myChart,st,et);


                        $('input[name="daterange"]').val(s);
                    }
                }
            });

            // $('input[name="daterange"]').val(d.data_range);

            $('#search').on('click',function (e) {
                var date = $('input[name="daterange"]').val();
                var arr = date.split('~');
                st = arr[0];
                et = arr[1];

                var department = $('#department').val();
                var user = $('#user').val();
                var time_type = $('#time_type').val();


                var url = '?app=usercard' + '&department=' + department + '&time_type=' + time_type +'&user=' + user + '&st=' + st + '&et=' + et;
                window.location.href = url;
            });






			listInit();

			//增加卡片链接
			$('.add_card_href').hide();
			//新增栏目
			$('#list_add_panel').hide();
			//list列表菜单按钮
			$('.list_menu').hide();

			$('body').on("click",".card",function(e){
				if(e.toElement && e.toElement.type == 'checkbox')return;
				showCard( $(this).data('id') );
			});

			//popover统一关闭逻辑
			$('body').on("click",".close_popover",function(e){
				$(this).parents('.pop-over').remove();
			});


			//title前的复选框
			$('body').on("click",".finishcheck",function(){
			    var that = $(this);
				var cardid = $(this).parents('.card').data('id');

                // if (isQA()){
                //     if (!isSetQALabel(cardid)){
                //         $(this).prop("checked",false);
                //         alert('请设置问题类型');
                //         return;
                //     }
                // }

                checkQA(function (isok) {
                    if (isok){
                        if (!isSetQALabel(cardid)){
                            that.prop("checked",false);
                            alert('请设置问题类型');
                            return;
                        }
                        var labels = DATA.cards[cardid].labelIds;
                        for(var i=0;i<labels.length;i++){
                            doSubmitSetLabel(cardid,labels[i]);
                        }

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

                        var _oldTitle = DATA.cards[cardid].title;
                        if(_oldTitle.indexOf('~~') == -1){
                            _oldTitle = '~~'+ _oldTitle + '~~';
                            doSubmitCommonts('我勾选了<font color=blue>[完成]</font>卡片',DATA.boardid,cardid);

                            if(window.MYINFO && DATA.cards[ cardid ].userId != window.MYINFO._id ){
                                //如果这个单子不是我创建的
                                var ownerInfo = DATA.users[DATA.cards[ cardid ].userId];
                                if(ownerInfo && ownerInfo.profile.fullname){
                                    var msgInfo = window.MYINFO.profile.fullname + "完成了任务["+ DATA.cards[ cardid  ].title+']';
                                    sendDDMSG(ownerInfo.profile.fullname,msgInfo,location.href,ownerInfo.dduserid);
                                }
                            }

                        }else{
                            _oldTitle = _oldTitle.replace(/~/g,'');
                        }
                        doSubmitTitle(_oldTitle, DATA.boardid, cardid,function(){});

                    }else {
                        //	检查卡片是否是qa创建的 qa自己创建的单子qa自己关
                        if(DATA.cards && DATA.cards[cardid] && DATA.cards[cardid].userId){
                            checkQA(function (isqa) {
                                if (isqa){
                                    that.prop("checked",false);
                                    alert('QA提交的单子让QA验收关闭');
                                    return;
                                }

                                var labels = DATA.cards[cardid].labelIds;
                                for(var i=0;i<labels.length;i++){
                                    doSubmitSetLabel(cardid,labels[i]);
                                }

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

                                var _oldTitle = DATA.cards[cardid].title;
                                if(_oldTitle.indexOf('~~') == -1){
                                    _oldTitle = '~~'+ _oldTitle + '~~';
                                    doSubmitCommonts('我勾选了<font color=blue>[完成]</font>卡片',DATA.boardid,cardid);

                                    if(window.MYINFO && DATA.cards[ cardid ].userId != window.MYINFO._id ){
                                        //如果这个单子不是我创建的
                                        var ownerInfo = DATA.users[DATA.cards[ cardid ].userId];
                                        if(ownerInfo && ownerInfo.profile.fullname){
                                            var msgInfo = window.MYINFO.profile.fullname + "完成了任务["+ DATA.cards[ cardid  ].title+']';
                                            sendDDMSG(ownerInfo.profile.fullname,msgInfo,location.href,ownerInfo.dduserid);
                                        }
                                    }

                                }else{
                                    _oldTitle = _oldTitle.replace(/~/g,'');
                                }
                                doSubmitTitle(_oldTitle, DATA.boardid, cardid,function(){});

                            },DATA.cards[cardid].userId)
                        }
                    }



                });

			});



			//textarea ctrl+Enter处理
			$('body').on('keydown','textarea,input',function(e){
				if(e.keyCode == 13 && e.ctrlKey ){
					var _select = $(this).data('bindbtn');
					$(this).parent().find(_select).click();
				}
			});

			//快捷键
			$('body').on('keydown',function(e){
				//console.log(e);
				//ALT+M
				if(e.keyCode == 77 && e.altKey ){
					if(filterList._lastFiler!='my'){
						filterList.my();
						$('#filterText').val('my');
					}else{
						filterList.null();
						$('#filterText').val('');
					}
				}
			});
		});
		</script>
	</body>
</html>


