<?php
require_once(ROOT."./inc/common.php");
require_once(ROOT.'./inc/filedb.php');
require_once(ROOT.'./inc/guide.php');

session_start();

// 乐谷work管理看板
$LEGUWORK_BOARDID = 'XNt2hy8Q89tEfmwC7';
// 设置的列表id 【设置】
$LEGUWORK_SETTING_LISTID = '5ce68ddfa5ebb';
$LEGUWORK_SETTING_LIST_NAME = '【设置】';

// 延期分组列表
$LEGUWORK_YANQI_LISTID = '5ce68e49bd298';
$LEGUWORK_YANQI_LIST_NAME = '【设置】延期分组';


$mongo = new MongoClient( $_CONFIG['mongo'] );
$wekan = $mongo->selectDB('wekan');



//获取看板列表
function getboards($userid=null,$archived=false){
	global $MYID,$wekan;
	if(isn($userid))$userid = $MYID;
	$docs = $wekan->boards->find(array('members.userId'=>$MYID,'archived'=>$archived));
	$res = iterator_to_array($docs);
	return $res;
}

function getboardsByAdmin($admin){
	global $MYID,$wekan;
	if($admin=='all'){
		$docs = $wekan->boards->find(array('archived'=>false));
	}else{
		$docs = $wekan->boards->find(array('org'=>$admin,'archived'=>false));
	}
	$res = iterator_to_array($docs);
	return $res;
}

function getorgs(){
	global $wekan;
	$docs = $wekan->users->find(array(),array('org'=>1,'orgname'=>1));
	$res = array();
	$rss = iterator_to_array($docs);
	foreach($rss as $rs){
		$res[ $rs['org'] ] = $rs['orgname'];
	}
	return $res;
}

function getcards($boardid,$lists=null){
	global $MYID,$wekan;
	
	if($lists==null){
		$docs = $wekan->cards->find(array('boardId'=>$boardid,'archived'=>false)); //'listId'=>$listid,
	}else{
		$docs = $wekan->cards->find(array('boardId'=>$boardid,'listId'=>array('$in'=>$lists),'archived'=>false));
	}
	$res = iterator_to_array($docs);
	return $res;
}


function getmycards(){
    global $MYID,$wekan;
    $docs = $wekan->cards->find(array('members'=>$MYID,'archived'=>false)); //'listId'=>array('$in'=>$lists),
    $res = iterator_to_array($docs);
    return $res;
}

function getUserCards($uid, $st = null, $et = null)
{
    global $MYID, $wekan;

    $mongostart = new MongoDate(strtotime($st));
//    $mongostart = new MongoDate(1546272000);

    $mongoend = new MongoDate(strtotime($et));
//    $mongoend = new MongoDate(1548950400);


    $docs = $wekan->cards->find(array(
            'members' => $uid,
//            "createdAt" => array('$gte' => $mongostart)
//            "createdAt" => array('$gte' => $mongostart, '$lte' => $mongoend)
            "mem_time.{$uid}.start" => array('$gte' => strtotime($st)),
            "mem_time.{$uid}.end" => array('$lte' => strtotime($et))
        )
    ); //'listId'=>array('$in'=>$lists),
    $res = iterator_to_array($docs);
    return $res;
}

// 某个用户完成的单子
function getUserCards4Finish($uid, $st = null, $et = null)
{
    global $MYID, $wekan;

    $mongostart = new MongoDate(strtotime($st));
//    $mongostart = new MongoDate(1546272000);

    $mongoend = new MongoDate(strtotime($et));
//    $mongoend = new MongoDate(1548950400);


    $docs = $wekan->cards->find(array(
            'members' => $uid,
			'$or'=>array(
				array(
					//'qalabelIds'=>'gongnengyanfa',
					"mem_time.{$uid}.start" => array('$gte' => strtotime($st)),
					"mem_time.{$uid}.end" => array('$lte' => strtotime($et))
				),
				array(
					//'qalabelIds'=>array('$ne'=>'gongnengyanfa'),
					"finishAt" => array('$gte' => strtotime($st),'$lte' => strtotime($et)),
				),
			),
//            "createdAt" => array('$gte' => $mongostart)
//            "createdAt" => array('$gte' => $mongostart, '$lte' => $mongoend)
        )
    ); //'listId'=>array('$in'=>$lists),
    $res = iterator_to_array($docs);
	
	$arr = array();
	foreach($res as $id=>$val){
		$qalabelIds = array();
		if($val['qalabelIds']){
			$qalabelIds = $val['qalabelIds'];
		}
		if( in_array('gongnengyanfa',$qalabelIds) ){
			//功能研发单，则判断标记时间
			if( $val['mem_time'][$uid] && $val['mem_time'][$uid]['start']>=strtotime($st) &&  $val['mem_time'][$uid]['end']<=strtotime($et) ){
				
			}else{
				continue;
			}
		}
		$arr[$id] = $val;
	}
    return $arr;
}

function getUserCards4New($uid, $st = null, $et = null)
{
    global $MYID, $wekan;

    $mongostart = new MongoDate(strtotime($st));
    $mongoend = new MongoDate(strtotime($et));

    $docs = $wekan->cards->find(array(
            'members' => $uid,
			"createdAt" => array('$gte' => ($mongostart),'$lte' => ($mongoend))
    )); 
    $res = iterator_to_array($docs);
    return $res;
}


function getcard($cardid){
	global $MYID,$wekan;
//	$docs = $wekan->cards->find(array('_id'=>$cardid,'archived'=>false)); //'listId'=>$listid,
	$docs = $wekan->cards->find(array('_id'=>$cardid)); //'listId'=>$listid,
	$res = iterator_to_array($docs);
	return $res;
}


function getboardsettingcard($boardid,$cardtitle){
    global $MYID,$wekan;
    $cardtitle = "__setting.".$cardtitle;
    $docs = $wekan->cards->find(array('boardId'=>$boardid,'title'=>$cardtitle,'archived'=>false)); //'listId'=>$listid,
    $res = iterator_to_array($docs);

    return $res;
}

function getlists($boardid){
	global $MYID,$wekan;
	$docs = $wekan->lists->find(array('boardId'=>$boardid,'archived'=>false));
	$res = iterator_to_array($docs);
	return $res;
}
function getlist($listid){
	global $MYID,$wekan;
	$docs = $wekan->lists->find(array('_id'=>$listid));
	$res = iterator_to_array($docs);
	return $res;
}

function getBoard($boardid){
	global $MYID,$wekan;
	$docs = $wekan->boards->find(array('_id'=>$boardid));
	$res = iterator_to_array($docs);
	return $res;
}

function getusers(){
	global $MYID,$wekan;
	if(isn($userid))$userid = $MYID;
    $docs = $wekan->users->find(array(), array(
        'username' => true,
        'emails' => true,
		'org'=>true,
		'orgname'=>true,
		'dduserid'=>true,
        'profile.fullname' => true,
        'profile.avatarUrl' => true,
        'legulabel'=>true,
        'legugroup'=>true,
        'lastlogin'=>true,
    ));
	$res = iterator_to_array($docs);
	return $res;	
}

function getUserInfo($userid){
	global $MYID,$wekan;
	$docs = $wekan->users->find(array("_id"=>$userid));
	$res = iterator_to_array($docs);
	return $res[$userid];
}

function getcard_comments($cardid){
	global $MYID,$wekan;
	$docs = $wekan->card_comments->find(array('cardId'=>$cardid))->sort(array('createdAt'=>-1));
	$res = iterator_to_array($docs);
	return $res;
}


function initLables(){
	$labels = array(
        array(
            "color" =>"legublue",
            "name" =>"策"
        ),
        array(
            "color" =>"legublue",
            "name" =>"策配"
        ),
        array(
            "color" =>"legublue",
            "name" =>"策验"
        ),
		array(
            "color" =>"legublue",
            "name" =>"审UI"
        ),
        array(
            "color" =>"legured",
            "name" =>"前程"
        ),
        array(
            "color" =>"legured",
            "name" =>"后程"
        ),
        array(
            "color" =>"legupurple",
            "name" =>"UI"
        ),
        array(
            "color" =>"legupurple",
            "name" =>"UI验"
        ),
        array(
            "color" =>"leguyellow",
            "name" =>"美"
        ),
		array(
			"color" =>"legugreen",
			"name" =>"美验"
		),
		array(
			"color" =>"legublue",
			"name" =>"动效"
		),
		array(
			"color" =>"legured",
			"name" =>"动验"
		),
		array(
			"color" =>"legupink",
			"name" =>"QA"
		),
		array(
			"color" =>"legugray",
			"name" =>"运营"
		),
        array(
            "color" =>"legugray",
            "name" =>"打包"
        )
	);
	
	
	foreach($labels as $idx => $label){
		$labels[$idx]['_id'] = uniqid().$idx;
	}

	//return $labels;
	return array();
}

function getAllRiskLabels(){
    global $MYID,$wekan;
    $docs = $wekan->risktags->find(array(), array(
        '_id' => false,
        'issueId' => true,
        'tagId' => true,
        'tag' => true,
        'reasonTag' => true,
        'color' => true,
        'description' => true,
        'reason'=>true,
        'department'=>true,
        'issueColor'=>issueColor
    ));

    $labels = iterator_to_array($docs);

    $res = array();
    foreach($labels as $val){
        $res[ $val['tagId'] ][] = $val;
    }

    return $res;
}

function getRiskLabels(){
    global $MYID,$wekan;
    $labels = $wekan->command (
            array(
                "aggregate" => "risktags",
                "pipeline" =>
                    array(
                        array( '$group' => array( "_id" => ['_id' =>'$tagId', 'name' => '$tag', 'color' => '$color'])),
                        array( '$replaceRoot' => array( "newRoot" => '$_id' ))
                    ),
                "cursor" => ['batchSize' => 200]
            )
    );
    $res = array();

    foreach($labels['cursor']['firstBatch'] as $val){
        $res[ $val['_id'] ] = $val;
    }
    return $res;
}

function initQALables(){
    $labels = array(
        array(
            "_id"=>"bug",
            "color" =>"legured",
            "name" =>"BUG"
        ),
        array(
            "_id"=>"ziyuanqueshi",
            "color" =>"leguyellow",
            "name" =>"资源缺失"
        ),
        array(
            "_id"=>"geleiyouhua",
            "color" =>"legublue",
            "name" =>"各类优化"
        ),
        array(
            "_id"=>"gongnengyanfa",
            "color" =>"leguaqua",
            "name" =>"功能研发"
        ),
        array(
            "_id"=>"xingnengyouhua",
            "color" =>"legupurple",
            "name" =>"性能问题"
        ),
        array(
            "_id"=>"qita",
            "color" =>"legugray",
            "name" =>"其他"
        ),

    );


//    foreach($labels as $idx => $label){
//        $labels[$idx]['_id'] = uniqid().$idx;
//    }

    //return $labels;
	return array();
}

function eventData($act,$data){
	return json_encode(array(
		"_k"=>"EVENT",
		"act"=>$act,
		"data" => $data,
	));
}

// 根据boardId获取看板的标签的名字数组 _id=>name
function getBoardLabelIdNames($boardId){
    global $wekan;
    $resBoards =  $wekan->boards->find(array(
        "archived" => false,
        "_id" => $boardId,
    ));
    $boardData = iterator_to_array($resBoards);
    $board = $boardData[$boardId];
    $boardLabels = $board['labels'];
    $boardLabelArr = array();
    foreach ($boardLabels as $label){
        $boardLabelArr[$label['_id']] = $label['name'];
    }
    return $boardLabelArr;
}

// 获取延期列表数据 部门对应用户
// 5ce68e49bd298
function getYanQiDepartmentUser(){
    global $MYID,$wekan,$LEGUWORK_SETTING_LISTID,$LEGUWORK_BOARDID,$LEGUWORK_YANQI_LISTID;

    $cardData = $wekan->cards->find(array('archived'=>false,'boardId'=>$LEGUWORK_BOARDID,'listId'=>$LEGUWORK_YANQI_LISTID));
    $cardData = iterator_to_array($cardData);

    $boardData =  $wekan->boards->findOne(array(
        "_id" => $LEGUWORK_BOARDID,
    ));

    $boardLabels = $boardData['labels'];
    $labelNameIdArr = array();
    $labelIdNameArr = array();
    foreach ($boardLabels as $k => $v) {
        $labelNameIdArr[$v['name']] = $v['_id'];
        $labelIdNameArr[$v['_id']] = $v['name'];
    }

    $labelUserArr = array();
    $labelIdUserArr = array();
    foreach ($cardData as $k => $v) {
        // 延期成员在的部门
        $labelIds = $v['labelIds'];
        $members = $v['members'];

//        var_dump($members);

        foreach ($labelIds as $labelID) {
            $labelIdUserArr[$labelID] = array(
                'name'=>$labelIdNameArr[$labelID],
                'user'=>$members
            );
        }
    }

    return $labelIdUserArr;

}



$MYID = $_SESSION['leguworkUID']; //;// 'NNCQpGcDX9L2EexLQ';//
$LEGUWORKUSER = $_SESSION['leguworkUser'];
$DTALK_APPID = "";
if($LEGUWORKUSER){
	$DTALK_APPID = $LEGUWORKUSER['appid'];
}
?>