<?php

namespace Kylin\Payment\Services;

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

/**
 * 支付通知服务类
 */
class NotificationService
{
    /**
     * 构造函数
     */
    public function __construct(
        protected readonly Container $app
    ) {
    }

    /**
     * 发送支付通知
     */
    public function notify(string $type, array $data, array $channels = ['mail']): array
    {
        $results = [];

        foreach ($channels as $channel) {
            try {
                $result = match ($channel) {
                    'mail' => $this->sendMailNotification($type, $data),
                    'sms' => $this->sendSmsNotification($type, $data),
                    'wechat' => $this->sendWechatNotification($type, $data),
                    'alipay' => $this->sendAlipayNotification($type, $data),
                    default => false,
                };

                $results[$channel] = $result;
            } catch (\Exception $e) {
                Log::error('发送支付通知失败', [
                    'channel' => $channel,
                    'type' => $type,
                    'data' => $data,
                    'error' => $e->getMessage(),
                ]);
                $results[$channel] = false;
            }
        }

        return $results;
    }

    /**
     * 发送邮件通知
     */
    protected function sendMailNotification(string $type, array $data): bool
    {
        // 检查是否配置了邮件通知
        if (!isset($data['email']) || empty($data['email'])) {
            return false;
        }

        // 构建邮件内容
        $subject = $this->getNotificationSubject($type, $data);
        $message = $this->getNotificationMessage($type, $data);

        // 发送邮件
        // 这里使用Laravel的Mail facade发送邮件
        // 实际使用时需要创建对应的邮件类
        // Mail::to($data['email'])->send(new PaymentNotification($subject, $message));

        Log::info('发送邮件通知', [
            'type' => $type,
            'email' => $data['email'],
            'subject' => $subject,
        ]);

        return true;
    }

    /**
     * 发送短信通知
     */
    protected function sendSmsNotification(string $type, array $data): bool
    {
        // 检查是否配置了短信通知
        if (!isset($data['phone']) || empty($data['phone'])) {
            return false;
        }

        // 构建短信内容
        $message = $this->getNotificationMessage($type, $data);

        // 发送短信
        // 这里需要集成短信服务提供商的API

        Log::info('发送短信通知', [
            'type' => $type,
            'phone' => $data['phone'],
            'message' => $message,
        ]);

        return true;
    }

    /**
     * 发送微信通知
     */
    protected function sendWechatNotification(string $type, array $data): bool
    {
        // 检查是否配置了微信通知
        if (!isset($data['openid']) || empty($data['openid'])) {
            return false;
        }

        // 构建微信通知内容
        $message = $this->getNotificationMessage($type, $data);

        // 发送微信通知
        // 这里需要集成微信消息模板API

        Log::info('发送微信通知', [
            'type' => $type,
            'openid' => $data['openid'],
            'message' => $message,
        ]);

        return true;
    }

    /**
     * 发送支付宝通知
     */
    protected function sendAlipayNotification(string $type, array $data): bool
    {
        // 检查是否配置了支付宝通知
        if (!isset($data['user_id']) || empty($data['user_id'])) {
            return false;
        }

        // 构建支付宝通知内容
        $message = $this->getNotificationMessage($type, $data);

        // 发送支付宝通知
        // 这里需要集成支付宝消息模板API

        Log::info('发送支付宝通知', [
            'type' => $type,
            'user_id' => $data['user_id'],
            'message' => $message,
        ]);

        return true;
    }

    /**
     * 获取通知主题
     */
    protected function getNotificationSubject(string $type, array $data): string
    {
        return match ($type) {
            'payment_success' => '支付成功通知',
            'payment_failed' => '支付失败通知',
            'refund_success' => '退款成功通知',
            'refund_failed' => '退款失败通知',
            'payment_expired' => '支付过期通知',
            default => '支付通知',
        };
    }

    /**
     * 获取通知消息
     */
    protected function getNotificationMessage(string $type, array $data): string
    {
        $outTradeNo = $data['out_trade_no'] ?? '未知';
        $amount = $data['amount'] ?? 0;
        $refundAmount = $data['refund_amount'] ?? 0;

        return match ($type) {
            'payment_success' => "尊敬的用户，您的订单 {$outTradeNo} 已支付成功，支付金额为 {$amount} 元，感谢您的支持！",
            'payment_failed' => "尊敬的用户，您的订单 {$outTradeNo} 支付失败，请稍后重试或联系客服，谢谢！",
            'refund_success' => "尊敬的用户，您的订单 {$outTradeNo} 退款成功，退款金额为 {$refundAmount} 元，请注意查收！",
            'refund_failed' => "尊敬的用户，您的订单 {$outTradeNo} 退款失败，请联系客服处理，谢谢！",
            'payment_expired' => "尊敬的用户，您的订单 {$outTradeNo} 已过期，请重新下单支付，谢谢！",
            default => "尊敬的用户，您的订单 {$outTradeNo} 状态有更新，请查看详情，谢谢！",
        };
    }

    /**
     * 发送支付成功通知
     */
    public function notifyPaymentSuccess(array $data, array $channels = ['mail']): array
    {
        return $this->notify('payment_success', $data, $channels);
    }

    /**
     * 发送支付失败通知
     */
    public function notifyPaymentFailed(array $data, array $channels = ['mail']): array
    {
        return $this->notify('payment_failed', $data, $channels);
    }

    /**
     * 发送退款成功通知
     */
    public function notifyRefundSuccess(array $data, array $channels = ['mail']): array
    {
        return $this->notify('refund_success', $data, $channels);
    }

    /**
     * 发送退款失败通知
     */
    public function notifyRefundFailed(array $data, array $channels = ['mail']): array
    {
        return $this->notify('refund_failed', $data, $channels);
    }

    /**
     * 发送支付过期通知
     */
    public function notifyPaymentExpired(array $data, array $channels = ['mail']): array
    {
        return $this->notify('payment_expired', $data, $channels);
    }
}