<?php

namespace App\Http\Controllers\Admin;

use App\Models\Course;
use App\Models\RemarkDetail;
use App\Models\Teacher;
use App\Models\TeacherCourse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class TeacherController extends Controller
{
    protected $redirect_index = '/admin/Teacher/index';

    protected $view_path = 'admin.teachers.';

    protected $pre_uri = '/admin/Teacher/';

    protected $model_name = '讲师';

    protected $model;

    public function __construct()
    {
        parent::__construct();
        $this->model = new Teacher();
    }

    public function index(Request $request)
    {
        $list = $this->model->where('id', '>', 0)->orderBy('created_at', 'desc');

        if(!empty($request->input('keyword')) && !empty(trim($request->input('keyword')))) {
            $keyword = '%' . trim($request->input('keyword')) . '%';
            $list = $list->where('name', 'like', $keyword);
        }

        $list = $list->paginate()->withPath($this->getPaginateUrl());

        foreach($list as $item) {
            $item->average_score = RemarkDetail::where('remark_id', $item->id)->get()->avg('score');
            $item->average_score = round($item->average_score, 1);
        }

        list($pre_uri, $model_name) = array($this->pre_uri, $this->model_name);
        return view($this->view_path . 'index', compact('list', 'pre_uri', 'model_name'));
    }

    public function create(Request $request)
    {
        $courses = Course::all();

        list($pre_uri, $model_name, $model) = array($this->pre_uri, $this->model_name, $this->model);
        return view($this->view_path . 'create', compact('pre_uri', 'model_name', 'model', 'courses', 'teachers'));
    }

    public function store(Request $request)
    {
        if(!$request->isMethod('POST')) {
            return $this->showWarning('访问错误');
        }

        if(empty($request->input('data')) || !is_array($request->input('data'))) {
            return $this->showWarning('数据错误');
        }

        $validator = Validator::make($request->input('data'), [
            'phone' => 'required|unique:teachers',
            'password' => 'required|min:6',
        ], [
            'phone.required' => '手机必填',
            'phone.unique' => '手机已存在',
            'password.required' => '密码必填',
            'password.min' => '密码不少于6位',
        ]);
        if($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $data = $request->input('data');
        $data['password'] = bcrypt($data['password']);

        $res = $this->model->create($data);
        if(!$res) {
            return $this->showWarning('数据库保存失败！');
        }

        if(!empty($request->input('courses'))) {
            TeacherCourse::where('teacher_id', $res->id)->delete();
            foreach($request->input('courses') as $item) {
                TeacherCourse::create([
                    'teacher_id' => $res->id,
                    'course_id' => $item
                ]);
            }
        }

        return $this->showMessage('操作成功', $this->redirect_index);
    }

    public function edit(Request $request)
    {
        if(empty($request->input('id')) || empty($item = $this->model->find($request->input('id')))) {
            return $this->showWarning('数据错误！');
        }

        $courses = Course::all();
        list($pre_uri, $model_name, $model) = array($this->pre_uri, $this->model_name, $this->model);

        $ids_string = $item->courses->implode('id', ',');
        return view($this->view_path . 'edit', compact('item','pre_uri', 'model_name', 'model', 'courses', 'ids_string'));
    }

    public function update(Request $request)
    {
        if(!$request->isMethod('POST')) {
            return $this->showWarning('访问错误');
        }

        if(empty($request->input('id')) || empty($request->input('data')) || !is_array($request->input('data'))) {
            return $this->showWarning('数据错误');
        }

        $validator = Validator::make($request->input('data'), [
            'phone' => 'required'
        ], [
            'phone.required' => '手机必填'
        ]);

        if($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $data = $request->input('data');

        $tmp = $this->model->where([
            ['phone', '=', $data['phone']],
            ['id', '<>', $request->input('id')],
        ])->first();
        if(!empty($tmp)) {
            $validator->errors()->add('phone', '手机号已存在');
            return back()->withErrors($validator)->withInput();
        }

        if($request->has('is_update_password') && $request->input('is_update_password') == 1) {
            $data['password'] = bcrypt($request->input('password', 123456));
        }

        $res = $this->model->where('id', $request->input('id'))->update($data);
        if(!$res) {
            return $this->showWarning('数据库保存失败！');
        }

        $teacher = $this->model->find($request->input('id'));
        if(empty($teacher)) {
            return $this->showWarning('找不到讲师！');
        }
        if(!empty($request->input('courses'))) {
            TeacherCourse::where('teacher_id', $teacher->id)->delete();
            foreach($request->input('courses') as $item) {
                TeacherCourse::create([
                    'teacher_id' => $teacher->id,
                    'course_id' => $item
                ]);
            }
        }

        return $this->showMessage('操作成功', $this->redirect_index);
    }

    public function delete(Request $request)
    {
        if(!$request->isMethod('POST')) {
            return $this->showWarning('访问错误');
        }
        if(empty($request->input('id')) || empty($item = $this->model->find($request->input('id')))) {
            return $this->showWarning('访问错误');
        }

        TeacherCourse::where('teacher_id', $item->id)->delete();
        $res = $item->delete();
        if(!$res) {
            return $this->showWarning('数据库删除失败');
        }
        return $this->showMessage('操作成功');
    }
}
