<?php 

namespace App\Services\Payment;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Response;
use App\Services\BaseService;
use Illuminate\Support\Facades\Lang;
use App\Models\RechargeChannel;

class SanJinService extends BaseService
{
    const REQUEST_URL = 'https://jkapi-sanjin.jkcbb.com/';

    
    const PRODUCT_TEST = 'T888'; // 测试支付通道

    public static $CHANNEL = [
        'wxsm' => '微信扫码',
        'zfbsm' => '支付宝扫码',
        'zfbge' => '支付宝固额',
        'zfbzk' => '支付宝转卡',
        'ylsm' => '银联扫码',
        'szrmb' => '数字人民币',
        'sdjt' => '手动金条',
    ];

    /**
     * @description: 获取支付频道
     * @return {*}
     */    
    public static function getChannel($type = '')
    {
        if ($type) {
            $name = RechargeChannel::where('type', $type)->value('name');
            return Lang($name);
        } else {
            $channel = [];
            $product = self::product();
            foreach($product as $v){
                $channel[$v['type']] = lang($v['name']);
            }
            return $channel;
        }
    }

    // public static $PRODUCT = [
    //     // 'T888' => [
    //     //     'type' => 'test',
    //     //     'rate' => 0.02,
    //     //     'max' => 5000,
    //     //     'min' => 10
    //     // ],
    //     'WX002' => [
    //         'type' => 'wxsm',
    //         'rate' => 0.095,
    //         'max' => 3000,
    //         'min' => 100
    //     ],
    //     'YL001' => [
    //         'type' => 'ylsm',
    //         'rate' => 0.05,
    //         'max' => 500,
    //         'min' => 50
    //     ],
    //     'SZ002' => [
    //         'type' => 'szrmb',
    //         'rate' => 0.05,
    //         'max' => 100,
    //         'min' => 10
    //     ],
    //     'SZ001' => [
    //         'type' => 'szrmb',
    //         'rate' => 0.048,
    //         'max' => 5000,
    //         'min' => 100
    //     ],
    //     'ZFB001' => [
    //         'type' => 'zfbsm',
    //         'rate' => 0.085,
    //         'max' => 200,
    //         'min' => 100
    //     ],
    //     'ZFB002' => [
    //         'type' => 'zfbsm',
    //         'rate' => 0.057,
    //         'max' => 1000,
    //         'min' => 200
    //     ],
    //     'ZFB003' => [
    //         'type' => 'zfbsm',
    //         'rate' => 0.052,
    //         'max' => 3000,
    //         'min' => 1000
    //     ],
    //     'ZFB004' => [
    //         'type' => 'zfbsm',
    //         'rate' => 0.042,
    //         'max' => 20000,
    //         'min' => 3000
    //     ],
    //     'ZFB005' => [
    //         'type' => 'zfbge',
    //         'rate' => 0.027,
    //         'fixed' => [945 ,988 ,990]
    //     ],
    //     'ZFBZK001' => [
    //         'type' => 'zfbzk',
    //         'rate' => 0.05,
    //         'max' => 2000,
    //         'min' => 200
    //     ],
    //     'JT000' => [
    //         'type' => 'sdjt',
    //         'rate' => 0.08,
    //         'max' => 300,
    //         'min' => 100
    //     ],
    //     'JT001' => [
    //         'type' => 'sdjt',
    //         'rate' => 0.08,
    //         'max' => 3000,
    //         'min' => 300
    //     ],
    //     'JT002' => [
    //         'type' => 'sdjt',
    //         'rate' => 0.08,
    //         'max' => 5000,
    //         'min' => 500
    //     ],
    // ];
    public static function product()
    {
        return RechargeChannel::product(1);
    }

    // 获取商户ID
    public static function getMerchantId()
    {
        return config('app.tree_pay_mch_id');
    }
    // 获取商户秘钥
    public static function getSecret()
    {
        return config('app.tree_pay_key');
    }

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


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

    // 签名
    public static function signature($params = [],$must = [])
    {
        if($must){
            foreach($params as $k => $v){
                if(!in_array($k,$must)){
                    unset($params[$k]);
                }
            }
        }
        ksort($params, SORT_STRING);
     

        $parts = [];
        foreach($params as $k => $v){
            array_push($parts,$k.'='.$v);
        }
        $mch_key = self::getSecret();
        $parts[] = "key=".$mch_key;

        $sign = md5(implode('&',$parts));
        return $sign;
    }

    /**
     * @description: 发起支付订单
     * @param {*} $amount 金额单位分
     * @param {*} $orderNo  订单号
     * @param {*} $type 支付通道
     * @return {*}
     */    
    public static function pay($amount,$orderNo,$type = self::PRODUCT_TEST)
    {

        $must = ['mchId','productId','outTradeNo','amount','reqTime','notifyUrl'];
        $mch_id = self::getMerchantId();

        
        
        $data = [];
        $data['mchId'] = $mch_id;
        $data['amount'] = $amount;
        $data['outTradeNo'] = $orderNo;
        $data['notifyUrl'] = self::getNotifyUrl();
        $data['reqTime'] = time() * 1000;
        $data['productId'] = $type;

        
        $data['sign'] = self::signature($data,$must);
        $client = self::getClient();
        $response = $client->post('api/v1/pay/unifiedOrder', [
            'json' => $data,
            'headers' => [
                'Content-Type' => 'application/json',
            ]
        ]);

        $body = $response->getBody();
        return json_decode($body->getContents(), true);
    }

    /**
     * @description: 查询订单
     * @param {*} $orderNo  订单号
     * @return {*}
     */    
    public static function queryOrder($orderNo)
    {

        $must = ['mchId','outTradeNo','reqTime'];
        $mch_id = self::getMerchantId();

        
        
        $data = [];
        $data['mchId'] = $mch_id;
        $data['outTradeNo'] = $orderNo;
        $data['reqTime'] = time() * 1000;
        
        $data['sign'] = self::signature($data,$must);
        $client = self::getClient();
        $response = $client->post('api/v1/pay/queryOrder', [
            'json' => $data,
            'headers' => [
                'Content-Type' => 'application/json',
            ]
        ]);

        $body = $response->getBody();
        return json_decode($body->getContents(), true);
    }

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

}