<?php
namespace app\models\coin;

use crmeb\traits\ModelTrait;
use crmeb\basic\BaseModel;

class UserCoinTransfer extends BaseModel {

    use ModelTrait;

    /**
     * 增加一条挖矿记录
     *
     * @param $uid
     * @param $orderId
     * @param $symbol
     * @param $amount
     * @return UserCoinTransfer|\think\Model
     */
    public static function addMining($uid, $orderId, $symbol, $amount) {
        $data = [
            'uid' => $uid,
            'order_id' => $orderId,
            'symbol' => $symbol,
            'amount' => $amount,
            'ts' => time(),
        ];

        return self::create($data);
    }

    /**
     * 增加一条提现记录
     *
     * @param $uid
     * @param $symbol
     * @param $amount
     */
    public static function withdrawal($uid, $symbol, $to, $amount) {
        return self::create([
            'uid' => $uid,
            'symbol' => $symbol,
            'to' => $to,
            'amount' => $amount,
            'ts' => time(),
            'out' => 1,
            'status' => 1,
        ]);
    }

    /**
     * 确认提币操作
     *
     * @param $id
     * @return UserCoinTransfer
     */
    public static function confirmWithdrawal($id) {
        return self::where('id', $id)->update(['status'=>0]);
    }

    /**
     * 取得用户币变动记录
     *
     * @param $uid
     * @param $page
     * @param int $limit
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getUserTransferred($uid, $page, $limit=20) {
        $res = self::where('uid', $uid)->order('ts desc')
            ->alias('t')->join('dict_coin c', 'c.symbol=t.symbol')
            ->field('t.symbol, c.icon, t.from, t.to, t.amount, t.out, t.ts')
            ->limit(($page-1) * $limit, $limit)->select()->toArray();
        return $res;
    }

    /**
     * $uid 的 $symbol 币, $addr 这个地址是否提现过
     *
     * @param $uid
     * @param $symbol
     * @param $addr
     * @return object|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function hasTransferred($uid, $symbol, $addr) {
        $row = self::where(['uid'=>$uid, 'symbol'=>$symbol, 'to'=>$addr, 'out'=>1])->limit(1)->find();
        return $row;
    }
}