<?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\HttpCurl;
use App\Http\helper\NumConfig;
use App\Jobs\Order;
use App\Models\Cpf;
use App\Notification\TelegramBot;
use App\Services\CreateLog;
use App\Services\Crypto;
use App\Services\OrderServices;
use App\Services\PayConfig;
use App\Util;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class CryptoLogic extends BaseApiLogic
{
    public $result;
    public function pay_order($userId, $pay_amount, $userPhone, $userEmail, $userName, $GiftsID, $buyIP,$AdId,$eventType)
    {
        $dao = new AccountPayInfo();
        [$userPhone, $userName, $userEmail] = $dao->payInfo($userId);

        $pay_amount = (int)$pay_amount;
        // 礼包类型验证
        $PayVerify = new PayController();
        $pay_amount = $PayVerify->verify($userId, $GiftsID, $pay_amount) ;
        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;
        }

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

        $order_sn = CreateOrder::order_sn($userId);

        // 生成订单信息
        $logic = new OrderLogic();

        $amount = $pay_amount * NumConfig::NUM_VALUE;
        $logic->orderCreate($order_sn, $amount, 'Crypto', $userId, '', $GiftsID,$AdId,$eventType);


        $service = new Crypto();

        $data = [
            "totalPrice" => $pay_amount,  // Total price of the purchase (should match sum of line items)
            "fiatCurrency" => "EUR",  // Fiat currency (e.g., EUR, USD)
            "cryptoAllowedSlippage" => 0.1,  // Allowed slippage for the crypto conversion
            "externalOrderId" => $order_sn,  // Unique order ID
            "lineItems" => [
                [
                    "quantity" => 1,  // Quantity of the product
                    "price" => $pay_amount,  // Price of the product
                    "name" => "Test Item",  // Name of the item
                    "description" => "Description of the item"  // Description of the item
                ]
            ],
            "timeout" => 3600,  // Timeout for the purchase in seconds
            "transactionStatusWebhookUrl" => $config['notify'],
            "kyc" => [
                "email" => $userEmail,  // User's email for KYC (Know Your Customer) verification
                "phoneNumber" => $userPhone,  // User's phone number
                "firstName" => $userName,  // User's first name
                "lastName" => $userName,  // User's last name
                "countryTax" => "EU",  // User's country tax information
            ]
        ];

        // 生成用户请求信息日志
        if (is_array($data)) {
            $request_extra = \GuzzleHttp\json_encode($data);
        } else {
            $request_extra = '';
        }
        CreateLog::pay_request($userPhone, $request_extra, $order_sn, $userEmail, $userId, $userName);


        $result = $service->curlPost('/merchant/v1/purchase/init', $data);
//        $this->result=compact('result','data');
        Util::WriteLog('Crypto','Crypto支付请求'.$request_extra);
        Util::WriteLog('Crypto','Crypto支付结果'.json_encode($result));
        try {
            $data = $result;
            $data['mchOrderNo'] = $order_sn;
        }catch (\Exception $e){
            Util::WriteLog("Crypto_error",[$result,$e->getMessage(),$e->getTraceAsString()]);
            return false;
        }
        return  $data;

    }

    public function notify($post)
    {

        $order_sn = $post['externalOrderId'];

        try {
            // 查询订单信息
            $order = DB::connection('write')->table('agent.dbo.order')->where('order_sn', $order_sn)->first();

            if (!$order) {
                Util::WriteLog('Crypto','订单不存在');
                return '{"success":false,"message":"商户自定义出错信息"}';
            }

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




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

            $apply_data = [
                'order_id' => $order->id,
                'payment_sn' => $post['cryptoTransactionId'],
                'payment_code' => 'Crypto',
                'return' => \GuzzleHttp\json_encode($post),
                'is_error' => 0,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ];

            $ordStatus = $post['status']=='Confirmed'?3:4;
            $GiftsID = $order->GiftsID ?: '';
            $userID = $order->user_id ?: '';
            $AdId = $order->AdId ?: '';
            $eventType = $order->eventType ?: '';
            $payAmt = (int)$post['totalPrice'];

            if(!$AdId){
                $redis = Redis::connection();
                $AdId = $redis->get('user_ad_'.$userID);
            }



            // 说明:除了成功，失败和退款状态,都可以认为是处理中
            switch ($ordStatus) {
                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'] = $payAmt * NumConfig::NUM_VALUE;
                    $config = (new PayConfig())->getConfig('Crypto');
                    $body['payment_fee']=$body['amount']*$config['payin_fee'];
                    try {
                        // 获取金额
                        $service = new OrderServices();

                        if ($order->amount != $body['amount']) {
                            $body['GiftsID'] = 0;
                            $body['amount'] = $payAmt * NumConfig::NUM_VALUE;
                            $Recharge = $payAmt;
                            $give = 0;
                            $favorable_price = $Recharge + $give;
                            $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);
                        // 成功处理回调
                        Order::dispatch([$userID, $payAmt, $Score, $favorable_price, $GiftsID, $order_sn]);

                    }catch (\Exception $exception) {
                        TelegramBot::getDefault()->sendProgramNotify("OrderService Except ",$exception->getMessage() );
                    }
//                    $cpf = @$post['reference'];
//                    if($cpf){
//                        Cpf::insertCpf($userID,$cpf);
//                    }

                    break;
                case 4:    // 支付失败
                    $body['pay_status'] = 2;
                    $apply_data['is_error'] = 1;
                    break;
            }

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

            $apply = DB::connection('write')->table('agent.dbo.payment_apply')
                ->insert($apply_data);

            if (($order_up && $apply) != true) {
                Util::WriteLog('SitoBank','订单更新失败');
                return '{"success":false,"message":"商户自定义出错信息"}';
            }

            //Util::WriteLog('SitoBank','success');

            return 'SUCCESS';
        } catch (\Exception $exception) {
            Util::WriteLog('SitoBank','Goopago 支付失败' . $exception->getMessage());
            $this->error = $exception->getMessage();
            return '{"success":false,"message":"商户自定义出错信息"}';
        }
    }

    public function pay_search($orderNo){
        $payConfigService = new PayConfig();
        $config = $payConfigService->getConfig('Goopago');
        $service = new Goopago();
        $data = [
            'mchId' =>$config['merchantID'],
            'nonceStr' => $service->getNonceStr(),
            'mchOrderNo' => $orderNo,
        ];

        $sign = $service->sign($data);
        $data['sign'] = $sign;
        $url = $config['pay_search'];
        $result = $service->curlPost($url, $data, 60);
        Log::info(var_export('Goopago 支付结果查询：', true), [$result]);



        try {
            $data = json_decode($result, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                return false;
            }
            if ($data['resCode'] != 'SUCCESS') {
                return false;
            }
            $orderInfo = $data['orderInfo'];
            if(is_array($orderInfo)){
                $orderStatus = $orderInfo['status'] == 2?1:0;
            }else{
                $orderInfo = json_decode($orderInfo,true);
                $orderStatus = $orderInfo['status'] == 2?1:0;
            }
            return $orderStatus;
        } catch (\Exception $e) {
            return false;
        }
    }
}
