<?php

namespace Modules\Mall\Http\Controllers\Admin;

use App\Admin\Traits\WithUploads;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Illuminate\Http\Request;
use Modules\Mall\Models\Activity;
use Modules\Mall\Models\Address;
use Modules\Mall\Models\Goods;
use Modules\Mall\Models\GoodsSku;

class AjaxController
{

    /**
     * Notes: 获取用户收货地址
     *
     * @Author: 玄尘
     * @Date: 2022/7/29 13:33
     * @param  Request  $request
     * @return mixed
     */
    public function address(Request $request)
    {
        $user_id = $request->get('q');

        return Address::ByUserId($user_id)
            ->oldest('is_default')
            ->get()
            ->map(function ($address) {
                return [
                    'id'   => $address->id,
                    'text' => $address->getFullAddress(),
                ];
            });

    }

    /**
     * Notes: 获取商品
     *
     * @Author: 玄尘
     * @Date: 2022/7/29 13:46
     * @param  Request  $request
     */
    public function goods(Request $request)
    {
        $address_id = $request->q;
        if (!$address_id){
            return [];
        }
        $address    = Address::find($address_id);

        return GoodsSku::query()
            ->whereHas('goods', function ($q) {
                $q->where('channel', Goods::CHANNEL_FREE)->where('status', Goods::STATUS_UP);
            })
            ->get()
            ->map(function ($sku) use ($address) {
                $stockData = $address->user->getStockData();
                return [
                    'id'   => $sku->id,
                    'text' => $sku->goods->name."(库存：{$stockData['residue']})",
                ];
            });
    }
}
