<?php

namespace Modules\Mall\Http\Controllers\Api;

use App\Api\Controllers\Controller;
use App\Api\Resources\Area\AreaCodeResource;
use App\Api\Resources\User\UserBaseResource;
use App\Models\AreaCode;
use Exception;
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\OrderBuy\OrderBuyRequest;
use Modules\Mall\Http\Resources\Api\Address\AddressResource;
use Modules\Mall\Models\Address;
use Modules\Mall\Models\Cart;
use Modules\Mall\Models\Goods;
use Modules\Mall\Models\GoodsSku;

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;

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


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

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

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


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

        $item = new Item($goods_sku, null, $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;
        }

        $areaCode = $user->info->areaCode;
        if (! $areaCode && $type == OrderModel::TYPE_SAMPLE) {
            return $this->failed('您没有提货码不可参与此活动');
        }
        if ($areaCode->status != AreaCode::STATUS_INIT && $type == OrderModel::TYPE_SAMPLE) {
            return $this->failed('提货码已被使用，不可重复使用');
        }

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

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

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

        if ($type == OrderModel::TYPE_SAMPLE) {
            $data['areaCode'] = new AreaCodeResource($areaCode);
        }

        if ($address) {
            $data['address'] = new AddressResource($address);
        }

        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(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());
        }

        $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;


        $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, null, $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;
        }

        $areaCode = $user->info->areaCode;
        if (! $areaCode && $type == OrderModel::TYPE_SAMPLE) {
            return $this->failed('您没有提货码不可参与此活动');
        }
        if ($areaCode->status != AreaCode::STATUS_INIT && $type == OrderModel::TYPE_SAMPLE) {
            return $this->failed('提货码已被使用，不可重复使用');
        }

        $address = Address::where('user_id', $user->id)->where('id', $address_id)->first();

        if (in_array($type, [OrderModel::TYPE_SCORE, OrderModel::TYPE_NORMAL]) && ! $address) {
            return $this->failed('未找到收货地址');
        }

        if ($type == OrderModel::TYPE_SAMPLE) {
            $orders = (new Order)->user($user)
                ->remark($remark)
                ->items($detail)
                ->areaCode($areaCode)
                ->type($type)
                ->source(['share_user_id' => $share_user_id,])
                ->create();
        } else {
            $orders = (new Order)->user($user)
                ->remark($remark)
                ->items($detail)
                ->address($address)
                ->type($type)
                ->source(['share_user_id' => $share_user_id,])
                ->create();
        }

        foreach ($orders as $order) {
            if ($type == OrderModel::TYPE_SAMPLE) {
                $order->pay();
                $order->areaCode->used();
            }
        }

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

}