<?php
namespace common\pay\renren;

use backend\models\RemitOrder;
use common\helpers\Utils;
use common\pay\BaseRemitHandler;
use Yii;
use yii\httpclient\Client;

class RemitHandler extends BaseRemitHandler
{
    public $payUrl;
    public $MerchantID;
    public $secretKey;
    public $remitKey;

    /**
     * @inheritdoc 初始化
     */
    public function init()
    {
        parent::init();
        if ($this->payUrl == null) {
            $this->payUrl = Yii::$app->params['renren.payUrl'];
        }
        if ($this->MerchantID == null) {
            $this->MerchantID = Yii::$app->params['renren.MerchantID'];
        }
        if ($this->secretKey == null) {
            $this->secretKey = Yii::$app->params['renren.secretKey'];
        }
        if ($this->remitKey == null) {
            $this->remitKey = Yii::$app->params['renren.remitKey'];
        }
    }

    /**
     * @param array $remitOrder
     * @param array $params
     * @return array
     */
    public function outRemit($remitOrder, $params = [])
    {
        $data = [];
        $data['TradeType'] = 'bis.pay.payment'; // 交易类型
        $data['OperatorID'] = $this->MerchantID; // 操作员 默认商户编号
        $data['PayType'] = '0101'; // 支付类型 0101-单笔实时代付
        $data['TerminalType'] = 'PC'; // 终端类型
        $data['PayPWD'] = strtoupper(md5($params['password'] . $this->remitKey)); // 支付密码 （支付密码+工作密钥）MD5加密,商户必填
        $data['MerchantID'] = $this->MerchantID; // 商户编号
//        $data['BankID'] = $remitOrder['bank_code']; // 银行代码 存折必须填写
        $data['OrderID'] = $remitOrder['remit_no']; // 订单号
        $data['BankAccountType'] = '00'; // 银行账户类型 0银行卡，01存折，02信用卡。不填默认为银行卡00。
        $data['BankAccountNo'] = $remitOrder['bank_card_no']; // 银行账号
        $data['BankAccountName'] = $remitOrder['payee_name']; // 银行账户名称
        $data['Province'] = $remitOrder['bank_province']; // 开户行所在省
        $data['City'] = $remitOrder['bank_city']; // 开户行所在市 如北京市，不能填北京
        $data['BankName'] = $remitOrder['bank_name']; // 开户行名称
        $data['AccountProp'] = ($remitOrder['is_business'] == 1) ? '1' : '0'; // 账号属性 0-对私 1-对公
//        $data['CardType'] = ''; // 开户证件类型
//        $data['CardNum'] = ''; // 证件号码
//        $data['Tel'] = ''; // 手机号码（预留在银行的）
        if ($remitOrder['is_business'] == 1) {
            $data['BranchBankID'] = $remitOrder['bank_branch_code']; // 支行号	对公户必填
        }
        $data['DeviceID'] = ''; // 设备号
        $data['MachineIP'] = isset($params['ip']) ? $params['ip'] : Utils::getClientIp(); // 终端IP	订单生成的机器IP
        $data['NotifyUrl'] = $this->notifyUrl; // 通知地址
        $data['SubmitTime'] = date('YmdHis'); // 订单提交时间
        $data['Amt'] = $remitOrder['amount'] * 100; // 交易金额 单位为分，不含小数点
//        $data['Summary'] = ''; // 交易附言
        $data['Sign'] = PayUtils::makeSign($data, $this->secretKey); // 签名,详见数据签名说明

        $client = new Client();
        $response = $client->post($this->payUrl, $data)->send();
        Yii::warning("outRemit result[{$response->getStatusCode()}]: {$response->getContent()}", __METHOD__);
        $result = [];
        if ($response->getIsOk()) {
            $str = $response->getContent();
            parse_str($str, $arr);
            if (isset($arr['RetStatus']) && $arr['RetStatus'] == 0) {
                $result['pay_status'] = RemitOrder::STATUS_PAY_OUTER_PROCESS; // 外部打款中
            }
            $retMsg = '';
            isset($arr['OrderID']) && $result['remit_no'] = trim($arr['OrderID']); // 打款单号
            isset($arr['RetStatus']) && $result['ret_code'] = trim($arr['RetStatus']); // 返回状态码
            isset($arr['RetMsg']) && $retMsg .= trim($arr['RetMsg']) . ','; // 返回信息描述
            isset($arr['RetDesc']) && $retMsg .= trim($arr['RetDesc']) . ','; // 返回信息描述
            isset($arr['RetCode']) && $result['res_code'] = trim($arr['RetCode']); // 交易状态码
            $result['ret_msg'] = trim($retMsg, ',');
        }
        return $result;
    }

    /**
     * @param array $data
     * @return bool
     */
    public function handleNotify($data)
    {
        if (PayUtils::checkSign($data, $this->secretKey)) {
            if (isset($data['RetStatus']) && $data['RetStatus'] == 0 && isset($data['DealStatus']) && $data['DealStatus'] == 0
                && isset($data['Status']) && $data['Status'] == '02'
            ) {
                $merOrderId = trim($data['OrderID']);
                /** @var RemitOrder $model */
                $model = RemitOrder::findByRemitNo($merOrderId);
                if ($model) {
//                    $model->type = 1;
//                    $model->save(false);
                    return true;
                }
            }
        }
        return false;
    }

    public function outNotify($success)
    {
        if ($success == true) {
            return "SUCCESS";
        } else {
            return "FAIL";
        }
    }
}



