<?php

namespace App\Services;

use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;

class PaidRewardStatisticsService
{
    /**
     * @param $DateID
     * @param $type
     * @param mixed $amount 单位：分
     * @return mixed
     */
    public function incrementRecordByDateIDAndType($DateID, $type, $amount)
    {
        $this->createIfNotExist($DateID, $type);
        return DB::table('QPRecordDB.dbo.RecordPaidRewardDailyStatistics')
            ->where(['DateID' => $DateID, 'StatType' => $type])
            ->increment('TotalAmount', $amount);
    }

    private function createIfNotExist($DateID, $type)
    {
        $exist = DB::table('QPRecordDB.dbo.RecordPaidRewardDailyStatistics')
            ->where(['DateID' => $DateID, 'StatType' => $type])->first();
        if (!$exist) {
            try {
                DB::table('QPRecordDB.dbo.RecordPaidRewardDailyStatistics')->insert([
                    'DateID' => $DateID,
                    'StatType' => $type,
                ]);
            } catch (QueryException $e) {
                if (stripos($e->getMessage(), 'duplicate key') === false) {
                    throw $e;
                }
            }

        }
        return true;
    }
}
