<?php

namespace SRVX\Service\Pay;

use AopCertClient;
use SRVX\Service\BaseService;
use AlipayFundTransUniTransferRequest;
use AopClient;
use AlipayFundTransToaccountTransferRequest;


class AlipayServiceToTransfer extends BaseService
{

    protected $config = [];
    protected $aopClient;

    public $gatewayUrl = 'https://openapi.alipay.com/gateway.do';
    public $apiVersion = '1.0';
    public $signType = 'RSA2';
    public $postCharset = 'UTF-8';
    public $format = 'json';

    public function __construct($config)
    {
        $this->config = $config;
        $this->aopClient();
    }


    private function aopClient()
    {
        if ($this->config["pay_ali_use_type"] == "1") {
            $this->aopClient                = new AopCertClient();
            $this->aopClient->appId         = $this->config['pay_ali_new_app_id'];
            $this->aopClient->rsaPrivateKey = $this->config['pay_ali_new_private_key'];
            $this->aopClient->appCertSN     = $this->aopClient->getCertSNV2($this->config['pay_ali_new_app_cert_sn']);
//                $this->aopClient->alipayRootCertSN   = $this->aopClient->getRootCertSN($filePath . $this->config['pay_alipay_root_cert_sn']);
            //https://opendocs.alipay.com/support/01ravs  解析根key有问题 官方说可以写死  2028年失效 TODO
            $this->aopClient->alipayRootCertSN   = "687b59193f3f462dd5336e5abf83c5d8_02941eef3187dddf3d3b83462e1dfcf6";
            $this->aopClient->alipayrsaPublicKey = $this->aopClient->getPublicKeyV2($this->config['pay_ali_new_alipayrsa_public_key']);
        } else {
            $this->aopClient                     = new AopClient();
            $this->aopClient->appId              = $this->config['pay_ali_app_id'];
            $this->aopClient->rsaPrivateKey      = $this->config['pay_ali_private_key'];
            $this->aopClient->alipayrsaPublicKey = $this->config['pay_ali_public_key'];
        }

        $this->aopClient->gatewayUrl  = $this->gatewayUrl;
        $this->aopClient->apiVersion  = $this->apiVersion;
        $this->aopClient->signType    = $this->signType;
        $this->aopClient->postCharset = $this->postCharset;
        $this->aopClient->format      = $this->format;
        if (!empty($signType) && $this->config['pay_ali_key_len_type'] != "" && $this->config['pay_ali_use_type'] != "1") {
            $this->aopClient->signType = $signType['pay_ali_key_len_type'] == "0" ? "RSA2" : "RSA";
        }
    }
    

    /**
     * [转账]
     * @return [type] [description]
     */
    public function transfer($args)
    {
        logger($args, 'alipay_Transfer_index', true);
        try {
            if ($this->config["pay_ali_use_type"] == "1") {//新接口
                $request      = new AlipayFundTransUniTransferRequest();
                $transferData = [
                    'out_biz_no'      => $args['applyOrder'],
                    'payee_type'      => 'ALIPAY_LOGONID',
                    'amount'          => $args['price'],
                    'trans_amount'    => $args['price'],
                    'payer_show_name' => $args['payer_show_name'],
                    'payee_account'   => $args['alipayAccount'],
                    'payee_real_name' => $args['realName'],
                    "payee_info"      => array("identity" => $args['alipayAccount'], "identity_type" => 'ALIPAY_LOGON_ID', "name" => $args['realName']),
                    "product_code"    => 'TRANS_ACCOUNT_NO_PWD',
                    "biz_scene"       => 'DIRECT_TRANSFER',
                    'remark'          => $args['remark'] ?? ""
                ];
            } else {
                $request      = new AlipayFundTransToaccountTransferRequest();
                $transferData = [
                    'out_biz_no'      => $args['applyOrder'],
                    'payee_type'      => 'ALIPAY_LOGONID',
                    'amount'          => $args['price'],
                    'payer_show_name' => $args['payer_show_name'],
                    'payee_account'   => $args['alipayAccount'],
                    'payee_real_name' => $args['realName'],
                    'remark'          => $args['remark'] ?? ""
                ];
            }

            $transferJson = json_encode($transferData);
            $request->setBizContent($transferJson);
            $response     = $this->aopClient->execute($request);
            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $responseData = json_decode(json_encode($response->$responseNode), true);
            logger($responseData, 'alipay_Transfer_index', true);
            if ($responseData['code'] == 10000) {
                return $this->returnRes(true, $responseData['msg'], $responseData);
            } else {
                return $this->returnRes(false, ($responseData['sub_msg'] ?? $responseData['msg']), $responseData);
            }
        } catch (\Exception $e) {
            logger($e->getMessage(), 'alipay_Transfer_index', true);
            return $this->returnRes(false, $e->getMessage());

        }
    }
}