<?php

namespace App\Libs\Pay\Merchants;

require_once dirname(__FILE__) . '../../../AliApp/aop/AopClient.php';
require_once dirname(__FILE__) . '../../../AliApp/aop/request/AlipayTradeWapPayRequest.php';
require_once dirname(__FILE__) . '../../../AliApp/aop/request/AlipayTradeAppPayRequest.php';
require_once dirname(__FILE__) . '../../../AliApp/aop/request/AlipayTradeQueryRequest.php';

class AliPay implements PayMerchantInterface
{
    private  $aop;

    const  GATE_WAY_URL = 'https://openapi.alipay.com/gateway.do';

    const  APPID = '2019102968728764';

    const  RSAPRIVATEKEY = 'MIIEowIBAAKCAQEArQwM9Q9D/Ou8jkRfCEzwqm4nDSoyMxOobgqm7bqj9qvY+pRzLZFpTujfxYscdGRFPtBGQY3FehDI3SZBrX0PNAMgiXmVhPP7/qYBVsCmiEODlC2EjCVSau/BSwDderl746yUcvvZQhYicPyhpxzIK4wMQeChocsWIT9xJ9QHLmruoyeI9Av7gDRWtexOaeYcQtebVYV1K8PzvSfkRhCQHOg3kSXZzd0EgYHjTbudH+eVH1d5mJbx5ucvGNRY9rlUKw9MbkZTKqr4vdKvZvF9zHfKpAx+pzJCoXJmK+h6i6Lz77DpsGESucKtSAaSDbYrDQznYyPvxfW6paBV8voWxQIDAQABAoIBAE1ybj4jRedlTe9SNEIPxUpRoFKpBuyLKL+PLuSIuqdEhAip9d54DOyPFs9fki2ZTtBtAHSIUdBuwKcRXyWZKfu6Ro6ghsWJOMfgXgsIj7++j536vS7H6VoI0baSvY0WhJcB/zJy+uoz49gziNm07PVoaXf2ZAB4VwAsV6VepJQl8wl70oxw/Rgt33srTJfLQBFll9tDunyFXGA3WOLMpXR/l5l6y8R0EZDmLRBOvqhwbipOaCvdwAqAm3I/btplnwATQOYCWIAa+G04czetfzbUepLDaFAr48BjVYD11JKxB9WfIfY976NS0vUv2FMth5tuz0tQui+HOgFi6hw9GUUCgYEA9DcSqzRMOm8CeR57RMGoC5YNGZ2onGdK4qPKp0mE79R6FwV41fyLXsuer9JqxsIu1KoUoQn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TeJeywXbae5KiI713fEN/wVKzA8zX96SBt+XiRTbtIk/GL12tixbR4Q6C7pAND5vE8jm3PEz6xHX0G9myezVlx564Lk1vLg5mSMJ3qk91MW2n/oUvBgspk1kxuLzZDb1QIDAQAB';

    const  SIGN_TYPE = 'RSA2';

    private $rsaPublicKeyFilePath;

    private $pay_merchant_id;

    public function __construct(array $config)
    {
        $this->aop = new \AopClient;
        $this->aop->appId = $config['app_id'];
        $this->aop->rsaPrivateKey = $config['pri_key'];
        $this->aop->alipayrsaPublicKey = $config['ali_pub_key'];
        $this->aop->signType = self::SIGN_TYPE;
        $this->aop->gatewayUrl = self::GATE_WAY_URL;
        $this->aop->format = 'json';
    }

    public function send(array $data)
    {
        $type = $data['type'];
        $params = [
            'body' => $data['body'],
            'subject' => $data['subject'],
            'out_trade_no' => $data['out_trade_no'],
            'timeout_express' => $data['timeout_express'],
            'total_amount' => $data['total_amount'],
            'product_code' => 'QUICK_WAP_WAY',
            'passback_params' => urlencode($data['pay_merchant_id']),
        ];
        switch ($type) {
            case 'App':
                return $this->AlipayTradeAppPayRequest($data);
                break;
            case 'Wap':
                $return_url = $data['return_url'];
                return $this->AlipayTradeWapPayRequest($params, $return_url);
                break;
        }
    }

    private function AlipayTradeWapPayRequest(array $data, $return_url)
    {
        $request = new \AlipayTradeWapPayRequest();
        $request->setBizContent(json_encode($data));
        $request->setNotifyUrl(env('ALI_PAY_CALL_BACK'));
        $request->setReturnUrl($return_url);
        return $this->aop->pageExecute($request);
    }

    private function AlipayTradeAppPayRequest(array $data)
    {
        $request = new \AlipayTradeAppPayRequest();
        $request->setBizContent(json_encode($data));
        $request->setNotifyUrl(env('ALI_PAY_CALL_BACK'));
        return $this->aop->sdkExecute($request);
    }


    public function notify(array $data)
    {
        if (isset($data['sign']) && isset($data['trade_status'])  && $data['trade_status'] == 'TRADE_SUCCESS') {
            return $this->aop->rsaCheckV1($data, $this->rsaPublicKeyFilePath, self::SIGN_TYPE);
        } else {
            return false;
        }
    }

    public function query(string $trade_no)
    {
        $request = new \AlipayTradeQueryRequest();
        $request->setBizContent(json_encode(['out_trade_no' => $trade_no]));
        $result = $this->aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if (!empty($resultCode) && $resultCode == 10000) {
            return $result->$responseNode->trade_no;
        } else {
            return false;
        }
    }

    public function refund(array $data)
    {
    }

    public function makeSign(array $data)
    {
    }
}
