<?php

namespace addons\exam\controller;

use addons\exam\enum\CommonStatus;
use addons\exam\model\QuestionCollectModel;
use addons\exam\model\QuestionModel;
use addons\exam\model\UserModel;
use app\admin\model\exam\QuestionWrongModel;


/**
 * 试题接口
 */
class Question extends Base
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * 看题模式
     */
    public function lookPage()
    {
        $model = new QuestionModel();
        $total = $model->where('cate_id', $this->request->param('cate_id'))->count('id');
        $this->success('', compact('total'));
    }

    /**
     * 练习模式
     */
    public function train()
    {
        $param            = $this->request->param();
        $param['user_id'] = $this->auth->id;

        // 验证是否需要绑定手机号
        //UserModel::isMustBindMobile($this->auth->getUser());

        $list = QuestionModel::getList($param);
        // $total     = $list['total'];

        $this->success('', $list);
    }

    /**
     * 根据关键词模糊查询10条题目
     */
    public function search()
    {
        $query = QuestionModel::with(
            [
                'cates'          => function ($query) {
                    $query->field('id,name');
                },
                'materialParent' => function ($query) {
                    $query->field('id,title');
                },
            ]
        )->where('status', CommonStatus::NORMAL);

        if ($keyword = input('keyword/s', '', 'trim,strip_tags,htmlspecialchars,xss_clean')) {
            if (mb_strlen($keyword) < 2) {
                $this->error('请输入不少于2个字的关键词进行搜索');
            }

            $query->where('title', 'like', '%' . $keyword . '%');
        }

        if ($sort_type = input('sort_type/s')) {
            $query->order($sort_type);
        }

        if (input('sort_rand/d', 0)) {
            $query->orderRaw('rand()');
        }

        $list = $query->paginate(15, true)->toArray();
        // 最多搜索5页
        if (input('page/d') >= 5) {
            $list['has_more'] = false;
        }

        $this->success('', ['list' => $list]);
    }

    /**
     * 试题详情
     */
    public function detail()
    {
        $id = input('id');
        $this->success('', (new QuestionModel)->get($id));
    }

    /**
     * 收藏列表
     */
    public function collectList()
    {
        $user_id         = $this->auth->id;
        $collectQuestion = new QuestionCollectModel();

        $list  = $collectQuestion::with('question')->where('user_id', $user_id)->order('id desc')->paginate(999, true);
        $total = $collectQuestion::where('user_id', $user_id)->count();

        $this->success('', compact('list', 'total'));

        // $list  = $collectQuestion::with([
        //     'question.materialQuestions.question'
        // ])->where('user_id', $user_id)->order('id desc')->paginate(999, true);
        // $total = $list->count();
        //
        // $list = $list->toArray();
        // ddd($list);
        // // 合并材料题子题目
        // $list['data'] = QuestionModel::mergeMaterialQuestions($list['data']);

        // $this->success('', compact('list', 'total'));
    }

    /**
     * 添加收藏
     */
    public function collectAdd()
    {
        if (!$question_id = input('question_id/d', 0)) {
            $this->error('缺少题目ID');
        }
        if (!QuestionModel::where('id', $question_id)->count()) {
            $this->error('题目数据不存在');
        }

        if ($res = QuestionCollectModel::updateOrCreate(
            [
                'user_id'     => $this->auth->id,
                'question_id' => $question_id
            ],
            [
                'user_id'     => $this->auth->id,
                'question_id' => $question_id
            ])
        ) {
            $this->success('收藏成功', $res);
        }
        $this->error('收藏失败');
    }

    /**
     * 取消收藏
     */
    public function collectCancel()
    {
        if (!$question_id = input('question_id/d', 0)) {
            $this->error('缺少题目ID');
        }
        $result = QuestionCollectModel::where('question_id', $question_id)->where('user_id', $this->auth->id)->delete();

        if ($result) {
            $this->success('取消成功');
        }
        $this->error('取消失败');
    }

    /**
     * 获取错题列表
     */
    public function wrongList()
    {
        $user_id = $this->auth->id;

        if ($ids = input('question_ids')) {
            $total = QuestionWrongModel::where('user_id', $user_id)->whereIn('question_id', $ids)->count();
            $list  = $total ? QuestionWrongModel::with('question')
                ->whereIn('question_id', $ids)
                ->where('user_id', $user_id)
                ->order('id desc')
                ->paginate(999, true)->toArray() : [];
        } else {
            $total = QuestionWrongModel::where('user_id', $user_id)->count();
            $list  = $total ? QuestionWrongModel::with('question')
                ->where('user_id', $user_id)
                ->order('id desc')
                ->paginate(999, true)->toArray() : [];
        }

        if (isset($list['data']) && $list['data']) {
            $questions = [];
            foreach ($list['data'] as $item) {
                $questions[] = array_merge($item['question'], ['wrong_id' => $item['id'], 'user_answer' => $item['user_answer']]);
            }
//            $list['data'] = \addons\exam\model\QuestionModel::isCollected($user_id, $questions);
            $list['data'] = $questions;
        } else {
            $list['data'] = [];
        }

        $this->success('', compact('list', 'total'));
    }

    /*
     * 记录错题
     */
    public function wrongAdd()
    {
        if (!$question_id = input('question_id/d', 0)) {
            $this->error('缺少题目ID');
        }

        if (QuestionWrongModel::add($this->auth->id, $question_id))
            $this->success('记录成功');
        else
            $this->error('记录失败');
    }

    /**
     * 删除错题
     */
    public function wrongDelete()
    {
        if (!$question_id = input('question_id/d', 0)) {
            $this->success('缺少错题ID');
        }

        if (QuestionWrongModel::where('question_id', $question_id)->where('user_id', $this->auth->id)->delete()) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }

    /**
     * 清空所有错题
     */
    public function wrongClear()
    {
        if (QuestionWrongModel::where('user_id', $this->auth->id)->delete()) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }
}
