<?php

namespace App\Http\logic\api;

use App\dao\Estatisticas\RechargeWithDraw;
use App\Http\helper\NumConfig;
use App\Inter\CashierInterFace;
use App\Models\PrivateMail;
use App\Models\RecordUserDataStatistics;
use App\Services\SfPay;
use App\Services\PayConfig;
use App\Services\StoredProcedure;
use App\Util;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class SfPayCashierLogic implements CashierInterFace
{
    const AGENT = 108; // SfPay代付渠道值（对应 admin_configs config_value）
    protected $agent = 108;

    /**
     * 支付方式位掩码 → SfPay payProduct 映射（代付）
     * 1=cashapp, 2=paypal
     */
    protected $payoutProductMap = [
        1 => 'USA202', // cashapp
        2 => 'USA203', // paypal
    ];

    /**
     * PixType → 代付方式映射
     */
    protected $bankTypeMap = [
        1 => 'USA202', // cashapp
        2 => 'USA203', // paypal
    ];

    /**
     * 提交代付申请
     */
    public function payment($RecordID, $amount, $accountName, $phone, $email, $OrderId, $PixNum, $PixType, $IFSCNumber, $BranchBank, $BankNO)
    {
        // 查询订单
        $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('RecordID', $RecordID)->first();
        if (!$query) return 'fail';

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

        $service = new SfPay();

        // 确定代付产品
        $payProduct = $this->payoutProductMap[$PixType] ?? 'USA202';

        // 构建收款账号
        if ($PixType == 1) {
            // CashApp: cashtag，需 $ 前缀
            $account = ($PixNum && strpos($PixNum, '$') !== 0) ? '$' . $PixNum : $PixNum;
        } elseif ($PixType == 2) {
            // PayPal: 邮箱
            $account = $email ?: $PixNum;
        } else {
            $account = $PixNum ?: $email;
        }

        // 构建代付请求参数
        $params = [
            'merchantOrderNo'    => $OrderId,
            'amount'             => (float)number_format($amount / NumConfig::NUM_VALUE, 2, '.', ''),
            'beneficiaryAccount' => $account,
            'beneficiaryName'    => $accountName ?: 'user',
            'countryId'          => 'USA',
            'payProduct'         => $payProduct,
            'notifyUrl'          => $config['cash_notify_url'] ?? '',
            'beneficiaryEmail'   => $email ?: '',
            'beneficiaryPhoneNo' => $phone ?: '',
        ];

        Log::info('SfPay 提现参数：', $params);

        $url = $service->apiUrl . '/gateway/payout/init';

        try {
            $result = $service->curlPost($url, $params);
        } catch (\Exception $exception) {
            Log::info('SfPay 提现请求异常：', [$exception->getMessage()]);
            Util::WriteLog('SfPay_error', 'SfPay 提现请求异常：' . $exception->getMessage());
            return 'fail';
        }

        Log::info('SfPay 提现结果：', [$result ?? 'no result']);

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

        // SfPay 代付成功响应: code=0
        if (isset($data['code']) && $data['code'] === 0) {
            return $data;
        }

        // 同步失败处理：回复玩家金币，标记订单失败
        if ($query->State == 5) {
            $msg = 'Liquidation failure';
            $WithDraw = $query->WithDraw + $query->ServiceFee;
            $bonus = '30000,' . $WithDraw;

            PrivateMail::failMail($query->UserID, $OrderId, $WithDraw, $msg, $bonus);

            $withdraw_data = [
                'State'      => 6,
                'agent'      => 1080,
                'finishDate' => now(),
                'remark'     => json_encode($data)
            ];
            DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')
                ->where('OrderId', $query->OrderId)
                ->update($withdraw_data);

            $RecordData = ['after_state' => 6, 'update_at' => now()];
            DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')
                ->where('type', 1)
                ->where('RecordID', $RecordID)
                ->update($RecordData);
        }
        return 'fail';
    }

    /**
     * 代付异步回调处理
     *
     * SfPay代付回调格式（POST JSON，不加密）:
     * {
     *   "data": {
     *     "amount": "30.00",
     *     "orderNo": "...",
     *     "message": "...",
     *     "type": "payout",
     *     "merchantOrderNo": "...",
     *     "processedTime": "...",
     *     "processAmount": "0.00",
     *     "status": "SUCCESS"
     *   },
     *   "signature_n": "..."
     * }
     */
    public function notify($post)
    {
        if (!is_array($post)) {
            $post = \GuzzleHttp\json_decode($post, true);
        }

        Util::WriteLog('SfPay', 'SfPay 提现回调：' . json_encode($post));

        try {
            $callbackData = $post['data'] ?? [];
            $signatureN = $post['signature_n'] ?? '';

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

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

            // 判断订单是否存在
            $OrderId = $callbackData['merchantOrderNo'] ?? '';
            $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')
                ->where('OrderId', $OrderId)
                ->first();

            if (!$query) {
                Util::WriteLog('SfPay', '提现订单不存在: ' . $OrderId);
                return 'SUCCESS';
            }

            // 订单已完成处理
            if ($query->State != 5 && $query->State != 7) {
                Util::WriteLog('SfPay', $OrderId . '_订单状态已完成');
                return 'SUCCESS';
            }

            $agentID = DB::connection('write')->table('agent.dbo.admin_configs')
                ->where('config_value', self::AGENT)
                ->where('type', 'cash')
                ->select('id')
                ->first()->id ?? '';

            $now = now();
            $notify_data = [
                'state'      => 1,
                'finish_at'  => $now,
                'casOrdNo'   => $callbackData['orderNo'] ?? '',
                'extra'      => \GuzzleHttp\json_encode($post),
                'created_at' => $now,
                'updated_at' => $now,
                'order_sn'   => $OrderId,
                'amount'     => $query->WithDraw,
            ];

            // 判断回调结果: SUCCESS=成功, FAILURE=失败
            $status = $callbackData['status'] ?? '';
            $orderStatus = 0;

            if ($status === 'SUCCESS') {
                $orderStatus = 1; // 成功
            } elseif ($status === 'FAILURE' || $status === 'REVERSED') {
                $orderStatus = 2; // 失败
            }

            if (!$orderStatus) {
                Util::WriteLog('SfPay', 'SfPay 提现处理中：' . $OrderId);
                return 'SUCCESS';
            }

            Util::WriteLog('SfPay', 'SfPay 提现结果：' . $OrderId . '_' . $orderStatus);

            $UserID = $query->UserID;
            $TakeMoney = $query->WithDraw + $query->ServiceFee;

            $withdraw_data = [];

            switch ($orderStatus) {
                case 1: // 提现成功
                    Util::WriteLog('SfPay', 'SfPay提现成功');

                    $withdraw_data = [
                        'State'      => 2,
                        'agent'      => $agentID,
                        'finishDate' => $now
                    ];

                    // 增加提现记录
                    $first = DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')
                        ->where('UserID', $UserID)->first();
                    if ($first) {
                        DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')
                            ->where('UserID', $UserID)
                            ->increment('TakeMoney', $TakeMoney);
                    } else {
                        DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')
                            ->insert(['TakeMoney' => $TakeMoney, 'UserID' => $UserID]);
                        try {
                            PrivateMail::praiseSendMail($UserID);
                        } catch (\Exception $e) {
                            // 忽略邮件发送失败
                        }
                    }

                    // 免审的时候，修改免审状态
                    $withdrawal_position_log = DB::connection('write')
                        ->table('agent.dbo.withdrawal_position_log')
                        ->where('order_sn', $OrderId)
                        ->first();
                    if ($withdrawal_position_log) {
                        DB::connection('write')->table('agent.dbo.withdrawal_position_log')
                            ->where('order_sn', $OrderId)
                            ->update(['take_effect' => 2, 'update_at' => date('Y-m-d H:i:s')]);
                    }

                    try {
                        StoredProcedure::addPlatformData($UserID, 4, $TakeMoney);
                    } catch (\Exception $exception) {
                        Util::WriteLog('StoredProcedure', $exception);
                    }

                    $ServiceFee = $query->ServiceFee;
                    // 增加用户提现值
                    RecordUserDataStatistics::updateOrAdd($UserID, $TakeMoney, 0, $ServiceFee);

                    // 数据统计后台 -- 提现记录添加
                    (new RechargeWithDraw())->withDraw($UserID, $TakeMoney, 0, $ServiceFee);

                    $redis = Redis::connection();
                    $redis->incr('draw_' . date('Ymd') . $UserID);
                    PrivateMail::successMail($UserID, $OrderId, $TakeMoney);
                    break;

                case 2: // 提现失败
                    $msg = 'Encomenda rejeitada pelo banco';
                    $bonus = '30000,' . $TakeMoney;
                    PrivateMail::failMail($query->UserID, $OrderId, $TakeMoney, $msg, $bonus);

                    Util::WriteLog('SfPayEmail', [$query->UserID, $OrderId, $TakeMoney, $msg, $bonus]);
                    $withdraw_data = [
                        'State'  => 6,
                        'agent'  => $agentID,
                        'remark' => $callbackData['message'] ?? ''
                    ];
                    $notify_data['state'] = 2;
                    break;
            }

            $RecordData = [
                'before_state' => $query->State,
                'after_state'  => $withdraw_data['State'] ?? 0,
                'RecordID'     => $query->RecordID,
                'update_at'    => date('Y-m-d H:i:s')
            ];

            // 添加用户提现操作记录
            DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')
                ->updateOrInsert(['RecordID' => $query->RecordID, 'type' => 1], $RecordData);
            DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')
                ->where('OrderId', $query->OrderId)
                ->update($withdraw_data);

            if (isset($withdraw_data['State']) && $withdraw_data['State'] == 2) {
                // 单控标签
                StoredProcedure::user_label($UserID, 2, $TakeMoney);
            }

            return 'SUCCESS';

        } catch (\Exception $exception) {
            Util::WriteLog('SfPay', 'SfPay异步业务逻辑处理失败：' . $exception->getMessage());
            return 'SUCCESS';
        }
    }
}
