<?php

namespace app\api\service;
use app\model\Course;
use app\model\CourseClass;
use app\model\CourseProgress;
use app\model\CourseUserWork;
use app\model\CourseWork;

class CourseProgressService
{
    /**
     * 更新学习进度
     * @param int $userId 用户ID
     * @param int $courseId 课程ID
     * @param int $classId 课时ID
     * @param int $currentTime 当前观看位置(秒)
     * @param int $duration 视频总时长(秒)
     * @return array
     */
    public static function updateProgress($userId, $courseId, $classId, $currentTime)
    {

        $duration = CourseClass::where('id',$classId)->value('tvtime');
//        $duration = 50;
        if (!$duration) {
            return false;
        }


        // 判断是否看完（观看进度超过95%或最后10秒）
        $isFinished = ($currentTime >= $duration - 10) || ($currentTime >= $duration * 0.95);

        // 查找或创建记录
        $progress = CourseProgress::where([
            'user_id' => $userId,
            'course_id' => $courseId,
            'class_id' => $classId
        ])->findOrEmpty();

        if ($progress->isEmpty()) {
            // 新记录
            $progress = CourseProgress::create([
                'user_id' => $userId,
                'course_id' => $courseId,
                'class_id' => $classId,
                'tvtime' => $duration,
                'look_tvtime' => $currentTime,
                'is_wc_look' => $isFinished ? 1 : 0
            ]);
        } else {
            // 更新记录（只更新必要字段）
            $updateData = [
                'look_tvtime' => $currentTime,
                'is_wc_look' => $isFinished ? 1 : $progress->is_wc_look
            ];

            // 如果视频总时长有变化才更新
            if ($duration != $progress->tvtime) {
                $updateData['tvtime'] = $duration;
            }

            $progress->save($updateData);
        }


        return [
            'progress' => $progress->look_tvtime,
            'duration' => $progress->tvtime,
            'is_finished' => $progress->is_wc_look
        ];
    }

    /**添加作业
     * @param $userId
     * @param $courseId
     * @return true
     */
    public static function addUserWork($userId, $courseId)
    {

        $workIds = CourseWork::where([
            'user_id' => $userId,
            'course_id' => $courseId,
        ])->column('id');

        if (empty($workIds)) {
            return true;
        }

        $existingWorks = CourseUserWork::where([
            'user_id' => $userId,
            'course_id' => $courseId,
        ])->whereIn('work_id', $workIds)
            ->column('work_id');

        $newWorkIds = array_diff($workIds, $existingWorks);

        if (!empty($newWorkIds)) {
            $insertData = array_map(function($workId) use ($userId, $courseId) {
                return [
                    'user_id' => $userId,
                    'course_id' => $courseId,
                    'work_id' => $workId,
                    'createtime' => time()
                ];
            }, $newWorkIds);

            CourseUserWork::insertAll($insertData);
        }

        return true;
    }


    /** 获取当前用户所有课程进度统计
     * @param $userId
     *
     */
    public static function getUserAllCoursesProgress($userId, $page = 1, $pageSize = 10)
    {
        // 获取用户学习过的所有课程ID（去重）
        $courseIds = CourseProgress::where('user_id', $userId)
            ->distinct(true)
            ->column('course_id');

        // 如果没有学习记录，返回空分页
        if (empty($courseIds)) {
            return [
                'total' => 0,
                'per_page' => $pageSize,
                'current_page' => $page,
                'data' => []
            ];
        }



        // 分页查询课程基本信息
        $query = Course::where('id', 'in', $courseIds)
            ->with(['thumb'])
            ->field('id,title,description,thumb');

        $paginator = $query->paginate([
            'list_rows' => $pageSize,
            'page' => $page
        ]);

        // 获取分页数据
        $list = $paginator->items();

        // 为每个课程添加进度信息
        foreach ($list as $k => $v) {
            $list[$k]['progress'] = self::getCourseProgress($userId, $v['id']);
        }

        return [
            'total' => $paginator->total(),
            'per_page' => $paginator->listRows(),
            'current_page' => $paginator->currentPage(),
            'last_page' => $paginator->lastPage(),
            'data' => $list
        ];
    }

    /**
     * 获取用户课程进度统计
     * @param int $userId 用户ID
     * @param int $courseId 课程ID
     * @return array
     */
    public static function getCourseProgress($userId, $courseId)
    {
        // 获取所有课时进度
        $progressList = CourseProgress::with(['class'])
            ->where('user_id', $userId)
            ->where('course_id', $courseId)
            ->select();
        // 统计计算
        $finishedCount = 0;
        $totalDuration = 0;
        $learnedDuration = 0;

        $classProgress = [];
        foreach ($progressList as $item) {
            if ($item->is_wc_look) {
                $finishedCount++;
            }
            $totalDuration += $item->tvtime;
            $learnedDuration += min($item->look_tvtime, $item->tvtime);

            $classProgress[$item->class_id] = [
                'progress' => $item->look_tvtime,
                'duration' => $item->tvtime,
                'is_finished' => $item->is_wc_look,
                'last_learn' => $item->createtime,
                'class_id' => $item->class_id//课时id,
            ];
        }

        return [
            'finished_count' => $finishedCount,
            'total_classes' => count($progressList),
            'progress_percent' => $totalDuration > 0 ? round($learnedDuration / $totalDuration * 100) : 0,
            'classes' => $classProgress
        ];
    }


    /**
     * 获取课程最后学习时间
     */
    private static function getLastLearnTime($userId, $courseId)
    {
        $lastProgress = CourseProgress::where('user_id', $userId)
            ->where('course_id', $courseId)
            ->order('createtime', 'desc')
            ->value('createtime');

        return $lastProgress ? date('Y-m-d H:i', $lastProgress) : '未学习';
    }


    /**
     * 获取用户最后学习的课时
     * @param int $userId 用户ID
     * @param int $courseId 课程ID
     * @return array|null
     */
    public static function getLastLearnedClass($userId, $courseId)
    {
        $progress = CourseProgress::with(['class'])
            ->where('user_id', $userId)
            ->where('course_id', $courseId)
            ->where('look_tvtime', '>', 0)
            ->order('createtime', 'desc')
            ->find();


        return $progress ? [
            'class_id' => $progress->class_id,
            'progress' => $progress->look_tvtime,
            'duration' => $progress->tvtime,
            'last_time' => $progress->createtime,
            'is_finished' => $progress->is_wc_look
        ] : null;
    }

    /**多条
     * 获取用户最后学习的课时
     * @param int $userId 用户ID
     * @param int $courseId 课程ID
     * @return array|null
     */
    public static function getLearnedClasses($userId, $courseId)
    {
        $progressList = CourseProgress::with(['class'])
            ->where('user_id', $userId)
            ->where('course_id', $courseId)
            ->where('look_tvtime', '>', 0)
            ->order('createtime', 'desc')
            ->select()
            ->toArray();

        if (empty($progressList)) {
            return [];
        }
        // 返回所有记录（按时间倒序）
        return array_map(function ($progress) {
            return [
                'class_id'  => $progress['class_id'],
                'progress'  => $progress['look_tvtime'],
                'duration'  => $progress['tvtime'],
                'last_time' => $progress['createtime'],
                'is_wc_look' => $progress['is_wc_look']
            ];
        }, $progressList);
    }


    /**用户课程学习情况看板
     * @param $userId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getUserLearningReport($userId)
    {
        // 已学习课程数
        $learnedCourses = CourseProgress::where('user_id', $userId)
            ->group('course_id')
            ->count();

        // 总学习时长(小时)
        $totalHours = CourseProgress::where('user_id', $userId)
                ->sum('look_tvtime') / 3600;

        // 最近学习记录
        $recent = CourseProgress::with(['course', 'class'])
            ->where('user_id', $userId)
            ->order('createtime', 'desc')
            ->limit(5)
            ->select();

        return [
            'learned_courses' => $learnedCourses,
            'total_hours' => round($totalHours, 1),
            'recent_learning' => $recent
        ];
    }
}