<?php


namespace App\Services;

use App\Services\BaseService;
use App\Models\Recharge;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use App\Services\WalletService;
use App\Services\CollectService;
use App\Services\UserService;
use App\Services\BalanceLogService;
use App\Helpers\TronHelper;

/**
 * 用户充值记录
 */
class RechargeService extends BaseService
{
    /**
     * @description: 模型
     * @return {string}
     */
    public static function model(): string
    {
        return Recharge::class;
    }

    /**
     * @description: 枚举
     * @return {*}
     */
    public static function enum(): string
    {
        return '';
    }

    /**
     * @description: 获取查询条件
     * @param {array} $search 查询内容
     * @return {array}
     */
    public static function getWhere(array $search = []): array
    {
        $where = [];
        if (isset($search['coin']) && !empty($search['coin'])) {
            $where[] = ['coin', '=', $search['coin']];
        }
        if (isset($search['net']) && !empty($search['net'])) {
            $where[] = ['net', '=', $search['net']];
        }
        if (isset($search['to_address']) && !empty($search['to_address'])) {
            $where[] = ['to_address', '=', $search['to_address']];
        }
        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['txid']) && !empty($search['txid'])) {
            $where[] = ['txid', '=', $search['txid']];
        }
        if (isset($search['status']) && $search['status'] != '') {
            $where[] = ['status', '=', $search['status']];
        }
        if (isset($search['type']) && $search['type'] != '') {
            $where[] = ['type', '=', $search['type']];
        }
        return $where;
    }

    /**
     * @description: 查询单条数据
     * @param array $search
     * @return \App\Models\Coin|null
     */
    public static function findOne(array $search): ?Recharge
    {
        return self::model()::where(self::getWhere($search))->first();
    }

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

    /**
     * @description: 分页查询
     * @param array $search
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public static function paginate(array $search = [])
    {
        $limit = isset($search['limit']) ? $search['limit'] : 15;
        $paginator = self::model()::where(self::getWhere($search))
            ->orderBy("created_at", 'desc')
            ->paginate($limit);
        return ['total' => $paginator->total(), 'data' => $paginator->items()];
    }


    /**
     * @description: 同步会员的USDT充值记录
     * @param {*} $memberId
     * @return {*}
     */
    public static function syncUsdtRechargeRecords($memberId)
    {
        $walletInfo = WalletService::findOne(['member_id' => $memberId]);
        $data = TronHelper::getTrc20UsdtRecharges($walletInfo->address);
        
        foreach ($data as $k => $v) {
            $v['member_id'] = $memberId;
            $v['net'] = $walletInfo->net;
            $V['type'] = self::model()::TYPE_AUTO;
            $v['created_at'] = now();
            $v['updated_at'] = now();
            $data[$k] = $v;
        }
        $m = new (self::model());
        $result = $m->insertOrIgnore($data);
        return $result;
    }

    /**
     * @description: 充值确认
     * @param {*} $txid
     * @return {*}
     */
    public static function handleRechargeConfirmation($txid)
    {
        $info = self::findOne(['txid' => $txid]); // 获取充值的信息

        // 待处理进行充值
        if ($info['status'] == self::model()::STATUS_STAY) {
            $result = TronHelper::getTransactionConfirmations($txid);

            if ($result['success']) {
                $data = [];
                $data['block_height'] = $result['block_number'];
                $data['confirmations'] = $result['latest_block'] - $result['block_number'];

                if ($data['confirmations'] >= TronHelper::CONFIRMED_NUMBER) {
                    $data['status'] = self::model()::STATUS_SUCCESS;
                    $where = self::getWhere(['txid' => $txid, 'status' => self::model()::STATUS_STAY]);
                    $recharge = self::model()::where($where)->update($data);

                    // 更新成功，变动可用余额
                    if ($recharge) {
                        $balanceData = WalletService::updateBalance($info->member_id, $info->amount);
                        BalanceLogService::addLog($info->member_id, $info->amount, $balanceData['before_balance'], $balanceData['after_balance'], '充值', $info->id, '');

                        CollectService::createCollect($info->to_address, $info->coin, $info->net);

                        $amount = floatval($info->amount);
                        $text = "  ➕ 充币到帐 +{$amount} USDT\n";
                        $text .= "链上哈希：{$txid}\n";
                        $text .= "当前余额：{$balanceData['after_balance']}\n";
                        TopUpService::notifyTransferSuccess($info->member_id, $text);
                    }
                }
            }
        }

    }

    /**
     * @description: 同步待处理的充值记录
     * @return {*}
     */
    public static function syncRechargeStay()
    {
        $list = self::findAll(['status' => self::model()::STATUS_STAY ,'type' => self::model()::TYPE_AUTO]);
        foreach ($list as $k => $v) {
            self::handleRechargeConfirmation($v->txid);
        }
    }
}