<?php

namespace Kylin\Payment\Gateways;

/**
 * 微信支付网关
 */
class WechatGateway extends AbstractGateway
{
    /**
     * 发起支付
     */
    public function pay(array $params): mixed
    {
        // 构建支付参数
        $payParams = [
            'appid' => $this->getConfig('app_id'),
            'mch_id' => $this->getConfig('mch_id'),
            'nonce_str' => $this->generateNonceStr(),
            'body' => $params['body'],
            'out_trade_no' => $params['out_trade_no'],
            'total_fee' => $params['total_fee'],
            'spbill_create_ip' => $params['spbill_create_ip'] ?? '127.0.0.1',
            'notify_url' => $this->getConfig('notify_url'),
            'trade_type' => $params['trade_type'] ?? 'JSAPI',
        ];

        // 根据支付类型添加额外参数
        match ($payParams['trade_type']) {
            'JSAPI' => $payParams['openid'] = $params['openid'],
            'NATIVE' => null, // 扫码支付无需额外参数
            default => null,
        };

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

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

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

        return $result;
    }

    /**
     * 查询订单
     */
    public function query(string $orderNo): mixed
    {
        // 构建查询参数
        $queryParams = [
            'appid' => $this->getConfig('app_id'),
            'mch_id' => $this->getConfig('mch_id'),
            'nonce_str' => $this->generateNonceStr(),
            'out_trade_no' => $orderNo,
        ];

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

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

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

        return $result;
    }

    /**
     * 退款
     */
    public function refund(array $params): mixed
    {
        // 构建退款参数
        $refundParams = [
            'appid' => $this->getConfig('app_id'),
            'mch_id' => $this->getConfig('mch_id'),
            'nonce_str' => $this->generateNonceStr(),
            'out_trade_no' => $params['out_trade_no'],
            'out_refund_no' => $params['out_refund_no'] ?? 'REFUND_' . date('YmdHis') . rand(1000, 9999),
            'total_fee' => $params['total_fee'],
            'refund_fee' => $params['refund_fee'],
            'refund_desc' => $params['refund_desc'] ?? '',
            'notify_url' => $this->getConfig('refund_notify_url'),
        ];

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

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

        // 发起请求（需要证书）
        $result = $this->request($url, $refundParams);

        return $result;
    }

    /**
     * 关闭订单
     */
    public function close(string $orderNo): mixed
    {
        // 构建关闭参数
        $closeParams = [
            'appid' => $this->getConfig('app_id'),
            'mch_id' => $this->getConfig('mch_id'),
            'nonce_str' => $this->generateNonceStr(),
            'out_trade_no' => $orderNo,
        ];

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

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

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

        return $result;
    }

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

        // 处理支付结果
        if ($data['return_code'] === 'SUCCESS' && $data['result_code'] === 'SUCCESS') {
            // 支付成功，处理订单
            return [
                'code' => 'SUCCESS',
                'message' => '回调处理成功',
                'data' => [
                    'out_trade_no' => $data['out_trade_no'],
                    'transaction_id' => $data['transaction_id'],
                    'total_fee' => $data['total_fee'],
                    'time_end' => $data['time_end']
                ]
            ];
        } else {
            // 支付失败
            return [
                'code' => 'FAIL',
                'message' => $data['return_msg'] ?? '支付失败',
                'data' => []
            ];
        }
    }
}
