<?php

namespace App\Services;

use App\Models\AccountsInfo;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class FirstPayStatService
{
    public function stat($order_sn)
    {
        Log::info(
            '首次付费统计start',
            [
                'order_sn' => $order_sn
            ]
        );
        $order = \App\Models\Order::query()->where([
            'order_sn' => $order_sn
        ])->first();
        if(!$order){
            return false;
        }
        $has = \App\Models\Order::where([
            'user_id' => $order->user_id,
            ['finished_at', '<', $order['created_at']]
        ])->count();
        if (!$has) {

            Log::info(
                '首次付费统计新增',
                [
                    'order_sn' => $order_sn
                ]
            );
            $res = DB::table('QPStatisticsDB.dbo.UserFirstPayPlayRoundPoints')->where('UserID', $order['user_id'])->first();
            if (!$res) {
                $account = AccountsInfo::query()->where('UserID', $order['user_id'])->first();
                $counts = DB::table('QPRecordDB.dbo.RecordUserGameDayCount')
                    ->select('GameID', DB::raw('sum(Cnt) as Cnt'))
                    ->where([
                        'UserID' => $order->user_id,
                        ['DateID', '<=', date('Ymd')],
                    ])
                    ->groupBy('GameID')
                    ->orderBy('Cnt', 'desc')->first();
                DB::table('QPStatisticsDB.dbo.UserFirstPayPlayRoundPoints')->insert([
                    'UserID' => $order->user_id,
                    'GameID' => $account->GameID,
                    'RegTime' => $account->RegisterDate,
                    'KindID' => $counts->GameID ?? 0,
                    'FirstPayTime' => $order->finished_at,
                    'PlayRounds' => $counts->Cnt ?? 0,
                    'UpdatedAt' => date('Y-m-d H:i:s'),
                ]);
            }
            $res = DB::table('QPStatisticsDB.dbo.DailyProfitStat')
                ->where('Date', date('Y-m-d'))->count();
            if ($res) {
                DB::table('QPStatisticsDB.dbo.DailyProfitStat')
                    ->where('Date', date('Y-m-d'))
                    ->increment('HadPaidUsers');
            } else {
                DB::table('QPStatisticsDB.dbo.DailyProfitStat')->insert([
                    'Date' => date('Y-m-d'),
                    'NewUsers' => 0,
                    'HadPaidUsers' => 1,
                    'PlayUsers' => 0,
                    'UpdatedAt' => date('Y-m-d H:i:s'),
                ]);
            }
            return true;
        }
        return false;
    }
}
