<?php

namespace App\Services\Payment;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Response;
use App\Services\BaseService;

class QianBaoService extends BaseService
{
    // SanJin payment service methods would go here
    const REQUEST_URL = 'https://api.qbdf13.com/';

    // 提现通道
    const ALIPAY_TO_CARD = 'DF001'; // 支付宝转卡
    const ALIPAY_TO_ALIPAY = 'DF002'; // 支付宝转支付宝
    const PROVISION_TO_CARD = 'DF003'; // 备付金转卡
    const PROVISION_TO_ALIPAY = 'DF004'; // 备付金转支付宝
    const NUMBER_RMB = 'DF005'; // 数字人民币

    // 支付通道
    const PAY_ZFB1 = 'ZFB001';

    public static $PAY_CHANNEL = [
        'ZFB001' => [10,100]
    ];

    public static function withdrawChannel()
    {
        return [
            self::ALIPAY_TO_CARD => lang('银行卡'),
            self::ALIPAY_TO_ALIPAY => lang('支付宝'),
            self::NUMBER_RMB => lang('数字人民币'),
        ];
    }

    // 获取异步的通知地址
    public static function getNotifyUrl()
    {
        $host = config('app.url');
        return $host.'/api/pay/notify';
    }

    // 获取商户ID
    public static function getMerchantId()
    {
        return config('app.tree_payment_merchant_id');
    }
    // 获取商户ID
    public static function getSecret()
    {
        return config('app.tree_payment_secret');
    }


    
    /**
     * @description: 获取请求客户端
     * @return {*}
     */
    public static function getClient(): Client
    {
        return new Client([
            'base_uri' => self::REQUEST_URL,
            'timeout' => 5.0,
        ]);
    }

    /**
     * @description: 查询商户余额
     * @return {array}
     *         {array.success - 是否成功 true|false}
     *         {array.msg - 返回错误消息}
     *         {array.code - 返回状态码：200成功，其他失败}
     *         {array.timestamp - 时间戳 13位}
     *         {array.data - 商户余额}
     */    
    public static function findBalance()
    {
        $merchant_id  = self::getMerchantId();
        $secret = self::getSecret();
        $sign = md5($merchant_id . $secret);
        $data = [
            'merchantNum' => $merchant_id,
            'sign' => $sign,
        ];

        $client = self::getClient();
        $response = $client->get('api/findBalance', [
            'query' => $data,
        ]);
        $body = $response->getBody();
        return json_decode($body->getContents(), true);
    }

    /**
     * @description: 查询代付订单信息
     * @param {*} $order_no 代付订单
     * @return {array} $result
     */    
    public static function findPayoutOrderInfo($order_no)
    {
        $merchant_id  = self::getMerchantId();
        $secret = self::getSecret();

        $data = [];
        $data['merchantNum'] = $merchant_id;
        $data['orderNo'] = $order_no;
        $sign = md5($merchant_id.$order_no.$secret);
        $data['sign'] = $sign;
        $client = self::getClient();
        $response = $client->get('api/findPayoutOrderInfo', [
            'query' => $data,
        ]);
        $body = $response->getBody();
        return json_decode($body->getContents(), true);
    }

    /**
     * @description: 查询代收订单信息
     * @param {*} $order_no 代收订单
     * @return {array} $result
     */    
    public static function findPayOrderInfo($order_no)
    {
        $merchant_id  = self::getMerchantId();
        $secret = self::getSecret();

        $data = [];
        $data['merchantNum'] = $merchant_id;
        $data['orderNo'] = $order_no;
        $sign = md5($merchant_id.$order_no.$secret);
        $data['sign'] = $sign;
        $client = self::getClient();
        $response = $client->get('api/findPayOrderInfo', [
            'query' => $data,
        ]);
        $body = $response->getBody();
        return json_decode($body->getContents(), true);
    }

    // 代收
    public static function pay($amount, $order_no, $payType = self::PAY_ZFB1)
    {
        $data = [];
        $merchant_id  = self::getMerchantId();
        $secret = self::getSecret();
        $notify_url = self::getNotifyUrl();
        $data['merchantNum'] = $merchant_id;
        $data['amount'] = $amount;
        $data['orderNo'] = $order_no;
        $data['notifyUrl'] = $notify_url;
        $data['payType'] = $payType;
        // $data['returnUrl'] = $return_url;

        $signStr = $merchant_id .  $order_no . $amount . $secret;
        $sign = md5($signStr);
        $data['sign'] = $sign;
        
        $client = self::getClient();
        $response = $client->post('api/pay', [
                'form_params' => $data,
                'headers' => [
                    'Content-Type' => 'application/x-www-form-urlencoded',
                ]
            ]);
        $body = $response->getBody();
        $result = json_decode($body->getContents(), true);
        
        return $result;
    }

    // 代付
    public static function payout($amount, $order_no, $bank_name, $account, $card_no, $payType = self::ALIPAY_TO_ALIPAY)
    {
        $data = [];
        $merchant_id  = self::getMerchantId();
        $secret = self::getSecret();
        $notify_url = self::getNotifyUrl();

        $data['merchantNum'] = $merchant_id;
        $data['amount'] = $amount;
        $data['orderNo'] = $order_no;
        $data['notifyUrl'] = $notify_url;
        $data['payType'] = $payType;

        switch($payType){
            case self::ALIPAY_TO_ALIPAY:
                $bank_name = '支付宝';
                break;
            case self::NUMBER_RMB:
                $bank_name = '数字人民币';
                break;
        }

        $signStr = $merchant_id .  $order_no . $amount . $secret;
        $sign = md5($signStr);
        $data['sign'] = $sign;

        $data['bankName'] = $bank_name;
        $data['account'] = $account;
        $data['cardNumber'] = $card_no;
        

        $client = self::getClient();
        $response = $client->post('api/payout', [
                'form_params' => $data,
                'headers' => [
                    'Content-Type' => 'application/x-www-form-urlencoded',
                ]
            ]);
        $body = $response->getBody();
        $result = json_decode($body->getContents(), true);
        
        return $result;
    }

    /**
     * @description: 异步通知签名加密
     * @param {*} $state
     * @param {*} $order_no
     * @param {*} $amount
     * @return {*}
     */    
    public static function verifyNotifySign($state,$order_no,$amount)
    {
        $merchant_id = self::getMerchantId();
        $secret = self::getSecret();
        $sign = md5($state.$merchant_id.$order_no.$amount.$secret);
        return $sign;
    }

    public static function getWhere(array $search = []): array
    {
        return [];
    }
}