<?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\BotImPayService;
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 BotImPayCashierLogic implements CashierInterFace
{
    const AGENT = 107; // BotImPay代付渠道值
    protected $agent = 107;

    /**
     * PixType 到币种简称映射
     * 3=BTC, 4=ETH, 5=USDT, 6=USDC
     */
    protected $currencyMap = [
        3 => 'BTC',
        4 => 'ETH',
        5 => 'USDT',
        6 => 'USDC',
    ];

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

        // 确定币种：根据 PixType 映射
        $currency = $this->currencyMap[$PixType] ?? 'USDT';

        // 构建代付请求参数（BotImPay: bank_code 固定 trc20）
        $params = [
            'mer_no'     => $config['mer_no'] ?? '',
            'order_no'   => $OrderId,
            'amount'     => number_format($amount / NumConfig::NUM_VALUE, 2, '.', ''),
            'currency'   => $currency,
            'bank_code'  => 'trc20',
            'name'       => $accountName ?: 'user',
            'account'    => $PixNum ?: $email,
            'phone'      => $phone ?: '0000000000',
            'email'      => $email ?: '',
            'notify_url' => $config['notify_url'] ?? '',
        ];

        $service = new BotImPayService('BotImPayOut');
        $signedParams = $service->sign($params);

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

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

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

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

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

        // BotImPay 代付成功响应: code=200, data.sys_no 是系统流水号
        if (isset($data['code']) && $data['code'] == 200) {
            return $data;
        }

        // 同步失败处理
        if ($query->State == 5) {
            $WithDraw = $query->WithDraw + $query->ServiceFee;
            $bonus = '30000,' . $WithDraw;
            PrivateMail::failMail($query->UserID, $OrderId, $WithDraw, 'Liquidation failure', $bonus);

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

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

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

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

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

            if ($query->State != 5 && $query->State != 7) {
                Util::WriteLog('BotImPay', $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 = $post['result'] ?? '';
            $orderStatus = 0;
            if ($result === 'success') {
                $orderStatus = 1;
            } elseif ($result === 'fail') {
                $orderStatus = 2;
            }

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

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

            $UserID = $query->UserID;
            $TakeMoney = $query->WithDraw + $query->ServiceFee;
            $withdraw_data = [];

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

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

                    // 计算代付手续费
                    $payConfigService = new PayConfig();
                    $outConfig = $payConfigService->getConfig('BotImPayOut');
                    $payRates = $outConfig['pay_rate'] ?? null;
                    if (is_array($payRates)) {
                        $pixType = $query->PixType ?? 5;
                        $payRate = $payRates[$pixType] ?? ($payRates[5] ?? [1, 1]);
                        $feePercent = $payRate[0] ?? 1;
                        $feeFixed = $payRate[1] ?? 1;
                        $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) {}
                    }

                    // 免审状态更新
                    $log = DB::connection('write')->table('agent.dbo.withdrawal_position_log')
                        ->where('order_sn', $OrderId)->first();
                    if ($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 $e) {
                        Util::WriteLog('StoredProcedure', $e);
                    }

                    $ServiceFee = $query->ServiceFee;
                    RecordUserDataStatistics::updateOrAdd($UserID, $TakeMoney, 0, $ServiceFee);
                    (new RechargeWithDraw())->withDraw($UserID, $TakeMoney, $withdraw_data['withdraw_fee'] ?? 0, $ServiceFee);

                    Redis::connection()->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('BotImPayEmail', [$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('BotImPay', 'BotImPay异步业务逻辑处理失败：' . $exception->getMessage());
            return 'SUCCESS';
        }
    }
}
