<?php

namespace App\Http\Controllers\Business;

use App\Events\BusinessOrdersUpdate;
use App\Http\Controllers\Controller;
use App\Http\Resources\BusinessGoodsSkuResource;
use App\Models\BusinessGoodsSku;
use App\Models\BusinessOrderItem;
use App\Models\GoodsSku;
use App\Models\Log as LogModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class BusinessGoodsSkusController extends Controller
{
    public function __construct(Request $request)
    {
        $this->log = new LogModel([
            'module' => 'plat',
            'action' => $request->getMethod(),
            'target_type' => 'goods',
        ]);
    }

    public function index(Request $request)
    {
        $businessGoodsSkus = BusinessGoodsSku::query()
            ->filter()
            ->where('quantity_type', 0)
            ->with(['shop:id,name'])
            ->paginate($request->get('per_page'));

        return BusinessGoodsSkuResource::collection($businessGoodsSkus);
    }

    public function update($id, Request $request)
    {
        $validator = Validator::make($request->all(), [
            'is_sync' => ['required', Rule::in([0, 1])]
        ]);
        if ($validator->fails()) {
            $this->setValidatorFailResponse($validator->getMessageBag()->getMessages());

            return response($this->res, $this->res['httpCode']);
        }
        $sku = BusinessGoodsSku::query()->find($id);
        $this->setBeforeUpdate($sku->is_sync);
        $sku->is_sync = $request->input('is_sync');
        $sku->save();
        $this->setAfterUpdate($sku->is_sync);
        $this->addLog($id, 'status');

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

    public function destroy($id, Request $request)
    {
        DB::beginTransaction();
        try {
            $sku = BusinessGoodsSku::query()->find($id);
            $this->setBeforeUpdate($sku->toArray());
            BusinessOrderItem::query()->where('goods_id', $sku->goods_id)->where('sku_id', $sku->sku_id)->delete();
            $sku->delete();
            $this->setAfterUpdate('');
            $this->addLog($id, '');
            DB::commit();
        } catch (Exception $exception) {
            DB::rollBack();
            // 返回错误
            $this->setValidatorFailResponse($exception->getMessages());
        }

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

    public function syncStock($id, Request $request)
    {
        $businessGoodsSku = BusinessGoodsSku::query()->where('is_sync', 1)->find($id);
        [$goodsCode, $skuCode] = explode('_', $businessGoodsSku->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)) {
            $this->setValidatorFailResponse('未找到对应的商品,请核实后再次同步或删除此平台商品');
        } else {
            event(new BusinessOrdersUpdate($businessGoodsSku, 0));
            $this->res['message'] = '库存同步请求发送成功,具体结果查看日志';
        }
        return response($this->res, $this->res['httpCode']);
    }
}
