<?php


namespace App\Modules\OrangeSite\Services\CheckReport;


use App\Modules\OrangeSite\Services\OrangeSitePromotionService;
use App\Modules\OrangeSite\Services\OrangeSiteRechargeReportCheckContext;
use Closure;
use Log;

class PromotionProtectCheck
{
    /**
     * 判断计划保护数
     * @param $context OrangeSiteRechargeReportCheckContext
     * @param Closure $next
     * @return mixed
     */
    public function handle($context, Closure $next)
    {
        $channelPromotionProtectSettingNum = $context->channelCallbackConfig->eligible_count ?: 0;
        $userBindInfo = OrangeSitePromotionService::getUserBindInfo($context->user->id);
        if (OrangeSitePromotionService::judgeNoUserMatch($userBindInfo)) {
            Log::debug('[orangeSiteRechargeReport]当前用户没有匹配的report_user_bind_record', [
                'traceInfo' => $context->traceContext->getTraceInfo()]);
            $context->result = [
                'result' => false,
                'type' => 'no_user_match',
                'firstReason' => 'PromotionProtectCheck',
                'content' => '无用户匹配'
            ];
            return $context;
        }
        $promotionId = $userBindInfo->promotion_id ?? '';
        if (!$promotionId) {
            \Log::debug('[orangeSiteRechargeReport]当前用户没有匹配的promotionId,不走计划保护数', [
                'traceInfo' => $context->traceContext->getTraceInfo()
            ]);
            return $next($context);
        }
        $context->reportInfo['promotionId'] = $promotionId;
        $currentProtectNum = OrangeSitePromotionService::getCurrentPromotionProtectNum($context->user->distribution_channel_id,
            $promotionId);
        if ($currentProtectNum < $channelPromotionProtectSettingNum) {
            Log::debug('[orangeSiteRechargeReport]处于计划保护数之内', [
                'promotionId' => $promotionId,
                'currentProtectNum' => $currentProtectNum,
                'channelPromotionProtectSettingNum' => $channelPromotionProtectSettingNum,
                'traceInfo' => $context->traceContext->getTraceInfo()]);
            // !! 如果满足计划保护,那么 result 为true ,直接回传,不经过比例
            $context->result['result'] = true;
            $context->result['type'] = 'protected_eligible';
            $context->result['firstReason'] = 'PromotionProtectCheck';
            $context->result['result_ok_reason'] = 'promotionProtect';
            $context->result['content'] = '订单被计划保护';
            return $context;
        } else {
            return $next($context);
        }

    }
}