<?php

// 用户加入指定的圈子
require_once ("../user_include.inc");

ErrorLogger::doOutput("Compass...ajax_user_join_circle.php....Start.", 0);

//获取参数
$unionId = ParamUtil::getRequestString("unionId");
$circleId = ParamUtil::getRequestNumber("circleId", 0);//圈子id

$result = array();

//参数检查
if(empty($unionId) || empty($circleId)) {
	$result["message"] = "参数错误！";
	responseNG($result);
}

//判断用户是否存在
$param = array();
$param['unionid'] = $unionId;
$param['delete_flg'] = false;
$userList = UserMst::getList($param,'id','desc', 0, 1);
if(empty($userList)) {
	$result["message"] = "用户不存在！";
	responseNG($result);
}

$userMst = $userList[0];

//判断圈子是否存在
$circleDat = CircleDat::getById($circleId);
if(empty($circleDat)) {
	$result["message"] = "圈子不存在！";
	responseNG($result);
}

//是否已经加入圈子
$param = array();
$param['circle_id'] = $circleDat->id;
$param['user_id'] = $userMst->id;
$param['delete_flg'] = false;
$tmpCount = CircleMemberDat::getListCount($param);
if($tmpCount >= 1) {
	$result["message"] = "已经是圈子成员！";
	responseMember($result);
}

//加入圈子处理
//是否需要审核
if($circleDat->need_check) {
	//需要审核的情况下，发送一条消息给圈主。
	$userMessageDat = new UserMessageDat();
	$userMessageDat->user_id = $circleDat->owner_id;
	$userMessageDat->title = "您的圈子有一条加入申请";
	$userMessageDat->comment = "嘀嘀嘀！" . $userMst->name . "申请加入您的圈子！";
	
	//添加附件附件
	$userMessageDat->attach_dat_type = "CIRCLE";
	$userMessageDat->attach_dat_id = $circleDat->id;
	$userMessageDat->attach_dat_path = "pages/checkJoinCircle/checkJoinCircle?userId={$userMst->id}&circleId={$circleDat->id}";
	$result["message"] = "申请成功，请等待圈主审核！";
	responseOK($result);
		
} else {
	//不需要审核的情况下，直接加入圈子
	$circleMemberDat = new CircleMemberDat();
	$circleMemberDat->circle_id = $circleDat->id;
	$circleMemberDat->user_id = $userMst->id;
	$circleMemberDat->name = $userMst->name;
	$circleMemberDat->save();
	//圈子成员数+1
	$circleDat->member_count++;
	$circleDat->save();
	
	$result["message"] = "加入成功！";
	responseMember($result);
}


//组装返回数据
$result["circleList"] = $circleList;

ErrorLogger::doOutput("Compass...ajax_user_join_circle.php....End.", 0);

//返回结果
responseOK($result);

function responseNG($result) {
	$result = array("status"=>"NG", "result"=>$result);
	print json_encode($result);
	exit;
}

function responseMember($result) {
	$result = array("status"=>"MEMBER", "result"=>$result);
	print json_encode($result);
	exit;
}

function responseOK($result) {
	$result = array("status"=>"OK", "result"=>$result);
	print json_encode($result);
	exit;
}
?>