<?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\WiwiPay;
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 WiwiPayCashierLogic implements CashierInterFace
{
    const AGENT = 99; // 需要根据实际情况修改
    protected $agent = 99;

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

        // 直接使用 PayUtils 签名（使用 WiwiPayOut 的 key）
        $apiKey = $config['key'];
        $signedParams = PayUtils::sign($params, $apiKey);

        $url = $config['apiUrl'];

        Log::info('WiwiPay 提现参数：', $signedParams);
        
        try {
            // 使用独立的 curlPost 方法发送请求
            $result = $this->curlPost($url, $signedParams);
        } catch (\Exception $exception) {
            Log::info('WiwiPay 提现请求异常：', [$exception->getMessage()]);
            return 'fail';
        }

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

        try {
            $data = \GuzzleHttp\json_decode($result, true);
        } catch (\Exception $e) {
            Util::WriteLog("WiwiPay_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' => $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)) $post = \GuzzleHttp\json_decode($post, true);
        
        Util::WriteLog('WiwiPay', 'WiwiPay 提现回调：' . json_encode($post));

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

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

            if ($query->State != 5 && $query->State != 7) {
                Util::WriteLog('WiwiPay',$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,
            ];
            //state
            //0-订单生成
            //1-支付中
            //2-支付成功
            //3-支付失败
            //4-已撤销
            //5-已退款
            //6-订单关闭

            // 判断订单状态
            $orderStatus = 0;
            if (isset($post['state'])) {
                // state: 2=成功, 3=失败
                if ($post['state'] == 2) {
                    $orderStatus = 1; // 成功
                } elseif ($post['state'] == 3) {
                    $orderStatus = 2; // 失败
                }
            }

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

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


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

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

                    $redis = Redis::connection();
                    $redis->incr('draw_' . date('Ymd') . $UserID);
                    break;

                case 2: // 提现失败
                    $msg = 'Encomenda rejeitada pelo banco';
                    $bonus = '30000,' . $TakeMoney;
                    PrivateMail::failMail($query->UserID, $OrderId, $TakeMoney, $msg, $bonus);
                    
                    Util::WriteLog('WiwiPayEmail', [$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.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);
            }
            
            return 'success';

        } catch (\Exception $exception) {
            Util::WriteLog('WiwiPay', 'WiwiPay异步业务逻辑处理失败：' . $exception->getMessage());
            return '{"success":false,"message":"商户自定义出错信息"}';
        }
    }

    /**
     * POST请求方法（复用 WiwiPay 的实现）
     */
    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('WiwiPay_error', 'CURL Error: ' . $error);
            curl_close($ch);
            return false;
        }

        if (strstr($result, 'code') || $httpCode != 200) {
            // 可选：记录错误日志
        }

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

