<?php


namespace App\Services;

use App\Services\BaseService;
use App\Models\Collect;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use App\Helpers\TronHelper;
use App\Services\WalletService;

/**
 * 归集记录
*/
class CollectService extends BaseService 
{
    public static $THRESHOLD = 10; // 最小归集金额（USDT）
    /**
     * @description: 模型
     * @return {string}
     */    
    public static function model() :string
    {
        return Collect::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['txid']) && !empty($search['txid'])){
            $where[] = ['txid', '=', $search['txid']];
        }
        if(isset($search['status']) && $search['status'] != ''){
            $where[] = ['status', '=', $search['status']];
        }
        if (isset($search['amount']) && is_numeric($search['amount'])) {
            $where[] = ['amount', '>=', $search['amount']];
        }
        return $where;
    }

     /**
     * @description: 查询单条数据
     * @param array $search
     * @return \App\Models\Coin|null
     */
    public static function findOne(array $search): ?Collect
    {
        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))->paginate($limit);
        return ['total' => $paginator->total(), 'data' => $paginator->items()];
    }
    

    /**
     * @description: 生成归集记录
     * @param {*} $address
     * @param {*} $coin
     * @param {*} $net
     * @return {*}
     */    
    public static function createCollect($address ,$coin ,$net)
    {
        $amount = TronHelper::getTrc20Balance($address);    // 获取地址的余额

        $info = self::findOne(['from_address' => $address ,'status' => self::model()::STATUS_STAY]);
        
        if($amount >= 0 ){
            if(empty($info)){
                $data = [];
                $data['from_address'] = $address;
                $data['amount'] = $amount;
                $data['coin'] = $coin;
                $data['net'] = $net;
                self::model()::create($data);

            }else{
                $info->amount = $amount;
                $info->save();
            }
        }

    }

    /**
     * @description: 处理待归集的
     * @return {*}
     */    
    public static function syncCollectStay()
    {
        $to_address = self::getUsdtAddress();   // 转账的接收地址
        $trx_private_key = self::getTrxPrivateKey(); // 获取TRX能量的秘钥
        if($to_address && $trx_private_key){
            $list = self::findAll(['status' => self::model()::STATUS_STAY ,'amount' => self::$THRESHOLD]);
            foreach($list as $k => $v){
                $data = [];
                $wallets = WalletService::findOne(['address' => $v['from_address']]);
                $privateKey = $wallets['private_key'];

                $trxBalance = TronHelper::getTrxBalance($v['from_address']);
                if($trxBalance < 10){
                    TronHelper::sendTrx($trx_private_key,$v['from_address'],10);
                }

                $transferResult = TronHelper::transferUSDT($privateKey,$to_address,$v['amount']);
                $data['to_address'] = $to_address;
                if($transferResult['success']){
                    $data['txid'] = $transferResult['txid'];
                    $data['remark'] = 'success';
                    $data['status'] = self::model()::STATUS_START;
                }else{
                    $data['remark'] = $transferResult['error'];
                }
                $data['updated_at'] = now();
                self::model()::where(self::getWhere(['id' => $v['id']]))->update($data);
            }
        }

    }

    /**
     * @description: 获取归集平台的接收地址
     * @return {*}
     */    
    public static function getUsdtAddress()
    {
        $usdt_address = config('app.usdt_address');
        return $usdt_address;
    }

    /**
     * @description: 获取TRX能量账号秘钥
     * @return {*}
     */    
    public static function getTrxPrivateKey()
    {
        $str = config('app.trx_private_key');
        return $str;
    }
   
}