<?php

namespace App\Http\logic\api;

use App\dao\Pay\AccountPayInfo;
use App\dao\Pay\PayController;
use App\Http\helper\CreateOrder;
use App\Http\helper\NumConfig;
use App\Jobs\Order;
use App\Services\SfPay;
use App\Services\CreateLog;
use App\Services\OrderServices;
use App\Services\PayConfig;
use App\Util;
use Illuminate\Support\Facades\DB;

class SfPayLogic extends BaseApiLogic
{
    public $result;

    /**
     * 支付方式位掩码 → SfPay payProduct 映射
     *
     * 1=cashapp, 2=paypal, 4=applepay, 16=btc(CASH_BTC), 1024=usdt
     */
    protected $payProductMap = [
        1    => 'USA102', // CashApp
        2    => 'USA107', // PayPal
        4    => 'USA103', // APPLE_PAY
        16   => 'USA106', // CASH_BTC
        1024 => 'USA105', // USDT
    ];

    /**
     * 代收下单
     */
    public function pay_order($userId, $pay_amount, $userPhone, $userEmail, $userName, $GiftsID, $buyIP, $AdId, $eventType, $pay_method = '')
    {
        $dao = new AccountPayInfo();
        [$userPhone, $userName, $userEmail] = $dao->payInfo($userId);

        // 礼包类型验证
        $PayVerify = new PayController();
        $pay_amount = $PayVerify->verify($userId, $GiftsID, $pay_amount);
        if ($PayVerify->verify($userId, $GiftsID, $pay_amount) === false) {
            $this->error = $PayVerify->getError();
            return false;
        }
        if ($pay_amount < 0) {
            $this->error = 'Payment error_4';
            return false;
        }

        $service = new SfPay();
        $config = $service->config;

        $order_sn = CreateOrder::order_sn($userId);

        // 生成订单信息
        $logic = new OrderLogic();
        $amount = (int) round($pay_amount * NumConfig::NUM_VALUE);
        $logic->orderCreate($order_sn, $amount, 'SfPay', $userId, $pay_method, $GiftsID, $AdId, $eventType);

        // 确定 payProduct
        $payProduct = $this->payProductMap[$pay_method] ?? ($config['pay_product'] ?? 'USA102');

        // 构建支付请求参数（明文，后续AES加密）
        // 必传: merchantOrderNo, amount, payProduct, gameId
        $params = [
            'merchantOrderNo' => $order_sn,
            'amount'          => (float)$pay_amount,
            'payProduct'      => $payProduct,
            'gameId'          => (int) ($config['game_id'] ?? 0),
        ];

        // 可选参数（传了收银台会预填，不传则需要用户手动输入）
        if (!empty($userName))           $params['customerName']  = $userName;
        if (!empty($userEmail))          $params['customerEmail'] = $userEmail;
        if (!empty($userPhone))          $params['customerPhone'] = $userPhone;
        if (!empty($config['notify_url'])) $params['notifyUrl']   = $config['notify_url'];
        if (!empty($config['return_url'])) $params['returnUrl']   = $config['return_url'];

        // 可选辅助参数
        $params['countryId'] = 'USA';  // 货币单位依据countryId
        $params['userAgent'] = $_SERVER['HTTP_USER_AGENT'] ?? 'Mozilla/5.0';
        $params['ip']        = $buyIP ?: ($_SERVER['REMOTE_ADDR'] ?? '');

        // 生成用户请求信息日志
        $request_extra = \GuzzleHttp\json_encode($params);
        CreateLog::pay_request($userPhone, $request_extra, $order_sn, $userEmail, $userId, $userName);

        $url = $service->apiUrl . '/gateway/payment/init';
        Util::WriteLog('SfPay', 'SfPay支付请求: ' . $url . ' | ' . $request_extra);
        $result = $service->curlPost($url, $params);
        Util::WriteLog('SfPay', 'SfPay支付结果: ' . ($result ?: '空结果'));

        if ($result === false) {
            $this->error = 'Payment processing error';
            return false;
        }

        try {
            $data = \GuzzleHttp\json_decode($result, true);
        } catch (\Exception $e) {
            Util::WriteLog("SfPay_error", [$result, $e->getMessage()]);
            $this->error = 'Payment processing error';
            return false;
        }

        return $data;
    }

    /**
     * 代收异步回调处理
     *
     * SfPay回调格式（POST JSON，不加密）:
     * {
     *   "data": {
     *     "amount": "20.00",
     *     "orderNo": "...",
     *     "message": "Success",
     *     "type": "payment",
     *     "merchantOrderNo": "...",
     *     "processedTime": "...",
     *     "transferMode": "PIX",
     *     "status": "SUCCESS"
     *   },
     *   "signature_n": "..."
     * }
     */
    public function notify($post)
    {
        $callbackData = $post['data'] ?? [];
        $signatureN = $post['signature_n'] ?? '';

        if (empty($callbackData) || empty($signatureN)) {
            Util::WriteLog('SfPay', '回调数据不完整');
            return 'ok';
        }

        // 验签
        $service = new SfPay();
        if (!$service->verifySign($callbackData, $signatureN)) {
            Util::WriteLog('SfPay', '回调签名验证失败');
            return 'ok';
        }

        $order_no = $callbackData['merchantOrderNo'] ?? '';

        // 查询订单信息
        $order = DB::connection('write')->table('agent.dbo.order')
            ->where('order_sn', $order_no)
            ->first();

        if (!$order) {
            Util::WriteLog('SfPay', '订单不存在: ' . $order_no);
            return 'ok';
        }

        // 已处理过则直接返回
        if (!empty($order->pay_at) || !empty($order->finished_at)) {
            return 'ok';
        }

        $status = $callbackData['status'] ?? '';
        $body = [
            'payment_sn' => $callbackData['orderNo'] ?? '',
            'updated_at' => date('Y-m-d H:i:s'),
        ];

        // status: SUCCESS=成功, FAILURE=失败, PENDING=处理中
        if ($status !== 'SUCCESS') {
            Util::WriteLog('SfPay', "支付未完成订单: {$order_no}, status: {$status}");
            return 'ok';
        }

        // 支付成功
        $GiftsID = $order->GiftsID ?: '';
        $userID = $order->user_id ?: '';
        $AdId = $order->AdId ?: '';
        $eventType = $order->eventType ?: '';

        $payAmt = (float)($callbackData['amount'] ?? 0);

        $body['pay_status'] = 1;
        $body['pay_at'] = date('Y-m-d H:i:s');
        $body['finished_at'] = date('Y-m-d H:i:s');
        $body['amount'] = (int) round($payAmt * NumConfig::NUM_VALUE);

        try {
            $orderService = new OrderServices();

            if (intval($order->amount) != $body['amount']) {
                $body['GiftsID'] = 0;
                $body['amount'] = (int) round($payAmt * NumConfig::NUM_VALUE);
                $Recharge = $payAmt;
                $give = 0;
                $favorable_price = $Recharge + $give;
                $czReason = 1;
                $cjReason = 45;
            } else {
                [$give, $favorable_price, $Recharge, $czReason, $cjReason] = $orderService->getPayInfo(
                    $GiftsID, $userID, $payAmt
                );
            }

            // 增加充值记录
            [$Score] = $orderService->addRecord(
                $userID, $payAmt, $favorable_price, $order_no, $GiftsID,
                $Recharge, $czReason, $give, $cjReason, $AdId, $eventType,
                0
            );

            // 异步处理后续任务
            Order::dispatch([$userID, $payAmt, $Score, $favorable_price, $GiftsID, $order_no]);
        } catch (\Exception $exception) {
            Util::WriteLog("SfPay_error", $exception->getMessage());
        }

        // 更新订单状态
        $order_up = DB::connection('write')->table('agent.dbo.order')
            ->where('order_sn', $order_no)
            ->update($body);

        if (!$order_up) {
            Util::WriteLog('SfPay', '订单更新失败: ' . $order_no);
            return 'ok';
        }

        Util::WriteLog("SfPay", 'success: ' . $order_no);
        return 'ok';
    }

    /**
     * 代收订单查询
     *
     * POST /gateway/payment/orderQuery
     * 请求: {"merchantOrderNo": "xxx"}（AES加密）
     * 响应: code=0, data={status, amount, orderNo, ...}
     *
     * @param string $merchantOrderNo 商户订单号
     * @return array|false
     */
    public function orderQuery($merchantOrderNo)
    {
        $service = new SfPay();
        $params = ['merchantOrderNo' => $merchantOrderNo];

        $url = $service->apiUrl . '/gateway/payment/orderQuery';

        Util::WriteLog('SfPay', 'SfPay订单查询: ' . $url . ' | ' . $merchantOrderNo);

        $result = $service->curlPost($url, $params);

        if ($result === false) {
            $this->error = 'Query processing error';
            return false;
        }

        try {
            $data = \GuzzleHttp\json_decode($result, true);
        } catch (\Exception $e) {
            Util::WriteLog("SfPay_error", [$result, $e->getMessage()]);
            $this->error = 'Query processing error';
            return false;
        }

        return $data;
    }
}
