<?php

namespace App\Services;

use App\Constants\HttpStatus;
use App\Models\Backflow;
use App\Models\Config;
use Carbon\Carbon;
use Exception;

class BackflowService extends BaseService
{
    public static string $MODEL = Backflow::class;


    public static function findOne(array $search): ?Backflow
    {
        return self::$MODEL::where(static::getWhere($search))->first();
    }


    /**
     * 进行回水操作
     * @param $id
     * @return bool
     * @throws Exception
     */
    public static function grant($id): bool
    {
        $params = ['id' => $id];
        $backflow = static::findOne($params);
        if (!$backflow) throw new Exception('数据不存在', HttpStatus::CUSTOM_ERROR);
        if ($backflow->status !== 0) throw new Exception("已回水，无需再次回水", HttpStatus::CUSTOM_ERROR);
        $date = Carbon::now('Asia/Shanghai')->format('Y-m');
        if (strtotime($backflow->date) >= strtotime($date)) {
            throw new Exception('未到发放时间', HttpStatus::CUSTOM_ERROR);
        }

        //回水门槛金额
        $restriction = Config::where('field', 'huishui_restriction')->first()->val;
        $amount = bcadd($backflow->recharge_amount, $backflow->withdrawal_amount, 2);
        $amount = abs($amount);
        if ($amount >= $restriction) {
            //回水比例
            $ratio = Config::where('field', 'huishui_percentage')->first()->val;
            $backflow->backflow_ratio = $ratio;
            $backflow->amount = bcmul($amount, $backflow->backflow_ratio, 2);
            if ($backflow->amount > 0) {
                $percentage = bcmul($ratio, 100, 2);//返水比例百分比
                $percentage = floatval($percentage);
                $res = WalletService::updateBalance($backflow->member_id, $backflow->amount);
                BalanceLogService::addLog($backflow->member_id, $backflow->amount, $res['before_balance'], $res['after_balance'], "回水", $backflow->id, "日期:$backflow->date;盈亏:-{$amount}；回水比例:$percentage%");
            }
        } else {
            $backflow->amount = 0;
        }
        $backflow->grant_time = time();
        $backflow->status = 1;
        if (false !== $backflow->save()) return true;
        throw new Exception('发放失败', HttpStatus::CUSTOM_ERROR);
    }


    /**
     * @param $memberId string 会员ID
     * @param  $changeAmount float 充值或提现金额
     * @return Backflow
     */
    public static function updateOrCreate(string $memberId, float $changeAmount): Backflow
    {
        $data['date'] = Carbon::now('Asia/Shanghai')->format('Y-m');
        $data['backflow_ratio'] = Config::where('field', 'huishui_percentage')->first()->val;
        $data['member_id'] = $memberId;
        if ($changeAmount > 0) $data['recharge_amount'] = $changeAmount;
        else $data['withdrawal_amount'] = $changeAmount;

        $backflow = static::$MODEL::where('date', $data['date'])
            ->where('member_id', $memberId)->first();
        if ($backflow) {
            if ($changeAmount > 0) $field = "recharge_amount";
            else $field = 'withdrawal_amount';
            $backflow->backflow_ratio = $data['backflow_ratio'];
            $backflow->increment($field, $changeAmount);
            $backflow->save();
        } else {
            $backflow = static::$MODEL::create($data);
        }
        $restriction = Config::where('field', 'huishui_restriction')->first()->val;
        $difference = bcadd($backflow->recharge_amount, $backflow->withdrawal_amount, 2);
        $difference = abs($difference);
        if ($difference >= $restriction) {
            $backflow->amount = bcmul($difference, $backflow->backflow_ratio, 2);
        } else {
            $backflow->amount = 0;
        }
        $backflow->save();
        return $backflow;
    }


    public static function getWhere(array $search = []): array
    {
        $where = [];
        if (isset($search['id']) && !empty($search['id'])) {
            $where[] = ['backflow.id', '=', $search['id']];
        }

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

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


        if (isset($search['status']) && $search['status'] != '') {
            $where[] = ['backflow.status', '=', $search['status']];
        }
        
        if (!empty($search['first_name'])) {
            $where[] = ['users.first_name','like', '%'.$search['first_name'].'%'];
        }

        return $where;
    }

    public static function paginate(array $search = []): array
    {

        $date = Carbon::now('Asia/Shanghai')->format('Y-m');
        $query = static::$MODEL::join('users', 'users.member_id', '=', 'backflow.member_id')
                ->where(static::getWhere($search))
                ->where('backflow.date', '<', $date);

        $paginator = $query->select("backflow.*", "users.first_name","users.admin_note as user_admin_note")->orderByDesc('date')->orderBy('status')
            ->paginate($search['limit']);

//        $count = $query->count();
//        $query->with(['user'])->orderByDesc('date')->orderBy('status');
//        $list = $query->forPage($search['page'], $search['limit'])->get()->toArray();
//        return ['total' => $count, 'data' => $list];
        return ['total' => $paginator->total(), 'data' => $paginator->items()];
    }
}