<?php

namespace App\Http\logic\api;

use App\dao\Estatisticas\RechargeWithDraw;
use App\dao\Pay\AccountPayInfo;
use App\Http\helper\NumConfig;
use App\Inter\CashierInterFace;
use App\Models\PrivateMail;
use App\Models\RecordUserDataStatistics;
use App\Services\PagYeepPay;
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 PagYeepPayCashierLogic implements CashierInterFace
{
    const AGENT = 103; // PagYeepPay代付渠道值
    protected $agent = 103;

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

        $dao = new AccountPayInfo();
        [$userPhone, $userName, $userEmail] = $dao->payInfo($query->UserID);

        // 使用PagYeepPay服务类进行签名（PagYeepPayOut配置）
        $service = new PagYeepPay();
        $payConfigService = new PayConfig();
        $config = $payConfigService->getConfig('PagYeepPayOut');
        $service->config = $config;
        $service->key = $config['key'] ?? '';
        $service->orgNo = $config['orgNo'] ?? '';
        $service->custId = $config['custId'] ?? '';
        
        // PagYeepPay支付方式映射（根据文档：CASH / CASH_APP / APPLE_PAY）
        $payOutTypes = [
            1 => 'ecashapp',  // CashApp
            2 => 'paypal'     // PayPal
        ];
        
        // 根据PixType选择账号和代付方式
        // PixType: 1=CashApp, 2=PayPal
        $account = '';
        $payOutType = $payOutTypes[$PixType] ?? 'ecashapp';
        
        if ($PixType == 1) {
            if ($PixNum && strpos($PixNum, '$') !== 0) {
                $PixNum = '$' . $PixNum;
            }
            $account = $PixNum;  // CashApp标签，如: $abcd1234
        } elseif ($PixType == 2) {
            $account = $email;   // PayPal邮箱，如: 1111@gmail.com
        }

        // 构建提现请求参数（根据文档）
        $params = [
            "version" => $config['version'] ?? "2.1",  // 版本号
            "orgNo" => $service->orgNo,  // 机构编号
            "custId" => $service->custId,  // 商户编号
            "custOrdNo" => $OrderId,  // 商户代付订单号
            "country" => "US",  // 国家
            "currency" => "USD",  // 货币
            "casAmt" => (int) $amount,  // 代付金额（分）
            "callBackUrl" => $config['callBackUrl'],
            "payoutType" => 'EPS',  // 代付方式
            "accountName" => $accountName ?: 'U'.$query->UserID,  // 收款人姓名
            "cardType" => $payOutType,
            "cardNo" => $account,
            "phone" => $userPhone,
            "email" => $userEmail,

        ];

        // 如果有回调地址配置
        if (!empty($config['callBackUrl'])) {
            $params["callBackUrl"] = $config['callBackUrl'];
        }

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

        $url = $config['apiUrl'].'/establish/withdrawal.ac';

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

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

        try {
            // 解析返回结果（可能是form表单格式或JSON格式）
            parse_str($result, $data);
            if (empty($data)) {
                $data = \GuzzleHttp\json_decode($result, true);
            }
        } catch (\Exception $e) {
            Util::WriteLog("PagYeepPay_payout_error", ['解析失败', $result, $e->getMessage()]);
            return 'fail';
        }

        // 根据文档，返回码000000表示成功
        if (isset($data['code']) && $data['code'] == '000000') {
            Util::WriteLog('PagYeepPay_payout', "提现订单创建成功: {$OrderId}");
            return $data;
        } else {
            // 提现失败处理
            Util::WriteLog('PagYeepPay_payout_error', "提现失败: {$OrderId} | " . json_encode($data));
            
            if ($query->State == 5) {
                // 同步失败，发送邮件给玩家，退还金币
                $msg = $data['msg'] ?? 'Transfer failed';
                $WithDraw = $query->WithDraw + $query->ServiceFee;
                $bonus = '30000,' . $WithDraw;

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

                $withdraw_data = [
                    'State' => 6, 
                    'agent' => $this->agent, 
                    '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)) {
            // 可能是form表单格式
            parse_str($post, $post);
            if (empty($post)) {
                $post = \GuzzleHttp\json_decode($post, true);
            }
        }
        
        Util::WriteLog('PagYeepPay', 'PagYeepPay 提现回调：' . json_encode($post));

        try {
            // 根据文档，回调参数：custOrderNo, prdOrdNo, payAmt, ordStatus, casDesc, utr, sign
            $OrderId = $post['custOrderNo'] ?? '';
            $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $OrderId)->first();

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

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

            $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['prdOrdNo'] ?? '',  // 平台代付订单号
                'extra' => \GuzzleHttp\json_encode($post),
                'created_at' => $now,
                'updated_at' => $now,
                'order_sn' => $OrderId,
                'amount' => $query->WithDraw,
            ];

            // 根据文档，代付状态：07=清算完成（成功）, 08=清算失败
            $orderStatus = 0;
            $ordStatus = $post['ordStatus'] ?? '';
            if ($ordStatus == '07') {
                $orderStatus = 1;  // 提现成功
            } elseif ($ordStatus == '08') {
                $orderStatus = 2;  // 提现失败
            }

            if (!$orderStatus) {
                Util::WriteLog('PagYeepPay_payout', 'PagYeepPay提现处理中：' . $OrderId . ', 状态: ' . $ordStatus);
                return 'SC000000';
            }

            Util::WriteLog('PagYeepPay_payout', 'PagYeepPay提现回调：' . $OrderId . ', 状态: ' . $ordStatus . ', 处理结果: ' . $orderStatus);
            
            $UserID = $query->UserID;
            $TakeMoney = $query->WithDraw + $query->ServiceFee;

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

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

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

                    $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 = $post['casDesc'] ?? 'Encomenda rejeitada pelo banco';
                    $bonus = '30000,' . $TakeMoney;
                    PrivateMail::failMail($query->UserID, $OrderId, $TakeMoney, $msg, $bonus);
                    
                    Util::WriteLog('PagYeepPayEmail', [$query->UserID, $OrderId, $TakeMoney, $msg, $bonus]);
                    $withdraw_data = ['State' => 6, 'agent' => $agentID, 'remark' => $msg];
                    $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);
            }
            
            Util::WriteLog('PagYeepPay_payout', "提现回调处理完成: {$OrderId}");
            
            return 'SC000000';

        } catch (\Exception $exception) {
            Util::WriteLog('PagYeepPay_payout_error', 'PagYeepPay提现回调处理失败：' . $exception->getMessage() . "\n" . $exception->getTraceAsString());
            return 'SC000000';
        }
    }

}
