<?php

namespace App\Http\Service;

use App\Http\Enum\Message\MessageTypeEnum;
use App\Models\DeveloperConfig;
use App\Models\WebsiteMessages;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class MessageService
{
    public $roleIdsMapKeyByNoticeType = [];

    public function __construct()
    {
        $DeveloperConfig = DeveloperConfig::query()->whereIn("key", MessageTypeEnum::MESSAGE_ALL_TYPE)
            ->pluck("value", "key")->toArray();
        $this->roleIdsMapKeyByNoticeType = [
            MessageTypeEnum::PRICE_EXCEPTION_NOTICE => !empty($DeveloperConfig[MessageTypeEnum::PRICE_EXCEPTION_NOTICE])
                ? explode(",", $DeveloperConfig[MessageTypeEnum::PRICE_EXCEPTION_NOTICE]) : MessageTypeEnum::DEFAULT_ROLE_IDS,
            MessageTypeEnum::LOW_STOCK_NOTICE => !empty($DeveloperConfig[MessageTypeEnum::LOW_STOCK_NOTICE])
                ? explode(",", $DeveloperConfig[MessageTypeEnum::LOW_STOCK_NOTICE]) : MessageTypeEnum::DEFAULT_ROLE_IDS,
            MessageTypeEnum::QUALITY_PERIOD_EXPIRE_NOTICE => !empty($DeveloperConfig[MessageTypeEnum::QUALITY_PERIOD_EXPIRE_NOTICE])
                ? explode(",", $DeveloperConfig[MessageTypeEnum::QUALITY_PERIOD_EXPIRE_NOTICE]) : MessageTypeEnum::DEFAULT_ROLE_IDS
        ];
    }

    //值为角色ids


    public function createPriceExceptionMessage(string $businessOrderId, string $productName, string $skuName, string $goodsPrice, string $cost)
    {
        $roleIds = $this->roleIdsMapKeyByNoticeType[MessageTypeEnum::PRICE_EXCEPTION_NOTICE] ?? [];
        if (empty($roleIds)) {
            Log::error("消息配置异常", $this->roleIdsMapKeyByNoticeType);
        }
        $date = Carbon::now()->format('Ymd');
        foreach ($roleIds as $v) {
            $arr['title'] = "订单价格异常告警";
            $arr['role_id'] = $v;
            $arr['unique_key'] = $date . "-" . $businessOrderId . "-" . $v;
            $arr['type'] = MessageTypeEnum::PRICE_EXCEPTION_NOTICE;
            $arr['content'] = $date . "订单号:{$businessOrderId}-商品{$productName}
        规格{$skuName}价格有异常，当前售价{$goodsPrice}/支，当前成本价{$cost}/支";
            $this->saveWebsiteMessages($arr);
        }

    }

    /**
     * 低库存告警
     * @param $inventory
     * @param $goodsSku
     * @return void
     */
    public function createLowerStockNoticeMessage($inventory, $goodsSku)
    {
        $roleIds = $this->roleIdsMapKeyByNoticeType[MessageTypeEnum::LOW_STOCK_NOTICE] ?? [];
        if (empty($roleIds)) {
            Log::error("消息配置异常", $this->roleIdsMapKeyByNoticeType);
        }
        $date = Carbon::now()->format('Ymd');
        foreach ($roleIds as $v) {
            $arr['title'] = "商品库存不足告警";
            $arr['role_id'] = $v;
            $arr['unique_key'] = $date . "-" . $goodsSku['id'] . "-" . $v;
            $arr['type'] = MessageTypeEnum::LOW_STOCK_NOTICE;
            $arr['content'] = $date . "规格{$goodsSku['name']}库存可能需要补货，当前实际库存{$goodsSku['stock']}，上次库存盘点数{$inventory}";
            $this->saveWebsiteMessages($arr);
        }
    }

    /**
     * 保質期告警
     * @param $goodsSku
     * @return void
     */
    public function skuQualityPeriodNoticeMessage($goodsSku)
    {
        $roleIds = $this->roleIdsMapKeyByNoticeType[MessageTypeEnum::QUALITY_PERIOD_EXPIRE_NOTICE] ?? [];
        if (empty($roleIds)) {
            Log::error("消息配置异常", $this->roleIdsMapKeyByNoticeType);
        }
        $date = Carbon::now()->format('Ymd');
        foreach ($roleIds as $v) {
            $arr['title'] = "商品保质期告警";
            $arr['role_id'] = $v;
            $arr['unique_key'] = $date . "-" . $goodsSku['id'] . "-" . $v;//这个场景下实际是采购单的id
            $arr['type'] = MessageTypeEnum::QUALITY_PERIOD_EXPIRE_NOTICE;
            $arr['content'] = $date . "规格{$goodsSku['name']}编码{$goodsSku['external_sku_id']},即将过期，目前实际库存{$goodsSku['stock']},当时采购数量为{$goodsSku['num']},录入采购时间为{$goodsSku['created_at']}";

            $this->saveWebsiteMessages($arr);
        }
    }


    public function saveWebsiteMessages($arr)
    {
        $hasMessage = WebsiteMessages::query()->where("type", "=", $arr['type'])
            ->where("unique_key", "=", $arr['unique_key'])->first();
        if (!empty($hasMessage)) {
            //已经写入过了
            return true;
        }
        $websiteMessages = new  WebsiteMessages();
        $websiteMessages->title = $arr['title'];
        $websiteMessages->type = $arr['type'];
        $websiteMessages->role_id = $arr['role_id'];
        $websiteMessages->content = $arr['content'];
        $websiteMessages->unique_key = $arr['unique_key'];
        if (!empty($arr['uid'])) {
            $websiteMessages->uid = $arr['uid'];
        }
        Log::info("站内消息保存", (array)$arr);
        return $websiteMessages->save($arr);
    }


}