<?php
/**
 * 分销用户钱包
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/5/4
 * Time: 10:29
 */

namespace common\util;


use common\models\FxUserAccount;
use common\models\FxUserAmountLog;
use common\models\OrderMain;

class FxAmount
{
    /**
     * 余额支付
     * @param $fx_uid
     * @param $amount
     * @return array
     */
    public static function pay($fx_uid, $amount)
    {
        /****判断余额是否充足***/
        $fxUserAccount = new FxUserAccount();
        $info = $fxUserAccount->getMyCommission($fx_uid);
        if ($info['remaining_sum'] < $amount) {
            return Util::returnArrEr('账户余额不足！');
        }
        /**扣除余额**/
        $flag = $fxUserAccount->deductAmount($fx_uid, $amount);
        if ($flag) {
            static::addLog($fx_uid, 2, $amount, '');
            return Util::returnArrSu();
        } else {
            return Util::returnArrEr('余额支付失败！');
        }
    }

    /**
     *  退款
     * @param $fx_uid
     * @param $amount
     * @return array
     */
    public static function refund($fx_uid, $amount)
    {
        $fxUserAccount = new FxUserAccount();
        $flag = $fxUserAccount->rechargeAmount($fx_uid, $amount);
        if ($flag) {
            static::addLog($fx_uid, 3, $amount, '');
            return Util::returnArrSu();
        } else {
            return Util::returnArrEr('退款失败！[amount_1001]');
        }
    }

    /**
     *  充值
     * @param $fx_uid
     * @param $amount
     * @return array
     */
    public static function recharge($fx_uid, $amount)
    {
        $fxUserAccount = new FxUserAccount();
        $flag = $fxUserAccount->rechargeAmount($fx_uid, $amount);
        if ($flag) {
            static::addLog($fx_uid, 1, $amount, '');
            return Util::returnArrSu();
        } else {
            return Util::returnArrEr('充值失败！[amount_1002]');
        }
    }

    /**
     * 添加日志
     * @param $fx_uid
     * @param $trade_type int 交易类型 1、充值 2、支出 3、退款
     * @param $amount
     * @param $msg
     * @return array
     */
    public static function addLog($fx_uid, $trade_type, $amount, $msg)
    {
        $fxUserAccount = new FxUserAccount();
        $info = $fxUserAccount->getMyCommission($fx_uid);
        $remaining_sum = $info['remaining_sum'];
        $fxUserAmountLog = new FxUserAmountLog();
        return $fxUserAmountLog->addLog($fx_uid, $trade_type, $amount, $remaining_sum, $msg);
    }

    /**
     * 取消订单加扣款
     * @param $params
     * @return array
     */
    public function cancelOrder($params)
    {
        $order = new OrderMain();
        $orderInfo = $order->getOrderInfo($params['order_id']);
        $fx_uid = $orderInfo['fx_uid'];
        return self::refund($fx_uid, $params['refund_fee']);
    }
}