<?php

namespace app\admin\controller\sys_manage;

use app\admin\validate\sys_manage\AdvValidate;
use app\controller\Curd;
use app\model\Adv;
use support\exception\BusinessException;
use support\Request;
use support\Response;

class AdvController extends Curd
{
    public function __construct()
    {
        $this->model = new Adv();
        $this->validate = true;
        $this->validateClass = new AdvValidate();
    }

    /** 列表
     * @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['adv_category'] = 'adv';
        $order = $request->get('order', 'desc');
        $field = $field ?? 'adv_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' => function ($query) {
                $query->select('category_id', 'category_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;
    }

    public function afterQuery($items)
    {
        foreach ($items as &$item) {
            if (!empty($item->adv_media_json)) {
                $mediaJson = json_decode($item->adv_media_json, true);
                if (isset($mediaJson['type'])) {
                    $item->adv_media_json = $mediaJson['type'];
                }
                if (isset($mediaJson['advType'])) {
                    $item->adv_type = $mediaJson['advType'];
                }
                if (isset($mediaJson['advMain'])) {
                    $item->adv_main = $mediaJson['advMain'];
                }
                if (isset($mediaJson['cover'])) {
                    $item->cover = getenv("STORAGE_DOMAIN") . $mediaJson['cover'];
                }
                if (empty($mediaJson)) {
                    $item->adv_media_json = "";
                }
            }
            if (!empty($item->adv_config_json)) {
                $configJson = json_decode($item->adv_config_json, true);
                $item->adv_cover_type = 'cover';
                if (!empty($configJson['sliderList'])) {
                    $item->adv_cover_type = 'slider';
                    $sliderList = [];
                    foreach ($configJson['sliderList'] as $slider) {
                        $sliderList[] = [
                            'cover' => getenv('STORAGE_DOMAIN') . $slider['url'],
                            'href' => $slider['href']
                        ];
                    }
                    $item->slider_list = $sliderList;
                }
                if (!empty($configJson['cover'])) {
                    $item->cover = getenv('STORAGE_DOMAIN') . $configJson['cover'];
                }
            }
        }

        return $items;
    }

    /**
     * @Desc
     * @Author Gorden
     * @Date 2024/3/27 10:24
     *
     * @param Request $request
     * @return array
     * @throws \support\exception\BusinessException
     */
    protected function insertInput(Request $request): array
    {
        $type = $request->post('adv_type', 0);
        $advMain = $request->post('adv_main', '');
        $cover = $request->post('cover', '');
        $advCoverType = $request->post('adv_cover_type');
        $sliderList = $request->post('slider_list');

        $data = $this->inputFilter($request->post());
        $mediaJson = [];
        if (!empty($data['adv_media'])) {
            $mediaJson = ['type' => $data['adv_media_json']];
        }
        if ($type != 0) {
            $mediaJson['advType'] = $type;
        }
        if ($type == 3) {
            $mediaJson['advMain'] = $advMain;
        }
        if (!empty($cover)) {
            $mediaJson['cover'] = str_replace(getenv("STORAGE_DOMAIN"), '', $cover);
        }

        $data['adv_media_json'] = json_encode($mediaJson);
        $configJson = [];
        // 轮播
        if ($advCoverType == 'slider') {
            $data['adv_href'] = '';
            foreach ($sliderList as $slider) {
                $configJson['sliderList'][] = [
                    'url' => str_replace(getenv('STORAGE_DOMAIN'), '', $slider['cover']),
                    'href' => $slider['href']
                ];
            }
        } elseif ($advCoverType == 'cover') {
            $configJson['cover'] = str_replace(getenv('STORAGE_DOMAIN'), '', $cover);
        }

        $data['adv_config_json'] = json_encode($configJson);

        return $data;
    }

    protected function updateInput(Request $request): array
    {
        $type = $request->post('adv_type', 0);
        $advMain = $request->post('adv_main', '');
        $cover = $request->post('cover', '');
        $advCoverType = $request->post('adv_cover_type');
        $sliderList = $request->post('slider_list');

        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());

        $model = $this->model->find($id);
        $configJson = [];
//        if (!empty($model->adv_config_json)) {
//            $configJson = json_decode($model->adv_config_json, true);
//        }

        $mediaJson = [];
        if (!empty($model->adv_media_json)) {
            $mediaJson = json_decode($model->adv_media_json, true);
            $mediaJson['type'] = $data['adv_media_json'];
        }
        if (!empty($data['adv_media_json'])) {
            $mediaJson['type'] = $data['adv_media_json'];
        }
        if ($type != 0) {
            $mediaJson['advType'] = $type;
        }
        if ($type == 3) {
            $mediaJson['advMain'] = $advMain;
        }
        if (!empty($cover)) {
            $mediaJson['cover'] = str_replace(getenv("STORAGE_DOMAIN"), '', $cover);
        }

        $data['adv_media_json'] = json_encode($mediaJson);

        // 轮播
        if ($advCoverType == 'slider') {
            $data['adv_href'] = '';
            unset($configJson['cover']);
            foreach ($sliderList as $slider) {
                $configJson['sliderList'][] = [
                    'url' => str_replace(getenv('STORAGE_DOMAIN'), '', $slider['cover']),
                    'href' => $slider['href']
                ];
            }
        } elseif ($advCoverType == 'cover') {
            unset($configJson['sliderList']);
            $configJson['cover'] = str_replace(getenv('STORAGE_DOMAIN'), '', $cover);
        }

        $data['adv_config_json'] = json_encode($configJson);

        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }
        unset($data[$primary_key]);
        return [$id, $data];
    }
}