<?php

namespace Kylin\Payment\Gateways;

/**
 * 抖音支付网关
 */
class DouyinGateway extends AbstractGateway
{
    /**
     * 发起支付
     */
    public function pay(array $params): mixed
    {
        // 构建支付参数
        $payParams = [
            'app_id' => $this->getConfig('app_id'),
            'merchant_id' => $this->getConfig('merchant_id'),
            'out_order_no' => $params['out_trade_no'],
            'total_amount' => $params['total_amount'],
            'currency' => $params['currency'] ?? 'CNY',
            'subject' => $params['subject'],
            'body' => $params['body'] ?? '',
            'notify_url' => $this->getConfig('notify_url'),
            'return_url' => $this->getConfig('return_url'),
            'trade_type' => $params['trade_type'] ?? 'APP',
            'timestamp' => time(),
        ];

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

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

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

        return $result;
    }

    /**
     * 查询订单
     */
    public function query(string $orderNo): mixed
    {
        // 构建查询参数
        $queryParams = [
            'app_id' => $this->getConfig('app_id'),
            'merchant_id' => $this->getConfig('merchant_id'),
            'out_order_no' => $orderNo,
            'timestamp' => time(),
        ];

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

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

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

        return $result;
    }

    /**
     * 退款
     */
    public function refund(array $params): mixed
    {
        // 构建退款参数
        $refundParams = [
            'app_id' => $this->getConfig('app_id'),
            'merchant_id' => $this->getConfig('merchant_id'),
            'out_order_no' => $params['out_trade_no'],
            'out_refund_no' => $params['out_refund_no'] ?? 'REFUND_' . date('YmdHis') . rand(1000, 9999),
            'refund_amount' => $params['refund_amount'],
            'refund_reason' => $params['refund_reason'] ?? '',
            'timestamp' => time(),
        ];

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

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

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

        return $result;
    }

    /**
     * 关闭订单
     */
    public function close(string $orderNo): mixed
    {
        // 构建关闭参数
        $closeParams = [
            'app_id' => $this->getConfig('app_id'),
            'merchant_id' => $this->getConfig('merchant_id'),
            'out_order_no' => $orderNo,
            'timestamp' => time(),
        ];

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

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

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

        return $result;
    }

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

        // 处理支付结果
        if ($data['order_status'] === 'SUCCESS') {
            // 支付成功，处理订单
            return [
                'code' => 'SUCCESS',
                'message' => '回调处理成功',
                'data' => [
                    'out_order_no' => $data['out_order_no'],
                    'order_id' => $data['order_id'],
                    'total_amount' => $data['total_amount'],
                    'order_status' => $data['order_status']
                ]
            ];
        } else {
            // 支付失败
            return [
                'code' => 'FAIL',
                'message' => '支付失败',
                'data' => [
                    'out_order_no' => $data['out_order_no'] ?? '',
                    'order_status' => $data['order_status']
                ]
            ];
        }
    }
}
