<?php

namespace App\Services\Client;

use App\Models\Order;
use App\Models\MemberUser;
use Illuminate\Support\Facades\Auth;
use Exception;

class PaymentService
{
    /**
     * 获取支付配置
     *
     * @param int $orderId 订单编号
     * @return array
     * @throws Exception
     */
    public function getPaymentConfig($orderId)
    {
        // 获取当前用户
        $userId = Auth::id();
        $user = MemberUser::where('state', 'enable')->findOrFail($userId);

        // 查询订单
        $order = Order::where('id', $orderId)
            ->where('user_id', $userId)
            ->where('state', 'unpaid')
            ->firstOrFail();

        // 生成微信支付配置
        $outTradeNo = $this->generateOutTradeNo();
        $config = $this->generateWxPayConfig($order, $outTradeNo);

        // 更新订单外部交易号
        $order->out_trade_no = $outTradeNo;
        $order->save();

        // 发送抢单通知
        $this->sendGrabOrderNotification($order);

        return $config;
    }

    /**
     * 生成外部交易号
     */
    private function generateOutTradeNo()
    {
        return date('YmdHis') . mt_rand(1000, 9999);
    }

    /**
     * 生成微信支付配置
     */
    private function generateWxPayConfig($order, $outTradeNo)
    {
        // TODO: 对接微信支付,生成JSAPI支付配置
        return [
            'appId' => config('wechat.payment.app_id'),
            'timeStamp' => time(),
            'nonceStr' => uniqid(),
            'package' => 'prepay_id=xxx',
            'signType' => 'MD5',
            'paySign' => 'xxx'
        ];
    }

    /**
     * 发送抢单通知
     */
    private function sendGrabOrderNotification($order)
    {
        // TODO: 对接极光推送,发送抢单通知
    }
}