<?php


namespace App\Models;


use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class RecordUserDataStatistics extends Model
{
    const TABLE = 'QPRecordDB.dbo.RecordUserDataStatistics';
    protected $table = self::TABLE;

    // 用户记录表
    public static function updateOrAdd($UserID, $Withdraw = 0, $Recharge = 0, $ServiceFee = 0,$Handsel = 0)
    {
        $first = DB::connection('write')->table('QPRecordDB.dbo.RecordUserDataStatisticsNew')
            ->where('DateID',date('Ymd'))
            ->where('UserID', $UserID)
            ->first();
        $userTotal = DB::connection('write')->table('QPRecordDB.dbo.RecordUserTotalStatistics')
            ->where('UserID', $UserID)
            ->first();

        $RechargeTimes=$Recharge?1:0;

        // 存在就修改  充值  提现数据
        if (!$userTotal) {
            $TotalData = [
                'Recharge' => $Recharge,
                'Withdraw' => $Withdraw,
                'UserID' => $UserID,
                'ServiceFee' => $ServiceFee,
                'Handsel' => $Handsel,
                'RechargeTimes'=>$RechargeTimes
            ];
            DB::connection('write')->table('QPRecordDB.dbo.RecordUserTotalStatistics')->insert($TotalData);
        }else{
            $updateData = [
                'Recharge' => $userTotal->Recharge + $Recharge,
                'Withdraw' => $userTotal->Withdraw + $Withdraw,
                'ServiceFee' => $userTotal->ServiceFee + $ServiceFee,
                'Handsel' => $userTotal->Handsel + $Handsel,
                'RechargeTimes'=>$userTotal->RechargeTimes + $RechargeTimes
            ];
            DB::connection('write')->table('QPRecordDB.dbo.RecordUserTotalStatistics')
                ->where('UserID', $UserID)
                ->update($updateData);
        }

        // 每日数据
        if (!$first) {
            $data = [
                'Recharge' => $Recharge,
                'Withdraw' => $Withdraw,
                'UserID' => $UserID,
                'DateID' => date('Ymd'),
                'ServiceFee' => $ServiceFee,
                'Handsel' => $Handsel,
                'RechargeTimes'=>$RechargeTimes
            ];
            DB::connection('write')->table('QPRecordDB.dbo.RecordUserDataStatisticsNew')->insert($data);

        }else{
            $updateData = [
                'Recharge' => $first->Recharge + $Recharge,
                'Withdraw' => $first->Withdraw + $Withdraw,
                'ServiceFee' => $first->ServiceFee + $ServiceFee,
                'Handsel' => $first->Handsel + $Handsel,
                'RechargeTimes'=>$first->RechargeTimes + $RechargeTimes
            ];
            DB::connection('write')->table('QPRecordDB.dbo.RecordUserDataStatisticsNew')
                ->where('UserID', $UserID)
                ->where('DateID',date('Ymd'))
                ->update($updateData);
        }

    }
}

