<?php

namespace app\admin\controller\life;

use app\admin\validate\life\CollegeTeacherValidate;
use app\controller\Curd;
use app\model\CollegeTeacher as TeacherModel;
use support\exception\BusinessException;
use support\Request;
use support\Response;

class CollegeTeacherController extends Curd
{
    public function __construct()
    {
        $this->model = new TeacherModel();
        $this->validate = true;
        $this->validateClass = new CollegeTeacherValidate();
    }

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

    /**
     * @Desc
     * @Author Gorden
     * @Date 2024/3/20 11:55
     *
     * @param $items
     * @return mixed
     */
    protected function afterQuery($items)
    {
        foreach ($items as &$item){
            $item->teacher_img = getenv("STORAGE_DOMAIN").$item->teacher_img;
        }
        return $items;
    }

    /**
     * @Desc
     * @Author Gorden
     * @Date 2024/3/20 11:55
     *
     * @param Request $request
     * @return array
     * @throws \support\exception\BusinessException
     */
    protected function insertInput(Request $request): array
    {
        $data = $this->inputFilter($request->post());
        $data['teacher_img'] = str_replace(getenv('STORAGE_DOMAIN'),'',$data['teacher_img']);

        return $data;
    }

    protected function updateInput(Request $request): array
    {
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }

        $data['teacher_img'] = str_replace(getenv('STORAGE_DOMAIN'),'',$data['teacher_img']);

        unset($data[$primary_key]);
        return [$id, $data];
    }

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

        return json_success('success');
    }
}