<?php     
namespace common\pay;

use backend\models\Deposit;
use backend\models\Member;
use common\helpers\RateHelper;
use yii\base\Model;

class PayForm extends Model
{
    public $amount;
    public $login;
    public $memberId;
    public $payType;
    public $notifyUrl;
    public $returnUrl;
    public $bankCode;
    public $ip;
    public $orderSn;

    private $_outPayResult;
    private $_outNotifyResult;
    private $_outReturnResult;

    public static $payNames = [
        1 => '人人支付',
        2 => '网通支付',
        3 => '杉德支付',
		4 => '顺通支付',
        5 => '3xmta支付',
        6 => '迅捷支付',
		7 => 'Ctype支付',

    ];

    /**
     * @return array
     */
    public function rules()
    {
        return [
            [['amount', 'login', 'memberId', 'payType', 'notifyUrl', 'returnUrl','orderSn'], 'required'],
            ['amount', 'match', 'pattern' => '/^([1-9]\d*|[0])(\.\d{1,2})?$/'],
            [['login', 'memberId', 'payType'], 'integer'],
            [['notifyUrl', 'returnUrl', 'ip', 'orderSn'], 'string'],
            ['payType', 'in', 'range' => array_keys(self::$payNames)],
            ['bankCode', 'required', 'when' => function ($model) {
                /** @var PayForm $model */
                return in_array($model->payType, [1,3]);
            }, 'message' => '请选择银行'],
            ['login', 'checkLogin'],
        ];
    }

    /**
     * @param string $attribute
     * @param array $params
     */
    public function checkLogin($attribute, $params = [])
    {
        if (!$this->hasErrors()) {
            $member = Member::findById($this->memberId);
            if ($member == null) {
                $this->addError($attribute, '用户不存在');
            } else {
                $logins = preg_split('/\s*,\s*/', $member['logins']);
                if (!in_array($this->login, $logins)) {
                    $this->addError($attribute, 'MT4账户不属于当前用户');
                }
            }
        }
    }

    /**
     * @return bool
     */
    public function outPay()
    {
        if ($this->validate()) {
            $rate = RateHelper::getRate();
            if (empty($rate['sellRate'])) {
                $this->addError('amount', '汇率获取失败');
                return false;
            }
            $payType = $this->payType;
            $model = new Deposit();
            $model->type = 0;
            $model->member_id = $this->memberId;
            $model->amount = $this->amount;
            $model->rate = $rate['sellRate'];
            $model->rmb = number_format($this->amount * $model->rate, 2, '.', '');
            $model->in_time = intval(microtime(true) * 1000);
            $model->pay_name = isset(self::$payNames[$payType]) ? trim(self::$payNames[$payType]) : '';
            $model->login = $this->login;
            $model->order_sn = $this->orderSn;
            if ($model->save()) {
                $handler = BasePayHandler::getPayHandlerByPayType($payType);
                if ($handler == null) {
                    $this->addError('amount', '支付方式不存在');
                    return false;
                }
                $handler->notifyUrl = $this->notifyUrl;
                $handler->returnUrl = $this->returnUrl;
                $params = [];
                $params['bankCode'] = $this->bankCode;
                $params['ip'] = $this->ip;
                $this->_outPayResult = $handler->outPay($model->getAttributes(), $params);
            }
        }
        return !$this->hasErrors();
    }

    /**
     * @return mixed
     */
    public function getOutPayResult()
    {
        return $this->_outPayResult;
    }

    /**
     * @param array $data
     * @return bool
     */
    public function handleNotify($data)
    {
        $payType = isset($data['payType']) ? trim($data['payType']) : '';
        unset($data['token']);
        unset($data['payType']);
        $handler = BasePayHandler::getPayHandlerByPayType($payType);
        $success = false;
        if ($handler != null) {
            $success = $handler->handleNotify($data);
            $this->_outNotifyResult = $handler->outNotify($success);
        }
        return $success;
    }

    /**
     * @return mixed
     */
    public function getOutNotifyResult()
    {
        return $this->_outNotifyResult;
    }

    /**
     * @param array $data
     * @return bool
     */
    public function handleReturn($data)
    {
        $payType = isset($data['payType']) ? trim($data['payType']) : '';
        unset($data['token']);
        unset($data['payType']);
        $handler = BasePayHandler::getPayHandlerByPayType($payType);
        $success = false;
        if ($handler != null) {
            $success = $handler->handleReturn($data);
            $this->_outReturnResult = $handler->outReturn($success);
        }
        return $success;
    }

    /**
     * @return mixed
     */
    public function getOutReturnResult()
    {
        return $this->_outReturnResult;
    }
}


