<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/5/4
 * Time: 11:47
 */

namespace common\models;


use common\util\Util;
use yii\db\ActiveRecord;
use yii\db\Expression;

class FxUserAmountLog extends ActiveRecord
{
    public static function tableName()
    {
        return 'fx_user_amount_log';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['log_id', 'fx_uid', 'trade_type'], 'integer'],
            [['amount', 'remaining_sum'], 'number'],
            [['create_time', 'update_time'], 'safe'],
            [['msg'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'log_id' => 'log_id',
            'fx_uid' => 'fx_uid',
            'amount' => 'amount',
            'remaining_sum' => 'remaining_sum',
            'trade_type' => 'trade_type',
            'create_time' => 'create_time',
            'update_time' => 'Update Time',
            'msg' => 'msg',
        ];
    }

    /**
     *  添加记录
     * @param $fx_uid
     * @param $trade_type
     * @param $amount
     * @param $msg
     * @return array
     */
    public function addLog($fx_uid, $trade_type, $amount, $remaining_sum, $msg)
    {
        $param = [
            'fx_uid' => $fx_uid,
            'amount' => $amount,
            'trade_type' => $trade_type,
            'remaining_sum' => $remaining_sum,
            'create_time' => date('Y-m-d H:i:s'),
            'msg' => $msg
        ];
        $this->attributes = $param;
        $insertFlag = $this->insert();
        if (!$insertFlag) {
            return Util::returnArrEr('add amount_log fail!');
        }
        return Util::returnArrSu();
    }

    /**
     * 获取账户变更记录
     * @param $params
     * @return array
     */
    public function getList($params)
    {
        $offset = ($params['current_page'] - 1) * $params['page_size'];
        $select = [
            new Expression('FORMAT(amount,0) as amount'),
            'trade_type',
            new Expression('FORMAT(remaining_sum,0) as remaining_sum'),
            'create_time',
            new Expression("if(trade_type=1,'充值',if(trade_type=2,'支出','退款')) as type_name")
        ];
        $where = ['=', 'fx_uid', $params['fx_uid']];
        $result = self::find()->select($select)
            ->from(self::tableName())
            ->where($where)
            ->orderBy('create_time DESC')
            ->offset($offset)
            ->limit($params['page_size'])
            ->asArray()
            ->all();
        return $result;
    }


}