<?php

namespace app\api\controller;

use app\api\middleware\Auth;
use app\api\service\UserService;
use app\api\validate\CourseValidate;
use app\BaseController;
use think\facade\Request;
use app\api\service\CourseProgressService;

class CourseProgress extends BaseController
{

    protected $middleware = [
        Auth::class,
    ];



    /**
     * 上报学习进度API
     */
    public function reportProgress()
    {
        $vo = (new CourseValidate())->goCheck(['course_id','current_time','class_id']);
        if ($vo !== true) {
            return $vo;
        }

        $data = Request::only(['course_id', 'class_id', 'current_time']);
        $token = Request::header('token');

        $userId = UserService::getUserInfo($token)['id'];

        $result = CourseProgressService::updateProgress(
            $userId,
            $data['course_id'],
            $data['class_id'],
            $data['current_time'],
        );

        if (!$result) {
            return $this->returnMsg('视频不存在',0);
        }

        return $this->returnMsg('操作成功',1,$result);

    }

    /**
     * 获取课程进度API
     */
    public function getProgress()
    {

//        $vo = (new CourseValidate())->goCheck(['course_id']);
//        if ($vo !== true) {
//            return $vo;
//        }

        $token = Request::header('token');

        $userId = UserService::getUserInfo($token)['id'];
//        $data = Request::only(['course_id','page','pageSize']);
        $page = Request::param('page', 1);
        $pageSize = Request::param('pageSize', 10);

        $progress = CourseProgressService::getUserAllCoursesProgress($userId, $page, $pageSize);

        return $this->returnMsg('操作成功',1,$progress);

    }

    /**
     * 获取最后学习位置API
     */
    public function getLastLearn()
    {
        $vo = (new CourseValidate())->goCheck(['course_id']);
        if ($vo !== true) {
            return $vo;
        }

        $token = Request::header('token');

        $userId = UserService::getUserInfo($token)['id'];
        $data = Request::only(['course_id']);
        $lastLearn = CourseProgressService::getLearnedClasses($userId, $data['course_id']);

        return $this->returnMsg('操作成功',1,$lastLearn);

    }

    /**添加用户作业
     *
     */
    public function addUserWork()
    {
        $vo = (new CourseValidate())->goCheck(['course_id']);
        if ($vo !== true) {
            return $vo;
        }

        $token = Request::header('token');

        $userId = UserService::getUserInfo($token)['id'];
        $data = Request::only(['course_id']);

        $userWork = CourseProgressService::addUserWork($userId, $data['course_id']);

        return $this->returnMsg('操作成功',1,$userWork);
    }
}