<?php

namespace Modules\Project\Http\Controllers\Api;

use Illuminate\Support\Facades\Input;
use Modules\Project\Entities\Goods;
use SMG\Categories\Models\Category;
use SMG\Slider\SliderModel;
use SMG\Slider\SliderTransformer;

class GoodsCategoryController extends \Modules\Base\Http\Controllers\Api\ApiController
{
    protected $pageSize = 3;

    protected $offset = 0;

    /**
     * @throws \ErrorException
     *
     * @return mixed
     *
     * @OA\Get(
     *     tags={"分类首页"},
     *     summary="首页",
     *     path="/api/goods/categories/index",
     *     @OA\Response(
     *          response="200",
     *          description="成功",
     *          @OA\MediaType(
     *             mediaType="application/json",
     *              @OA\Schema(
     *                  type="object",
     *                  @OA\Property(
     *                      property="data",
     *                      type="array",
     *                      @OA\Items(ref="#/components/schemas/GoodsCategory"),
     *                      description="列表"
     *                  ),
     *              )
     *          )
     *      )
     * )
     */
    public function index()
    {
        $root_cats = Goods::category()->where('parent_id', null)->get();

        $res = [];

        foreach ($root_cats as $root_cat) {
            $res_root = $this->formatGoodsCategory($root_cat->toArray());

            $res_root['children'] = [];

            $children = $root_cat->children()->get();

            foreach ($children as $cat) {
                $res_children = $cat->toArray();

                $goods_list = Goods::withCategory([$cat->category_flag => $cat->id])->offset($this->offset)->limit($this->pageSize)->get();

                $res_children['goods'] = $this->formatGoodsList($goods_list);

                $res_root['children'][] = $this->formatGoodsCategory($res_children);
            }

            $res[] = $res_root;
        }

        //$res = $this->addBrand($res);

        return $this->response->array(['data' => $res]);
    }

    protected function addBrand($res)
    {
        $scope = ['categorizable_type' => Goods::class, 'category_flag' => ['brand']];

        $children = Category::scoped($scope)->where('parent_id', null)->get();

        $res_root = [
            'id' => '-100',
            'name' => '品牌',
            'parent_id' => null,
            'children' => [],
            'goods' => [],
        ];

        $res_root['children'] = [];

        foreach ($children as $cat) {
            $res_children = $cat->toArray();

            $goods_list = Goods::withCategory([$cat->category_flag => $cat->id])->offset($this->offset)->limit($this->pageSize)->get();

            $res_children['goods'] = $this->formatGoodsList($goods_list);

            $res_root['children'][] = $this->formatGoodsCategory($res_children);
        }

        $res[] = $res_root;

        return $res;
    }

    /**
     * @return \Dingo\Api\Http\Response
     *
     * @OA\Get(
     *     tags={"幻灯片"},
     *     summary="获取商品分类的幻灯片",
     *     path="/api/goods/categories/slider",
     *     description="id需要到后台查看",
     *     @OA\Parameter(
     *         name="category_id",
     *         in="query",
     *         description="分类id",
     *         required=true,
     *         @OA\Schema(
     *             type="integer"
     *         )
     *     ),
     *     @OA\Parameter(
     *         name="position_code",
     *         in="query",
     *         description="position_code",
     *         required=false,
     *         @OA\Schema(
     *             type="string"
     *         )
     *     ),
     *     @OA\Response(
     *          response="200",
     *          description="成功",
     *          @OA\MediaType(
     *             mediaType="application/json",
     *              @OA\Schema(
     *                  type="object",
     *                  @OA\Property(
     *                      property="data",
     *                      type="array",
     *                      @OA\Items(ref="#/components/schemas/Slider"),
     *                      description="列表"
     *                  ),
     *              )
     *          )
     *      )
     * )
     */
    public function slider()
    {
        Category::macro('slider', function () {
            return $this->morphedByMany(SliderModel::class, 'categorizable');
        });

        $goods_category_id = Input::get('category_id', false);

        $position_code = Input::get('position_code', 'goods_category');

        $slider = Category::scoped([
            'categorizable_type' => SliderModel::class,
            'category_flag' => 'position',
        ])->with([
            'slider' => function ($query)use($goods_category_id){

                $query->where('disabled', 0)->orderBy('sort', 'asc');

                if($goods_category_id){

                    $query->attrWhere('goods_category', $goods_category_id);

                }
                
            },
        ])->attrWhereIn('position_code', $position_code)
            ->get()->first();

        return $this->response->collection($slider->slider ?? [], new SliderTransformer());
    }

    private function formatGoodsList($data)
    {
        $res = [];

        foreach ($data as $v) {
            $res[] = [

                'id' => $v['id'],

                'title' => $v['title'],

                'market_price' => $v['market_price'],//市场价

                'selling_price' => $v['selling_price'],//售价

                'cover_picture' => $v['cover_picture'],

            ];
        }

        return $res;
    }

    private function formatGoodsCategory($data)
    {

        /*
        $slider = [];

        Category::macro('slider', function () {
            return $this->morphedByMany(SliderModel::class, 'categorizable');
        });

        $goods_category_id = $data['id'];

        $list = Category::scoped([
            'categorizable_type' => SliderModel::class,
            'category_flag' => 'position',
        ])->with([
            'slider' => function ($query) use($goods_category_id){
                $query->attrWhere('goods_category',$goods_category_id)->where('disabled', 0)->orderBy('sort', 'asc');
            },
        ])->attrWhereIn('position_code', 'goods_category')
            ->get()->first();

        //dump($list->toArray());

        //exit;


        */

        return [

            'id' => $data['id'],

            'name' => $data['name'],

            //'image' => isset($data['attr']['goods_category_image']) ? $data['attr']['goods_category_image'] : '',

            //'slider' => $list->slider,

            'parent_id' => $data['parent_id'],

            'children' => isset($data['children']) ? $data['children'] : [],

            'goods' => isset($data['goods']) ? $data['goods'] : [],

        ];
    }

    /**
     * @throws \ErrorException
     *
     * @return mixed
     *
     * @OA\Get(
     *     tags={"热搜"},
     *     summary="热搜",
     *     path="/api/goods/categories/hot_search",
     *     @OA\Response(
     *          response="200",
     *          description="成功",
     *          @OA\MediaType(
     *             mediaType="application/json",
     *              @OA\Schema(
     *                  type="object",
     *                  @OA\Property(
     *                      property="data",
     *                      type="array",
     *                      @OA\Items(),
     *                      description="列表"
     *                  ),
     *              )
     *          )
     *      )
     * )
     */
    public function hotSearch()
    {
        $hot_kw = db_config('热词', '');

        $res = [];

        if ($hot_kw) {
            $res = explode(',', $hot_kw);
        }

        return $this->response->array(['data' => $res]);
    }
}
