<?php

namespace app\admin\controller\content;

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

class SubjectController 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'] = 'SUBJECT';
        $field = 'content_addtimes';
        $order = 'DESC';
        $this->model = $this->model->with('user');
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    /**
     * @Desc 详情
     * @Author Gorden
     * @Date 2024/11/8 13:24
     *
     * @param Request $request
     * @return Response
     */
    public function info(Request $request): Response
    {
        $primaryKey = $this->model->getKeyName();

        $data = $this->model->with('user')->where($primaryKey, $request->get('id'))->first();

        if (method_exists($this, "afterInfoQuery")) {
            $data = call_user_func([$this, "afterInfoQuery"], $data);
        }

        return json_success('', $data);
    }

    public function afterInfoQuery($item)
    {
        if (!empty($item->content_config_json)) {
            $contentConfigJson = json_decode($item->content_config_json, true);
            if (!empty($contentConfigJson['cate'])) {
                $item->cate = $contentConfigJson['cate'];
            }
            if (!empty($contentConfigJson['goods'])) {
                $goodsIds = array_column($contentConfigJson['goods'], 'goods_id');
                $goodsList = Goods::whereIn('goods_id', $goodsIds)
                    ->select('goods_cover', 'goods_id', 'goods_name', 'goods_market_price', 'goods_sales_price')
                    ->get()
                    ->toArray();
                $formGoods = [];
                foreach ($goodsList as $key => $goods) {
                    foreach ($contentConfigJson['goods'] as $cateGoods) {
                        if ($cateGoods['goods_id'] == $goods['goods_id']) {
                            $goodsList[$key]['cate'] = $cateGoods['cate'];
                            $formGoods[] = [
                                'cate' => $cateGoods['cate'],
                                'goods_id' => $cateGoods['goods_id'],
                            ];
                        }
                    }
                    $goodsList[$key]['goods_cover'] = getenv('STORAGE_DOMAIN') . $goods['goods_cover'];
                }
                $item->goods = $formGoods;
                $item->goodsList = $goodsList;
            }
            if (!empty($contentConfigJson['slider'])) {
                $sliders = [];
                $originSliders = [];
                foreach ($contentConfigJson['slider'] as $slider) {
                    if (!empty($slider['url'])) {
                        $sliders[] = [
                            'url' => getenv('STORAGE_DOMAIN') . $slider['url'],
                            'href' => $slider['href'] ?? ''
                        ];
                        $originSliders[] = getenv('STORAGE_DOMAIN') . str_replace('/thumb', '', $slider['url']);
                    }
                }
                $item->sliders = $sliders;
                $item->originSliders = $originSliders;
            }
        }

        return $item;
    }

    public function insertInput(Request $request): array
    {
        $params = $request->post();
        $data = $this->inputFilter($request->post());
        $contentConfigJson = [];
        if (!empty($params['sliders'])) {
            $contentConfigJson['slider'] = [];
            foreach ($params['sliders'] as $slider) {
                $contentConfigJson['slider'][] = [
                    'url' => str_replace(getenv('STORAGE_DOMAIN'), '', $slider['url']),
                    'href' => $slider['href']
                ];
            }
        }
        if (!empty($params['cate'])) {
            $contentConfigJson['cate'] = $params['cate'];
        }
        if (!empty($params['goods'])) {
            $contentConfigJson['goods'] = $params['goods'];
        }
        $data['content_config_json'] = json_encode($contentConfigJson);
        $data['creator_user_id'] = JwtToken::getCurrentId();
        $data['join_content_category_id'] = 207;

        return $data;
    }

    protected function updateInput(Request $request): array
    {
        $params = $request->post();
        $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);
        }
        $contentConfigJson = [];
        if (!empty($model->content_config_json)) {
            $contentConfigJson = json_decode($model->content_config_json, true);
        }
        if (!empty($params['sliders'])) {
            $contentConfigJson['slider'] = [];
            foreach ($params['sliders'] as $slider) {
                $contentConfigJson['slider'][] = [
                    'url' => str_replace(getenv('STORAGE_DOMAIN'), '', $slider['url']),
                    'href' => $slider['href']
                ];
            }
        }else{
            unset($contentConfigJson['slider']);
        }
        if (!empty($params['cate'])) {
            $contentConfigJson['cate'] = $params['cate'];
        }
        if (!empty($params['goods'])) {
            $contentConfigJson['goods'] = $params['goods'];
        }
        $data['content_config_json'] = json_encode($contentConfigJson);
        $data['content_updatetimes'] = time();

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