<?php

namespace App\Http\logic\api;

use App\dao\Pay\AccountPayInfo;
use App\dao\Pay\PayController;
use App\Facade\TableName;
use App\Http\helper\CreateOrder;
use App\Http\helper\NumConfig;
use App\Jobs\Order;
use App\Notification\TelegramBot;
use App\Services\OrderServices;
use App\Services\PayConfig;
use App\Services\PagYeepPay;
use App\Services\CreateLog;
use App\Util;
use Illuminate\Support\Facades\DB;

class PagYeepPayLogic extends BaseApiLogic
{
    public $result;

    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 PagYeepPay();
        $config = $service->config;

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

        // 生成订单信息（PagYeepPay金额单位：分）
        $logic = new OrderLogic();
        $amount = (int) round($pay_amount * NumConfig::NUM_VALUE);
        $logic->orderCreate($order_sn, $amount, 'PagYeepPay', $userId, $pay_method, $GiftsID, $AdId, $eventType);

        // 支付方式映射（根据文档：CASH_APP、APPLE_PAY等）
        $payMethods = [
            1 => '1204',
//            2 => '1207',
            4 => '1205',
            8 => '1208'
        ];

        $payType = @$payMethods[$pay_method] ?: '1204';

        // 构建支付请求参数（根据文档）
        $params = [
            "version" => $config['version'] ?? "2.1",  // 接口版本号
            "orgNo" => $config['orgNo'],  // 机构编号
            "custId" => $config['custId'],  // 商户编号
            "custOrderNo" => $order_sn,  // 商户订单号
//            "tranType" => 1,
            "clearType" => "01",
            "tranType" => $payType,  // 支付类型
            "payAmt" => (int) round($pay_amount * 100),  // 支付金额（单位：分）

            "backUrl" => $config['notify'] ?? '',  // 支付结果异步通知地址
            "frontUrl" => $config['return'] ?? '',  // 支付成功返回地址
            "goodsName" => "Gift",
            "orderDesc" => "Gift Goos",
            "buyIp" => $buyIP,
            "userName" => $userName,
            "userEmail" => $userEmail,
            "userPhone" => $userPhone,
            "countryCode" => "US",
            "currency" => "USD",  // 货币
        ];

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

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

        $url = $service->apiUrl.'/establish/deposit.ac';

        $result = $service->curlPost($url, $signedParams);
        $rresult = compact('result', 'signedParams', 'url');
        
        Util::WriteLog('PagYeepPay', 'PagYeepPay支付请求' . $url . " | " . $request_extra);
        Util::WriteLog('PagYeepPay', 'PagYeepPay支付结果' . json_encode($rresult));
        
        try {
            // 解析返回结果（可能是form表单格式或JSON格式）
//            parse_str($result, $res);
//            if (empty($res)) {
                $res = \GuzzleHttp\json_decode($result, true);
//            }
        } catch (\Exception $e) {
            Util::WriteLog("PagYeepPay_error", [$result, $e->getMessage(), $e->getTraceAsString()]);
            $this->error = 'Payment processing failed';
            return false;
        }

        // 根据文档，返回码000000表示成功
        if (isset($res['code']) && $res['code'] == '000000') {
            // 转换为统一格式供控制器使用
            return [
                'code' => 0,  // 统一成功码
                'data' => [
                    'cashierUrl' => @$res['busContent']['url'],  // 支付链接（如果有）
                    'mchOrderNo' => $order_sn,  // 商户订单号
                    'orderNo' => $res['prdOrdNo'] ?? '',  // 平台订单号
                    'amount' => $pay_amount,
                    'currency' => 'USD',
                    'status' => 'initiated',
                ]
            ];
        } else {
            $this->error = $res['msg'] ?? 'Payment failed';
            Util::WriteLog('PagYeepPay_error', 'Payment failed: ' . json_encode($res));
            return false;
        }
    }

    public function notify($post)
    {
        try {
            if (!is_array($post)) {
                // 可能是form表单格式
                parse_str($post, $post);
                if (empty($post)) {
                    $post = \GuzzleHttp\json_decode($post, true);
                }
            }

            Util::WriteLog('PagYeepPay', "PagYeepPay异步回调处理\n" . json_encode($post, JSON_UNESCAPED_UNICODE));

            // 根据文档，回调参数：
            // version, orgNo, custId, custOrderNo, prdOrdNo, payAmt, ordStatus, sign
            $order_sn = $post['custOrderNo'] ?? '';  // 商户订单号

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

            if (!$order) {
                Util::WriteLog('PagYeepPay', '订单不存在: ' . $order_sn);
                return 'SC000000';  // 根据文档，返回SC000000表示成功
            }

            // 订单已处理，直接返回成功
            if ((!empty($order->pay_at) || !empty($order->finished_at))) {
                Util::WriteLog('PagYeepPay', '订单已处理: ' . $order_sn);
                return 'SC000000';
            }

            $body = [
                'payment_sn' => $post['prdOrdNo'] ?? '',  // 平台订单号
                'updated_at' => date('Y-m-d H:i:s'),
            ];

            $ordStatus = $post['ordStatus'] ?? '';  // 订单状态
            $GiftsID = $order->GiftsID ?: '';
            $userID = $order->user_id ?: '';
            $AdId = $order->AdId ?: '';
            $eventType = $order->eventType ?: '';
            // 金额单位：分
            $payAmt = intval($post['payAmt'] ?? 0);
            $payAmtYuan = $payAmt / 100;  // 转换为元

            // 根据文档，订单状态：01=成功, 02=失败, 其他=处理中
            switch ($ordStatus) {
                case '01':  // 支付成功
                    $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'] = $payAmt;  // 已经是分
                    $config = (new PayConfig())->getConfig('PagYeepPay');

                    $payRates = @$config['pay_rate'];
                    if(is_array($payRates)){
                        $payMethod = $order->order_title??1;
                        $payRate = $payRates[$payMethod] ?? $payRates[1];
                        $body['payment_fee'] = intval(($body['amount'] * ($payRate[0] ?? 15))/100)+($payRate[1]??0.3)*NumConfig::NUM_VALUE;
                    }

//                    $body['payment_fee'] = $body['amount'] * ($config['payin_fee'] ?? 0);
                    
                    try {
                        // 获取金额
                        $service = new OrderServices();

                        if (intval($order->amount) != $body['amount']) {
                            // 金额不匹配，按实际支付金额处理
                            $body['GiftsID'] = 0;
                            $body['amount'] = $payAmt;
                            $Recharge = $payAmtYuan;
                            $give = 0;
                            $favorable_price = $Recharge + $give;
                            $czReason = 1;
                            $cjReason = 45;
                        } else {
                            [$give, $favorable_price, $Recharge, $czReason, $cjReason] = $service->getPayInfo($GiftsID, $userID, $payAmtYuan);
                        }

                        // 增加充值记录
                        [$Score] = $service->addRecord($userID, $payAmtYuan, $favorable_price, $order_sn, $GiftsID, $Recharge, $czReason, $give, $cjReason, $AdId, $eventType, $body['payment_fee'] ?? 0);
                        // 成功处理回调
                        Order::dispatch([$userID, $payAmtYuan, $Score, $favorable_price, $GiftsID, $order_sn]);

                        Util::WriteLog("PagYeepPay", "订单处理成功: {$order_sn}, 用户: {$userID}, 金额: {$payAmtYuan}, 到账: {$Score}");

                    } catch (\Exception $exception) {
                        Util::WriteLog("PagYeepPay_error", "订单处理异常: " . $exception->getMessage());
                        throw $exception;
                    }

                    break;
                    
                case '02':    // 支付失败
                    $body['pay_status'] = 2;
                    Util::WriteLog('PagYeepPay', "订单支付失败: {$order_sn}, 状态: 02");
                    break;
                    
                default:          // 其他状态（处理中）
                    Util::WriteLog('PagYeepPay', "订单处理中: {$order_sn}, 状态: {$ordStatus}");
                    return 'SC000000';  // 返回成功
            }

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

            if (!$order_up) {
                Util::WriteLog('PagYeepPay', '订单更新失败: ' . $order_sn);
                return 'SC000000';  // 仍然返回成功
            }

            Util::WriteLog("PagYeepPay", "订单回调处理完成: {$order_sn}");

            return 'SC000000';

        } catch (\Exception $exception) {
            Util::WriteLog("PagYeepPay_error", "回调异常: " . $exception->getMessage() . "\n" . $exception->getTraceAsString());
            throw $exception;
        }
    }
}
