<?php

namespace Kylin\Payment\Gateways;

/**
 * 银联支付网关
 */
class UnionpayGateway extends AbstractGateway
{
    /**
     * 发起支付
     */
    public function pay(array $params): mixed
    {
        // 构建支付参数
        $payParams = [
            'merId' => $this->getConfig('mer_id'),
            'orderId' => $params['out_trade_no'],
            'txnTime' => date('YmdHis'),
            'txnAmt' => $params['total_amt'],
            'currencyCode' => $params['currency_code'] ?? '156',
            'txnType' => $params['txn_type'] ?? '01',
            'txnSubType' => $params['txn_sub_type'] ?? '01',
            'bizType' => $params['biz_type'] ?? '000201',
            'channelType' => $params['channel_type'] ?? '07',
            'frontUrl' => $this->getConfig('return_url'),
            'backUrl' => $this->getConfig('notify_url'),
            'accType' => $params['acc_type'] ?? '01',
        ];

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

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

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

        return $result;
    }

    /**
     * 查询订单
     */
    public function query(string $orderNo): mixed
    {
        // 构建查询参数
        $queryParams = [
            'merId' => $this->getConfig('mer_id'),
            'orderId' => $orderNo,
            'txnTime' => date('YmdHis'),
            'txnType' => '00',
            'txnSubType' => '00',
            'bizType' => '000000',
            'channelType' => '07',
        ];

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

        // 构建请求URL
        $baseUrl = $this->sandbox ? $this->getConfig('sandbox_gateway') : $this->getConfig('gateway');
        $url = str_replace('/frontTransReq.do', '/queryTrans.do', $baseUrl);

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

        return $result;
    }

    /**
     * 退款
     */
    public function refund(array $params): mixed
    {
        // 构建退款参数
        $refundParams = [
            'merId' => $this->getConfig('mer_id'),
            'orderId' => $params['out_trade_no'],
            'origQryId' => $params['orig_qry_id'],
            'txnTime' => date('YmdHis'),
            'txnAmt' => $params['refund_amt'],
            'currencyCode' => $params['currency_code'] ?? '156',
            'txnType' => '04',
            'txnSubType' => '00',
            'bizType' => '000201',
            'channelType' => '07',
            'backUrl' => $this->getConfig('notify_url'),
        ];

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

        // 构建请求URL
        $baseUrl = $this->sandbox ? $this->getConfig('sandbox_gateway') : $this->getConfig('gateway');
        $url = str_replace('/frontTransReq.do', '/backTransReq.do', $baseUrl);

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

        return $result;
    }

    /**
     * 关闭订单
     */
    public function close(string $orderNo): mixed
    {
        // 构建关闭参数
        $closeParams = [
            'merId' => $this->getConfig('mer_id'),
            'orderId' => $orderNo,
            'txnTime' => date('YmdHis'),
            'txnType' => '31',
            'txnSubType' => '00',
            'bizType' => '000201',
            'channelType' => '07',
            'backUrl' => $this->getConfig('notify_url'),
        ];

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

        // 构建请求URL
        $baseUrl = $this->sandbox ? $this->getConfig('sandbox_gateway') : $this->getConfig('gateway');
        $url = str_replace('/frontTransReq.do', '/backTransReq.do', $baseUrl);

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

        return $result;
    }

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

        // 处理支付结果
        if ($data['respCode'] === '00') {
            // 支付成功，处理订单
            return [
                'code' => 'SUCCESS',
                'message' => '回调处理成功',
                'data' => [
                    'orderId' => $data['orderId'],
                    'traceNo' => $data['traceNo'],
                    'txnAmt' => $data['txnAmt'],
                    'respCode' => $data['respCode']
                ]
            ];
        } else {
            // 支付失败
            return [
                'code' => 'FAIL',
                'message' => $data['respMsg'] ?? '支付失败',
                'data' => []
            ];
        }
    }
}
