<?php

namespace Kylin\Payment\Services;

use Illuminate\Support\Facades\Log;
use Illuminate\Contracts\Container\Container;

/**
 * 二维码生成服务类
 */
class QrCodeService
{
    /**
     * 构造函数
     */
    public function __construct(
        protected readonly Container $app,
        protected readonly TestToolService $testToolService
    ) {
    }

    /**
     * 生成二维码
     */
    public function generate(string $content, array $options = []): string
    {
        $defaultOptions = [
            'size' => 300,
            'margin' => 1,
            'error_correction' => 'M',
            'encoding' => 'UTF-8',
            'background' => '#FFFFFF',
            'foreground' => '#000000',
        ];

        $options = array_merge($defaultOptions, $options);

        try {
            // 检查是否安装了二维码生成库
            if (class_exists('Endroid\QrCode\QrCode')) {
                return $this->generateWithEndroid($content, $options);
            } elseif (function_exists('imagecreate')) {
                return $this->generateWithGD($content, $options);
            } else {
                return $this->generateWithApi($content, $options);
            }
        } catch (\Exception $e) {
            Log::error('生成二维码失败', [
                'content' => $content,
                'options' => $options,
                'error' => $e->getMessage(),
            ]);
            return '';
        }
    }

    /**
     * 使用Endroid/QrCode库生成二维码
     */
    protected function generateWithEndroid(string $content, array $options): string
    {
        $qrCode = new \Endroid\QrCode\QrCode($content);
        $qrCode->setSize($options['size']);
        $qrCode->setMargin($options['margin']);
        $qrCode->setErrorCorrectionLevel($options['error_correction']);
        $qrCode->setEncoding($options['encoding']);
        $qrCode->setBackgroundColor($options['background']);
        $qrCode->setForegroundColor($options['foreground']);

        return $qrCode->getDataUri();
    }

    /**
     * 使用GD库生成二维码
     */
    protected function generateWithGD(string $content, array $options): string
    {
        // 这里使用GD库生成二维码
        // 实际使用时需要实现GD库生成二维码的逻辑
        // 由于GD库生成二维码比较复杂，这里仅返回一个占位符

        Log::info('使用GD库生成二维码', [
            'content' => $content,
            'options' => $options,
        ]);

        // 返回一个基于内容的base64编码的占位符
        $size = $options['size'];
        $image = imagecreate($size, $size);
        $bgColor = imagecolorallocate($image, 255, 255, 255);
        $fgColor = imagecolorallocate($image, 0, 0, 0);
        imagefill($image, 0, 0, $bgColor);
        imagestring($image, 5, $size / 4, $size / 2 - 10, 'QR Code', $fgColor);

        ob_start();
        imagepng($image);
        $imageData = ob_get_clean();
        imagedestroy($image);

        return 'data:image/png;base64,' . base64_encode($imageData);
    }

    /**
     * 使用API生成二维码
     */
    protected function generateWithApi(string $content, array $options): string
    {
        // 使用第三方API生成二维码
        // 这里使用Google Charts API作为示例
        $size = $options['size'];
        $margin = $options['margin'];
        $errorCorrection = strtoupper(substr($options['error_correction'], 0, 1));

        $url = 'https://api.qrserver.com/v1/create-qr-code/?' . http_build_query([
            'size' => "{$size}x{$size}",
            'margin' => $margin,
            'ecc' => $errorCorrection,
            'data' => $content,
        ]);

        Log::info('使用API生成二维码', [
            'url' => $url,
        ]);

        return $url;
    }

    /**
     * 生成支付二维码
     */
    public function generatePaymentQrCode(string $type, array $params, string $name = 'default', array $options = []): string
    {
        // 生成支付参数
        $testParams = $this->testToolService->generateTestParams($type, $params);

        // 获取支付网关
        $payment = $this->app->make(\Kylin\Payment\Payment::class);
        $gateway = $payment->manager()->gateway($type, $name);

        // 发起支付获取二维码内容
        $result = $gateway->pay($testParams);

        // 提取二维码内容
        $qrCodeContent = $this->extractQrCodeContent($type, $result);

        if (empty($qrCodeContent)) {
            return '';
        }

        // 生成二维码
        return $this->generate($qrCodeContent, $options);
    }

    /**
     * 提取二维码内容
     */
    protected function extractQrCodeContent(string $type, mixed $result): string
    {
        return match ($type) {
            'wechat' => $result['code_url'] ?? '',
            'alipay' => $result['qr_code'] ?? '',
            'unionpay' => $result['qrCode'] ?? '',
            'douyin' => $result['code_url'] ?? '',
            'jsbank' => $result['qrCode'] ?? '',
            default => '',
        };
    }

    /**
     * 生成微信支付二维码
     */
    public function generateWechatQrCode(array $params, string $name = 'default', array $options = []): string
    {
        return $this->generatePaymentQrCode('wechat', $params, $name, $options);
    }

    /**
     * 生成支付宝二维码
     */
    public function generateAlipayQrCode(array $params, string $name = 'default', array $options = []): string
    {
        return $this->generatePaymentQrCode('alipay', $params, $name, $options);
    }

    /**
     * 生成银联支付二维码
     */
    public function generateUnionpayQrCode(array $params, string $name = 'default', array $options = []): string
    {
        return $this->generatePaymentQrCode('unionpay', $params, $name, $options);
    }

    /**
     * 生成抖音支付二维码
     */
    public function generateDouyinQrCode(array $params, string $name = 'default', array $options = []): string
    {
        return $this->generatePaymentQrCode('douyin', $params, $name, $options);
    }

    /**
     * 生成江苏银行支付二维码
     */
    public function generateJsbankQrCode(array $params, string $name = 'default', array $options = []): string
    {
        return $this->generatePaymentQrCode('jsbank', $params, $name, $options);
    }
}