<?php

namespace Modules\User\Http\Controllers\Api\Stock;

use App\Api\Controllers\Controller;
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 as OrderFacade;
use Modules\Mall\Http\Resources\Api\Address\AddressResource;
use Modules\Mall\Http\Resources\Api\Goods\GoodsBaseResource;
use Modules\Mall\Http\Resources\Api\Order\OrderCollection;
use Modules\Mall\Models\Address;
use Modules\Mall\Models\Goods;
use Modules\Mall\Models\GoodsSku;
use Modules\Mall\Models\Order;
use Modules\Mall\Models\Region;
use Modules\User\Http\Resources\stock\UserStockLogCollection;
use Modules\User\Http\Resources\UserIdentityBaseResource;
use Modules\User\Models\Identity;
use Modules\User\Models\UserStockLog;

class IndexController extends Controller
{

    /**
     * Notes   : 订单列表
     *
     * @Date   : 2021/5/13 5:17 下午
     * @Author : <Jason.C>
     * @param  Request  $request
     * @return JsonResponse
     */
    public function index(Request $request): JsonResponse
    {
        $state = $request->state ?? '';

        $list = Order::byUser(Api::user())
            ->TypeSample()
            ->when($state, function ($query) use ($state) {
                switch ($state) {
                    case 'init':
                        $query->paid()->unPay();
                        break;
                    case 'delivered':
                        $query->delivered();
                        break;
                }
            }, function ($query) {
                $query->common();
            })
            ->paginate(8);

        return $this->success(new OrderCollection($list));
    }

    /**
     * Notes: 提货前置
     *
     * @Author: 玄尘
     * @Date: 2022/8/1 11:32
     * @return JsonResponse
     */
    public function create(): JsonResponse
    {
        $user      = Api::user();
        $addresses = Address::where('user_id', $user->id)->orderBy('is_default', 'desc')->get();
        $address   = Address::where('user_id', $user->id)->orderBy('is_default', 'desc')->first();

        $data = [
            'addresses' => AddressResource::collection($addresses),
            'address'   => $address ? new AddressResource($address) : '',
            'stockData' => $user->getStockData(),
            'dientity'  => new UserIdentityBaseResource($user->identityFirst())
        ];

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

    /**
     * Notes: 提货
     *
     * @Author: 玄尘
     * @Date: 2022/8/1 11:33
     * @param  Request  $request
     * @return JsonResponse|mixed
     * @throws \Exception
     */
    public function store(Request $request)
    {
        $user = Api::user();

        $validator = Validator::make($request->all(), [
            'address_id' => 'required|integer',
            'qty'        => 'required|integer',
        ], [
            'qty.required'        => '缺少提货数量',
            'qty.integer'         => '数量必须是数字',
            'address_id.required' => '缺少收货地址',
            'address_id.integer'  => '收货地址必须是数字',
        ]);

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


        $remark     = $request->remark ?? '';
        $address_id = $request->address_id;
        $qty        = $request->qty;

        $address = Address::find($address_id);

        $userIdentity = $user->identityFirst();

        $goods_sku = GoodsSku::query()
            ->whereHas('goods', function ($q) {
                $q->where('channel', Goods::CHANNEL_FREE)->where('status', Goods::STATUS_UP);
            })
            ->first();

        if (! $goods_sku) {
            return $this->failed('缺少商品');
        }

        $stockData = $user->getStockData();

        if ($qty > $stockData['residue']) {
            return $this->failed('用户库存不足');
        }

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

        $orders = (new OrderFacade)->user($user)
            ->remark($remark)
            ->type(Order::TYPE_SAMPLE)
            ->items($detail)
            ->address($address)
            ->create();

        //提货自动完成
        foreach ($orders as $order) {
            if ($order->type == Order::TYPE_SAMPLE) {
                $order->pay();
            }
        }

        return $this->success('提货成功');

    }

    /**
     * Notes: 账变记录
     *
     * @Author: 玄尘
     * @Date: 2022/8/3 10:43
     */
    public function logs()
    {
        $user = Api::user();
        $logs = UserStockLog::query()
            ->ByUser($user)
            ->oldest()
            ->paginate();

        return $this->success(new UserStockLogCollection($logs));
    }

}
