<?php

// 提交用户观看信息
require_once ("../user_include.inc");

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

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


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

//检索用户是否存在
$param['unionid'] = $unionId;
$param['delete_flg'] = false;
$tmpUserMstList = UserMst::getList($param,'id','desc', 0, 1);
if(empty($tmpUserMstList)) {
	responseNG("参数错误！");
}

//检查媒体文件是否存在
$courseMediaDat = CourseMediaDat::getById($mediaId);
if(empty($courseMediaDat)) {
	responseNG("参数错误！");
}

//数据插入
$user = $tmpUserMstList[0];

//免费观看课程
if($courseMediaDat->is_free) {
	//观看次数+1
	$courseMediaDat->view_count++;
	$courseMediaDat->save();

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

}

//每页显示条数
$rowCount = 10;

$result = array();

$offset = $page * $rowCount;

//检索数据库
$param = array();
$param['parent_category_id'] = $parentId;
$param['sub_category_id'] = $subId;
$param['delete_flg'] = false;
$courseList = CourseMst::getList($param,'id','desc', $offset, $rowCount);
$allCount = CourseMst::getListCount($param);

//接口返回数据
$result["allCount"] = $allCount;
$result["page"] = $page;
$result["rowCount"] = $rowCount;
$result["list"] = $courseList;


ErrorLogger::doOutput("Compass...ajax_set_media_view_count.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;
}
?>