<?php

// 根据课程id获取课程详细信息
require_once ("../user_include.inc");

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

//获取参数
$unionId = ParamUtil::getRequestString("unionId");
$mediaId = ParamUtil::getRequestNumber("mediaId", 0);

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

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

$userMst = $userMstList[0];

$result = array();

//判断视频是否存在
$courseMediaDat = CourseMediaDat::getById($mediaId);
if(empty($courseMediaDat)) {
	$result["message"] = "视频不存在！";
	responseNG($result);
}

$courseMediaDat->haveBuy = false;
//付费会员、教育局领导、学校负责人、班级负责人可以免费观看
if($userMst->is_member || $userMst->role == 4 || $userMst->school_owner || $userMst->class_owner) {
	$courseMediaDat->haveBuy = true;
} else {
	//收费课程判断用户是否已经购买
	if($courseMediaDat->is_free==false) {
		//收费课程的情况下，判断用户是否已经购买本课程
		$param = array();
		$param['user_id'] = $userMst->id;
		$param['media_id'] = $courseMediaDat->id;
		$param['is_free'] = false;
		$param['status'] = 'SUCCESS';
		$param['delete_flg'] = false;
		$userMstBuyList = UserMediaDat::getList($param, "id", "desc", 0, 1);
		if(!empty($userMstBuyList)) {
			$courseMediaDat->haveBuy = true;
		}
	}
}

//添加播放次数[观看次数+1]
$courseMediaDat->view_count++;
$courseMediaDat->save();

//添加用户播放记录
//添加用户观看记录(已经观看过则更新时间变成最后观看)
$param = array();
$param['user_id'] = $userMst->id;
$param['course_id'] = $courseMediaDat->course_id;
$param['media_id'] = $mediaId;
$param['delete_flg'] = false;
$tmpUserMediaDatList = UserMediaDat::getList($param,'id','desc', 0, 1);
if(empty($tmpUserMediaDatList)) {
	//第一次观看则添加记录
	$userMstMediaDat = new UserMediaDat();
	$userMstMediaDat->user_id = $userMst->id;
	$userMstMediaDat->course_id = $courseMediaDat->course_id;
	$userMstMediaDat->media_id = $mediaId;
	$userMstMediaDat->is_free = $courseMediaDat->is_free;
	$userMstMediaDat->money = $courseMediaDat->price;
	$userMstMediaDat->save();
} else {
	//以前有观看记录则修改观看时间
	$tmpUserMediaDatList[0]->registration_date = date("Y-m-d H:i:s");
	$tmpUserMediaDatList[0]->save();
}

//接口返回数据
$result["courseMediaDat"] = $courseMediaDat;

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


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

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