<?php

namespace Modules\Mall\Http\Controllers\Api;

use App\Api\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Jason\Api\Api;
use Modules\Mall\Http\Requests\Cart\CartRequest;
use Modules\Mall\Http\Resources\Api\Goods\CartResource;
use Modules\Mall\Http\Resources\Api\Shop\ShopBaseInfoResource;
use Modules\Mall\Models\Cart;
use Modules\Mall\Models\GoodsSku;
use Modules\Mall\Models\Shop;

class CartController extends Controller
{

    /**
     * Notes   : 购物车内商品列表
     * @Date   : 2021/8/26 3:42 下午
     * @Author : <Jason.C>
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(): JsonResponse
    {
        $list = Cart::byUser(Api::user())->with('sku')->orderByDesc('updated_at')->get();

        $collection = $list->groupBy('shop_id');

        $items = [];

        foreach ($collection as $shopId => $item) {
            $items[] = [
                'shop'  => new ShopBaseInfoResource(Shop::find($shopId)),
                'items' => CartResource::collection($item),
            ];
        }

        return $this->success($items);
    }

    /**
     * Notes   : 加入购物车
     * @Date   : 2021/5/14 2:17 下午
     * @Author : <Jason.C>
     * @param  \Illuminate\Http\Request  $request
     * @return mixed
     */
    public function store(Request $request)
    {
        $skuId = $request->sku_id;
        $qty   = $request->qty ?? 1;

        $sku = GoodsSku::findOrFail($skuId);

        if (!$sku->canBuy($qty)) {
            return $this->failed('超过最大可购买数量');
        }

        $cart = Cart::where('user_id', Api::userId())->where('sku_id', $skuId)->first();

        if ($cart) {
            $cart->qty = $cart->qty + $qty;
            $cart->save();
        } else {
            $cart = Cart::create([
                'user_id' => Api::userId(),
                'shop_id' => $sku->goods->shop_id,
                'sku_id'  => $skuId,
                'qty'     => $qty,
            ]);
        }

        return $this->success($cart->qty);
    }

    /**
     * Notes   : 获取购物车商品数量
     * @Date   : 2021/5/14 1:47 下午
     * @Author : <Jason.C>
     */
    public function count(): JsonResponse
    {
        if (Api::userId()) {
            $count = Cart::where('user_id', Api::userId())->count();
        } else {
            $count = 0;
        }

        return $this->success($count);
    }

    /**
     * Notes   : 更新购物车商品数量
     * @Date   : 2021/5/13 2:52 下午
     * @Author : <Jason.C>
     * @param  \Modules\Mall\Http\Requests\Cart\CartRequest  $request
     * @param  \Modules\Mall\Models\Cart                     $cart
     * @return mixed
     */
    public function update(CartRequest $request, Cart $cart)
    {
        $skuId = $request->sku_id;
        $qty   = $request->qty;

        if ($cart->user()->isNot(Api::user())) {
            return $this->failed('', 404);
        }

        if ($skuId && ($skuId != $cart->sku_id)) {
            $sku = GoodsSku::find($skuId);

            if (!$cart->sku->goods->is($sku->goods)) {
                return $this->failed('错误的商品');
            }

            $cart->sku_id = $skuId;
        } else {
            $sku = $cart->sku;
        }

        if ($qty < 1 || $qty > $sku->stock) {
            return $this->failed('库存不足');
        }

        $cart->qty = $qty;
        $cart->save();

        return $this->success($qty);
    }

    /**
     * Notes   : 删除购物车商品
     * @Date   : 2021/5/17 4:00 下午
     * @Author : <Jason.C>
     * @param  string  $cart
     * @return mixed|string
     */
    public function destroy(string $cart)
    {
        if (Str::contains($cart, ',')) {
            $count = Cart::query()->where('user_id', Api::userId())->whereIn('id', explode(',', $cart))->delete();
            if (!$count) {
                return $this->failed('empty');
            }
        } else {
            $cart = Cart::find($cart);
            if ($cart->user()->isNot(Api::user())) {
                return $this->failed('', 404);
            }
            $cart->delete();
        }

        return $this->success('删除成功');
    }

}