<?php

namespace App\Http\Controllers\Goods;

use App\Events\StockUpdateEvent;
use App\Http\Controllers\Controller;
use App\Http\Resources\GoodsSkuResource;
use App\Models\CombinationGood;
use App\Models\Goods;
use App\Models\GoodsSku;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class GoodsCombinationController extends Controller
{
    public function index(Request $request)
    {
        $skus = GoodsSku::query()
            ->where('is_combination', 1)
            ->with([
                'combinationGoods:id,goods_sku_id,item_id,item_num',
                'combinationGoods.goodsSkuItem:id,goods_id,title,stock,external_sku_id,updated_at,yesterday_num,reference_price,status',
                'combinationGoods.goodsSkuItem.goods:id,title,img_url',
            ])
            ->paginate($request->get('per_page'));
        foreach ($skus as &$item) {
            $items = [];
            foreach ($item['combinationGoods'] as $combinationItem) {
                $items[] = [
                    'cost' => 0,
                    'external_sku_id' => $combinationItem['goodsSkuItem']['external_sku_id'],
                    'goods_id' => $combinationItem['goodsSkuItem']['goods_id'],
                    'id' => $combinationItem['item_id'],
                    'is_combination' => 0,
                    'num' => $combinationItem['item_num'],
                    'reference_price' => $combinationItem['goodsSkuItem']['reference_price'],
                    'status' => $combinationItem['goodsSkuItem']['status'],
                    'stock' => $combinationItem['goodsSkuItem']['stock'],
                    'thumb_url' => $combinationItem['goodsSkuItem']['goods']['img_url'],
                    'img_url' => $combinationItem['goodsSkuItem']['goods']['img_url'],
                    'title' => $combinationItem['goodsSkuItem']['goods']['title'] . $combinationItem['goodsSkuItem']['title'],
                    'updated_at' => $combinationItem['goodsSkuItem']['updated_at'],
                    'yesterday_num' => $combinationItem['goodsSkuItem']['yesterday_num'],
                ];
            }
            $item['children'] = $items;
            unset($item['combinationGoods']);
        }

        return GoodsSkuResource::collection($skus);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required',
            'external_sku_id' => 'required',
            'combination_goods.*' => 'required',
            'combination_goods.*.item_id' => 'required',
            'combination_goods.*.item_num' => 'required|gt:0',
        ]);
        if ($validator->fails()) {
            $this->setValidatorFailResponse($validator->getMessageBag()->getMessages());

            return response($this->res, $this->res['httpCode']);
        }
        DB::beginTransaction();
        try {
            $combinationGoods = $request->input('combination_goods');
            $itemIds = array_column($combinationGoods, 'item_id');
            $skus = GoodsSku::query()
                ->whereIn('id', $itemIds)
                ->pluck('stock', 'id')
                ->toArray();
            $stock = 0;
            foreach ($combinationGoods as $item) {
                $num = (int)($skus[$item['item_id']] / $item['item_num']);
                if (0 === $stock) {
                    $stock = $num;
                    continue;
                }
                if ($num < $stock) {
                    $stock = $num;
                }
            }
            if ($id = $request->input('id')) {
                $sku = GoodsSku::query()->findOrFail($id);
            } else {
                $sku = new GoodsSku();
                $sku->goods_id = 0;
                $sku->is_combination = 1;
            }
            $sku->title = $request->input('title');
            $sku->sku_code = $request->input('external_sku_id');
            $sku->external_sku_id = $request->input('external_sku_id');
            $sku->stock = $stock;
            $sku->save();
            CombinationGood::query()
                ->where('goods_sku_id', $sku->id)
                ->delete();
            foreach ($combinationGoods as $item) {
                CombinationGood::query()->create(['goods_sku_id' => $sku->id, 'item_id' => $item['item_id'], 'item_num' => $item['item_num']]);
            }
            DB::commit();
            event(new StockUpdateEvent($sku));
        } catch (\Exception $exception) {
            DB::rollBack();
            $this->res = [
                'httpCode' => 400,
                'errorCode' => 400500,
                'errorMessage' => $exception->getMessage(),
            ];
        }

        return response($this->res, $this->res['httpCode']);
    }

    public function show(Request $request, $id)
    {
        $sku = GoodsSku::query()
            ->with([
                'combinationGoods:id,goods_sku_id,item_id,item_num',
                'combinationGoods.goodsSkuItem:id,title,goods_id',
                'combinationGoods.goodsSkuItem.goods:id,title',
            ])
            ->findOrFail($id);
        $items = [];
        foreach ($sku['combinationGoods'] as $item) {
            $items[] = [
                'id' => $item['goodsSkuItem']['id'],
                'title' => $item['goodsSkuItem']['goods']['title'] . $item['goodsSkuItem']['title'],
            ];
        }
        $sku['skus'] = $items;

        return new GoodsSkuResource($sku);
    }

    public function destroy(Request $request, $id)
    {

    }

    public function goodsSkus(Request $request, $title)
    {
        $goodsIds = Goods::query()
            ->where('title', 'like', '%' . $title . '%')
            ->pluck('id');
        $skus = GoodsSku::query()
            ->whereIn('goods_id', $goodsIds)
            ->where('is_combination', 0)
            ->with('goods:id,title')
            ->get(['id', 'title', 'goods_id']);
        foreach ($skus as &$sku) {
            $sku['title'] = $sku['goods']['title'] . $sku['title'];
        }

        return GoodsSkuResource::collection($skus);
    }
}
