<?php

namespace App\Http\Controllers\Api;

use App\Models\Answer;
use App\Models\Course;
use App\Models\Module;
use App\Models\Question;
use App\Models\Subject;
use App\Models\Unit;
use App\Models\UserAnswer;
use App\Models\UserCourse;
use App\User;
use Exception;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;


use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class CountController extends BaseController
{
    // pre-test统计接口1 完成人数、平均分（三个学科，兴趣题目的平均分）（表格1-1）
    public function preTestAvg() {
        $users = UserCourse::where('unit_id', null)->where('type', 1)->get()->groupBy('user_id')->count();
        $score1 = UserCourse::where('subject_id', 1)->where('unit_id', null)->where('type', 1)->avg('score');
        $score2 = UserCourse::where('subject_id', 2)->where('unit_id', null)->where('type', 1)->avg('score');
        $score3 = UserCourse::where('subject_id', 3)->where('unit_id', null)->where('type', 1)->avg('score');
        $score4 = UserCourse::where('subject_id', 4)->where('unit_id', null)->where('type', 1)->avg('score');
        $score5 = UserCourse::where('subject_id', 5)->where('unit_id', null)->where('type', 1)->avg('score');
        $score6 = UserCourse::where('unit_id', null)->where('type', 2)->avg('score');
        $data = [
            'No' => number_format($users, 0),
            'Chem' => number_format($score1, 1),
            'Bio' => number_format($score2, 1),
            'Lab' => number_format($score3, 1),
            'motivation_avg' => number_format($score6, 1),
            'Subject4' => number_format($score4, 1),
            'Subject5' => number_format($score5, 1)
        ];
        return $this->response($data);
    }

    // pre-test知识类型每个问题的答题人数（表格1-2）
    public function preTestNo() {
        $subjects = Subject::query()->get();
        foreach($subjects as $subject) {
            $questions = Question::where('subject_id', $subject->id)->where('unit_id', null)->where('type', 1)->get();
            foreach($questions as $question) {
                $userAnswers = UserAnswer::where('question_id', $question->id)->get()->groupBy('user_id')->count();
                $question->count = $userAnswers;
            }
            $subject->questions = $questions;
        }
        return $this->response($subjects);
    }

    // pre-test兴趣问题的答题人数和平均分（表格1-3）
    public function preTestMotivation() {
        // 测试问题的兴趣问题
        $questions = Question::where('unit_id', null)->where('type', 2)->get();

        foreach($questions as $question) {
            $userAnswers = UserAnswer::where('question_id', $question->id)->get()->groupBy('answer');
            // 每个问题的人数统计
            $question->userAnswers = $userAnswers;
            // 每个问题的平均分
            $avg = UserAnswer::where('question_id', $question->id)->avg('answer');
            $question->avg = ceil($avg);
        }
        return $this->response($questions);
    }

    // 学生测试列表（表格1-4）
    public function preTestStudent(Request $request) {
        // 学生数据
        $per_page = $request->input('per_page') ?: 10;
        $students = User::where('role', 3)->paginate($per_page);
        foreach($students as $student) {
            $subjects = Subject::query()->get();
            foreach($subjects as $subject) {
                // 测试学科的成绩
                $score = UserAnswer::where('unit_id', null)->where('subject_id', $subject->id)->where('user_id', $student->id)->where('type', 1)->whereRaw('answer=correct_answer')->count();
                $student[$subject->name] = $score;
            }

            // 兴趣测试的
            $motivation_score  = UserAnswer::where('unit_id', null)->where('user_id', $student->id)->where('type', 2)->avg('answer');
            $student->motivation_score = ceil($motivation_score);
        }

        return $this->response($students);
    }

    // 统计说明（表格2-2）
    // 1.  questions 中 unit_id为null的为pre-test的问题
    // 2.  user_answers中 unit_id为null的为pre-test的答案
    // 3.  user_course表示学生已完成该某单元的题目，type1为第一次测验，type2为第二次测验，score为该次测验分数
    // 通过学科id查询学科下学生完成评估的数量
    public function countAssement(Request $request) {
        $subject = Subject::findOrFail($request->input('subject_id'));
        // 查询学科下所有的单元
        $units = $subject->units;

        foreach($units as $unit) {
            $course = Course::where('unit_id', $unit->id)->where('name', 'like', '%assessment%')->first();
            if(!$course) return $this->safeException('课程数据异常');
            $unit->num_count = $course->user_courses->count();
        }

        return $this->response($units);
    }

    // 某学科两次测验的平均分（表格2-1）
    public function countPreTest(Request $request) {
        $subject = Subject::findOrFail($request->input('subject_id'));
        // 查询学科下所有的单元
        $units = $subject->units;

        foreach($units as $unit) {
            $course = Course::where('unit_id', $unit->id)->where('name', 'like', '%Assessment%')->first();
            if(!$course) return $this->safeException('课程数据异常');
            $questions = Question::where('unit_id', $unit->id)->count();
            if($questions == 0 ) $questions = 10;
            $score1 = UserCourse::where('unit_id', $unit->id)->where('turn', 1)->avg('score');
            if($score1) $score1 = $score1/$questions;
            $score2 = UserCourse::where('unit_id', $unit->id)->where('turn', 2)->avg('score');
            if($score2) $score2 = $score2/$questions;
            $unit->first_attempt = round($score1, 2)*100 . '%';
            $unit->highest_score = round($score2, 2)*100 . '%';
        }
        return $this->response($units);
    }

    // 统计所有学科，所有模块的数据（first_attempt highest_score noOfStudents missingData）
    public function countSubject(Request $request) {
        $subjects = Subject::query()->get();

        foreach($subjects as $subject) {
            // 计算该学科 的 两次pre-test
            $questions = Question::where('subject_id', $subject->id)->where('unit_id', null)->pluck('id')->toArray();
            $answers1 = UserAnswer::whereIn('question_id', $questions)
                                    ->where('type', 1)
                                    ->whereRaw('answer=correct_answer')
                                    ->get();
            $subject->pre_test->first_attempt = round(($answers1/$questions), 2) * 100;

            $answers2 = UserAnswer::whereIn('question_id', $questions)
                                    ->where('type', 2)
                                    ->whereRaw('answer=correct_answer')
                                    ->get();
            $subject->pre_test->highest_score = round(($answers2/$questions), 2) * 100;

            // $subject->pre_test->numOfStudents = UserCourse::where('subject_id', $subject->id)->where('unit_id', null)

            // $modules = Module::where('subject_id', $subject)->get();
            // foreach($modules as $module) {
            //     $subject[$model->name]->
            // }
        }
        // 查询学科下所有的单元
        $units = $subject->units;

        foreach($units as $unit) {
            $course = Course::where('unit_id', $unit->id)->where('name', 'like', '%assessment%')->first();
            if(!$course) return $this->safeException('课程数据异常');
            $questions = Question::where('unit_id', $unit->id)->count();
            if($questions == 0 ) return $this->safeException('问题数据异常');
            $score1 = UserCourse::where('unit_id', $unit->id)->where('type', 1)->avg('score');
            $score2 = UserAnswer::where('unit_id', $unit->id)->where('type', 2)->whereRaw('answer=correct_answer')->count();
            $unit->first_attempt = $score1;
            $unit->highest_score = $score2;
        }
        return $this->response($units);
    }

    // 表2-3
    public function countProjectOverView1(Request $request) {

        // 表头
        $modules = Module::where('subject_id', $request->subject_id)->get();
        $unitKey = 1;
        foreach($modules as $module) {
            $units = Unit::where('module_id', $module->id)->get();
            foreach($units as $index => $unit) {
                $unit->slot = 'title' . $unit->id;
                $unit->index = 'u' . $unitKey;
                $unitKey ++;
            }
            $module->unitData = $units;
        }

        // 表数据
        $lines = [
            [],
            [],
            [],
            [],
            []
        ];
        $units = $units = Unit::where('subject_id', $request->subject_id)->get();

        foreach($lines as $index => $line) {

            foreach($units as $index2 => $unit) {
                $key = 'u' . ($index2 + 1);
                if($index == 0) {
                    // first_attempt
                    $lines[$index][$key] = 1;
                }
                if($index == 1) {
                    // first_range
                    $lines[$index][$key] = 1;
                }
                if($index == 2) {
                    // seoond_attempt
                    $lines[$index][$key] = 1;
                }
                if($index == 3) {
                    // second_range
                    $lines[$index][$key] = 1;
                }
                if($index == 4) {
                    // no of student
                    $lines[$index][$key] = 1;
                }
            }
        }

        $data = [
            'modules' => $modules,
            'lines' => $lines
        ];
        return $this->response($data);
    }


    // 表2-4
    public function countProjectOverView2(Request $request) {
        // 表数据
        $lines = [
            [
                'u1' => 1,
                'u2' => 1,
                'u3' => 1,
                'u4' => 1,
                'u5' => 1,
                'u6' => 1,
                'u7' => 1,
                'u8' => 1,
                'u9' => 1
            ],
            [
                'u1' => 1,
                'u2' => 1,
                'u3' => 1,
                'u4' => 1,
                'u5' => 1,
                'u6' => 1,
                'u7' => 1,
                'u8' => 1,
                'u9' => 1
            ],
            [
                'u1' => 1,
                'u2' => 1,
                'u3' => 1,
                'u4' => 1,
                'u5' => 1,
                'u6' => 1,
                'u7' => 1,
                'u8' => 1,
                'u9' => 1
            ],
            [
                'u1' => 1,
                'u2' => 1,
                'u3' => 1,
                'u4' => 1,
                'u5' => 1,
                'u6' => 1,
                'u7' => 1,
                'u8' => 1,
                'u9' => 1
            ],
        ];
        return $this->response($lines);
    }


    // 表2-5
    public function countProjectOverView3(Request $request) {

        // 学生数据
        $per_page = $request->input('per_page') ?: 10;
        $students = User::where('role', 3)->paginate($per_page);
        $units = Unit::where('subject_id', $request->subject_id)->get();
        foreach($students as $student) {
            $firstAttempt = [];
            $highestScore = [];
            foreach($units as $index => $unit) {
                $key = 'u' . ($index + 1);
                $firstAttempt[$key] =  '10%';
                $highestScore[$key] =  '10%';
            }
            $student->firstAttempt = $firstAttempt;
            $student->highestScore = $highestScore;
        }

        return $this->response($students);
    }


    // 修改
    public function updateUnit(Request $request) {
        $Unit = Unit::findOrFail($request->input('id'));
        $data = $Unit->update([
            'name' => $request->input('name'),
            'title' => $request->input('title'),
            'order' => $request->input('order')
        ]);
        return $this->response($data);
    }

    // 删除
    public function deleteUnit(Request $request) {
        $model = Unit::findOrFail($request->input('id'));
        if(!empty($model->courses->count())) return $this->safeException('该模块下有相关课程，请移除课程后重试');
        $model->delete();
        return $this->response($model);
    }

    // 通过unit_id计算成绩（两次测验）  平均分 范围 完成的学生数量 学生缺失的数量
    public function countUnit($unit_id) {
        $score1 = UserCourse::where('unit_id', $unit_id)->where('type', 1)->avg('score');
        $score2 = UserCourse::where('unit_id', $unit_id)->where('type', 2)->avg('score');
        $min1 = UserCourse::where('unit_id', $unit_id)->where('type', 1)->orderBy('score', 'desc')->first()->score;
        $min2 = UserCourse::where('unit_id', $unit_id)->where('type', 2)->orderBy('score', 'desc')->first()->score;
        $max1 = UserCourse::where('unit_id', $unit_id)->where('type', 1)->orderBy('score', 'asc')->first()->score;
        $max2 = UserCourse::where('unit_id', $unit_id)->where('type', 2)->orderBy('score', 'asc')->first()->score;
        $count = UserCourse::where('unit_id', $unit_id)->where('type', 1)->count();
        $data = [
            'first_attempt' => [
                'avg' => $score1,
                'min' => $min1,
                'max' => $max1
            ],
            'highest_score' => [
                'avg' => $score2,
                'min' => $min2,
                'max' => $max2
            ],
            'num_complete' => $count
        ];
        return $data;
    }

    public function countModule($module_id) {
        $score1 = UserCourse::where('module_id', $module_id)->where('type', 1)->avg('score');
        $score2 = UserCourse::where('module_id', $module_id)->where('type', 2)->avg('score');

        // 模块下完成所有单元测试的人数
        $num = Unit::where('module_id', $module_id)->count();

        $users = UserCourse::where('module_id', $module_id)->where('type', 1)->get()->groupBy('user_id');
        $num_complete = 0;
        foreach($users as $user) {
            if($user->count() == $num) $num_complete++;
        }
        $num_count = $users->count();

        $data = [
            'first_attempt_avg' => $score1 ?: 0,
            'highest_score_avg' => $score2 ?: 0,
            'num_complete' => $num_complete,
            'num_miss' => $num_count - $num_complete,
            'num_count' => $num_count
        ];
        return $data;
    }

    public function countPretestModel($module_id) {
        $score1 = UserCourse::where('module_id', $module_id)->where('type', 1)->avg('score');
        $score2 = UserCourse::where('module_id', $module_id)->where('type', 2)->avg('score');

        // 模块下完成所有单元测试的人数
        $num = Unit::where('module_id', $module_id)->count();

        $users = UserCourse::where('module_id', $module_id)->where('type', 1)->get()->groupBy('user_id');
        $num_complete = 0;
        foreach($users as $user) {
            if($user->count() == $num) $num_complete++;
        }
        $num_count = $users->count();

        $data = [
            'first_attempt_avg' => $score1 ?: 0,
            'highest_score_avg' => $score2 ?: 0,
            'num_complete' => $num_complete,
            'num_miss' => $num_count - $num_complete,
            'num_count' => $num_count
        ];
        return $data;
    }

}

