<?php

namespace common\models;

use fx\util\FxUtil;
use Yii;
use yii\base\Exception;

/**
 * This is the model class for table "fx_user_account".
 *
 * @property integer $id
 * @property integer $fx_uid
 * @property string $available_commission
 * @property string $closed_commission
 * @property string $total_commission
 * @property string $apply_commission
 * @property string $create_time
 * @property string $update_time
 * @property integer $status
 * @property integer $delete_flag
 */
class FxUserAccount extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'fx_user_account';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['fx_uid'], 'required'],
            [['fx_uid', 'status', 'delete_flag'], 'integer'],
            [['available_commission', 'closed_commission', 'total_commission', 'apply_commission', 'remaining_sum'], 'number'],
            [['create_time', 'update_time'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'fx_uid' => 'Fx Uid',
            'available_commission' => 'Available Commission',
            'closed_commission' => 'Closed Commission',
            'total_commission' => 'Total Commission',
            'apply_commission' => 'Apply Commission',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
            'status' => 'Status',
            'delete_flag' => 'Delete Flag',
        ];
    }

    /**
     * Function Description:获取账户信息
     * Function Name: getMyCommission
     * @return array|null|\yii\db\ActiveRecord
     *
     * @author 娄梦宁
     */
    public function getMyCommission($fx_uid = '')
    {
        if (empty($fx_uid)) {
            $fx_uid = FxUtil::$uid;
        }
        $select = [
            'a.headimgurl',
            'a.phone',
            'a.nickname',
            'b.status as accountStatus',
            'ifnull(b.available_commission,0) available_commission',
            'ifnull(b.total_commission,0) total_commission',
            'ifnull(b.apply_commission,0) apply_commission',
            'FORMAT(ifnull(b.remaining_sum,0),0) remaining_sum_s',
            'b.remaining_sum',
            'wx_openid'
        ];
        $result = self::find()->select($select)
            ->from('fx_user as a')
            ->leftJoin(self::tableName() . ' as b', 'a.uid=b.fx_uid')
            ->where(['=', 'a.uid', $fx_uid])
            ->asArray()
            ->one();
        return $result;
    }

    public function ApplyCommission($available_commission, $new_apply_commission)
    {
        $values = [
            'available_commission' => $available_commission,
            'apply_commission' => $new_apply_commission
        ];
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $base_one = self::findOne(['fx_uid' => FxUtil::$uid, 'delete_flag' => 0, 'status' => 1]);
            $base_one->attributes = $values;
            $res = $base_one->update();
            if (!$res) {
                throw new Exception('修改出错');
            }
            $transaction->commit();
            return true;
        } catch (Exception $e) {
            # 回滚事务
            $transaction->rollBack();
            return false;
        }
    }

    /**
     * Function Description:分销商注册手机号后开账户
     * Function Name: InsertNewUser
     *
     * @return bool
     *
     * @author 娄梦宁
     */
    public function InsertNewUser()
    {
        $values = [
            'fx_uid' => FxUtil::$uid,
            'create_time' => date('Y-m-d H:i:s')
        ];
        $this->attributes = $values;
        $res = $this->insert();
        if (!$res) {
            return false;
        }
        return true;
    }

    /*
     * 提现后用户账户变化
     */
    public function changeAccount($apply_id)
    {
        $fx_info = FxCommissionApply::find()->select(['fx_uid', 'apply_money'])
            ->from('fx_commission_apply')
            ->where(['id' => $apply_id])
            ->asArray()
            ->one();
        $money = (int)$fx_info['apply_money'];
        $fx_uid = $fx_info['fx_uid'];
        $sql = "UPDATE fx_user_account 
         set apply_commission=apply_commission -$money,
        closed_commission=closed_commission+$money
        where fx_uid=$fx_uid 
        ";
        $res = $this->getDb()->createCommand($sql)->execute();
        if (!$res) {
            return false;
        }
        return true;
    }

    /**
     * Des:修改分销账户状态
     * Name: changeStatus
     * @param $param
     * @return int
     * @author 倪宗锋
     */
    public function changeStatus($param)
    {
        if ($param['fx_status_id'] == 2) {
            $status = 1;
        } else {
            $status = 2;
        }
        $count = self::updateAll(['status' => $status], ['=', 'fx_uid', $param['fx_uid']]);
        return $count;
    }

    /**
     * Des:扣除用户余额
     * Name: changeStatus
     * @param $fx_uid
     * @param $money
     * @return bool
     * @author 倪宗锋
     */
    public function deductAmount($fx_uid, $money)
    {
        $sql = "UPDATE fx_user_account 
         set remaining_sum=remaining_sum - $money
        where fx_uid=$fx_uid 
        ";
        $res = $this->getDb()->createCommand($sql)->execute();
        if (!$res) {
            return false;
        }
        return true;
    }

    /**
     * Des:用户余额充值
     * Name: changeStatus
     * @param $fx_uid
     * @param $money
     * @return bool
     * @author 倪宗锋
     */
    public function rechargeAmount($fx_uid, $money)
    {
        $sql = "UPDATE fx_user_account 
         set remaining_sum=remaining_sum + $money
        where fx_uid=$fx_uid 
        ";
        $res = $this->getDb()->createCommand($sql)->execute();
        if (!$res) {
            return false;
        }
        return true;
    }
}
