<?php
namespace backend\models\forms;

use backend\models\WithdrawApi;
use Yii;
use yii\base\Model;

class WithdrawForm extends Model
{
    public $login;
    public $amount;
    public $true_name;
    public $bank_province;
    public $bank_city;
    public $bank_name;
    public $bank_sub_name;
    public $bank_card_no;
    public $swift;
    public $mobile;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['login', 'amount', 'true_name', 'bank_province', 'bank_city', 'bank_name', 'bank_sub_name', 'bank_card_no', 'swift', 'mobile'], 'required'],
            [['login'], 'integer'],
            [['amount'], 'match', 'pattern' => '/^([1-9]\d*|[0])(\.\d{1,2})?$/'],
            [['bank_card_no'], 'integer'],
            [['mobile'], 'match', 'pattern' => '/^1(3[0-9]|4[57]|5[0-35-9]|7[01678]|8[0-9])\d{8}$/'],
        ];
    }

    /**
     * @return bool
     */
    public function addWithdraw()
    {
        if (Yii::$app->getUser()->getIsGuest()) {
            $this->addError('login', '用户未登录');
            Yii::$app->getUser()->loginRequired();
            return false;
        }
        if ($this->validate()) {
            $data = [];
            $data['member_id'] = Yii::$app->getUser()->getId();
            $data['amount'] = $this->amount;
            $data['true_name'] = $this->true_name;
            $data['bank_name'] = $this->bank_name;
            $data['bank_sub_name'] = $this->bank_sub_name;
            $data['bank_card_no'] = $this->bank_card_no;
            $data['bank_province'] = $this->bank_province;
            $data['bank_city'] = $this->bank_city;
            $data['mobile'] = $this->mobile;
            $data['login'] = $this->login;
            $data['swift'] = $this->swift;
            $api = new WithdrawApi();
            $result = $api->addWithdraw($data);
            if ($result['code'] == 0) {
                if (is_array($result['message'])) {
                    $this->addErrors($result['message']);
                } else {
                    $this->addError('receivers', $result['message']);
                }
            }
        }
        return !$this->hasErrors();
    }
}