<?php

namespace App\Http\Controllers\API\Redis;

use App\Models\SetAddress;
use App\Models\TransferRecord;
use App\Models\UserWallet;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class CheckArrivalCl
{
    public function check($hash, $price, $address, $to)
    {
        # 添加订单后--查询是否到账--最多检测20次
        for ($i = 1; $i <= 10; $i++) {
            $type = self::IntervalCheck($hash, $price, $address, $to);
            if ($type) {
                Log::error('购买成功');
                break;
            }
            Log::error('未到账');
            sleep(1);
        }
    }

    /**
     * 向redis发送请求
     */
    public function IntervalCheck($hash, $price, $address, $to)
    {
        # 获取状态
        $item = UserWallet::query()->where('hash', $hash)->first(['status']);
        if ($item->status == 1) {
            return true;
        }
        # 获取交易
        $obj = (object)[];
        $obj->hash = $hash;
        $obj->notify_url = config('address.callback');
        $obj->retry = 1;
        $obj->amount = $price;
        # 要转小写
        $obj->form = strtolower($address);
        # 保留一个旧的
        $obj->old_form = $address;
        $obj->to = strtolower($to);
        Redis::rpush('pay_notify', json_encode($obj));
        return false;
    }

    /**
     * 中奖转账--只能发起一次
     */
    public function WinnerTransfer($to, $box_id, $amount, $type)
    {
        if (empty($to) || empty($box_id) || empty($amount) || empty($type)) {
            Log::info('缺少转账信息');
            return false;
        }
        # 不能重复
        $transter = TransferRecord::query()->where('blind_box_id', $box_id)->where('to', $to)->get();
        if ($transter && count($transter)) {
            Log::info('此账户购买的盒已转账或退款');
            return false;
        }
        # 获取收款钱包和私钥
        $items = SetAddress::query()->first(['address', 'key_word']);
        $my_address = $items->address;
        $key_word = $items->key_word;
        $obj = [
            'form' => $my_address,
            'to' => $to,
            'key_word' => $key_word,
            'amount' => $amount,
            'box_id' => $box_id,
            'type' => $type
        ];
        # 向redis插入数据
        Redis::rpush('winner_transfer', json_encode($obj));
        return true;
    }

    /**
     * 转账回调
     * item = {
     *  to:"",
     *  box_id:'',
     *  hash:'',
     *  status:',
     *  amount:'
     * }
     */
    public function TransferCallback($item)
    {
        # 无论成功与否，都添加记录
        TransferRecord::query()->create(['to' => $item['to'], 'price' => $item['amount'],
            'hash' => $item['hash'], 'status' => $item['status'], 'blind_box_id' => $item['box_id'], 'type' => $item['type']]);
        return true;
    }
}
