<?php

namespace app\admin\controller\sys_manage;

use app\admin\validate\sys_manage\AdvValidate;
use app\admin\validate\sys_manage\ArticleValidate;
use app\admin\validate\sys_manage\ContentValidate;
use app\controller\Curd;
use app\model\Adv;
use app\model\Article;
use app\model\Content;
use Firebase\JWT\JWT;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use Tinywan\Jwt\JwtToken;

class HealthyClassroomController extends Curd
{
    public function __construct()
    {
        $this->model = new Content();
        $this->validate = true;
        $this->validateClass = new ContentValidate();
    }

    /** 列表
     * @Desc
     * @Author Gorden
     * @Date 2024/3/5 10:00
     *
     * @param Request $request
     * @return Response
     * @throws \support\exception\BusinessException
     */
    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $where['content_category'] = 'CLASSROOM';
        $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->with('category','user');
        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;
    }

    public function afterQuery($items)
    {
        foreach ($items as &$item) {
//            if (!empty($item->content_title_prefix)) {
//                $item->content_title_prefix = ltrim($item->content_title_prefix, '【');
//                $item->content_title_prefix = rtrim($item->content_title_prefix, '】');
//            }
            if (!empty($item->content_config_json)) {
                $configJson = json_decode($item->content_config_json, true);
                foreach ($configJson as $key => $item1) {
                    if (substr($item1, 0, 4) != 'http') {
                        $configJson[$key] = getenv('STORAGE_DOMAIN') . $item1;
                    }
                }
                $item->content_config_json = $configJson;
            }
        }

        return $items;
    }

    public function insert(Request $request): Response
    {
        if ($this->validate && !$this->validateClass->scene('add')->check($request->post())) {
            return json_fail($this->validateClass->getError());
        }

        try {
            $data = $this->insertInput($request);
            $data['creator_user_id'] = JwtToken::getCurrentId();
            $this->doInsert($data);
        } catch (BusinessException $customException) {
            return json_fail($customException->getMessage());
        } catch (\Exception $e) {
            dump($e->getMessage());
            return json_fail('数据写入失败11');
        }
        return json_success('success');
    }

    /**
     * @Desc
     * @Author Gorden
     * @Date 2024/3/27 10:24
     *
     * @param Request $request
     * @return array
     * @throws \support\exception\BusinessException
     */
    protected function insertInput(Request $request): array
    {
        $params = $request->post();
        if (!empty($params['content_config_json'])){
            foreach ($params['content_config_json'] as $key => $item){
                $params['content_config_json'][$key] = str_replace(getenv("STORAGE_DOMAIN"),'',$item);
            }

            $params['content_config_json'] = json_encode($params['content_config_json'], JSON_UNESCAPED_UNICODE);
        }else{
            $params['content_config_json'] = '[]';
        }
        $data = $this->inputFilter($params);

        $data['content_title_prefix'] = $data['content_title_prefix'];
        $data['content_category'] = 'CLASSROOM';

        return $data;
    }

    protected function updateInput(Request $request): array
    {
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $params = $request->post();
        if (!empty($params['content_config_json'])){
            foreach ($params['content_config_json'] as $key => $item){
                $params['content_config_json'][$key] = str_replace(getenv("STORAGE_DOMAIN"),'',$item);
            }

            $params['content_config_json'] = json_encode($params['content_config_json'], JSON_UNESCAPED_UNICODE);
        }
        $data = $this->inputFilter($params);
        $data['content_title_prefix'] = $data['content_title_prefix'];
        $data['content_updatetimes'] = time();
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }
        unset($data[$primary_key]);
        return [$id, $data];
    }
}