<?php


namespace App\Modules\OrangeSite\Services;


use Illuminate\Support\Facades\DB;

class OrangeSitePromotionService
{
    public static function getCurrentPromotionProtectNum($channelId, $promotionId)
    {
        return DB::table('orange_site_recharge_report_protect_records')
                ->where([
                    ['channel_id', '=', $channelId],
                    ['use_type', '=', 'promotionId'],
                    ['use_type_id', '=', $promotionId],
                    ['is_enabled', '=', 1]
                ])->orderBy('id', 'desc')
                ->first()->current_protect_num ?? 0;
    }

    public static function setCurrentPromotionProtectNum($channelId, $promotionId, $maxNum)
    {
        $now = date('Y-m-d H:i:s');
        $exists = DB::table('orange_site_recharge_report_protect_records')
            ->where([
                'channel_id' => $channelId,
                'use_type' => 'promotionId',
                'use_type_id' => $promotionId,
                'is_enabled' => 1
            ])->exists();
        if ($exists) {
            DB::table('orange_site_recharge_report_protect_records')
                ->where([
                    'channel_id' => $channelId,
                    'use_type' => 'promotionId',
                    'use_type_id' => $promotionId,
                    'is_enabled' => 1,
                ])->where('current_protect_num', '<', $maxNum)
                ->increment('current_protect_num', 1, ['updated_at' => $now]);
        } else {
            DB::table('orange_site_recharge_report_protect_records')
                ->insert([
                    'channel_id' => $channelId,
                    'use_type' => 'promotionId',
                    'use_type_id' => $promotionId,
                    'is_enabled' => 1,
                    'current_protect_num' => 1,
                    'created_at' => $now,
                    'updated_at' => $now,
                ]);
        }

    }

    /**
     * 获取用户匹配信息
     * @param $uid
     * @return mixed
     */
    public static function getUserBindInfo($uid)
    {
        return DB::table('report_user_bind_records')
            ->where(['uid' => $uid])
            ->select('platform', 'uid', 'promotion_id')
            ->first();
    }

    /**
     * 判断是否有用户匹配track , true-无用户匹配,false-有用户匹配
     * @param $userBindRecord
     * @return bool
     */
    public static function judgeNoUserMatch($userBindRecord)
    {
        if (!$userBindRecord) {
            return true;
        }
        if ('no_track' == $userBindRecord->platform) {
            return true;
        }

        if ('orange' != $userBindRecord->platform) {
            return true;
        }

        return false;

    }
}