<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\S1CartInfoModel;
use App\Models\S1CateAttrModel;
use App\Models\S1CommentInfoModel;
use App\Models\S1GoodsInfoModel;
use App\Models\S1UserFavoriteModel;
use App\Services\Base\ErrorCode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class GoodsController extends Controller
{

    /**
     * @api {get} /api/goods/show 商品详情
     * @apiDescription 商品详情
     * @apiGroup Goods
     * @apiParam {string}   appid          appid
     * @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": {
            "id": 1,
            "appid": "dsfbdffd32434dfvdf",
            "cate_id": 4,
            "is_home_cate": 1,
            "home_cate_id": 3,
            "attr_id": 0,
            "name": "商品1",
            "number": "0011",
            "pic": "/upload/s1/goods/face/20171013/effbecdc6d9de83d0128e3f08ec6d636.jpg",
            "weight": 1001,
            "stock": 10081,
            "status": 1,
            "market_price": 100100,
            "price": 101100,
            "cost_price": 99100,
            "junior_price": 0,
            "middle_price": 0,
            "top_price": 0,
            "sale_number": 91,
            "info": "好东西1",
            "is_address": 1,
            "sort": 11,
            "is_favorite": 1,  或 0  1已经收藏
            "ground_time": "2017-10-13 10:29:19",
            "draw_time": "0000-00-00 00:00:00",
            "created_at": "2017-10-13 02:29:19",
            "updated_at": "2017-10-13 03:02:21",
            "deleted_at": null,
            'attr_info':null                  已经选择的属性
            "attr": {                          属性
                "规格": [
                    "ML",
                    "L",
                    "XL",
                    "XXL"
                ],
                "颜色": [
                    "黑色",
                    "白色"
                ]
            },
            "images": [                     图片
                {
                    "url": "/upload/s1/goods/shows/20171013/46072732d071540939acd5e875f383dd.jpg",
                },
            ],
            "comments": [                  评论
                {
                    "id": 1,
                    "wx_user_id": 1,
                    "wx_user_avatar": "0",   头像
                    "wx_user_nickname": "0",  昵称
                    "comment": "dsgdsfdfsdfbf",
                    "created_at": null,
                    "updated_at": null
                }
            ]
        }
    }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     */
    public function show(Request $request)
    {
        $user = Auth::guard('api')->user();
        if (!$user) return $this->error(ErrorCode::ERROR_POWER);
        $validator = Validator::make($request->all(),
            [
                'id' => 'required',
                'appid' => 'required',
            ],
            [
                'id.required' => '商品不存在',
                'appid.required' => 'appid不存在',
            ]
        );

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS);
        }
        $appid = $request->input('appid');
        $id = $request->input('id');
        $is_favorite = S1UserFavoriteModel::where('s1_goods_id',$id)->where('wx_user_id',$user->id)->first();
        if (empty($is_favorite)){
            $is_favorite = 0;
        }else{
            $is_favorite = 1;
        }
        $goods = S1GoodsInfoModel::with('images','comments')->find($id);
        $attr = S1CateAttrModel::where('cate_id',$goods->home_cate_id)->get()->toArray();
        $attr_info = [] ;
        foreach ($attr as $key =>$item) {
            $attr_info[$key]['attr_group_name'] = $item['name'];
            $attr_info[$key]['attr_group_id'] = $item['id'];
            $arr = ( explode(',',$item['value']));
            foreach ($arr as $k => $v){
                $attr_info[$key]['attr_list'][] = ['id'=>$k,'name'=>$v];
            }
        }
       /* $attr_info = array_column($attr,'value','name');
        foreach ($attr_info as $key => $value) {
            $arr = explode(',',$value);
            $attr_info[$key] = $arr;
        }*/
        $goods->is_favorite = $is_favorite;
        $goods->attr = $attr_info;
        if (session('attr_info') && session('attr_info')['user_id']==$user->id && session('attr_info')['goods_id']==$id) {
            $goods->attr_info = session('attr_info')['attr_info'];
        }else{
            $goods->attr_info = null;
        }
        return $this->api($goods);
    }


    /**
     * @api {get} /api/goods/chose_attr 选择属性
     * @apiDescription 选择属性
     * @apiGroup Goods
     * @apiParam {int}   id          商品id
     * @apiParam {array}   attr         商品属性
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     *  HTTP/1.1 200 OK
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     */
    public function choseAttr(Request $request)
    {
        $user = Auth::guard('api')->user();
        if (!$user) return $this->error(ErrorCode::ERROR_POWER);
        $validator = Validator::make($request->all(),
            [
                'id' => 'required',
                'attr' => 'required',
            ],
            [
                'id.required' => '商品不存在',
                'attr.required' => '商品属性不存在',
            ]
        );

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS);
        }
        $attr = json_decode($request->input('attr'),true);
        $id = $request->input('id');
        $str = '';
        if (is_array($attr)) {
            foreach ($attr as $k => $v){
                $str .= $v['attr_group_name'].':'.$v['attr_name'].',';
            }
        }
        $arr = [
            'user_id'=>$user->id,
            'goods_id'=>$id,
            'attr_info'=>$str
        ];
        Cache::put('attr_info', $arr, 10);  //存储十分钟
        $id = $request->input('id');
        $is_favorite = S1UserFavoriteModel::where('s1_goods_id',$id)->where('wx_user_id',$user->id)->first();
        if (empty($is_favorite)){
            $is_favorite = 0;
        }else{
            $is_favorite = 1;
        }
        $goods = S1GoodsInfoModel::with('images','comments')->find($id);
        $attr = S1CateAttrModel::where('cate_id',$goods->home_cate_id)->get()->toArray();
        $attr_info = [] ;
        foreach ($attr as $key =>$item) {
            $attr_info[$key]['attr_group_name'] = $item['name'];
            $attr_info[$key]['attr_group_id'] = $item['id'];
            $arr = ( explode(',',$item['value']));
            foreach ($arr as $k => $v){
                $attr_info[$key]['attr_list'][] = ['id'=>$k,'name'=>$v];
            }
        }
        $goods->is_favorite = $is_favorite;
        $goods->attr = $attr_info;
        if (Cache::get('attr_info') && Cache::get('attr_info')['user_id']==$user->id && Cache::get('attr_info')['goods_id']==$id) {
            $goods->attr_info = Cache::get('attr_info')['attr_info'];
        }else{
            $goods->attr_info = null;
        }
        return $this->api($goods);
    }

    /**
     * @api {get} /api/goods/addtocar 添加至购物车
     * @apiDescription 添加至购物车
     * @apiGroup Goods
     * @apiParam {string}   appid          appid
     * @apiParam {int}   id          商品id
     * @apiParam {int}   number          商品数量
     * @apiParam {array}   attr          商品属性
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     *  HTTP/1.1 200 OK
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     */
    public function addToCar(Request $request)
    {
        $user = Auth::guard('api')->user();
        if (!$user) return $this->error(ErrorCode::ERROR_POWER);
        $validator = Validator::make($request->all(),
            [
                'id' => 'required',
                'appid' => 'required',
                'number' => 'required',
                'attr' => 'required',
            ],
            [
                'id.required' => '商品不存在',
                'appid.required' => 'appid不存在',
                'number.required' => '商品数量不能为空',
                'attr.required' => '商品属性不能为空',
            ]
        );

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS);
        }
        $appid = $request->input('appid');
        $id = $request->input('id');
        $number = $request->input('number');
        $attr = json_decode($request->input('attr'),true);
        $str = '';
        if (is_array($attr)) {
            foreach ($attr as $k => $v){
                $str .= $v['attr_group_name'].':'.$v['attr_name'].',';
            }
        }
        $arr = [
            'appid'=>$appid,
            'wx_user_id'=>$user->id,
            's1_goods_id'=>$id,
            'number'=>$number,
            'attr_info'=>$str,
        ];
        $data = S1CartInfoModel::where('appid',$appid)->where('wx_user_id',$user->id)->where('s1_goods_id',$id)->first();
        if(empty($data)){
            $ok = S1CartInfoModel::create($arr);
        }else{
            $data->goods_num += $number;
            $ok = $data->save();
        }
        if($ok) return $this->api('');
        return $this->error(ErrorCode::OP_ERROR);
    }

    /**
     * @api {get} /api/goods/collection 收藏/取消
     * @apiDescription 收藏/取消
     * @apiGroup Goods
     * @apiParam {int}   id          商品id
     * @apiParam {int}   value          0或1 0(取消收藏)
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     *  HTTP/1.1 200 OK
     {
        "status": true,
        "status_code": 0,
        "message": "",
        "data": ""
     }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     */
    public function collection(Request $request)
    {
        $user = Auth::guard('api')->user();
        if (!$user) return $this->error(ErrorCode::ERROR_POWER);
        $validator = Validator::make($request->all(),
            [
                'id' => 'required',
                'value' => 'required',
            ],
            [
                'id.required' => '商品不存在',
                'value.required' => '收藏值不存在',
            ]
        );

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS);
        }
        $s1_goods_id = $request->input('id');
        $value = $request->input('value');
        $wx_user_id = $user->id;
        $arr = compact('s1_goods_id','wx_user_id');
        if ($value==1) {
           $ok = S1UserFavoriteModel::firstOrCreate($arr);
        }else{
            $ok = S1UserFavoriteModel::where('s1_goods_id',$s1_goods_id)->where('wx_user_id',$wx_user_id)->delete();
        }
        if ($ok) return $this->api('');
        return $this->error(ErrorCode::OP_ERROR);
    }

    /**
     * @api {post} /api/goods/comment 评价/回复评价
     * @apiDescription 评价
     * @apiGroup Goods
     * @apiParam {int}   goods_id         商品id
     * @apiParam {int}   level         评论星级(321好中差)
     * @apiParam {string}   comment         评论内容不能为空
     * @apiParam {int}   [comment_id]          评论id
     * @apiParam {array}   [images]          上传图片
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     *  HTTP/1.1 200 OK
    {
        "status": true,
        "status_code": 0,
        "message": "",
        "data": ""
    }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
    {
        "status": false,
        "status_code": 2006,
        "message": "操作失败",
        "data": null
    }
     */
    public function comment(Request $request)
    {
        $user = Auth::guard('api')->user();
        if (!$user) return $this->error(ErrorCode::ERROR_POWER);
        $validator = Validator::make($request->all(),
            [
                'goods_id' => 'required',
                'level' => 'required',
                'comment' => 'required',
            ],
            [
                'goods_id.required' => '商品不存在',
                'comment.required' => '评论内容不能为空',
                'level.required' => '评论星级不存在',
            ]
        );

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS);
        }
        $goods_id = $request->input('goods_id');
        $level = $request->input('level');
        $images = $request->input('images');
        $comment = $request->input('comment');
        $comment_id = $request->input('comment_id');
        $arr = [];
        $arr['wx_user_id'] = $user->id;
        $arr['wx_user_avatar'] = $user->avatar;
        $arr['wx_user_nickname'] = $user->nickname;
        $arr['s1_goods_id'] = $goods_id;
        $arr['comment'] = $comment;
        $arr['level'] = $level;
        if(!empty($images)) $arr['images'] = json_encode($images);
        if ($comment_id) {   //表示回复
            $arr['comment_info_id'] = $comment_id;
        }
        $ok = S1CommentInfoModel::firstOrCreate($arr);
        if($ok) return $this->api('');
        return $this->error(ErrorCode::OP_ERROR);
    }
}
