<?php

namespace app\admin\controller\content;

use app\controller\Curd;
use app\model\Content;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use Tinywan\Jwt\JwtToken;

class SpecialController extends Curd
{
    public function __construct()
    {
        $this->model = new Content();
    }

    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $where['content_category'] = 'PAGE';
        $order = $request->get('order', 'desc');
        $field = $field ?? 'content_addtimes';
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    protected function doSelect(array $where, string $field = null, string $order = 'desc')
    {
        $model = $this->model;
        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;
    }

    protected function afterQuery($items)
    {
        foreach ($items as &$item) {
            if (!empty($item->content_config_json)) {
                $configJson = json_decode($item->content_config_json, true);
                if (isset($configJson['cover'])) {
                    $item->cover = getenv('STORAGE_DOMAIN') . $configJson['cover'];
                }
            }

            $item->content_main = htmlspecialchars_decode($item->content_main);
        }

        return $items;
    }

    protected function insertInput(Request $request): array
    {
        $data = $this->inputFilter($request->post());
        $configJson = [];
        if (!empty($request->post('cover'))) {
            $configJson['cover'] = str_replace(getenv("STORAGE_DOMAIN"), '', $request->post('cover'));
        }
        $data['content_config_json'] = json_encode($configJson);
        $data['content_updatetimes'] = time();
        $data['creator_user_id'] = JwtToken::getCurrentId();

        return $data;
    }

    protected function updateInput(Request $request): array
    {
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        $data['content_updatetimes'] = time();

        $model = $this->model->find($id);

        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }
        $configJson = [];
        if (!empty($request->post('cover'))) {
            $configJson = !empty($model->content_config_json) ? json_decode($model->content_config_json, true) : [];
            $configJson['cover'] = str_replace(getenv("STORAGE_DOMAIN"), '', $request->post('cover'));
        }
        $data['content_config_json'] = json_encode($configJson);

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