<?php

namespace Kylin\Payment\Gateways;

/**
 * 支付宝国际版网关
 */
class AlipayGlobalGateway extends AbstractGateway
{
    /**
     * 发起支付
     */
    public function pay(array $params): mixed
    {
        // 构建业务参数
        $bizContent = [
            'out_trade_no' => $params['out_trade_no'],
            'total_amount' => $params['total_amount'],
            'currency' => $params['currency'] ?? 'USD',
            'subject' => $params['subject'],
            'product_code' => $params['product_code'] ?? 'FAST_INSTANT_TRADE_PAY',
        ];

        // 构建请求参数
        $requestParams = [
            'app_id' => $this->getConfig('app_id'),
            'method' => $params['method'] ?? 'alipay.trade.page.pay',
            'format' => 'JSON',
            'charset' => $this->getConfig('charset'),
            'sign_type' => $this->getConfig('sign_type'),
            'timestamp' => date('Y-m-d H:i:s'),
            'version' => '1.0',
            'notify_url' => $this->getConfig('notify_url'),
            'return_url' => $this->getConfig('return_url'),
            'biz_content' => json_encode($bizContent),
        ];

        // 签名（实际项目中需要根据支付宝国际版签名规则生成）
        $requestParams['sign'] = 'test_sign';

        // 构建请求URL
        $url = $this->sandbox ? $this->getConfig('sandbox_gateway') : $this->getConfig('gateway');

        // 发起请求
        $result = $this->request($url, $requestParams);

        return $result;
    }

    /**
     * 查询订单
     */
    public function query(string $orderNo): mixed
    {
        // 构建业务参数
        $bizContent = [
            'out_trade_no' => $orderNo,
        ];

        // 构建请求参数
        $requestParams = [
            'app_id' => $this->getConfig('app_id'),
            'method' => 'alipay.trade.query',
            'format' => 'JSON',
            'charset' => $this->getConfig('charset'),
            'sign_type' => $this->getConfig('sign_type'),
            'timestamp' => date('Y-m-d H:i:s'),
            'version' => '1.0',
            'biz_content' => json_encode($bizContent),
        ];

        // 签名
        $requestParams['sign'] = 'test_sign';

        // 构建请求URL
        $url = $this->sandbox ? $this->getConfig('sandbox_gateway') : $this->getConfig('gateway');

        // 发起请求
        $result = $this->request($url, $requestParams);

        return $result;
    }

    /**
     * 退款
     */
    public function refund(array $params): mixed
    {
        // 构建业务参数
        $bizContent = [
            'out_trade_no' => $params['out_trade_no'],
            'refund_amount' => $params['refund_amount'],
            'refund_currency' => $params['refund_currency'] ?? 'USD',
            'out_request_no' => $params['out_request_no'] ?? 'REFUND_' . date('YmdHis') . rand(1000, 9999),
            'refund_reason' => $params['refund_reason'] ?? '',
        ];

        // 构建请求参数
        $requestParams = [
            'app_id' => $this->getConfig('app_id'),
            'method' => 'alipay.trade.refund',
            'format' => 'JSON',
            'charset' => $this->getConfig('charset'),
            'sign_type' => $this->getConfig('sign_type'),
            'timestamp' => date('Y-m-d H:i:s'),
            'version' => '1.0',
            'biz_content' => json_encode($bizContent),
        ];

        // 签名
        $requestParams['sign'] = 'test_sign';

        // 构建请求URL
        $url = $this->sandbox ? $this->getConfig('sandbox_gateway') : $this->getConfig('gateway');

        // 发起请求
        $result = $this->request($url, $requestParams);

        return $result;
    }

    /**
     * 关闭订单
     */
    public function close(string $orderNo): mixed
    {
        // 构建业务参数
        $bizContent = [
            'out_trade_no' => $orderNo,
        ];

        // 构建请求参数
        $requestParams = [
            'app_id' => $this->getConfig('app_id'),
            'method' => 'alipay.trade.close',
            'format' => 'JSON',
            'charset' => $this->getConfig('charset'),
            'sign_type' => $this->getConfig('sign_type'),
            'timestamp' => date('Y-m-d H:i:s'),
            'version' => '1.0',
            'biz_content' => json_encode($bizContent),
        ];

        // 签名
        $requestParams['sign'] = 'test_sign';

        // 构建请求URL
        $url = $this->sandbox ? $this->getConfig('sandbox_gateway') : $this->getConfig('gateway');

        // 发起请求
        $result = $this->request($url, $requestParams);

        return $result;
    }

    /**
     * 回调处理
     */
    public function callback(array $data): mixed
    {
        // 验证签名
        // $signature = $data['sign'];
        // unset($data['sign']);
        // $unsignedData = $this->buildSignString($data);
        // $generatedSignature = $this->generateSignature($unsignedData, $this->getConfig('public_key'));
        // if ($signature !== $generatedSignature) {
        //     return ['code' => 'FAIL', 'message' => '签名验证失败'];
        // }

        // 处理支付结果
        $tradeStatus = $data['trade_status'] ?? '';
        if (in_array($tradeStatus, ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
            // 支付成功，处理订单
            return [
                'code' => 'SUCCESS',
                'message' => '回调处理成功',
                'data' => [
                    'out_trade_no' => $data['out_trade_no'],
                    'trade_no' => $data['trade_no'],
                    'total_amount' => $data['total_amount'],
                    'currency' => $data['currency'],
                    'trade_status' => $tradeStatus
                ]
            ];
        } else {
            // 支付失败
            return [
                'code' => 'FAIL',
                'message' => '支付失败',
                'data' => [
                    'out_trade_no' => $data['out_trade_no'] ?? '',
                    'trade_status' => $tradeStatus
                ]
            ];
        }
    }
}
