<?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\WDPay;
use App\Services\PayConfig;
use App\Services\PayUtils;
use App\Services\StoredProcedure;
use App\Util;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class WDPayCashierLogic implements CashierInterFace
{
    const AGENT = 100; // WDPay代付渠道值，需要根据实际配置修改
    protected $agent = 100;

    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';    // 订单不存在

        // 使用WDPay服务类进行签名（WDPayOut配置）
        $service = new WDPay();
        $payConfigService = new PayConfig();
        $config = $payConfigService->getConfig('WDPayOut');
        $service->config = $config;
        $service->key = $config['key'] ?? '';
        
        // WDPay支付方式映射
        $wayCode = [
            1 => 'cashapp',  // CashApp
            2 => 'paypal'    // PayPal
        ];
        
        // 根据PixType选择账号
        // PixType: 1=CashApp, 2=PayPal
        $account = '';
        if ($PixType == 1) {
            if ($PixNum && strpos($PixNum, '$') !== 0) {
                $PixNum = '$' . $PixNum;
            }
            $account = $PixNum;  // CashApp标签，如: $abcd1234
        } elseif ($PixType == 2) {
            $account = $email;   // PayPal邮箱，如: 1111@gmail.com
        }

        // 构建提现请求参数（按WDPay官方文档 /charging/create-pay-out）
        $params = [
            "country" => "US",  // 国家，默认US
            "currency" => "USD",  // 货币，默认USD
            "wayCode" => $wayCode[$PixType] ?? 'cashapp',  // cashapp或paypal
            "account" => $account,  // CashApp标签或PayPal邮箱
            "username" => $accountName ?: $email,  // 用户名称，没有则用email
            "amount" => number_format($amount / 100, 2, '.', ''),  // 价格，保留2位小数（元）
            "platform" => Util::getDeviceType(),  // 设备：android/ios，默认ios
            "ip" => Util::getClientIp(),  // 用户真实IP
            "customer" => $config['customer'],  // 商户简称
            "customerNo" => $config['customerNo'],  // 商户编号
            "customerOrderNo" => $OrderId,  // 商户自定义订单号
            "timestamp" => (string)round(microtime(true) * 1000),  // 13位时间戳（毫秒）
            "callback" => $config['cashNotify'] ?? '',  // 回调地址
            "signType" => "MD5",  // 传MD5
        ];

        // 使用WDPay的签名方法
        $signedParams = $service->sign($params);

        $url = $config['apiUrl'] ?? '';  // /charging/create-pay-out

        Util::WriteLog('WDPay_payout', 'WDPay提现请求: ' . $url . ' | 参数: ' . json_encode($signedParams));
        
        try {
            // 使用独立的 curlPost 方法发送请求
            $result = $this->curlPost($url, $signedParams);
        } catch (\Exception $exception) {
            Util::WriteLog('WDPay_payout_error', '提现请求异常：' . $exception->getMessage());
            return 'fail';
        }

        Util::WriteLog('WDPay_payout', 'WDPay提现结果: ' . ($result ?? "no result"));

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

        // WDPay官方返回格式：{"code": 200, "data": {...}, "message": "success"}
        if (isset($data['code']) && $data['code'] == 200) {
            Util::WriteLog('WDPay_payout', "提现订单创建成功: {$OrderId}");
            return $data;
        } else {
            // 提现失败处理
            Util::WriteLog('WDPay_payout_error', "提现失败: {$OrderId} | " . json_encode($data));
            
            if ($query->State == 5) {
                // 同步失败，发送邮件给玩家，退还金币
                $msg = $data['message'] ?? 'Transfer failed';
                $WithDraw = $query->WithDraw + $query->ServiceFee;
                $bonus = '30000,' . $WithDraw;

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

                $withdraw_data = [
                    'State' => 6, 
                    'agent' => 1040,
                    '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';
        }
    }

    public function notify($post)
    {
        if (!is_array($post)) $post = \GuzzleHttp\json_decode($post, true);
        
        Util::WriteLog('WDPay', 'WDPay 提现回调：' . json_encode($post));

        try {
            // 判断订单是否存在（WDPay使用customerOrderNo作为商户订单号）
            $OrderId = $post['customerOrderNo'] ?? '';
            $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $OrderId)->first();

            if (!$query) {
                Util::WriteLog('WDPay_payout','提现订单不存在: ' . $OrderId);
                return '{"msg":"success","code":200}';
            }

            if ($query->State != 5 && $query->State != 7) {
                Util::WriteLog('WDPay_payout', $OrderId . '_提现订单状态已完成');
                return '{"msg":"success","code":200}';
            }

            $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['orderNo'] ?? '',  // WDPay交易号
                'extra' => \GuzzleHttp\json_encode($post),
                'created_at' => $now,
                'updated_at' => $now,
                'order_sn' => $OrderId,
                'amount' => $query->WithDraw,
            ];

            // 判断订单状态（WDPay提现状态：PAID=成功, REJECTED=失败）
            $orderStatus = 0;
            if (isset($post['status'])) {
                $status = strtoupper($post['status']);
                if ($status == 'PAID') {
                    $orderStatus = 1;  // 提现成功
                } elseif ($status == 'REJECTED') {
                    $orderStatus = 2;  // 提现失败
                }
            }

            if (!$orderStatus) {
                Util::WriteLog('WDPay_payout', 'WDPay提现处理中：' . $OrderId . ', 状态: ' . ($post['status'] ?? 'unknown'));
                return '{"msg":"success","code":200}';
            }

            Util::WriteLog('WDPay_payout', 'WDPay提现回调：' . $OrderId . ', 状态: ' . ($post['status'] ?? '') . ', 处理结果: ' . $orderStatus);
            
            $UserID = $query->UserID;
            $TakeMoney = $query->WithDraw + $query->ServiceFee;

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

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

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

                    $payRates = @$config['pay_rate'];
                    if(is_array($payRates)){
                        $payMethod = $query->PixType??1;
                        $payRate = $payRates[$payMethod] ?? $payRates[1];
                        $withdraw_data['withdraw_fee'] = intval(($query->WithDraw * ($payRate[0] ?? 15))/100)+($payRate[1]??0.3)*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('WDPayEmail', [$query->UserID, $OrderId, $TakeMoney, $msg, $bonus]);
                    $withdraw_data = ['State' => 6, 'agent' => $agentID, 'remark' => @$post['transMsg'] ?: ''];
                    $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.withdraw_notify')->updateOrInsert(['order_sn' => $OrderId], $notify_data);
            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);
            }
            
            Util::WriteLog('WDPay_payout', "提现回调处理完成: {$OrderId}");
            
            return '{"msg":"success","code":200}';

        } catch (\Exception $exception) {
            Util::WriteLog('WDPay_payout_error', 'WDPay提现回调处理失败：' . $exception->getMessage() . "\n" . $exception->getTraceAsString());
            return '{"msg":"error","code":500}';
        }
    }

    /**
     * POST请求方法 - application/x-www-form-urlencoded（WDPay协议）
     */
    private function curlPost($url, $payload)
    {
        $timeout = 20;

        // WDPay使用 application/x-www-form-urlencoded 格式
        $data = http_build_query($payload);

        // ✅ 加上真实 User-Agent
        $userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
            . 'AppleWebKit/537.36 (KHTML, like Gecko) '
            . 'Chrome/120.0.0.0 Safari/537.36';

        $headers = [
            'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
            'User-Agent: ' . $userAgent,
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // ✅ 再保险：显式设置 CURLOPT_USERAGENT（防代理/转发丢失）
        curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);

        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if (curl_errno($ch)) {
            $error = curl_error($ch);
            Util::WriteLog('WDPay_error', 'CURL Error: ' . $error);
            curl_close($ch);
            return false;
        }

        if ($httpCode != 200) {
            Util::WriteLog('WDPay_error', 'HTTP Code: ' . $httpCode . " | Response: " . $result);
        }

        curl_close($ch);
        return $result;
    }
}
