<?php
namespace app\models\user;

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

class UserCoin extends BaseModel {

    use ModelTrait;

    public static function upsertAddr($uid, $symbol, $addr) 
    {
        $cond = ['uid'=>$uid, 'symbol'=>$symbol];
        $row = self::where($cond)->find();
        if ($row) {
            return self::where($cond)->update(['addr'=>$addr]);
        }else{
            return self::create([
                'uid'=>$uid,
                'symbol'=>$symbol,
                'addr'=>$addr,
            ]);
        }
    }

    public static function upsertCoin($uid, $symbol, $amount)
    {
        $cond = ['uid'=>$uid, 'symbol'=>$symbol];
        $row = self::where($cond)->find();
        if ($row) {
            return self::where($cond)->inc('balance', $amount)->update();
        }else{
            return self::create([
                'uid'=>$uid,
                'symbol'=>$symbol,
                'balance'=>$amount,
            ]);
        }
    }

    public static function getUserCoin($uid, $page, $limit)
    {
        $rows = self::alias('c')->join('dict_coin d', 'c.symbol=d.symbol')
            ->where('c.uid', $uid)
            ->field('d.icon,c.symbol,c.balance,c.addr')
            ->order('c.symbol asc')
            ->page(intval($page), intval($limit))
            ->select();
        count($rows) && $rows = $rows->toArray();
        return $rows;
    }
}