<?php
$act = r('apiact');

function boards($onlyreturn=false){
	global $MYID;
	$orgid = r('orgid');
	$userinfo = getUserInfo($MYID);

	if($userinfo['extData'] && $userinfo['extData']['admin']){
		$admin = $userinfo['extData']['admin'];
		if($admin=='all' && !isn($orgid)){
			$admin = $orgid;
		}
		$data = getboardsByAdmin($admin);
	}else{
		$data = getboards();
		//echo json_encode( getboardsByAdmin($userinfo['org']) );
	}

	if($onlyreturn){
		return $data;
	}else{
		echo json_encode($data);
	}
}

function getcardinfo(){
	$cardid = r('cardid');
	$card = getcard( $cardid );	
	echo json_encode( $card );
}

function getsettingcardinfo(){
    $boardid = r('boardid');
    $cardtitle = r('cardtitle');
    $card = getboardsettingcard($boardid, $cardtitle );
    echo json_encode( $card );
}

function card_comments(){
	$cardid = r('cardid');
	$comments = getcard_comments( $cardid );
	echo json_encode( $comments );
}

function get_checklists(){
	global $MYID,$wekan;
	$cardid = r('cardid');
	$docs = $wekan->checklistItems->find(array('cardId'=>$cardid))->sort(array('sort'=>-1));
	$res = iterator_to_array($docs);
	echo json_encode( $res );
}

function get_risktags(){
    global $MYID,$wekan;
    $cardid = r('cardid');
    $risklabels = getRiskLabels($cardid);
    echo json_encode( $risklabels );
}

function get_allrisktags(){
    $risklabels = getAllRiskLabels();
    echo json_encode( $risklabels );
}	

function ipuser(){
	global $MYID,$wekan;
	$ip = r('ip');
	$docs = $wekan->usersip->find(array('ip'=>$ip));
	$res = iterator_to_array($docs);
	
	if(count($res)==0){
		we("null");
	}else{
		$info = array_values($res)[0];
		unset($info['_id']);
		we(json_encode($info));
	}
}

//新增检查项
function add_card_checklist(){
	global $MYID,$wekan;
	if(isn($MYID))needLogin();

	$cardid = r('cardid');
	$text = r('text');
	$sort = r('sort');
	if(isn($sort))$sort=0;
	
	$_id = uniqid();
	$data = array(
	    "_id" => $_id,
	    "title" => $text,
	    "sort" => $sort*1 ,
	    "isFinished" => false,
	    "checklistId" => "none",
	    "cardId" => $cardid,
	    'userId' => $MYID,
	    "createdAt" => new MongoDate(time()),
	);
	$res = $wekan->checklistItems->insert( $data );
	we (eventData('addchecklist',$data));
}

//设置完成状态
function set_checklist_finish(){
	global $MYID,$wekan;
	$id = r('id');
	$val = r('val');
	
	if($val=='true'){
		$v = true;
	}else{
		$v = false;
	}
	
	$res = $wekan->checklistItems->update(array(
		'_id' => $id
	),array(
		'$set'=>array(
			'isFinished' => $v
		)
	));
	
	$docs = $wekan->checklistItems->find(array('_id'=>$id));
	$res = iterator_to_array($docs);
	we (eventData('setchecklistfinish',$res[$id]));
}

function del_checklist(){
	global $MYID,$wekan;
	$id = r('id');
	
	$docs = $wekan->checklistItems->find(array('_id'=>$id));
	$r = iterator_to_array($docs);
	
	$res = $wekan->checklistItems->remove(array(
		'_id' => $id
	));
	
	we (eventData('delchecklist',$r[$id]));
}

function quit_board(){
	global $MYID,$wekan;
	$boardid = r('boardid');
	$wekan->boards->update(array(
        '_id'=>$boardid,
		'members.userId'=>$MYID
    ),array(
        '$pull'=>array('members'=>array('userId'=>$MYID))
    ));
	we($MYID);
}


function ping(){
    global $MYID,$wekan;
    $t = time();
    $wekan->users->update(array(
        '_id'=>$MYID
    ),array(
        '$set'=>array('lastlogin'=>$t)
    ));
	we($MYID.'@'.$t);
}

function needLogin(){
	we('{}');
}

//提交评论
function add_card_comments($cardid=null,$boardid=null,$text=null,$continue=false){
	global $MYID,$wekan;
	if(isn($MYID))needLogin();

	if(!$cardid)$cardid = r('cardid');
	if(!$boardid)$boardid = r('boardid');
	if(!$text)$text = r('text');
	
	$_id = uniqid();
	$data = array(
	    "_id" => $_id,
	    "text" => $text,
	    "boardId" => $boardid ,
	    "cardId" => $cardid,
	    "createdAt" => new MongoDate(time()),
	    "userId" => $MYID
	);
	$res = $wekan->card_comments->insert( $data );
	if(!$continue)we (eventData('addcomment',$data));
}

//文档被修改了
function doc_has_changed(){
	global $MYID,$wekan;
	$MYID = "system";

	$url = r('docurl');
	$doc = r('docname');

	$query=array("description"=>new MongoRegex("/.*".$url.".*/i"));
	$query2=array("description"=>new MongoRegex("/.*".urlencode($doc).".*/i"));
	
	
	$res = $wekan->cards->find(array('$or'=>array(
		$query,
		$query2
	)));
	
	foreach($res as $rs){
		add_card_comments( $rs['_id'], $rs['boardId'], "文档<font color=red>[更新]</font>了：{$doc}",true );

		$members = $rs['members'];
		
		$names = array();
		$meminfos = $wekan->users->find( array(
			"_id" => array('$in'=>$members)
		));
		foreach($meminfos as $_mid=>$meminfo){
			if( $meminfo['profile']['fullname'] ){
				$names[] = $meminfo['profile']['fullname'];
			}
		}
		

		if(count($names)>0){
			getHttpPage('http://10.0.0.5/senddmsg/index.php',array(
				'agentid'=>'164310138',
				'content'=>"【{$rs['title']}】附带的文档更新了",
				'name'=>implode(',',$names),
				'url'=>"http://10.0.0.5/leguwork/?app=list&boardid={$rs['boardId']}#cardid={$rs['_id']}"
			));
		}
	}
	we('ok');
}

//设置描述
function set_card_description(){
	
	global $MYID,$wekan;
	$cardid = r('cardid');
	$boardid = r('boardid');
	$text = r('text');
	
	$res = $wekan->cards->update(array(
		'_id' => $cardid
	),array(
		'$set'=>array(
			'description' => $text
		)
	));
	
	$ndata = getcard($cardid);
	we (eventData('setdescription',$ndata[$cardid]));
}

//设置标题
function set_card_title(){
	
	global $MYID,$wekan;
	$cardid = r('cardid');
	$boardid = r('boardid');
	$text = r('text');
	$uid = r('uid');
	
	$updateArr = array(
		'title' => $text
	);
	if(indexOf($text,'~~')==-1){
		$updateArr['finishAt'] = 0;
		$updateArr['finishUid'] = '';
	}else{
		$updateArr['finishAt'] = time();
		$updateArr['finishUid'] = $uid;
	}
	
	$res = $wekan->cards->update(array(
		'_id' => $cardid
	),array(
		'$set'=>$updateArr
	));
	
	$ndata = getcard($cardid);
	we (eventData('settitle',$ndata[$cardid]));
}

//增加卡片
function add_card(){
	global $MYID,$wekan;
	if(isn($MYID))needLogin();
	$listid = r('listid');
	$boardid = r('boardid');
	$text = r('text');
	$desc = r('description');

	$_id = uniqid();
	$data = array(
	    "_id" => $_id,
	    "title" => $text,
	    "members" => array($MYID),
	    "boardId" => $boardid ,
    	"labelIds" => array(),
        "risklabelIds" => array(),
    	"listId" => $listid,
    	"boardId" => $boardid,
    	"sort" => time(),
    	//"swimlaneId" : "JKaEWmCWHhLigJk3Z",
    	"archived" => false,
    	"createdAt" => new MongoDate(time()),
    	"dateLastActivity" => new MongoDate(time()),
    	"isOvertime" => false,
	    "userId" => $MYID
	);

	if (isset($desc)){
	    $data['description'] = $desc;
    }
	
	$res = $wekan->cards->insert( $data );
	we (eventData('addcard',$data));
}


// 删除卡片
function del_card(){
    global $MYID,$wekan;
    if(isn($MYID))needLogin();

    $cid = r('cardid');
//    $boardid = r('boardid');
//    $text = r('text');
//    $desc = r('description');


    $cardData = $wekan->cards->findOne(array('_id'=>$cid));

    if(!$cardData){
        we('{"msg":"id错误"}');
    }


    if($MYID != $cardData['userId']){
        we('{"msg":"不能删除"}');
    }

    $res = $wekan->cards->remove( array('_id'=>$cid) );
//    we('{"msg":"ok"}');
    we (eventData('delcard',$cardData));
//    we (eventData('addcard',$data));
}


function add_card2(){
    global $MYID,$wekan;
    if(isn($MYID))needLogin();
    $listid = r('listid');
    $boardid = r('boardid');
    $text = r('text');
    $desc = r('description');

    $_id = uniqid();
    $data = array(
        "_id" => $_id,
        "title" => $text,
        "members" => array($MYID),
        "boardId" => $boardid ,
        "labelIds" => array(),
        "risklabelIds" => array(),
        "listId" => $listid,
//        "_type" => 'task',         // todo 卡片类型 ci task date
        "_status" => 'unfinished',         // 卡片状态 unfinished 未完成卡片
        "sort" => time(),
        //"swimlaneId" : "JKaEWmCWHhLigJk3Z",
        "archived" => false,
        "createdAt" => new MongoDate(time()),
        "dateLastActivity" => new MongoDate(time()),
        "isOvertime" => false,
        "userId" => $MYID
    );

    if (isset($desc)){
        $data['description'] = $desc;
    }

    $res = $wekan->cards->insert( $data );
    we (eventData('addcard',$data));
}

//设置卡片状态
function set_card_status(){

    global $MYID,$wekan;
    $cardid = r('cardid');
    $boardid = r('boardid');
//    $text = r('text');
    $uid = r('uid');

    $updateArr = array(
//        '_type' => '',
        '_status' => 'show'
    );

    $res = $wekan->cards->update(array(
        '_id' => $cardid
    ),array(
        '$set'=>$updateArr
    ));

    $ndata = getcard($cardid);
    we (eventData('addcard',$ndata));
}


//设置列表标题
function set_list_title(){
	
	global $MYID,$wekan;
	$listid = r('listid');
	$boardid = r('boardid');
	$text = r('text');
	
	$res = $wekan->lists->update(array(
		'_id' => $listid
	),array(
		'$set'=>array(
			'title' => $text
		)
	));
	$ndata = getlist($listid);
	we (eventData('setlisttitle',$ndata[$listid]));
}

//增加列表
function add_list(){
	
	global $MYID,$wekan;
	$boardid = r('boardid');
	$text = r('text');
	
	$_id = uniqid();
	$data = array(
		"_id" => $_id,
	    "title" => $text,
	    "boardId" => $boardid,
	    "sort" => 0,
	    "archived" => false,
	    "createdAt" => new MongoDate(time()),
	    "updatedAt" => new MongoDate(time())
	);
	$res = $wekan->lists->insert( $data );
	we (eventData('addlist',$data));
}

function newcalendar(){
	global $MYID,$wekan;
	$userinfo = getUserInfo($MYID);

	$_id = uniqid();

	$data = array(
		"_id" => $_id,
	    "title" => r('title'),
		"start" => r('start'),
		"end" => r('end'),
		"org" => $userinfo['org'],
		"orgname" => $userinfo['orgname'],
	);
	$res = $wekan->events->insert( $data );
	we('1');
	//we (eventData('addlist',$data));
}

function modipmcalendar(){
	global $MYID,$wekan;
	$wekan->events->update(array(
		'_id'=>r('id'),
	),array(
		'$set'=>array(
			'title'=>r('title')
		)
	));
	we('1');
}

function movepmcalendar(){
	global $MYID,$wekan;
	$wekan->events->update(array(
		'_id'=>r('id'),
	),array(
		'$set'=>array(
			'start'=>r('start'),
			'end'=>r('start')
		)
	));
	we('1');
}

function delpmcalendar(){
	global $MYID,$wekan;
	$wekan->events->remove(array(
		'_id'=>r('id'),
	));
	we('1');
}

function getEvents(){
	global $MYID,$wekan;
	$userinfo = getUserInfo($MYID);
	$orgid = r('orgid');
	
	if(isn($orgid)){
		$orgid = $userinfo['org'];
	}
	/*
	$admin = $userinfo['org'];
	if($userinfo['extData'] && $userinfo['extData']['admin']){
		$admin = $userinfo['extData']['admin'];
		if($admin=='all' && !isn($orgid)){
			$admin = $orgid;
		}
	}
	*/

	$start = r('start');
	$end = r('end');

	$docs = $wekan->events->find(array('org'=>$orgid));
	$rss = iterator_to_array($docs);
	
	$res = array();

	foreach($rss as $rs){
		$rs['allDay'] = true;
		$res[] = $rs;
	}
	
	we(json_encode($res));
}

//设置成员
function set_member(){
	
	global $MYID,$wekan;
	$cardid = r('cardid');
	$memberid = r('memberid');
	$boardid = r('boardid');
	
	$data = getcard($cardid);
	$data = $data[$cardid];

    // 不在里面添加
	if(!in_array($memberid,$data['members'])){
		$wekan->cards->update(array(
			'_id'=>$cardid
		),array(
			'$push' => array('members'=>$memberid)
		));
		
		
		$boardHasMember = $wekan->boards->find( array(
			"_id" => $boardid,
			"members.userId" =>$memberid
		));
		if (count( iterator_to_array($boardHasMember) ) == 0){
			//看板里没有这个用户，则自动增加
			$wekan->boards->update(array(
				'_id'=>$boardid
			),array(
				'$push' => array('members'=>array(
					"userId" => $memberid,
		            "isAdmin" => false,
		            "isActive" => true,
		            "isCommentOnly" => false
				))
			));
		}
	}else{
	    // 在里面删掉
		$mem_time = $data['mem_time'];
		if(!$mem_time)$mem_time=array();
		unset( $mem_time[$memberid] );

		$wekan->cards->update(array(
			'_id'=>$cardid
		),array(
			'$pull' => array('members'=>$memberid),
			'$set' => array('mem_time'=>$mem_time)
		));

		// 特定列的标签 延期分组
        if ($data['listId'] == '5ce68e49bd298'){
            $cardLabelIdArr = $data['labelIds'];
            $labelNameArr = array();
            $boardLabelIdNameArr = getBoardLabelIdNames($data['boardId']);
            foreach ($cardLabelIdArr as $labelId){
                if (array_key_exists($labelId,$boardLabelIdNameArr)){
                    $labelNameArr[] = $boardLabelIdNameArr[$labelId];
                }
            }

            // 删掉对应用户的标签
            $wekan->users->update(array(
                '_id'=>$memberid
            ),array(
                '$pullAll' => array('legulabel'=>$labelNameArr)
            ));
        }

        // 特定列表 日程分组
        if ($data['listId'] == '5ce7a226c387f'){
            $wekan->users->update(array(
                '_id'=>$memberid,
            ),array(
                '$set'=>array('legugroup'=>'')
            ),array("multiple" => true));

        }

	}

	$data = getcard($cardid);

    // 刷新分组
    setYanQiLabelUserForCard($cardid);
    setRiChengLabelUserForCard($cardid);

	we (eventData('memberchange',$data[$cardid]));
}


//设置延期成员 - 舒展专用
function remove_yq_member(){

    global $MYID,$wekan;
    $cardid = r('cardid');
    $memberid = r('memberid');
    $boardid = r('boardid');

    $data = getcard($cardid);
    $data = $data[$cardid];
    $unsetKey = 'mem_time.'.$memberid.'.isyanqi';
    $wekan->cards->update(array(
        '_id'=>$cardid
    ),array(
        '$unset' => array($unsetKey=>1)
    ));


    $data = getcard($cardid);

    we (eventData('memberchange',$data[$cardid]));
}



//设置标签
function set_label(){
	
	global $MYID,$wekan;
	$cardid = r('cardid');
	$labelid = r('labelid');
	$timeto = r('timeto');
	
	$data = getcard($cardid);
	$data = $data[$cardid];
	$labels_time = $data['labels_time'];
	if(!$labels_time)$labels_time=array();
	
	if(!in_array($labelid,$data['labelIds'])){
		$wekan->cards->update(array(
			'_id'=>$cardid
		),array(
			'$push' => array('labelIds'=>$labelid)
		));
		
		if($timeto!=""){
			$labels_time[$labelid] = array('need'=>strtotime($timeto));
		}else{
			unset($labels_time[$labelid]);
		}
		
		$wekan->cards->update(array(
			'_id'=>$cardid
		),array(
			'$set' => array('labels_time'=>$labels_time)
		),array(
			'upsert'=>true
		));
		
	}else{
		$wekan->cards->update(array(
			'_id'=>$cardid
		),array(
			'$pull' => array('labelIds'=>$labelid)
		));
		
		if(!$labels_time[$labelid])$labels_time[$labelid]=array();
		$labels_time[$labelid]['finishtime'] = time();
		$labels_time[$labelid]['uid'] = $MYID;

		$wekan->cards->update(array(
			'_id'=>$cardid
		),array(
			'$set' => array('labels_time'=>$labels_time)
		),array(
			'upsert'=>true
		));


        // 特定列的标签 延期分组
        if ($data['listId'] == '5ce68e49bd298'){
            $labelNameArr = array();
            $boardLabelIdNameArr = getBoardLabelIdNames($data['boardId']);

            if (array_key_exists($labelid,$boardLabelIdNameArr)){
                $labelNameArr[] = $boardLabelIdNameArr[$labelid];
            }

            // 删掉对应用户的标签
            $wekan->users->update(array(
                '_id'=>array('$in'=>$data['members'])
            ),array(
                '$pullAll' => array('legulabel'=>$labelNameArr)
            ),array(
                "multiple" => true
            ));
        }



	}
	$data = getcard($cardid);

	// 刷新分组
    setYanQiLabelUserForCard($cardid);

	we (eventData('labelchange',$data[$cardid]));
}

//设置风险提示标签
function set_risklabel(){

    global $MYID,$wekan;
    // if(isn($MYID))needLogin();

    $cardid = r('cardid');
    $labelid = r('labelid');
    $timeto = r('timeto');

    $data = getcard($cardid);
    $data = $data[$cardid];
    $labels_time = $data['risklabels_time'];

    $num = count($data['risklabelIds']);

    if(!$labels_time)$labels_time=array();

    if(!in_array($labelid,$data['risklabelIds']) && $num<2){
        $wekan->cards->update(array(
            '_id'=>$cardid
        ),array(
            '$push' => array('risklabelIds'=>$labelid)
        ));

        if($timeto!=""){
            $labels_time[$labelid] = array('need'=>strtotime($timeto));
        }else{
            unset($labels_time[$labelid]);
        }

        $wekan->cards->update(array(
            '_id'=>$cardid
        ),array(
            '$set' => array('risklabels_time'=>$labels_time)
        ),array(
            'upsert'=>true
        ));

    }else{
        $wekan->cards->update(array(
            '_id'=>$cardid
        ),array(
            '$pull' => array('risklabelIds'=>$labelid)
        ));

        if(!$labels_time[$labelid])$labels_time[$labelid]=array();
        $labels_time[$labelid]['finishtime'] = time();

        $wekan->cards->update(array(
            '_id'=>$cardid
        ),array(
            '$set' => array('risklabels_time'=>$labels_time)
        ),array(
            'upsert'=>true
        ));
    }

    $data = getcard($cardid);

    // 刷新分组
    setYanQiLabelUserForCard($cardid);
    we (eventData('labelchange',$data[$cardid]));
}

//修改风险标签
function modify_risklabel(){
    global $MYID,$wekan;
    $boardid = r('boardid');
    $labelid = r('labelid');
    $labelname = r('labelname');
    $labelcolor = r('labelcolor');

    if(isn($labelid)){
        $_id = uniqid();
        $data = array(
            "_id" => $labelid,
            "color" => $labelcolor,
            "name" => $labelname
        );

        $res = $wekan->boards->update(array(
            '_id'=>$boardid
        ),array(
            '$push' => array('risklabels'=>$data)
        ));
    }else{
        $res = $wekan->boards->update(array(
            '_id'=>$boardid,
            'risklabels._id' => $labelid
        ),array(
            '$set' => array(
                'risklabels.$.color'=>$labelcolor,
                'risklabels.$.name'=>$labelname
            )
        ));
    }

    $data = getBoard($boardid);
    we (eventData('modifylabel',$data[$boardid]));
}

// 删掉风险标签
function del_risklabel(){
    global $MYID,$wekan;
    $boardid = r('boardid');
    $labelid = r('labelid');
    $labelname = r('labelname');
    $labelcolor = r('labelcolor');


    $res = $wekan->boards->update(array(
        '_id'=>$boardid,
        'risklabels._id' => $labelid
    ),array(
        '$pull' => array(
            'risklabels'=>array('_id'=>$labelid),
        )
    ));


    $data = getBoard($boardid);
    we (eventData('modifylabel',$data[$boardid]));
}


//设置角色完成时间
function set_mem_time(){
	
	global $MYID,$wekan;
	$cardid = r('cardid');
	$memid = r('memid');
	$times = r('times');
	$timee = r('timee');

	$data = getcard($cardid);
	$data = $data[$cardid];
	$mem_time = $data['mem_time'];
	if(!$mem_time)$mem_time=array();
	
	if(isn($times) && isn($timee)){
		unset($mem_time[$memid]);
	}else{
		$mem_time[$memid]['start'] = strtotime($times);
		$mem_time[$memid]['end'] = strtotime($timee);
		$mem_time[$memid]['timestr'] = $times.'~'.$timee;
	}
	$wekan->cards->update(array(
		'_id'=>$cardid
	),array(
		'$set' => array('mem_time'=>$mem_time)
	),array(
		'upsert'=>true
	));

	$data = getcard($cardid);
	we (eventData('memtimechange',$data[$cardid]));
}

function get_mem_time(){
	global $MYID,$wekan;
	$who = r('who');
	$start = r('start');
	$end = r('end');

	$where = array(
		'$or'=>array(
			array(
				'$and'=> array(
					array(
						"mem_time.{$MYID}.start" => array('$gte'=>$start*1)
					),
					array(
						"mem_time.{$MYID}.start" => array('$lte'=>$end*1)
					)
				),
			),
			array(
				'$and'=> array(
					array(
						"mem_time.{$MYID}.end" => array('$gte'=>$start*1)
					),
					array(
						"mem_time.{$MYID}.end" => array('$lte'=>$end*1)
					)
				),
			)
		)
		
	);
	$docs = $wekan->cards->find($where); //'listId'=>$listid,
	$rss = iterator_to_array($docs);
	
	$boards = getboards();
	
	$res = array();
	foreach($rss as $rs){
		$res[] = array(
			'title'=>$rs['title'],
			'allDay'=>true,
			'start'=> date('Y-m-d', $rs['mem_time'][ $MYID ]['start'] ),
			'end'=> date('Y-m-d', $rs['mem_time'][ $MYID ]['end'] ),
			'boardid'=>$rs['boardId'],
			'boardtitle'=>$boards[ $rs['boardId'] ]['title'],
			'url'=>"./?app=list&boardid={$rs['boardId']}#cardid={$rs['_id']}"
		);
	}
	
	we(json_encode(array(
		'calendarData'=>$res	
	)));
}

function get_timeline_users(){
	global $MYID,$wekan;
	$ts = time()-7*24*3600;
	
	$userinfo = getUserInfo($MYID);
	$where = array('lastlogin'=>array('$gt'=>$ts ),'org'=>$userinfo['org']);
	
	if($userinfo['extData'] && $userinfo['extData']['admin']=='all'){
		unset($where['org']);
	}

	$docs = $wekan->users->find($where); //'listId'=>$listid,
//	$docs = $wekan->users->find(array('legustatus'=>1,'lastlogin'=>array('$gt'=>time() - 7*24*3600 ))); //'listId'=>$listid,
//	$docs = $wekan->users->find(array('legustatus'=>1)); //'listId'=>$listid,
	$rss = iterator_to_array($docs);
	$res = array();

	foreach($rss as $rs){
//		$group = $rs['group'];
		$group = $rs['orgname'];
		if(isn($group))$group="其他";
		$res[] = array(
			'id'=>$rs['_id'],
			'group'=>$group,
			'title'=>$rs['profile']['fullname']
		);
	}
	we(json_encode($res));
}

// 我的看板 用户延期数据
function get_timeline_events(){
	global $MYID,$wekan;
    $nt = time();
	$start = strtotime(r('start'));
	$end = strtotime(r('end'));


    $resUser =  $wekan->users->find(array());
    $allUsers = iterator_to_array($resUser);

	$where = array("mem_time"=>array('$exists'=>true));
	$docs = $wekan->cards->find($where,array('_id'=>1, 'title'=>1,'mem_time'=>1,'boardId'=>1,'labels_time'=>1)); //'listId'=>$listid,
	$rss = iterator_to_array($docs);
	
	//we($rss);
	//$boards = getboards();
	$res = array();
	foreach($rss as $rs){
		if(count($rs['mem_time'])==0)continue;

		// 标签更新时间
        $labelsTime = $rs['labels_time'];

		foreach($rs['mem_time'] as $mid=>$mtime){
			if( ($mtime['start'] >= $start && $mtime['start'] <= $end) ||  ($mtime['end'] >= $start && $mtime['end'] <= $end) ){
				
				$title = $rs['title'];
				$finish = 0;
				$yanqi = 0;

				if( indexOf($rs['title'],'~~')!=-1 ){
					$title = '☑ '.str_replace('~','',$title);
					$finish = 1;
				}else{
					if($mtime['end']+24*3600-1<time()){
						$yanqi = 1;
						$title = '☹ '.$title;
					}
				}
                $addArr = array(
                    'resourceId'=>$mid,
                    'title'=>$title,
                    'allDay'=>true,
                    'start'=> date('Y-m-d', $mtime['start'] ),
                    'end'=> date('Y-m-d', $mtime['end']+24*3600 ),
                    'boardid'=>$rs['boardId'],
                    //'boardtitle'=>$boards[ $rs['boardId'] ]['title'],
                    'url'=>"./?app=list&boardid={$rs['boardId']}#cardid={$rs['_id']}",
					
                );

				if($finish==1){
					$addArr['backgroundColor'] = '#3eca20';
				}
				if($yanqi==1){
					$addArr['backgroundColor'] = '#e0225b';
				}

                $res[] = $addArr;

			}
		}
	}
	we(json_encode($res));
}

// 列表日程
function get_timeline_list_card(){
    global $MYID,$wekan;
    $list = r('list');
    $docs = $wekan->cards->find(array(
        'listId'=>$list,'archived' => false)
    ); //'listId'=>$listid,

    $rss = iterator_to_array($docs);


    $res = array();

    foreach($rss as $rs){
        $res[] = array(
            'id'=>$rs['_id'],
            'title'=>$rs['title'],
            'labels'=>$rs['labelIds'],
//            'isyanqi'=>true,
        );
    }
    we(json_encode($res));
}

function get_timeline_list_card_events(){
    global $MYID,$wekan;
    $nt = time();
    $list = r('list');

    $start = strtotime(r('start'));
    $end = strtotime(r('end'));

    $resUser =  $wekan->users->find(array());
    $allUsers = iterator_to_array($resUser);

    $where = array("listId"=>$list,"mem_time"=>array('$exists'=>true));
    $docs = $wekan->cards->find($where,array(
        'title'=>1,'mem_time'=>1,'boardId'=>1,'_id'=>1,'members'=>1)
    ); //'listId'=>$listid,
    $rss = iterator_to_array($docs);


    //we($rss);
    //$boards = getboards();
    $res = array();
    foreach($rss as $rs){
        if(count($rs['mem_time'])==0)continue;

        $members = $rs['members'];
        $docs_users = $wekan->users->find(array('_id'=>array('$in'=>$members )),array('profile.fullname'=>1)); //'listId'=>$listid,
        $rs_users = iterator_to_array($docs_users);

        foreach($rs['mem_time'] as $mid=>$mtime){
            if( ($mtime['start'] >= $start && $mtime['start'] <= $end) ||  ($mtime['end'] >= $start && $mtime['end'] <= $end) ){
                $title = '雷锋';
                if (array_key_exists($mid,$rs_users)){
                    $title = $rs_users[$mid]['profile']['fullname'];
                }
//                $title = "&lt;p&gt;fasdaa</p>";

                $addArr = array(
                    'resourceId'=>$rs['_id'],
                    'title'=>$title,
//                    'isyanqi'=>true,
                    'allDay'=>true,
                    'start'=> date('Y-m-d', $mtime['start'] ),
                    'end'=> date('Y-m-d', $mtime['end']+24*3600 ),
                    'boardid'=>$rs['boardId'],
                    'cardid'=>$rs['_id'],
                    //'boardtitle'=>$boards[ $rs['boardId'] ]['title'],
                    'url'=>"./?app=list&boardid={$rs['boardId']}#cardid={$rs['_id']}"
                );

                if (array_key_exists('isyanqi',$mtime)){
                    if ($mtime['isyanqi'] > 0){
                        $addArr['isyanqi'] = true;
                        $rt = $nt - $mtime['isyanqi'];

                        // 用户存在
                        if (array_key_exists($mid,$allUsers)){
                            $useLabelArr = $allUsers[$mid]['legulabel'];

                            // 面板
                            $resBoards =  $wekan->boards->find(array(
                                "_id" => $rs['boardId'],
                                "labels.name" =>array('$in' => $useLabelArr),
                                "archived" => false,
                            ));
                            $allBoards = iterator_to_array($resBoards);
                            if ($allBoards){
                                $boardLabels = $allBoards[$rs['boardId']]['labels'];
                                $isexistArr = array();
                                $newrt = 0;
                                foreach ($boardLabels as $label){
                                    $labelId = $label['_id'];
                                    if (in_array($label['name'],$useLabelArr)){
//                                    if(‌‌in_array($label['name'],$useLabelArr)){
                                        // 标签存在
                                        if ($rs['labels_time'] and array_key_exists($labelId,$rs['labels_time'])){
                                            if ($rs['labels_time'][$labelId]['finishtime']>$newrt){
                                                $newrt = $rs['labels_time'][$labelId]['finishtime'];
                                                $rt = $newrt - $mtime['isyanqi'];
                                            }
                                        }

                                    }


                                }
                            }
                        }



                        $yanqoDay = floor($rt/(24*3600));
                        $addArr['yanqiday'] = $yanqoDay;
                        // 延期了多久 秒
                        $yanqoRt = $rt;
                        $addArr['yanqiRt'] = $yanqoRt;
                    }
                }

                $res[] = $addArr;
            }
        }
    }
    we(json_encode($res));
}


//创建看板
function add_board(){
	global $MYID,$wekan,$LEGUWORKUSER;
	if(isn($MYID))needLogin();
	$text = r('text');
	
	$_id = uniqid();
	$data = array(
		"_id" => $_id ,
	    "title" => $text ,
	    "permission" =>"public",
	    "slug" => "board",
	    "archived" => false,
	    "view" => "board-view-lists",
	    "createdAt" => new MongoDate(time()),
	    "stars" => 0 ,
	    "labels" => initLables(),
	    "qalabels" => initQALables(),
        "risklabels" => array(),
	    "members" => array(
	        array(
	            "userId" => $MYID,
	            "isAdmin" => true,
	            "isActive" => true,
	            "isCommentOnly" => false
	        )
	    ),
	    "color" => "belize",
	    "modifiedAt" => new MongoDate(time()),
	    "watchers" => array( 
	        array(
	            "userId" => $MYID ,
	            "level" =>"tracking"
	        )
	    ),
		"creator"=>$MYID,
		"org"=>$LEGUWORKUSER['org'],
		"orgname"=>$LEGUWORKUSER['orgname'],
	);
	
	$res = $wekan->boards->insert( $data );
	we (eventData('addboard',$data));
}

//删除附件
function del_fujian(){
	
	global $MYID,$wekan;
	$cardid = r('cardid');
	$fujianid = r('fujianid');
	
	$data = getcard($cardid);
	$data = $data[$cardid];
	$attachments = $data['attachments'];
	
	foreach( $attachments as $idx=>$attachment){
		if( $attachment['_id'] == $fujianid){
			unset( $attachments[$idx]);
		}
	}
	
	
	$wekan->cards->update(array(
		'_id'=>$cardid
	),array(
		'$set' => array('attachments'=> array_values($attachments) )
	));
	
	$data = getcard($cardid);
	we (eventData('attachmentschange',$data[$cardid]));
}

//移动card
function set_card_listid(){
	global $MYID,$wekan;
	$cardid = r('cardid');
	$listid = r('listid');
	$cardorder = r('card');

    // listid必须要有
	if(!isset($listid) or $listid == 'undefined'){
	    return;
    }
	$wekan->cards->update(array(
		'_id'=>$cardid
	),array(
		'$set' => array('listId'=> $listid )
	));
	
	if($cardorder){
		foreach($cardorder as $sortIndex=>$cid){
			$wekan->cards->update(array(
				'_id'=>$cid
			),array(
				'$set' => array('sort'=> $sortIndex )
			));
		}
	}
	$data = getcard($cardid);
	we (eventData('changesort',$data[$cardid]));
}

//list排序
function sort_list(){
	global $MYID,$wekan;
	$boardid = r('boardid');
	$order = r('list');
	
	foreach($order as $sortIndex=>$listid){
		$wekan->lists->update(array(
			'_id'=>$listid
		),array(
			'$set' => array('sort'=> $sortIndex )
		));
	}
	
	$res = array(
		'boardId' => $boardid,
		'order'=>$order
	);
	
	we (eventData('listsort',$res));
}

//设置看板title
function modify_board_title(){
	global $MYID,$wekan;
	$boardid = r('boardid');
	$text = r('text');
	
	$res = $wekan->boards->update(array(
		'_id' => $boardid
	),array(
		'$set'=>array(
			'title' => $text
		)
	));
	$ndata = getBoard($boardid);
	we (eventData('boardtitlechange',$ndata[$boardid]));
}

//归档列表
function archived_list(){
	global $MYID,$wekan;
	$listid = r('listid');
	
	$res = $wekan->lists->update(array(
		'_id' => $listid
	),array(
		'$set'=>array(
			'archived' => true
		)
	));
    $res = $wekan->cards->update(array(
        'listId' => $listid,
        'archived' => false
    ),array(
        '$set'=>array(
            'archived' => true
        )
    ),array(
        "multiple" => true
    ));
	$ndata = getlist($listid);
	we (eventData('archivedlist',$ndata[$listid]));
}

//归档已完成项目
function archived_overedcards(){
	global $MYID,$wekan;
	$listid = r('listid');
	
	$res = $wekan->cards->find(array(
		'listId' => $listid,
		'title' => new MongoRegex("/~~/$i"),
		'archived' => false
	));
	
	$cards = array_keys(iterator_to_array($res));
	
	
	$res = $wekan->cards->update(array(
		'listId' => $listid,
		'title' => new MongoRegex("/~~/$i"),
		'archived' => false
	),array(
		'$set'=>array(
			'archived' => true
		)
	),array(
		"multiple" => true
	));
	
	we (eventData('archivedcards',array(
		'listId' => $listid,
		'cards' => $cards
	)));
}

//修改标签
function modify_label(){
	global $MYID,$wekan;
	$boardid = r('boardid');
	$labelid = r('labelid');
	$labelname = r('labelname');
	$labelcolor = r('labelcolor');
	
	if(isn($labelid)){
		$_id = uniqid();
		$data = array(
		    "_id" => $_id,
		    "color" => $labelcolor,
		    "name" => $labelname
		);
		
		$res = $wekan->boards->update(array(
			'_id'=>$boardid
		),array(
			'$push' => array('labels'=>$data)
		));
	}else{
		$res = $wekan->boards->update(array(
			'_id'=>$boardid,
			'labels._id' => $labelid
		),array(
			'$set' => array(
				'labels.$.color'=>$labelcolor,
				'labels.$.name'=>$labelname,
			)
		));
	}
	
	$data = getBoard($boardid);
	we (eventData('modifylabel',$data[$boardid]));
}

// 删掉标签
function del_label(){
    global $MYID,$wekan;
    $boardid = r('boardid');
    $labelid = r('labelid');
    $labelname = r('labelname');
    $labelcolor = r('labelcolor');


    $res = $wekan->boards->update(array(
        '_id'=>$boardid,
        'labels._id' => $labelid
    ),array(
        '$pull' => array(
            'labels'=>array('_id'=>$labelid),
        )
    ));


    $data = getBoard($boardid);
    we (eventData('modifylabel',$data[$boardid]));
}


//归档看板
function archived_board(){
	global $MYID,$wekan;
	
	$boardid = r('boardid');
	
	$res = $wekan->boards->update(array(
		'_id' => $boardid
	),array(
		'$set'=>array(
			'archived' => true
		)
	));
	$ndata = getBoard($boardid);
	we (eventData('archivedboard',$ndata[$boardid]));
}

function finishcount(){
	global $MYID,$wekan;
	$boardid = r('boardid');

	$timetoday = strtotime(date("Y-m-d",time()));
	$res = array();
	
	$finishSum = 0;
	$createSum = 0;
	
	for($i=10;$i>=0;$i--){
		$stime = $timetoday-$i*24*3600;
		$end = $stime+24*3600-1;
		
		$mongostart = new MongoDate($stime);
		$mongoend = new MongoDate($end);
		
		$create =$wekan->cards->count(array(
			"createdAt"=> array('$gt' => $mongostart,'$lte' => $mongoend),
			'boardId'=>$boardid,
		));
		$createSum+=$create;
		
		$finish = $wekan->cards->count(array(
			'finishAt' => array('$gte'=>$stime,'$lte'=>$end),
			'boardId'=>$boardid,
		));
		$finishSum+=$finish;
		
		$d = date("m-d",$stime);
		
		$res['day'][] = $d;
		$res['finish'][] = $finish;
		$res['create'][] = $create;
	}
	
	$res['title'] = array('新增['. $createSum .']','完成['. $finishSum .']');
	
	we(json_encode($res));
}

// 看板统计 当月QA问题类型标签
// title
// data
function reportQALables(){

    global $MYID,$wekan;
    $boardid = r('boardid');
    $act = r('act');

    $beginThismonth=mktime(0,0,0,date('m'),1,date('Y'));

    $endThisMonth = time();

    // 当前月份的上个月
    if ($act == 'lastmonth'){
        $beginThismonth=mktime(0,0,0,date('m') - 1,1,date('Y'));
        $endThisMonth = mktime(0,0,0,date('m'),date('d') - 1,date('Y'));
    }

    $mongostart = new MongoDate($beginThismonth);
    $mongoend = new MongoDate($endThisMonth);

    $res = array();


    $resCards =  $wekan->cards->find(array(
//        "archived" => true,
        "boardId" => $boardid,
        "createdAt"=> array('$gt' => $mongostart,'$lte' => $mongoend),
        "qalabelIds" => array('$exists'=>1),
    ),array(
        'qalabelIds'=>1
    ));
    $allCard = iterator_to_array($resCards);

    $data = array();
    $labelNameArr = getQANameForIdInBoard($boardid);
    foreach ($allCard as $item) {
        $qalabelIds = $item['qalabelIds'];
        foreach ($qalabelIds as $qid){
            if (array_key_exists($qid,$data)){
                $data[$qid] += 1;
            }else{
                $data[$qid] = 1;
            }

        }

    }

    $colorNameArr = getQAColorForBoard($boardid);

    $jdata = array();
    foreach ($data as $k=>$v){
        $jdata[] = array('value'=>$v,'name'=>$labelNameArr[$k],'itemStyle'=>array('color'=>$colorNameArr[$k]));

    }

    $res['title'] = array_values($labelNameArr);
    $res['data'] = $jdata;

    we(json_encode($res));
}


// 看板统计 当月全部标签完成情况
function reportshowRemainList(){

    global $MYID,$wekan;
    $boardid = r('boardid');
    $act = r('act');

    $beginThismonth=mktime(0,0,0,date('m'),1,date('Y'));

    $endThisMonth = time();

    // 当前月份的上个月
    if ($act == 'lastmonth'){
        $beginThismonth=mktime(0,0,0,date('m') - 1,1,date('Y'));
        $endThisMonth = mktime(0,0,0,date('m'),date('d') - 1,date('Y'));
    }

    $mongostart = new MongoDate($beginThismonth);
    $mongoend = new MongoDate($endThisMonth);

    $res = array();


    $resCards =  $wekan->cards->find(array(
//        "archived" => true,
        "boardId" => $boardid,
        "createdAt"=> array('$gt' => $mongostart,'$lte' => $mongoend),
    ));
    $allCard = iterator_to_array($resCards);

    $allNum = count($allCard);
    $data = array();
    //    已关闭（归档单子） 已完成（勾掉单子） 未完成（当前未验收未解决）
    $nameArr = array(
        '已关闭'=>array('value'=>0,'name'=>'已关闭','itemStyle'=>array('color'=>'rgb(51, 75, 92)')),
        '已完成'=>array('value'=>0,'name'=>'已完成','itemStyle'=>array('color'=>'rgb(116, 159, 131)')),
        '未完成'=>array('value'=>0,'name'=>'未完成','itemStyle'=>array('color'=>'rgba(213,58,53,1)'))
    );
    foreach ($allCard as $item) {
        // 关闭 归档
        $title = $item['title'];
        $isArchived = $item['archived'];
        if ($isArchived){
            $nameArr['已关闭']['value'] += 1;
        // 完成
        }elseif (strpos($title, '~~') === 0){
            $nameArr['已完成']['value'] += 1;
        }else{
            $nameArr['未完成']['value'] += 1;
        }

    }


    $res['title'] = array_keys($nameArr);
    $res['data'] = array_values($nameArr);
    $res['allnum'] = $allNum;

    we(json_encode($res));
}


// 每天0点执行 检查人员是否延期
function chkYanQiEverDay(){
    global $MYID,$wekan;

    $timetoday = strtotime(date("Y-m-d",time()));
    $nt = time();

    // 全部的卡片
    $resCards =  $wekan->cards->find(array(
        "archived" => false,
        "mem_time" => array('$exists'=>1),
    ));
    $allCard = iterator_to_array($resCards);

    $resBoards =  $wekan->boards->find(array(
        "archived" => false,
    ));
    $allBoards = iterator_to_array($resBoards);


    $resUser =  $wekan->users->find(array(
    ));

    $allUsers = iterator_to_array($resUser);

    // 看板
    foreach ($allBoards as $board){
        $boardId = $board['_id'];
        // 看板标签
        $boardLabels = $board['labels'];
        $boardLabelArr = array();
        foreach ($boardLabels as $label){
//            $boardLabelArr[$label['_id']] = $label;
            $boardLabelArr[$label['_id']] = $label['name'];
        }

        $resCards =  $wekan->cards->find(array(
            "archived" => false,
            "boardId" => $boardId,
        ));
        $allCard = iterator_to_array($resCards);

        foreach ($allCard as $card){
            // 用户标签
            $mem_time = $card['mem_time'];
            $cardLabelArr = $card['labelIds'];

            // 卡片的标签名字数组
            $cardLabelNameArr = array();
            foreach ($cardLabelArr as $labelId) {
                $labelName = $boardLabelArr[$labelId];
                $cardLabelNameArr[] = $labelName;
            }



            // 用户时间标签数组
            $memTimeArr = array();
            if (isset($mem_time)){
                $memTimeArr = array_keys($mem_time);
            }
            // 卡片标签 部门类标签
//            $labelIdsArr = $card['labelIds'];
            $labelIdsArr = array();
            foreach ($card['labelIds'] as $item) {
                $labelIdsArr[$item] = $item;

            }


            $isyanqi = false;
            foreach ($memTimeArr as $user){
                if (array_key_exists($user,$allUsers)){
                    // 检查用户的标签是否在看板的标签
                    if (array_key_exists('legulabel',$allUsers[$user])){
                        $userLabelNameArr = $allUsers[$user]['legulabel'];

                        // 存在
                        $result = array_intersect($cardLabelNameArr,$userLabelNameArr);

                        if (count($result) > 0){
                            $etime = $mem_time[$user]['end'] + 60*60*24-1;

                            // 大于今天 延期
                            if ($nt > $etime and !isset($mem_time[$user]['isyanqi'])){
                                $isyanqi = true;
                                $mem_time[$user]['isyanqi'] = $etime;
                            }
                        }
                    }
                }
            }

            // 设置延期时间
            if ($isyanqi){
                $wekan->cards->update(array(
                    '_id'=>$card['_id']
                ),array(
                    '$set'=>array('mem_time'=>$mem_time)
                ));
            }
        }
    }
    echo 'ok';
    // 记录运行的时间
    $cachechkYanQiEverDay = 'chkYanQiEverDay';
    $cache = $wekan->cache->update(array(
        'k'=>$cachechkYanQiEverDay
    ),array('k'=>$cachechkYanQiEverDay,'v'=>$nt),array('upsert'=>true));

//    we(json_encode($allUsers));


}



// QA标签

//设置QA标签 只设置一个
function set_qalabel(){

    global $MYID,$wekan;
    $cardid = r('cardid');
    $labelid = r('labelid');
    $timeto = r('timeto');

    $data = getcard($cardid);
    $data = $data[$cardid];
    $labels_time = $data['qalabels_time'];
    if(!$labels_time)$labels_time=array();

    if(!array_key_exists('qalabelIds',$data)){
        $wekan->cards->update(array(
            '_id'=>$cardid
        ),array(
//            '$addToSet' => array('qalabelIds'=>$labelid)
            '$set' => array('qalabelIds'=>array($labelid))
        ));

    }else{
        //    不在里面 添加
        if(!in_array($labelid,$data['qalabelIds'])){
            $wekan->cards->update(array(
                '_id'=>$cardid
            ),array(
//                '$addToSet' => array('qalabelIds'=>$labelid)
                '$set' => array('qalabelIds'=>array($labelid))
            ));

        }else{
//        在里面 删掉
            $wekan->cards->update(array(
                '_id'=>$cardid
            ),array(
//                '$pull' => array('qalabelIds'=>$labelid)
                '$set' => array('qalabelIds'=>array())
            ));

        }

    }

    $data = getcard($cardid);

    // 刷新分组
    setYanQiLabelUserForCard($cardid);

    we (eventData('labelchange',$data[$cardid]));
}

//修改QA标签
function modify_qalabel(){
    global $MYID,$wekan;
    $boardid = r('boardid');
    $labelid = r('labelid');
    $labelname = r('labelname');
    $labelcolor = r('labelcolor');

    if(isn($labelid)){
        $_id = uniqid();
        $data = array(
            "_id" => $_id,
            "color" => $labelcolor,
            "name" => $labelname
        );

        $res = $wekan->boards->update(array(
            '_id'=>$boardid
        ),array(
            '$push' => array('qalabels'=>$data)
        ));
    }else{
        $res = $wekan->boards->update(array(
            '_id'=>$boardid,
            'qalabels._id' => $labelid
        ),array(
            '$set' => array(
                'qalabels.$.color'=>$labelcolor,
                'qalabels.$.name'=>$labelname,
            )
        ));
    }

    $data = getBoard($boardid);
    we (eventData('modifylabel',$data[$boardid]));
}

// 删掉QA标签
function del_qalabel(){
    global $MYID,$wekan;
    $boardid = r('boardid');
    $labelid = r('labelid');
    $labelname = r('labelname');
    $labelcolor = r('labelcolor');


    $res = $wekan->boards->update(array(
        '_id'=>$boardid,
        'qalabels._id' => $labelid
    ),array(
        '$pull' => array(
            'qalabels'=>array('_id'=>$labelid),
        )
    ));


    $data = getBoard($boardid);
    we (eventData('modifylabel',$data[$boardid]));
}



// 所有日程 延期统计 月 周
function get_yqrank(){
    global $MYID,$wekan;
    $nt = time();
    $act = r('act');

    if(!isset($act)){
        $act = 'week';
    }

    $beginThisweek = mktime(0,0,0,date('m'),date('d')-date('w')+1,date('y'));
    $st = $beginThisweek;
    if($act == 'month'){
        $beginThismonth=mktime(0,0,0,date('m'),1,date('Y'));
        $st = $beginThismonth;

    }

    $nt = time();

    $cacheKey = 'cache_find_'.$act;
    // todo 缓存时间
    $cache = $wekan->cache->find(array(
        'k'=>$cacheKey,'et' => array('$gt'=>$nt)
    ));

    $cache = iterator_to_array($cache);
    if($cache){
        $v = array_values($cache);
        we(json_encode($v[0]['v']));
    }


    //  1 在职状态 0 离职
    $users = $wekan->users->find(array(
        'legustatus'=>1
    ),array(
        'profile.fullname'=>1
    ));
    $users = iterator_to_array($users);

    $nameArr = array();
    $dataArr = array();
    $allDataArr = array();

    foreach ($users as $user){
        $name = $user['profile']['fullname'];
        $uid = $user['_id'];
//        echo 'aa.'.$uid;
        $yanqiCount = $wekan->cards->count(array(
            "archived" => false,
            "mem_time.".$uid.".isyanqi" => array('$exists'=>1),
            "mem_time.".$uid.".start" => array('$gte'=>$st),
        ));
        if ($yanqiCount){
            $allDataArr[$name] = $yanqiCount;

        }
    }

    asort($allDataArr);
    foreach ($allDataArr as $key=>$value) {
        $nameArr[] = $key;
        $dataArr[] = $value;
    }

    $res = array(
        'xdata'=>$nameArr,
        'ydata'=>$dataArr,

    );

    $et = $nt + 24*60*60-1;
    $cache = $wekan->cache->update(array(
        'k'=>$cacheKey
    ),array('k'=>$cacheKey,'v'=>$res,'et'=>$et),array('upsert'=>true));

    we(json_encode($res));
}

// 获取work权限
function getWorkPermission(){
    // __setting.Permission.$permission
    global $wekan,$LEGUWORK_SETTING_LISTID;

    // 默认没有权限
    $res = false;
    $uid = r('uid');
    $permission = r('pms');

    $setKey = '__setting.Permission.'.$permission;
    $setData = $wekan->cards->findOne(array('title'=>$setKey,'listId'=>$LEGUWORK_SETTING_LISTID));
//    var_dump($setData);
//    var_dump($setData['members']);


    // 有权限 true
    if ($setData){
        // 直接判断uid
        if(in_array($uid,$setData['members'])){
            $res =  true;
        }else{
            // todo 判断组 用延期分组中的用户
        }

    }

    //we(json_encode($res));
	we("true");

}

// 获取延期列表数据 部门对应用户
// 5ce68e49bd298
function getYanQiDepartmentUser1(){
    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] = $members;
        }
    }



    we(json_encode($labelIdUserArr));
//    we(json_encode(array()));





}


if(function_exists($act)){
	$act();
}





// 根据卡片的用户和标签设置标签组
function setYanQiLabelUserForCard($cardid){
//function setYanQiUserForCard(){
//    $cardid = '5ce68f7366b3d';
    global $MYID,$wekan;
    $cardData = getcard($cardid);
    $card = $cardData[$cardid];

    $boardId = $card['boardId'];
    $listId = $card['listId'];

    // 特定列表的卡片 LeguWork 【设置】延期分组
    if ($listId != '5ce68e49bd298'){
        return;
    }
    $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'];
    }



    $members = $card['members'];
    $labels = $card['labelIds'];
    $labelNameArr = array();
    foreach ($labels as $label) {
        $labelNameArr[] = $boardLabelArr[$label];
    }
    $wekan->users->update(array(
        '_id'=>array('$in'=>$members),
    ),array(
//        '$push'=>array('legulabel'=> array('$each'=>$labelNameArr))
        '$addToSet'=>array('legulabel'=> array('$each'=>$labelNameArr))
    ),array("multiple" => true));

}

// 根据卡片的用户和标签设置日程分组
function setRiChengLabelUserForCard($cardid){
//function setYanQiUserForCard(){
//    $cardid = '5ce68f7366b3d';
    global $MYID,$wekan;
    $cardData = getcard($cardid);
    $card = $cardData[$cardid];

    $boardId = $card['boardId'];
    $listId = $card['listId'];
    $title = $card['title'];

    // 特定列表的卡片 LeguWork 【设置】日程分组
    if ($listId != '5ce7a226c387f'){
        return;
    }

    $members = $card['members'];

    $wekan->users->update(array(
        '_id'=>array('$in'=>$members),
    ),array(
        '$set'=>array('legugroup'=>$title)
    ),array("multiple" => true));

}


// 根据_id获取board中的标签的名字
function getNameForIdInBoard($boardId,$name){
    global $wekan;
    $resData =  $wekan->boards->find(array(
//        "archived" => true,
        "_id" => $boardId,
//        $name => array('$exists'=>1),
    ),array(
        $name=>1
    ));
    $resData = iterator_to_array($resData);
    $resArr = array();
    foreach ($resData as $items){
        $item = $items[$name];
        foreach ($item as $label){
            $resArr[$label['_id']] = $label['name'];
        }
    }
    return$resArr;
}

function getQANameForIdInBoard($boardId){
    return getNameForIdInBoard($boardId,'qalabels');
}


// 获取QA标签的颜色值
function getQAColorForBoard($boardId){
    global $wekan;

    $colorArr = array(
        'legured'=>'#cb1a44',
        'leguyellow'=>'#ffb11b',
        'legublue'=>'#278785',
        'leguaqua'=>'#39CCCC',
        'legupurple'=>'#76428d',
        'legugray'=>'#787878',
        'legugreen'=>'#5eac82',
        'legupink'=>'#f596aa',
    );

    $resData =  $wekan->boards->find(array(
//        "archived" => true,
        "_id" => $boardId,
//        $name => array('$exists'=>1),
    ),array(
        'qalabels'=>1
    ));
    $resData = iterator_to_array($resData);
    $resArr = array();
    foreach ($resData as $items){
        $item = $items['qalabels'];
        foreach ($item as $label){
            $resArr[$label['_id']] = $colorArr[$label['color']];
        }
    }

    return $resArr;


}

// 移除新手数据
// http://localhost:8081/?app=api&apiact=remove_guide_board&bid=5d4930074780b
function remove_guide_board(){
    global $MYID,$wekan;
    $boardId = r('bid');

    $resReturn = array();
    $res = $wekan->boards->remove(array(
        '_id' => $boardId
    ));
    $resReturn['boards'] = $res;

    $res = $wekan->lists->remove(array(
        'boardId' => $boardId
    ));
    $resReturn['lists'] = $res;

    $res = $wekan->cards->remove(array(
        'boardId' => $boardId
    ));
    $resReturn['cards'] = $res;

    we (json_encode($resReturn));
}


// 手动添加新手指导数据
// http://localhost:8081/?app=api&apiact=add_guide_board&uid=KJLYkgxSoBvDwGDB9&gname=服务端
function add_guide_board(){
    global $MYID,$wekan;

    $_uid = r('uid');
    $gname = r('gname');


    // 没有设置组名
    if (!isset($gname)){
        $hasMember = $wekan->users->findOne( array(
            "_id" =>$_uid
        ));

        $gname = $hasMember['group'];

        if(!$gname){
            we (json_encode(array(
                'err'=>'没有找到用户'
            )));
        }
    }

    $tBoardId = getTemplateBoardIdForUserGroupName($gname);
    $resReturn = insertGuideBoardForTemplateBoard($_uid,$tBoardId);

    we (json_encode($resReturn));

}


?>