<?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\SafePay;
use App\Services\CreateLog;
use App\Services\OrderServices;
use App\Services\PayConfig;
use App\Util;
use Illuminate\Support\Facades\DB;

class SafePayLogic extends BaseApiLogic
{
    public $result;

    /**
     * 支付方式到 pay_code 的映射
     * 1=cashapp, 2=paypal, 4=applepay, 8=googlepay
     */
    protected $payCodeMap = [
        1  => '1301', // 美国 CashApp
        2  => '1305', // 美国 PayPal
        4  => '1302', // 美国 ApplePay
        8  => '1303', // 美国 GooglePay
        16 => '1304', // 美国 BTC
    ];

    /**
     * 代收下单
     */
    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 SafePay();
        $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, 'SafePay', $userId, $pay_method, $GiftsID, $AdId, $eventType);

        // 确定 pay_code
        $payCode = $this->payCodeMap[$pay_method] ?? ($config['pay_code'] ?? '1301');

        // 构建支付请求参数
        $params = [
            'mer_no'     => $service->merNo,
            'order_no'   => $order_sn,
            'amount'     => (string)$pay_amount,
            'name'       => $userName ?: 'user',
            'email'      => $userEmail ?: ($userId . '@unknown.com'),
            'phone'      => $userPhone ?: '0000000000',
            'currency'   => $config['currency'] ?? 'USD',
            'pay_code'   => $payCode,
            'notify_url' => $config['notify_url'] ?? '',
            'extra'      => json_encode([
                'clientIP'  => $buyIP,
                'firstName' => $userName ?: '',
                'lastName'  => '',
            ]),
        ];

        // RSA签名
        $signedParams = $service->sign($params);

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

        $url = $service->apiUrl . '/open/api/order/in';

        $result = $service->curlPost($url, $signedParams);
        $rresult = compact('result', 'signedParams', 'url');

        Util::WriteLog('SafePay', 'SafePay支付请求' . $url . " | " . $request_extra);
        Util::WriteLog('SafePay', 'SafePay支付结果' . json_encode($rresult));

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

        return $data;
    }

    /**
     * 代收异步回调处理
     */
    public function notify($post)
    {
        $order_no = $post['order_no'] ?? '';

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

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

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

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

        // status: success=交易成功, 其他=失败/待处理
        if ($status !== 'success') {
            // 非成功状态（如 pending/waiting），不处理，等待后续通知
            Util::WriteLog('SafePay', "支付未完成订单: {$order_no}, status: {$status}");
            return 'ok';
        }

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

        $orderAmount = (float)($post['order_reality_amount'] ?? $post['order_amount'] ?? 0);
        $payAmt = $orderAmount;

        $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);

        $config = (new PayConfig())->getConfig('SafePay');

        // 根据支付方式计算代收手续费: 费率% * 金额 + 固定$
        // pay_rate 格式: [1=>[10,0.3], 2=>[13,0.3], 4=>[11,0.3], 8=>[12,0.3]]
        $payRates = $config['pay_rate'] ?? null;
        if (is_array($payRates)) {
            $payMethod = $order->order_title ?? 1;
            $payRate = $payRates[$payMethod] ?? ($payRates[1] ?? [10, 0.3]);
            $feePercent = $payRate[0] ?? 10;
            $feeFixed = $payRate[1] ?? 0.3;
            $body['payment_fee'] = intval(($body['amount'] * $feePercent) / 100)
                + (int)($feeFixed * NumConfig::NUM_VALUE);
        }

        try {
            $service = 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] = $service->getPayInfo(
                    $GiftsID, $userID, $payAmt
                );
            }

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

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

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

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

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