<?php

namespace app\api\controller;

use app\api\middleware\Auth;
use app\api\validate\CourseValidate;
use app\BaseController;
use think\facade\Request;
use app\model\CourseComment as courseCommentModel;

class CourseComment extends BaseController
{

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

    // 获取评论列表
    public function list()
    {
        $vo = (new CourseValidate())->goCheck(['course_id']);
        if ($vo !== true) {
            return $vo;
        }

        $courseId = Request::param('course_id/d', 0);
        $page = Request::param('page/d', 1);
        $pageSize = Request::param('pageSize/d', 10);

        $comments = courseCommentModel::getCommentList($courseId, $page, $pageSize);

        return $this->returnMsg('success',1, $comments);
    }

    // 发表评论
    public function create()
    {

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

        $userId = $this->request->userId;
        $courseId = Request::param('course_id/d', 0);
        $parentId = Request::param('parent_id/d', 0);
        $content = Request::param('content/s', '');


        // 如果是回复，检查父评论是否存在
        if ($parentId > 0) {
            $parentComment = courseCommentModel::where('id', $parentId)
                ->where('course_id', $courseId)
                ->find();

            if (!$parentComment) {
                return $this->returnMsg('父评论不存在');
            }

            // 限制只能回复一级评论
            if ($parentComment->parent_id > 0) {
                return $this->returnMsg('只能回复一级评论');
            }
        }

        // 创建评论
        $comment = courseCommentModel::create([
            'course_id' => $courseId,
            'user_id' => $userId,
            'parent_id' => $parentId,
            'content' => $content
        ]);

        return $this->returnMsg('success',1,$comment);


    }

    // 删除评论
    public function delete()
    {
        $userId = $this->request->userId;
        $commentId = Request::param('comment_id/d', 0);

        $comment = courseCommentModel::where('id', $commentId)
            ->where('user_id', $userId)
            ->find();

        if (!$comment) {
            return $this->returnMsg('评论不存在或无权删除');
        }

        $comment->together(['replies'])->delete();

        return $this->returnMsg('删除成功',1);

    }

}