<?php

namespace App\Services;

use App\Models\Config;
use App\Models\Rebate;
use App\Models\Rebate as RebateModel;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;

class RebateService extends BaseService
{

    public static string $MODEL = Rebate::class;

    /**
     * @description: 获取查询条件
     * @param array $search
     * @return array
     */
    public static function getWhere(array $search = []): array
    {
        $where = [];
        if (isset($search['id']) && !empty($search['id'])) {
            $where[] = ['id', '=', $search['id']];
        }

        if (isset($search['member_id']) && !empty($search['member_id'])) {
            $where[] = ['member_id', '=', $search['member_id']];
        }

        if (isset($search['first_name']) && !empty($search['first_name'])) {
            $where[] = ['first_name', '=', $search['first_name']];
        }

        if (isset($search['username']) && !empty($search['username'])) {
            $where[] = ['username', '=', $search['username']];
        }

        if (isset($search['status']) && $search['status'] != '') {
            $where[] = ['status', '=', $search['status']];
        }

        if (isset($search['date']) && !empty($search['date'])) {
            $where[] = ['date', '=', $search['date']];
        }

        return $where;
    }


    /**
     * @description: 查询单条数据
     * @param array $search
     * @return RebateModel|null
     */
    public static function findOne(array $search): ?Rebate
    {
        return self::$MODEL::where(static::getWhere($search))->first();
    }

    /**
     * @description: 查询所有数据
     * @param array $search
     * @return Collection
     */
    public static function findAll(array $search = []): Collection
    {
        return self::$MODEL::where(self::getWhere($search))->get();
    }

    /**
     * @description: 分页查询
     * @param array $search
     * @return array
     */
    public static function paginate(array $search = []): array
    {
        $limit = $search['limit'] ?? 15;
        $date = Carbon::now('America/New_York')->format('Y-m-d');
        $paginator = static::$MODEL::where(self::getWhere($search))
            ->where('date', '<', $date)
            ->with(['member'])
            ->orderByDesc('date')
            ->orderBy('status')
            ->orderByDesc('betting_amount')
            ->paginate($limit);
        return ['total' => $paginator->total(), 'data' => $paginator->items()];
    }


    //更新有效投注额
    public static function updateEffectiveBettingAmount($rebate, $amount): void
    {
        if ($rebate) {
            $rebate->increment('effective_betting_amount', $amount);
        }
    }

    //笔笔返 根据某天的有效投注额，和反水比例，进行笔笔返
    public static function BibiReturn(Rebate $rebate, $amount): bool
    {
        //比比返   返水比例
        $rebate_ratio = Config::where('field', 'rebate')->first()->val;
        //比比返   返水比例百分比
        $percentage = bcmul($rebate_ratio, 100, 2);
        $percentage = floatval($percentage);
        $rebateAmount = bcmul($amount, $rebate_ratio, 2); //
        $rebateAmount = floatval($rebateAmount);
        if ($rebateAmount > 0) {
            $res = WalletService::updateBalance($rebate->member_id, $rebateAmount);
            BalanceLogService::addLog($rebate->member_id, $rebateAmount, $res['before_balance'], $res['after_balance'], "笔笔返", $rebate->id, "日期:$rebate->date;有效投注:{$amount}；比例:$percentage%");
        }
        $rebate->rebate_ratio = $rebate_ratio;
        $rebate->status = RebateModel::STATUS_FAN_YONG;
        $rebate->amount = $rebateAmount;
        $rebate->audited_by = request()->user->username;
        $rebate->grant_time = time();
        if (false !== $rebate->save()) return true;
        return false;
    }

}