<?php

namespace App\Http\Controllers\Shop;

use App\Http\Controllers\Controller;
use App\Models\GoodsSku;
use App\Models\Shop;
use App\Http\Resources\ShopsResource;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Services\Business\BusinessFactory;
use Illuminate\Validation\Rule;
use App\Models\BusinessOrderItem;

class ShopsController extends Controller
{
    public function index(Request $request)
    {
        $shops = Shop::query()->paginate($request->get('per_page'));
        foreach ($shops as $shop) {
            $shop->authUrl = '';
            if ('妙选' !== $shop->plat_id && ('未授权' === $shop->status || '重新授权' === $shop->status)) {
                $shop->authUrl = BusinessFactory::init()->make($shop->plat_id)->getAuthUrl($shop->id, $shop->getOriginal('plat_id'));
            }
        }

        return ShopsResource::collection($shops);
    }

    public function getPlatList()
    {
        $shop = new Shop();

        return new ShopsResource($shop->getPlatList());
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:191|unique:shops,name',
            'plat_id' => 'required|integer',
        ]);
        if ($validator->fails()) {
            $this->setValidatorFailResponse($validator->getMessageBag()->getMessages());

            return response($this->res, $this->res['httpCode']);
        }
        $shop = new Shop();
        $shop->name = $request->name;
        $shop->plat_id = $request->plat_id;
        if (0 == $request->plat_id) {
            $shop->status = 2;
        }
        $shop->save();

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

    public function authBind(Request $request)
    {
        [$shopId, $platId] = explode('_', $request->get('state'));
        $shop = new Shop();
        $platList = $shop->getPlatList();
        $shop = $shop->find($shopId);
        if ($platList[$platId] === $shop->plat_id) {
            BusinessFactory::init()->make($shop->plat_id)->authCallback($request->get('code'), $shop);
        } else {
            $this->res = [
                'httpCode' => 403,
                'errorCode' => 403400,
                'errorMessage' => '信息不匹配',
            ];
        }

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

    public function business(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'type' => ['required', 'string', Rule::in(['goods', 'orders'])],
            'erp_shop_id' => ['required', 'integer', 'exists:shops,id'],
        ]);
        if ($validator->fails()) {
            $this->setValidatorFailResponse($validator->getMessageBag()->getMessages());

            return response($this->res, $this->res['httpCode']);
        }
        $shop = new Shop();
        $shop = $shop->find($request->get('erp_shop_id'));
        $business = BusinessFactory::init()->make($shop->plat_id);
        $business->setShop($shop);
        if ('goods' === $request->get('type')) {
            $business->bindGoods($request->get('data'));
        }
        if ('orders' === $request->get('type')) {
            $business->saveOrders($request->get('data'));
        }

        return response(['Code' => 10000, 'Message' => 'SUCCESS']);
    }

    public function countOrdersNumWithSkuCode(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'sku_code' => ['required', 'array'],
        ]);
        if ($validator->fails()) {
            $this->setValidatorFailResponse($validator->getMessageBag()->getMessages());

            return response($this->res, $this->res['httpCode']);
        }
        $fields = implode(',', [
            'shop_id',
            'external_sku_id',
            'sum(goods_number) as num',
        ]);
        $res = BusinessOrderItem::query()
            ->select(DB::raw($fields))
            ->whereIn('external_sku_id', $request->get('sku_code'))
            ->groupBy(['shop_id', 'external_sku_id'])
            ->with(['shop:id,name'])
            ->get();
        $data = [];
        foreach ($res as $item) {
            [$goodsCode, $skuCode] = explode('_', $item['external_sku_id']);
            $sku = GoodsSku::query()->where('sku_code', $skuCode)
                ->whereHas('goods', function ($query) use ($goodsCode) {
                    $query->where('goods_code', $goodsCode);
                })
                ->first();
            if (empty($sku)) {
                continue;
            }
            $sku = $sku->toArray();
            if (!isset($data[$sku['id']]['total'])) {
                $data[$sku['id']]['total'] = 0;
            }
            $data[$sku['id']]['total'] += $item->num;
            $data[$sku['id']]['items'][] = [
                'shop_name' => $item->shop->name,
                'num' => $item->num,
            ];
        }

        return $data;
    }

    public function downloadGoods($id, Request $request)
    {
        $shop = Shop::query()->find($id);
        $business = BusinessFactory::init()->make($shop->plat_id);
        $business->setShop($shop);
        $business->downloadGoodsListAndBind();

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