<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\S1GoodsCateModel;
use App\Models\S1GoodsInfoModel;
use App\Services\Base\ErrorCode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class CateController extends Controller
{
    /**
     * @api {get} /api/cate/index 分类
     * @apiDescription 分类
     * @apiGroup Cate
     * @apiParam {string}   appid          appid
     * @apiParam {int}      [page=1]            页码（分页参数）
     * @apiParam {int}      [id]            分类 id
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     *  HTTP/1.1 200 OK
    {
        "status": true,
        "status_code": 0,
        "message": "",
        "data": {
            "cates": [
                {
                    "id": 1,
                    "name": "首页分类1",
                    "pic": "/upload/goods/cate/20171013/2454820f914e59dd4a90b575cd47e03c.jpg",
                },
                {
                    "id": 3,
                    "name": "首页分类2",
                    "pic": "/upload/goods/cate/20171013/0e67c1d32c450c5ccd0a9aae5ec9ab96.jpg",
                }
            ],
            "goods": {
            "current_page": 1,
            "data": [
                {
                    "id": 1,
                    "name": "商品1",
                    "pic": "/upload/s1/goods/face/20171013/effbecdc6d9de83d0128e3f08ec6d636.jpg",
                }
            ],
            "first_page_url": "http://www.s1.com/api/cate/index?page=1",
            "from": 1,
            "last_page": 1,
            "last_page_url": "http://www.s1.com/api/cate/index?page=1",
            "next_page_url": null,
            "path": "http://www.s1.com/api/cate/index",
            "per_page": 10,
            "prev_page_url": null,
            "to": 1,
            "total": 1
            }
        }
    }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     */
    public function index(Request $request)
    {
        $validator = Validator::make($request->all(),
            [
                'appid' => 'required',
            ],
            [
                'appid.required' => 'appid不存在',
            ]
        );

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS);
        }
        $appid = $request->input('appid');
        $cate_id = $request->input('id');
        $model =  new S1GoodsInfoModel();
        $cates = S1GoodsCateModel::where('type_id',2)->orderBy('sort')->get();
        $query = $model->where('appid',$appid)->where('is_home_cate',1)->orderBy('sort','desc');
        if($cate_id) $query = $query->where('home_cate_id',$cate_id);
        $goods = $query->paginate();
        return $this->api(compact('cates','goods'));
    }
}
