<?php

namespace App\Http\Controllers\Message;

use App\Http\Controllers\Controller;
use App\Http\Enum\Goods\SkuStatusEnum;
use App\Http\Enum\Message\MessageTypeEnum;
use App\Models\GoodsSku;
use App\Models\WebsiteMessages;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class WebsiteMessageController extends Controller
{

    public function index(Request $request)
    {
        $roleIds = collect($request->user()->roles)->pluck('id')->toArray() ?? [];
        $status = $request->input('status') ?? 0;
        $websiteMessage = WebsiteMessages::query()->where('status', '=', $status);

        if (!empty($roleIds)) {
            $websiteMessagePage = $websiteMessage->whereIn('role_id', $roleIds)
                ->paginate($request->get('per_page'));
            return JsonResource::collection($websiteMessagePage);
        }

        return JsonResource::collection([]);
    }

    public function update($id, Request $request)
    {
        $validator = Validator::make($request->all(), [
            'status' => ['required', 'integer', 'in:0,1']
        ]);
        if ($validator->fails()) {
            $this->setValidatorFailResponse($validator->getMessageBag()->getMessages());
            return response($this->res, $this->res['httpCode']);
        }
        //更新站內信狀態
        $websiteMessages = WebsiteMessages::query()->find($id);
        if (empty($websiteMessages)) {
            $this->res = [
                'httpCode' => 400,
                'errorCode' => 400404,
                'errorMessage' => "站内信数据不存在",
            ];

            return response($this->res, "400");
        }
        $websiteMessages->status = $request->status;
        Log::info("管理員更新站內信", (array)$request->user());
        $websiteMessages->save();

        if ($request->status == 1) {
            //标记已读触发
            $this->hook($websiteMessages);
        }

        return $websiteMessages;
    }

    public function hook($websiteMessages)
    {
        if ($websiteMessages->type == MessageTypeEnum::LOW_STOCK_NOTICE) {
            $keyArray = explode("-", $websiteMessages->unique_key);//时间Ymd-对应id-角色id
            $skuId = $keyArray[1] ?? 0;
            if (!empty($skuId)) {
                //变更回上架状态
                GoodsSku::query()->where("id", "=", $skuId)->update(["status" => SkuStatusEnum::UP]);
            }
        }
    }

    public function batchRead(Request $request)
    {
        $params = $request->validate([
            'ids' => 'required|array'
        ], [
            'ids.required' => '需要操作的ids'
        ]);
        WebsiteMessages::query()->whereIn('id', $params['ids'])->update(['status' => 1]);
        return $this->success();
    }

}
