<?php
/**
 * Created by PhpStorm.
 * User: scstf
 * Date: 2018/9/25
 * Time: 18:09
 */

namespace App\Api\Model;

use \System\Model;

class Withdraw_rule extends Model
{
    protected $table = 'withdraw_rule';

    public static function setRule($idd, $startTime, $endTime, $bettingMoney, $needBettingMoney)
    {
        $data = [
            'account_identity' => $idd,
            'start_time' => is_int ($startTime) ? $startTime : strtotime ($startTime) ?? time (),
            'end_time' => is_int ($endTime) ? $endTime : strtotime ($endTime) ?? time (),
            'bettingMoney' => $bettingMoney,
            'updated_at' => date ('Y-m-d H:i:s'),
            'needBettingMoney' => $needBettingMoney,
            'donate_start' => date ('Y-m-d H:i:s'),
        ];
        return self::insertGetId ($data);
    }

    /**
     * 更新用户增量流水
     * @param string $idd 用户账户UUID
     * @param  $money 父订单金额
     * @param int $rate 增量倍数
     * @return int
     */
    function updateRule($idd, $money, $rate)
    {
        $withdrawRule = new self();
        $with = $withdrawRule->where ('account_identity', $idd)->first ();
        $time = date ('Y-m-d H:i:s');
        $ret = 1;
        $need = (float)$money * ($rate - 1);//目标流水差额
        if (!$with) {
            self::setRule ($idd, $time, $time, 0, $need);
        } else {
            $with->increment ('needBettingMoney', $need);//目标流水差额
            $with->updated_at = date ('Y-m-d H:i:s');
            $ret = $with->update ();
        }
        return $ret;
    }

    /**
     * 提现时验证用户的流水记录
     * @param string $idd 用户账户编号uuid
     * @return null 没有记录返回NULL,成功返回用户当前有效下注总流水和目标总流水
     */
     function check($idd)
    {
        $where = ['account_identity' => $idd];
        $data = self::where ($where)->first (['bettingMoney', 'needBettingMoney', 'donate_start']);
        if (!$data) return null;
        $time = $data->donate_start;
        $bet = (new MoneyBuy())->getBetMoney ($time, $idd);//常规投注
        $sixBet = (new SixMoneyBuy())::getBetMoney ($time, $idd);//六合投注
        $data->bettingMoney = $bet + $sixBet;//总投注流水
        $recharge = Money_recharge::where ('account_identity', $idd)
            ->where ('complete_time', '>=', $time) //首笔金额发生时间
            ->where ('status', 1) //订单状态为成功
            //->whereIn ('trade_type', [11, 14])
            ->sum (DB::Raw ('money * rate'));//资金表中的流水倍数和
        $data->needBettingMoney += $recharge;//差额流水+资金表中流水要求=总目标流水
        return $data;
    }

    public static function rmRule($idd)
    {
        return self::where ('account_identity', $idd)->delete ();
    }

    public static function getRule($id)
    {
        return self::where ('id', $id)->first ();
    }

}