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

class BotImPayLogic extends BaseApiLogic
{
    public $result;

    /**
     * 支付方式到 pay_code 的映射
     * 16=BTC, 32=ETH, 1024=USDT, 2048=USDC
     */
    protected $payCodeMap = [
        16   => '20303', // BTC
        32   => '20304', // ETH
        1024 => '20301', // USDT
        2048 => '20307', // USDC
    ];

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

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

        // 构建支付请求参数（BotImPay 多一个 ip 字段）
        $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'] ?? 'USDT',
            'pay_code'   => $payCode,
            'notify_url' => $config['notify_url'] ?? '',
            'ip'         => $buyIP,
        ];

        // 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('BotImPay', 'BotImPay支付请求' . $url . " | " . $request_extra);
        Util::WriteLog('BotImPay', 'BotImPay支付结果' . json_encode($rresult));

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

        return $data;
    }

    /**
     * 代收异步回调处理
     *
     * BotImPay 回调: { mer_no, order_no, pay_type_code, order_amount, order_reality_amount, status, sign }
     */
    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('BotImPay', '订单不存在: ' . $order_no);
            return 'ok';
        }

        if (!empty($order->pay_at) || !empty($order->finished_at)) {
            return 'ok';
        }

        $status = $post['status'] ?? '';
        if ($status !== 'success') {
            Util::WriteLog('BotImPay', "支付未完成订单: {$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 = [
            'payment_sn' => $post['sys_no'] ?? '',
            'updated_at' => date('Y-m-d H:i:s'),
            'pay_status' => 1,
            'pay_at'     => date('Y-m-d H:i:s'),
            'finished_at'=> date('Y-m-d H:i:s'),
            'amount'     => (int) round($payAmt * NumConfig::NUM_VALUE),
        ];

        // 根据支付方式计算代收手续费: 费率% * 金额 + 固定$
        $config = (new PayConfig())->getConfig('BotImPay');
        $payRates = $config['pay_rate'] ?? null;
        if (is_array($payRates)) {
            $payMethod = $order->order_title ?? 1024;
            $payRate = $payRates[$payMethod] ?? ($payRates[1024] ?? [3.5, 0]);
            $feePercent = $payRate[0] ?? 3.5;
            $feeFixed = $payRate[1] ?? 0;
            $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("BotImPay_error", $exception->getMessage());
        }

        $order_up = DB::connection('write')->table('agent.dbo.order')
            ->where('order_sn', $order_no)
            ->update($body);

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

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