<?php

namespace app\admin\controller\life;

use app\admin\validate\life\CollegeTeachingValidate;
use app\controller\Curd;
use app\model\CollegeTeaching as teachingModel;
use support\Request;
use support\Response;

class CollegeTeachingController extends Curd
{
    public function __construct()
    {
        $this->model = new teachingModel();
        $this->validate = true;
        $this->validateClass = new CollegeTeachingValidate();
    }

    /**
     * @Desc 列表
     * @Author Gorden
     * @Date 2024/2/27 10:29
     *
     * @param Request $request
     * @return Response
     * @throws \support\exception\BusinessException
     */
    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $where['teaching_is_del'] = 0;
        $order = $request->get('order', 'desc');
        $field = $field ?? 'teaching_addTime';
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    /**
     * @Desc 联表
     * @Author Gorden
     * @Date 2024/3/20 14:53
     *
     * @param array $where
     * @param string|null $field
     * @param string $order
     * @return \Illuminate\Database\Query\Builder
     */
    protected function doSelect(array $where, string $field = null, string $order = 'desc')
    {
        $model = $this->model->with([
            'course' => function ($query) {
                $query->select('courses_id', 'courses_name');
            },
        ]);
        foreach ($where as $column => $value) {
            if (is_array($value)) {
                if ($value[0] === 'like' || $value[0] === 'not like') {
                    $model = $model->where($column, $value[0], "%$value[1]%");
                } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
                    $model = $model->where($column, $value[0], $value[1]);
                } elseif ($value[0] == 'in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereIn($column, $valArr);
                } elseif ($value[0] == 'not in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereNotIn($column, $valArr);
                } elseif ($value[0] == 'null') {
                    $model = $model->whereNull($column);
                } elseif ($value[0] == 'not null') {
                    $model = $model->whereNotNull($column);
                } elseif ($value[0] !== '' || $value[1] !== '') {
                    $model = $model->whereBetween($column, $value);
                }
            } else {
                $model = $model->where($column, $value);
            }
        }
        if ($field) {
            $model = $model->orderBy($field, $order);
        }
        return $model;
    }

    /**
     * @Desc 新增
     * @Author Gorden
     * @Date 2024/2/27 10:19
     *
     * @param Request $request
     * @return Response
     * @throws \support\exception\BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($this->validate && !$this->validateClass->scene('add')->check($request->post())) {
            return json_fail($this->validateClass->getError());
        }

        $data = $this->insertInput($request);
        $data['teaching_time'] = strtotime($data['teaching_time']);
        $this->doInsert($data);
        return json_success('success');
    }

    /**
     * @Desc 修改
     * @Author Gorden
     * @Date 2024/2/27 10:26
     *
     * @param Request $request
     * @return Response
     * @throws \support\exception\BusinessException
     */
    public function update(Request $request): Response
    {
        if ($this->validate && !$this->validateClass->scene('update')->check($request->post())) {
            return json_fail($this->validateClass->getError());
        }

        [$id, $data] = $this->updateInput($request);
        $data['teaching_time'] = strtotime($data['teaching_time']);
        $this->doUpdate($id, $data);
        return json_success('success');

    }

    /**
     * @Desc 删除
     * @Author Gorden
     * @Date 2024/2/27 10:35
     *
     * @param Request $request
     * @return Response
     * @throws \support\exception\BusinessException
     */
    public function delete(Request $request): Response
    {
        $ids = $this->deleteInput($request);
        $this->doSoftDelete($ids, ['teaching_is_del' => 1]);

        return json_success('success');
    }


    /**
     * @Desc
     * @Author Gorden
     * @Date 2024/2/27 10:30
     *
     * @param $query
     * @param $format
     * @param $limit
     * @return Response
     */
    protected function doFormat($query, $format, $limit): Response
    {
        $methods = [
            'select' => 'formatSelect',
            'tree' => 'formatTree',
            'table_tree' => 'formatTableTree',
            'normal' => 'formatNormal',
        ];
        $paginator = $query->paginate($limit);
        $total = $paginator->total();
        $items = $paginator->items();
        if (method_exists($this, "afterQuery")) {
            $items = call_user_func([$this, "afterQuery"], $items);
        }
        $format_function = $methods[$format] ?? 'formatNormal';
        foreach ($items as &$item) {
            $item->teaching_time = date('Y-m-d H:i:s',$item->teaching_time);
        }
        return call_user_func([$this, $format_function], $items, $total);
    }
}