<?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\SafePay;
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 SafePayCashierLogic implements CashierInterFace
{
    const AGENT = 106; // SafePay代付渠道值
    protected $agent = 106;

    /**
     * 提交代付申请
     */
    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('SafePayOut');

        // PixType → bank_type/bank_code 映射（沿用现有系统的PixType约定）
        $bankTypeMap = [
            1 => 'CASHAPP',
            2 => 'PayPal',
        ];

        $bankType = $bankTypeMap[$PixType] ?? 'CASHAPP';

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

        // 构建代付请求参数
        $params = [
            'mer_no'     => $config['mer_no'] ?? '',
            'order_no'   => $OrderId,
            'amount'     => number_format($amount / NumConfig::NUM_VALUE, 2, '.', ''),
            'currency'   => $config['currency'] ?? 'USD',
            'bank_code'  => $bankType,
            'bank_type'  => $bankType,
            'name'       => $accountName ?: 'user'.$query->UserID,
            'account'    => $account,
            'email'      => $email ?: '',
            'phone'      => $phone ?: '0000000000',
            'notify_url' => $config['notify_url'] ?? '',
            'extra'      => json_encode([
                'userId'    => (string)($query->UserID ?? ''),
                'firstName' => $accountName ?: 'user'.$query->UserID,
            ]),
        ];

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

        $url = ($config['apiUrl'] ?? 'https://api.safepay.wang') . '/open/api/order/out';

        Log::info('SafePay 提现参数：', $signedParams);

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

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

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

        // SafePay 代付成功响应: code=200, data.sys_no 是系统流水号
        if (isset($data['code']) && $data['code'] == 200) {
            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'       => 1060,
                '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';
    }

    /**
     * 代付异步回调处理
     *
     * SafePay 代付回调格式（POST JSON）:
     * {
     *   "mer_no": 600000,
     *   "order_no": "xxx",
     *   "order_amount": "10.00",
     *   "order_reality_amount": "10.00",
     *   "currency": "USD",
     *   "result": "success",   // success=成功, fail=失败
     *   "sys_no": "212073",
     *   "sign": "xxx"
     * }
     */
    public function notify($post)
    {
        if (!is_array($post)) $post = \GuzzleHttp\json_decode($post, true);

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

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

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

            // 订单已完成处理
            if ($query->State != 5 && $query->State != 7) {
                Util::WriteLog('SafePay', $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'   => $post['sys_no'] ?? '',
                'extra'      => \GuzzleHttp\json_encode($post),
                'created_at' => $now,
                'updated_at' => $now,
                'order_sn'   => $OrderId,
                'amount'     => $query->WithDraw,
            ];

            // 判断回调结果: result=success=成功, result=fail=失败
            $result = $post['result'] ?? '';
            $orderStatus = 0;

            if ($result === 'success') {
                $orderStatus = 1; // 成功
            } elseif ($result === 'fail') {
                $orderStatus = 2; // 失败
            }

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

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

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

            $withdraw_data = [];

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

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

                    // 根据配置计算代付手续费: 费率% * 提现金额 + 固定$
                    // 例: pay_rate=[0.5,0.3] → 0.5% + $0.3
                    $payConfigService = new PayConfig();
                    $outConfig = $payConfigService->getConfig('SafePayOut');
                    $payRates = $outConfig['pay_rate'] ?? null;
                    if (is_array($payRates)) {
                        $payMethod = $query->PixType ?? 1;
                        $payRate = $payRates[$payMethod] ?? $payRates;
                        $feePercent = $payRate[0] ?? 0.5;
                        $feeFixed = $payRate[1] ?? 0.3;
                        $withdraw_data['withdraw_fee'] = intval(($query->WithDraw * $feePercent) / 100)
                            + (int)($feeFixed * NumConfig::NUM_VALUE);
                    }

                    // 增加提现记录
                    $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, $withdraw_data['withdraw_fee'] ?? 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('SafePayEmail', [$query->UserID, $OrderId, $TakeMoney, $msg, $bonus]);
                    $withdraw_data = [
                        'State'  => 6,
                        'agent'  => $agentID,
                        'remark' => $post['result_mes'] ?? ''
                    ];
                    $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('SafePay', 'SafePay异步业务逻辑处理失败：' . $exception->getMessage());
            return 'SUCCESS';
        }
    }
}
