<?php

namespace app\admin\controller\life;

use app\admin\validate\life\CinemaPerformersValidate;
use app\model\CinemaPerformers as CinemaPerformersModel;
use app\controller\Curd;
use support\exception\BusinessException;
use support\Request;
use support\Response;

class CinemaPerformersController extends Curd
{
    const PERFORMERS_TYPE = [
        1 => '导演',
        2 => '演员'
    ];

    public function __construct()
    {
        $this->model = new CinemaPerformersModel();
        $this->validate = true;
        $this->validateClass = new CinemaPerformersValidate();
    }

    /**
     * @Desc 人员列表
     * @Author Gorden
     * @Date 2024/3/21 9:11
     *
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $where['performers_is_del'] = 0;
        $order = $request->get('order', 'desc');
        $field = $field ?? 'performers_create_time';
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    protected function afterQuery($items)
    {
        foreach ($items as &$item) {
            $item->performers_type_text = self::PERFORMERS_TYPE[$item->performers_type];
            $item->performers_img = getenv("STORAGE_DOMAIN") . $item->performers_img;
        }

        return $items;
    }

    /**
     * @Desc 新增数据处理
     * @Author Gorden
     * @Date 2024/3/21 8:59
     *
     * @param Request $request
     * @return array
     * @throws \support\exception\BusinessException
     */
    protected function insertInput(Request $request): array
    {
        $data = $this->inputFilter($request->post());
        $data['performers_img'] = str_replace(getenv("STORAGE_DOMAIN"), '', $data['performers_img']);

        return $data;
    }

    /**
     * @Desc 更新数据处理
     * @Author Gorden
     * @Date 2024/3/21 9:02
     *
     * @param Request $request
     * @return array
     * @throws BusinessException
     */
    protected function updateInput(Request $request): array
    {
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        $data['performers_img'] = str_replace(getenv("STORAGE_DOMAIN"), '', $data['performers_img']);
        // 验证是否存在
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }

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