<?php

namespace Modules\Mall\Http\Controllers\Api;

use App\Api\Controllers\Controller;
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Jason\Api\Api;
use Modules\Mall\Facades\Item;
use Modules\Mall\Facades\Order;
use Modules\Mall\Models\Order as OrderModel;
use Modules\Mall\Http\Requests\Address\AddressRequest;
use Modules\Mall\Http\Requests\OrderBuy\OrderBuyRequest;
use Modules\Mall\Http\Resources\Api\Address\AddressResource;
use Modules\Mall\Http\Resources\Api\Goods\GoodsBaseResource;
use Modules\Mall\Http\Resources\Api\Goods\GoodsCollection;
use Modules\Mall\Models\Address;
use Modules\Mall\Models\Cart;
use Modules\Mall\Models\Goods;
use Modules\Mall\Models\GoodsSku;
use Monolog\Handler\IFTTTHandler;

class OrderBuyController extends Controller
{

    /**
     * Notes: 商品确认下单
     *
     * @Author: 玄尘
     * @Date  : 2021/5/14 11:54
     * @param  \Modules\Mall\Http\Requests\OrderBuy\OrderBuyRequest  $request
     * @return mixed
     * @throws \Exception
     */
    public function goodsCreate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'goods_sku_id' => 'required|integer',
            'qty'          => 'nullable|integer',
        ], [
            'goods_sku_id.required' => '缺少商品规格id',
            'goods_sku_id.integer'  => '商品规格id必须是数字',
            'qty.integer'           => '数量必须是数字',
        ]);

        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }

        $goods_sku_id = $request->goods_sku_id;
        $qty          = $request->qty;
        $address_id   = $request->address_id;

        $detail = collect();
        $user   = Api::user();

        if ($address_id) {
            $address = Address::find($address_id);
        } else {
            $address = Address::where('user_id', $user->id)->orderBy('is_default', 'desc')->first();
        }

        $goods_sku = GoodsSku::find($goods_sku_id);

        if (! $goods_sku) {
            return $this->failed('未找到商品');
        }

        if (! $goods_sku->canBuy($qty)) {
            return $this->failed($goods_sku->getGoodsName().'商品不可购买');
        }

        $item = new Item($goods_sku, $address, $qty);
        $detail->push($item);

        $freight = $item->freight();
        $amount  = $item->total();
        $weight  = $item->weight();

        $detail = (new Order)->items($detail)->splitOrderByShop();
        $items  = [];
        foreach ($detail as $item) {
            $items[] = $item;
        }

        $data = [
            'address' => $address ? new AddressResource($address) : '',
            'detail'  => $items,
            'amount'  => floatval(bcadd($amount, $freight, 2)),
            'freight' => $freight,
            'weight'  => $weight,
        ];

        return $this->success($data);

    }

    /**
     * Notes: 商品下单
     *
     * @Author: 玄尘
     * @Date  : 2021/5/14 13:53
     * @param  \Modules\Mall\Http\Requests\OrderBuy\OrderBuyRequest  $request
     * @return mixed
     * @throws \Exception
     */
    public function goodsBuy(OrderBuyRequest $request)
    {
        $validator = Validator::make($request->all(), [
            'goods_sku_id' => 'required|integer',
            'qty'          => 'nullable|integer',
            'address_id'   => 'required|integer',
        ], [
            'goods_sku_id.required' => '缺少商品规格id',
            'goods_sku_id.integer'  => '商品规格id必须是数字',
            'qty.integer'           => '数量必须是数字',
            'address_id.required'   => '缺少收货地址',
            'address_id.integer'    => '收货地址必须是数字',
        ]);

        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }

        $user          = Api::user();
        $remark        = $request->remark ?? '';
        $address_id    = $request->address_id ?? '';
        $goods_sku_id  = $request->goods_sku_id;
        $qty           = $request->qty;
        $share_user_id = $request->share_user_id ?? 0;

        $address = Address::where('user_id', $user->id)->where('id', $address_id)->first();
        if (! $address) {
            return $this->failed('未找到收货地址');
        }

        $detail = collect();

        $goods_sku = GoodsSku::find($goods_sku_id);

        if (! $goods_sku) {
            return $this->failed('未找到商品');
        }

        if (! $goods_sku->canBuy($qty)) {
            return $this->failed($goods_sku->getGoodsName().' 商品不可购买');
        }

        $item = new Item($goods_sku, $address, $qty);
        $detail->push($item);

        $type = OrderModel::TYPE_NORMAL;
        if ($goods_sku->goods->channel == Goods::CHANNEL_FREE) {
            $type = OrderModel::TYPE_SAMPLE;
        }

        if ($goods_sku->goods->channel == Goods::CHANNEL_SCORE) {
            $type = OrderModel::TYPE_SCORE;
        }

        $orders = (new Order)->user($user)
            ->remark($remark)
            ->items($detail)
            ->type($type)
            ->address($address)
            ->source(['share_user_id' => $share_user_id,])
            ->create();

        return $this->success([
            'order_no' => $orders->first()->order_no,
            'total'    => $orders->first()->total,
            'score'    => $user->account->score,
        ]);
    }

    /**
     * Notes: 购物车确认下单
     *
     * @Author: 玄尘
     * @Date  : 2021/5/17 10:14
     */
    public function cartsCreate(Request $request)
    {
        $user = Api::user();

        $cart_ids = $request->cart_ids;//1,2,3
        $cart_ids = explode(',', $cart_ids);
        $carts    = Cart::where('user_id', $user->id)->whereIn('id', $cart_ids)->get();
        if ($carts->isEmpty()) {
            return $this->failed('未找到购物车');
        }

        $detail = collect();

        $all_address = Address::where('user_id', $user->id)->orderBy('is_default', 'desc')->get();
        $address     = Address::where('user_id', $user->id)->orderBy('is_default', 'desc')->first();

        $amount = $weight = $freight = 0;
        foreach ($carts as $cart) {
            $goods_sku = $cart->sku;

            if (! $goods_sku) {
                return $this->failed('未找到商品');
            }

            if (! $goods_sku->canBuy($cart->qty)) {
                return $this->failed($goods_sku->getGoodsName().' 不可购买');
            }

            $item = new Item($goods_sku, $address, $cart->qty);
            $detail->push($item);

            $freight += $item->freight();
            $amount  += $item->total();
            $weight  += $item->weight();
        }

        try {
            $data = [
                'address'     => $address ? new AddressResource($address) : '',
                'all_address' => AddressResource::collection($all_address),
                'detail'      => (new Order)->items($detail)->splitOrderByShop(),
                'amount'      => bcadd($amount, $freight, 2),
                'freight'     => $freight,
                'weight'      => $weight,
            ];

            return $this->success($data);

        } catch (Exception $e) {
            return $this->failed($e->getMessage());
        }

    }

    /**
     * Notes: 购物车购买
     *
     * @Author: 玄尘
     * @Date  : 2021/5/17 10:14
     */
    public function cartsBuy(Request $request)
    {
        $user = Api::user();

        $cart_ids      = $request->cart_ids;        //1,2,3
        $cart_ids      = explode(',', $cart_ids);
        $address_id    = $request->address_id ?? 0;
        $remark        = $request->remark ?? '';
        $share_user_id = $request->share_user_id ?? 0;

        $carts = Cart::where('user_id', $user->id)->whereIn('id', $cart_ids)->get();
        if ($carts->isEmpty()) {
            return $this->failed('未找到购物车');
        }

        $address = Address::where('user_id', $user->id)->where('id', $address_id)->first();
        if (! $address) {
            return $this->failed('未找到收货地址');
        }

        $detail = collect();
        foreach ($carts as $cart) {
            $goods_sku = $cart->sku;

            if (! $goods_sku) {
                return $this->failed('未找到商品');
            }

            if (! $goods_sku->canBuy($cart->qty)) {
                return $this->failed($goods_sku->getGoodsName().' 不可购买');
            }

            $item = new Item($goods_sku, $address, $cart->qty);
            $detail->push($item);
        }

        try {
            (new Order)->user($user)
                ->remark($remark)
                ->items($detail)
                ->address($address)
                ->source(['share_user_id' => $share_user_id])
                ->create();
            //删除购物车
            Cart::whereIn('id', $cart_ids)->delete();

            return $this->success('下单成功');
        } catch (Exception $e) {
            return $this->failed($e->getMessage());
        }

    }

}