<?php

namespace App\Http\logic\api;

use App\dao\Pay\AccountPayInfo;
use App\dao\Pay\PayController;
use App\Facade\TableName;
use App\Http\helper\CreateOrder;
use App\Http\helper\NumConfig;
use App\Jobs\Order as OrderJob;
use App\Notification\TelegramBot;
use App\Services\AiPay;
use App\Services\OrderServices;
use App\Services\PayConfig;
use App\Services\CreateLog;
use App\Util;
use Illuminate\Support\Facades\DB;

class AiPayLogic extends BaseApiLogic
{
    public $result;

    public function pay_order($userId, $pay_amount, $userPhone, $userEmail, $userName, $GiftsID, $buyIP, $AdId, $eventType, $pay_method = '')
    {
        $dao = new AccountPayInfo();
        [$userPhone, $userName, $userEmail] = $dao->payInfo($userId);

        $PayVerify = new PayController();
        if ($PayVerify->verify($userId, $GiftsID, $pay_amount) === false) {
            $this->error = $PayVerify->getError();
            return false;
        }
        if ($pay_amount < 0) {
            $this->error = 'Payment error_4';
            return false;
        }

        $service = new AiPay();
        $config = $service->getConfig();

        $order_sn = CreateOrder::order_sn($userId);
        $orderLogic = new OrderLogic();
        $amountInt = (int) round($pay_amount * NumConfig::NUM_VALUE);
        $orderLogic->orderCreate($order_sn, $amountInt, 'AiPay', $userId, $pay_method, $GiftsID, $AdId, $eventType);

        $methodMap = [
            1 => '1101',
            2 => '1104',
            4 => '1108',
            8 => '1109',
        ];
        $paymentMethod = $methodMap[$pay_method] ?? ($config['paymentMethod'] ?? '1101');

        $params = [
            'mchNo' => $config['mchNo'] ?? '',
            'mchOrderNo' => $order_sn,
            'paymentMethod' => (string)$paymentMethod,
            'amount' => number_format($pay_amount, 2, '.', ''),
            'notifyUrl' => $config['notify'] ?? '',
            'returnUrl' => $config['return'] ?? '',
            'clientId' => (string)$userId,
            'clientIp' => $buyIP,
            'timestamp' => (string)round(microtime(true) * 1000),
        ];

//        if (!empty($config['accountData']) && is_array($config['accountData'])) {
//            $params['accountData'] = $config['accountData'];
//        }

        $signedParams = $service->sign($params);
        CreateLog::pay_request($userPhone, json_encode($signedParams), $order_sn, $userEmail, $userId, $userName);

        $response = $service->post('/api/payment', $signedParams);
        Util::WriteLog('AiPay', 'pay request => ' . json_encode($signedParams, JSON_UNESCAPED_UNICODE));
        Util::WriteLog('AiPay', 'pay response => ' . $response);

        try {
            $data = \GuzzleHttp\json_decode($response, true);
        } catch (\Throwable $e) {
            Util::WriteLog('AiPay_error', $e->getMessage());
            $this->error = 'Payment processing error';
            return false;
        }

        if (!isset($data['code']) || (int)$data['code'] !== 0) {
            $this->error = $data['msg'] ?? 'Payment request failed';
        }

        return $data;
    }

    public function notify(array $post)
    {
        $order_sn = $post['mchOrderNo'] ?? '';
        if (!$order_sn) {
            return '{"success":false,"message":"missing order"}';
        }

        $order = DB::connection('write')->table('agent.dbo.order')->where('order_sn', $order_sn)->first();
        if (!$order) {
            Util::WriteLog('AiPay', 'order not found: ' . $order_sn);
            return '{"success":false,"message":"order not found"}';
        }

        if (!empty($order->pay_at) && !empty($order->finished_at)) {
            return 'success';
        }

        $status = (int)($post['status'] ?? 0);
        $payAmt = (float)($post['actualAmount'] ?? $post['amount'] ?? 0);

        $body = [
            'payment_sn' => $post['sysOrderNo'] ?? '',
            'updated_at' => date('Y-m-d H:i:s'),
        ];

        $GiftsID = $order->GiftsID ?: '';
        $userID = $order->user_id ?: '';
        $AdId = $order->AdId ?: '';
        $eventType = $order->eventType ?: '';

        switch ($status) {
            case 3:
                $body['pay_status'] = 1;
                $body['pay_at'] = date('Y-m-d H:i:s');
                $body['finished_at'] = date('Y-m-d H:i:s');
                $body['amount'] = (int) round($payAmt * NumConfig::NUM_VALUE);

                $config = (new PayConfig())->getConfig('AiPay');
                if (!empty($config['payin_fee'])) {
                    $body['payment_fee'] = $body['amount'] * (float)$config['payin_fee'];
                }

                try {
                    $service = new OrderServices();
                    if ((int)$order->amount !== $body['amount']) {
                        $body['GiftsID'] = 0;
                        $Recharge = $payAmt;
                        $give = 0;
                        $favorable_price = $Recharge;
                        $czReason = 1;
                        $cjReason = 45;
                    } else {
                        [$give, $favorable_price, $Recharge, $czReason, $cjReason] = $service->getPayInfo($GiftsID, $userID, $payAmt);
                    }
                    [$Score] = $service->addRecord($userID, $payAmt, $favorable_price, $order_sn, $GiftsID, $Recharge, $czReason, $give, $cjReason, $AdId, $eventType, $body['payment_fee'] ?? 0);
                    OrderJob::dispatch([$userID, $payAmt, $Score, $favorable_price, $GiftsID, $order_sn]);
                } catch (\Throwable $exception) {
                    Util::WriteLog('AiPay_error', $exception->getMessage());
                    TelegramBot::getDefault()->sendProgramNotify('AiPay notify error', $exception->getMessage(), $exception);
                }
                break;

            case 4:
                $body['pay_status'] = 2;
                break;

            default:
                return 'fail';
        }

        DB::connection('write')->table('agent.dbo.order')->where('order_sn', $order_sn)->update($body);

        return 'success';
    }
}

