<?php

namespace App\Http\Controllers\Goods;

use App\Http\Controllers\Controller;
use App\Http\Requests\GoodsSkuRequest;
use App\Http\Resources\GoodsResource;
use App\Models\Log as LogModel;
use App\Utils\DateTimeUtils;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Models\Goods;
use App\Http\Requests\GoodsRequest;
use App\Models\DailyStockRecord;
use Illuminate\Support\Facades\Storage;

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

    public function index(Request $request)
    {
        $goods = Goods::query()->get(['id', 'title', 'img_url', 'type_id', 'brand_id', 'goods_code']);

        return GoodsResource::collection($goods);
    }

    public function store(Request $request)
    {
        $goodsRules = (new GoodsRequest())->rules();
        $skuRules = (new GoodsSkuRequest())->arrayRules('skus.*.');
        $validator = Validator::make($request->all(), array_merge($goodsRules, ['skus' => ['required', 'array']], $skuRules));
        if ($validator->fails()) {
            $this->setValidatorFailResponse($validator->getMessageBag()->getMessages());

            return response($this->res, $this->res['httpCode']);
        }
        DB::beginTransaction();
        try {
            if (!empty($request->goods_id)) {
                $goods = Goods::query()->find($request->goods_id);
            } else {
                $goods = new Goods();
                $goods->title = $request->title;
                $goods->img_url = $request->img_url;
                $goods->type_id = $request->type_id;
                $goods->brand_id = $request->brand_id;
                $goods->goods_code = $request->goods_code;
                $goods->save();
            }
            $goodsSkus = [];
            foreach ($request->skus as $item) {
                $item['goods_id'] = $goods->id;
                $item['stock'] = $item['num'];
                $item['reference_price'] = $item['cost'] * 1.5;
                $goodsSkus[] = $item;
            }
            $collection = $goods->skus()->createMany($goodsSkus)->toArray();
            $this->setAfterUpdate($collection);
            $this->addLog(0, 'add');
            $newRecords = [];
            foreach ($collection as $sku) {
                $newRecords[] = [
                    'sku_id' => $sku['id'],
                    'day' => DateTimeUtils::getToday(),
                ];
            }
            $record = new DailyStockRecord();
            $record->batchInsert($newRecords);
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            $this->res = [
                'httpCode' => 400,
                'errorCode' => 400416,
                'errorMessage' => $exception->getMessage(),
            ];
        }

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

    public function download()
    {
        $file = resource_path('templates/goods_skus_import.xlsx');
        $headers = [
            'Content-Type: application/xlsx',
        ];

        return response()->download($file, 'goods_skus_import.xlsx', $headers);
    }
}
