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

    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('AiNewPayOut');
        $wayCode = [
            1 => 'ecashapp',
            2 => 'paypal'
        ];
        $wayParam = [];

        if ($PixNum && strpos($PixNum, '$') !== 0) {
            $PixNum = '$' . $PixNum;
        }

        if($PixType == 1){
            $wayParam = ["cashtag" => $PixNum];
        }
        if($PixType == 2){
            $wayParam = ["email" => $email];
        }
        // 构建提现请求参数
        $params = [
            "mchNo" => $config['mchNo'] ?? '',
            "mchOrderNo" => $OrderId,
            "amount" => intval($amount),
            "currency" => $config['currency'] ?? "usd",
            "wayCode" => $wayCode[$PixType],
            "notifyUrl" => $config['cashNotify'],
            "wayParam" => $wayParam,
            "timestamp" => round(microtime(true) * 1000),
            "signType" => $config['signType'] ?? "MD5"
        ];

        // 使用 AiNewPayOut 的 key 签名
        $apiKey = $config['key'];
        $signedParams = PayUtils::sign($params, $apiKey);

        $url = $config['apiUrl'];

        Log::info('AiNewPay 提现参数：', $signedParams);
        
        try {
            $result = $this->curlPost($url, $signedParams);
        } catch (\Exception $exception) {
            Log::info('AiNewPay 提现请求异常：', [$exception->getMessage()]);
            return 'fail';
        }

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

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

        if (isset($data['code']) && $data['code'] == 0) {
            return $data;
        } else {
            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' => 1045, '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('AiNewPay', 'AiNewPay 提现回调：' . json_encode($post));

        try {
            $OrderId = $post['mchOrderNo'] ?? '';
            $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $OrderId)->first();

            if (!$query) {
                Util::WriteLog('AiNewPay','订单不存在');
                return '{"success":true,"message":"Accepted"}';
            }

            if ($query->State != 5 && $query->State != 7) {
                Util::WriteLog('AiNewPay',$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['mchOrderNo'] ?? '',
                'extra' => \GuzzleHttp\json_encode($post),
                'created_at' => $now,
                'updated_at' => $now,
                'order_sn' => $OrderId,
                'amount' => $query->WithDraw,
            ];

            $orderStatus = 0;
            if (isset($post['state'])) {
                if ($post['state'] == 2) {
                    $orderStatus = 1; // 成功
                } elseif ($post['state'] == 3) {
                    $orderStatus = 2; // 失败
                }
            }

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

            Util::WriteLog('AiNewPay', 'AiNewPay 提现结果：' . $OrderId . '_' . $orderStatus);
            
            $UserID = $query->UserID;
            $TakeMoney = $query->WithDraw + $query->ServiceFee;


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

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

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

                    $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('AiNewPayEmail', [$query->UserID, $OrderId, $TakeMoney, $msg, $bonus]);
                    $withdraw_data = ['State' => 6, 'agent' => $agentID, 'remark' => @$post['errMsg'] ?: ''];
                    $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('AiNewPay', 'AiNewPay异步业务逻辑处理失败：' . $exception->getMessage());
            return '{"success":false,"message":"商户自定义出错信息"}';
        }
    }

    /**
     * POST请求方法
     */
    private function curlPost($url, $payload)
    {
        $timeout = 20;
        $data = json_encode($payload, JSON_UNESCAPED_UNICODE);
        
        $headers = [
            'Content-Type: application/json',
        ];

        $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);

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

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

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