<?php
namespace backend\modules\ib\controllers;

use backend\models\forms\WithdrawForm;
use backend\models\RateApi;
use backend\models\searches\WithdrawSearch;
use backend\models\WithdrawApi;
use Yii;
use yii\bootstrap\Html;
use backend\models\MemberBankInfoApi;

class BankwithdrawController extends BaseController
{
    /**
     * @return string
     */
    public function actionIndex()
    {
        return $this->render('index', [
            'rate' => $this->getRate(),
//            'fee' => $this->getFee(),
            'bank_info' => $this->getBankInfo(),
        ]);
    }

    /**
     * @return \yii\web\Response
     */
    public function actionAjax()
    {
        $searchModel = new WithdrawSearch();
        $dataProvider = $searchModel->search(Yii::$app->getRequest()->getQueryParams());
        return $this->asJson($searchModel->outResult($dataProvider));
    }

    /**
     * @return \yii\web\Response
     */
    public function actionSave()
    {
        $model = new WithdrawForm();
        if (Yii::$app->getRequest()->getIsPost()) {
            $model->setAttributes(Yii::$app->getRequest()->post());
            if ($model->addWithdraw()) {
                return $this->asJson([
                    'isSuccess' => true,
                    'msg' => '提交成功,请等待审核',
                ]);
            } else {
                return $this->asJson([
                    'isSuccess' => false,
                    'msg' => Html::errorSummary($model, ['header' => '']),
                ]);
            }
        }
        return $this->asJson([
            'isSuccess' => false,
            'msg' => 'Bad Request',
        ]);
    }

    /**
     * @return array
     */
    protected function getRate()
    {
        $api = new RateApi();
        $result = $api->getRate();
        if ($result['code'] == 1) {
            return $result['data'];
        } else {
            return [];
        }
    }

    /**
     * @return bool
     * @deprecated 
     */
    protected function getFee()
    {
        $api = new WithdrawApi();
        $result = $api->getMonthWithdraw(Yii::$app->getUser()->getId());
        return !empty($result['data']) ? true : false;
    }

    protected function getBankInfo()
    {
        $api = new MemberBankInfoApi();
        $result = $api->getBankInfo(['member_id' => Yii::$app->getUser()->getId()]);
        return !empty($result['data']) ? $result['data'] : [];
    }
}

