<?php

namespace App\Http\logic\api;

use App\dao\Estatisticas\RechargeWithDraw;
use App\Inter\CashierInterFace;
use App\Models\PrivateMail;
use App\Models\RecordUserDataStatistics;
use App\Services\SupefinaSpei;
use App\Services\StoredProcedure;
use App\Util;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class SupefinaSpeiCashierLogic implements CashierInterFace
{
    /**
     * 代付渠道标识，对应 agent.dbo.admin_configs.config_value（type=cash）。
     * 使用前请在后台配置同名渠道值。
     */
    const AGENT = 106;

    /**
     * 创建 Supefina SPEI 代付订单。
     */
    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) {
            Util::WriteLog('SupefinaSpei', 'withdraw order not found: '.$RecordID);
            return 'fail';
        }

        $service = new SupefinaSpei('SupefinaSpeiOut');
        $config = $service->config;

        $merId = $config['merId'] ?? '';
        $baseUrl = $config['baseUrl'] ?? '';
        $payoutPath = $config['payoutPath'] ?? '/api/supefina/transactions/payout';
        $callbackUrl = $config['callbackUrl'] ?? '';
        $countryId = $config['countryId'] ?? 'MEX';
        $currency = $config['currency'] ?? 'MXN';

        if ($merId === '' || $baseUrl === '' || empty($config['key'])) {
            Util::WriteLog('SupefinaSpei_error', 'config missing merId/baseUrl/key');
            return 'fail';
        }

        // 账户号：优先 PixNum，其次 BankNO
        $account = $PixNum ?: $BankNO;
        if (!$account) {
            Util::WriteLog('SupefinaSpei_error', 'missing account for withdraw: '.$OrderId);
            return 'fail';
        }

        // 银行编号：优先 BankNO（如果看作 bankId），否则使用配置默认
        $bankId = $BranchBank;

        if ($bankId === '') {
            Util::WriteLog('SupefinaSpei_error', 'missing bankId for withdraw: '.$OrderId);
            return 'fail';
        }

        // payProduct：15=CLABE，16=卡号，简单按 PixType 区分，前端/配置需约定
        $payProduct = '15';
        if ((int)$PixType === 2) {
            $payProduct = '16';
        }

        // 提现金额是以分存储，转成两位小数金额
        $orderAmount = number_format($amount / 100, 2, '.', '');

        $customerName = $accountName ?: ($email ?: ('U'.$query->UserID));

        $params = [
            'account'       => (string)$account,
            'bankId'        => (string)$bankId,
            'callbackUrl'   => $callbackUrl,
            'countryId'     => $countryId,
            'currency'      => $currency,
            'customerName'  => $customerName,
            'description'   => 'withdraw_'.$OrderId,
            'merId'         => (string)$merId,
            'merOrderNo'    => (string)$OrderId,
            'nonceStr'      => $service->generateNonceStr(32),
            'orderAmount'   => $orderAmount,
            'payProduct'    => (string)$payProduct,
        ];

        $signedParams = $service->sign($params);

        $url = rtrim($baseUrl, '/').$payoutPath;

        Util::WriteLog('SupefinaSpei', 'payout request: '.$url.' | '.json_encode($signedParams, JSON_UNESCAPED_UNICODE));

        try {
            $result = $service->postJson($url, $signedParams);
        } catch (\Throwable $e) {
            Util::WriteLog('SupefinaSpei_error', 'payout request exception: '.$e->getMessage());
            return 'fail';
        }

        Util::WriteLog('SupefinaSpei', 'payout response: '.$result);

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

        // 文档示例：code=200 且 data.transactionStatus = "00" 表示下单成功
        if (isset($data['code']) && (string)$data['code'] === '200') {
            $transactionStatus = $data['data']['transactionStatus'] ?? null;
            if ((string)$transactionStatus === '00') {
                return $data;
            }
        }

        // 同步下单失败：如果订单在处理中（State=5），退回资金并标记失败
        if ((int)$query->State === 5) {
            $msg = $data['msg'] ?? 'Supefina payout failed';
            $WithDraw = $query->WithDraw + $query->ServiceFee;
            $bonus = '30000,'.$WithDraw;

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

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

    /**
     * Supefina SPEI 代付回调。
     *
     * @param array<string,mixed>|string $post
     */
    public function notify($post)
    {
        if (!is_array($post)) {
            $post = \GuzzleHttp\json_decode($post, true);
        }

        Util::WriteLog('SupefinaSpei', 'payout notify: '.json_encode($post, JSON_UNESCAPED_UNICODE));

        $service = new SupefinaSpei('SupefinaSpeiOut');

        // 验签
        if (!$service->verify($post)) {
            Util::WriteLog('SupefinaSpei_error', 'notify sign invalid');
            return 'fail';
        }

        // 只处理代付类型（02）
        if (($post['transactionType'] ?? '') !== '02') {
            Util::WriteLog('SupefinaSpei', 'ignore non-payout notify, transactionType='.$post['transactionType'] ?? '');
            return 'SUCCESS';
        }

        $OrderId = $post['merOrderId'] ?? $post['merOrderNo'] ?? '';
        if ($OrderId === '') {
            Util::WriteLog('SupefinaSpei_error', 'notify missing merOrderId');
            return 'fail';
        }

        $query = DB::connection('write')
            ->table('QPAccountsDB.dbo.OrderWithDraw')
            ->where('OrderId', $OrderId)
            ->first();

        if (!$query) {
            Util::WriteLog('SupefinaSpei_error', 'withdraw order not found in notify: '.$OrderId);
            return 'SUCCESS';
        }

        // 只处理 State=5 或 7 的订单，避免重复
        if (!in_array((int)$query->State, [5, 7], true)) {
            Util::WriteLog('SupefinaSpei', 'withdraw already handled: '.$OrderId);
            return 'SUCCESS';
        }

        // 映射交易状态：以 Supefina 文档为准，示例中仅说明状态码存在，此处按常规约定：
        // 01/02/00 视为成功，其它（如 03/04 等）视为失败；实际项目中可按回调字典表精细化。
        $status = (string)($post['status'] ?? '');
        $orderStatus = 0;
        if (in_array($status, ['00', '01', '02', 'SUCCESS'], true)) {
            $orderStatus = 1; // 成功
        } elseif ($status !== '') {
            $orderStatus = 2; // 失败
        }

        if ($orderStatus === 0) {
            Util::WriteLog('SupefinaSpei', 'payout processing: '.$OrderId.' status='.$status);
            return 'SUCCESS';
        }

        $agentID = DB::connection('write')
            ->table('agent.dbo.admin_configs')
            ->where('config_value', self::AGENT)
            ->where('type', 'cash')
            ->value('id') ?? '';

        $now = now();

        $UserID = $query->UserID;
        $TakeMoney = $query->WithDraw + $query->ServiceFee;

        // Supefina 回调里带有 amount/fee 和 realityAmount/realityFee
        // 提醒：这里仍以我们订单金额为准做账，仅将真实金额用于日志，可根据需要扩展到统计侧。
        $realityAmount = isset($post['realityAmount']) ? (float)$post['realityAmount'] : null;
        $realityFee = isset($post['realityFee']) ? (float)$post['realityFee'] : null;
        Util::WriteLog('SupefinaSpei', 'payout reality: amount='.$realityAmount.', fee='.$realityFee.', orderId='.$OrderId);

        $withdraw_data = [];

        switch ($orderStatus) {
            case 1: // 提现成功
                $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 (\Throwable $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 (\Throwable $exception) {
                    Util::WriteLog('StoredProcedure', $exception->getMessage());
                }

                $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 = $post['msg'] ?? 'Withdraw rejected';
                $bonus = '30000,'.$TakeMoney;
                PrivateMail::failMail($query->UserID, $OrderId, $TakeMoney, $msg, $bonus);

                Util::WriteLog('SupefinaSpeiEmail', [$query->UserID, $OrderId, $TakeMoney, $msg, $bonus]);

                $withdraw_data = [
                    'State'  => 6,
                    'agent'  => $agentID,
                    'remark' => $msg,
                ];
                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', $OrderId)
            ->update($withdraw_data);

        if (isset($withdraw_data['State']) && (int)$withdraw_data['State'] === 2) {
            StoredProcedure::user_label($UserID, 2, $TakeMoney);
        }

        return 'SUCCESS';
    }
}

