<?php

namespace App\Http\Controllers\Goods;

use App\Events\StockUpdateEvent;
use App\Http\Controllers\Controller;
use App\Http\Resources\GoodsSkuResource;
use App\Imports\CombinationGoodsImport;
use App\Models\BusinessOrderItem;
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;
use Illuminate\Validation\ValidationException;
use Maatwebsite\Excel\Facades\Excel;

class GoodsCombinationController extends Controller
{
    public function index(Request $request)
    {
        // ToDo
        //  可通过子商品查找主商品
        $skus = GoodsSku::query()
            ->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',
            ])
            ->where('is_combination', 1)
            ->filter()
            ->orderBy('stock', 'desc')
            ->paginate($request->get('per_page'));
        $fields = implode(',', [
            'shop_id',
            'external_sku_id',
            'sum(goods_number) as number',
            'sum(already_cancel_number) as cancel_number',
        ]);
        foreach ($skus as &$item) {
            $items = [];
            $lastInventoryTime = date('Y-m-d 07:00:00');
            $orderDetail = BusinessOrderItem::query()
                ->select(DB::raw($fields))
                ->with(['shop:id,name'])
                ->where('external_sku_id', $item['external_sku_id'])
                ->when($lastInventoryTime, function ($query) use ($lastInventoryTime) {
                    $query->where('created_at', '>', $lastInventoryTime);
                })
                ->groupBy(['shop_id', 'external_sku_id'])
                ->get()
                ->toArray();
            $addOrderGoodsNum = $reduceOrderGoodsNum = 0;
            if ($orderDetail) {
                $addOrderGoodsNum = array_sum(array_column($orderDetail, 'number'));
                $reduceOrderGoodsNum = array_sum(array_column($orderDetail, 'cancel_number'));
            }
            $item['order_goods_num'] = $addOrderGoodsNum - $reduceOrderGoodsNum;
            $item['order_detail'] = $orderDetail;
            $number = BusinessOrderItem::query()
                ->where('external_sku_id', $item['external_sku_id'])
                ->sum('goods_number');
            $cancelNumber = BusinessOrderItem::query()
                ->where('external_sku_id', $item['external_sku_id'])
                ->sum('already_cancel_number');
            $item['total_orders_num'] = $number - $cancelNumber;
            foreach ($item['combinationGoods'] as $combinationItem) {
                $items[] = [
                    'cost' => 0,
                    'external_sku_id' => $combinationItem['goodsSkuItem']['external_sku_id'],
                    'goods_id' => $combinationItem['goodsSkuItem']['goods_id'],
                    'id' => $combinationItem['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'],
                    'order_goods_num' => '请在商品列表查看',
                    'order_detail' => [],
                    'total_orders_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 = [];
            foreach ($combinationGoods as $item) {
                $stock[] = (int)($skus[$item['item_id']] / $item['item_num']);
            }
            $stock = min($stock);
            $status = $stock ? (5 < $stock ? 1 : 2) : 0;
            if ($id = $request->input('id')) {
                $sku = GoodsSku::query()->findOrFail($id);
            } else {
                $sku = new GoodsSku();
                $sku->goods_id = 0;
                $sku->is_combination = 1;
            }
            $sku->status = $status;
            $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, 0, true));
        } 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);
    }

    public function import(Request $request)
    {
        if (!$request->hasFile('combinationGoods')) {
            $this->res = [
                'httpCode' => 404,
                'errorCode' => 404404,
                'errorMessage' => 'not found file',
            ];
        }
        try {
            $import = new CombinationGoodsImport();
            $path = $request->file('combinationGoods');
            Excel::import($import, $path);
        } catch (ValidationException $exception) {
            $this->setValidatorFailResponse($exception->validator->getMessageBag()->getMessages());
        }

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