<?php


namespace App\Services;


// Ad广告充值来源
use App\Facade\TableName;
use App\Models\AccountsSource;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class AdRecharge
{
    public function attribute($UserID, $RegisterDate, $Recharge, $IsFirst = 0)
    {

        $dateID = Carbon::parse($RegisterDate)->format('Ymd');
        // 查找用户注册日期
        $diff_d = Carbon::parse($RegisterDate)->diff(now())->days;
        // 查找用户归属渠道
        $getUserAdChannel = (new AccountsSource())->getUserAdChannel($UserID);

        // 查询广告渠道是否存在
        $adChannelExist = cache()->remember('adChannelExist_' . $dateID . '_' . $getUserAdChannel, 60 * 24, function () use ($dateID, $getUserAdChannel) {

            return DB::table(TableName::QPRecordDB() . 'RecordAdChannelRecharge')
                ->where('DateID', $dateID)
                ->where('AdChannel', $getUserAdChannel)
                ->first();

        });

        $addCount = !empty($IsFirst) ? 1 : 0;

        if (in_array($diff_d, [0, 1, 2, 7]) && !empty($getUserAdChannel)) {
            if ($adChannelExist) {

                DB::table(TableName::QPRecordDB() . 'RecordAdChannelRecharge')
                    ->where('DateID', $dateID)
                    ->where('AdChannel', $getUserAdChannel)
                    ->increment("D{$diff_d}Count", $addCount, [
                        "D{$diff_d}Sum" => DB::raw("D{$diff_d}Sum + $Recharge")
                    ]);
            } else {
                DB::table(TableName::QPRecordDB() . 'RecordAdChannelRecharge')
                    ->where('DateID', $dateID)
                    ->where('AdChannel', $getUserAdChannel)
                    ->insert([
                        'DateID' => $dateID,
                        'AdChannel' => $getUserAdChannel,
                        "D{$diff_d}Count" => 1,
                        "D{$diff_d}Sum" => $Recharge
                    ]);
            }
        }


        return true;
    }
}
