<?php
session_start();

$user = $_SESSION['leguworkUser'];
$username = $user['pinyin'].$user['userid'];


// 测试用start
//$username = $_REQUEST['name'];
//$username = 'wu2194';
//$user['avatar'] = '';
//$user['legugroup'] = array('服务端');

//测试用end


$hasMember = $wekan->users->find( array(
	"username" =>$username
));

//记录最后IP
$wekan->usersip->update(array(
	'username'=>$username
),array(
	'$set'=>array(
		'username'=>$username,
		'fullname'=> $user['name'],
		'lastime'=>time(),
	),
	'$addToSet'=>array(
		'ip'=>getip()
	)
),array(
	'upsert'=>true
));


if (count( iterator_to_array($hasMember) ) == 0){
	//看板里没有这个用户，则自动增加
	$id = 'w'.uniqid();
	$_SESSION['leguworkUID'] = $id;

	$wekan->users->insert(array(
    	"_id" => $id,
    	"createdAt" => new MongoDate(time()),
    	"username" => $username,
    	"emails" => array(
        	array(
            	"address" => "{$user['pinyin']}@leguwork.cc",
            	"verified" => false
        	)
    	),
    	"isAdmin" => false,
    	"profile" => array(
        	"fullname" => $user['name'],
        	"avatarUrl" => $user['avatar'],
        	"hiddenSystemMessages" => true,
	        "tags" => array(
	            "notify-participate", 
	            "notify-watch"
	        ),
	        "starredBoards" => array(),
        
        	"language" => "zh-CN",
        	"boardView" => "board-view-lists"
        ),
		"org"=>$user['org'],
		"orgname"=>$user['orgname'],
        "group"=>$user['legugroup'][0],
		'dduserid'=>$user['userid']
    ));

	$hasMember = $wekan->users->find( array(
		"username" =>$username
	));
}

// 更新登录时间 用于筛选用户
$wekan->users->update(array(
	'username'=>$username
),array(
	'$set' => array(
		'lastlogin'=> time(),
		'group'=>$user['legugroup'][0],
		'dduserid'=>$user['userid']
	)
));


// 更新legulabel
/*
if (isset($user)){

    $legulabel = $wekan->users->find(array(
        'username'=>$username,
        'legulabel' => array('$in' => array($user['legugroup'][0])),
    ));

    $res = iterator_to_array($legulabel);
    // 没有设置 legulabel
    if (!$res){
        $legulabel = $wekan->users->update(array(
            'username'=>$username,
        ),array(
            '$push' => array('legulabel' => $user['legugroup'][0]),
        ));
    }

}
*/

$uinfo = iterator_to_array($hasMember);
$uinfo = array_keys($uinfo);

$_SESSION['leguworkUID'] = $uinfo[0];

header("Location:./?app=board");






//$tBoardId = getTemplateBoardIdForUserGroupName('服务端');
//
//insertGuideBoardForTemplateBoard($_SESSION['leguworkUID'],$tBoardId);
