<?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;
use App\Notification\TelegramBot;
use App\Services\OrderServices;
use App\Services\PayConfig;
use App\Services\WiwiPay;
use App\Services\CreateLog;
use App\Util;
use Illuminate\Support\Facades\DB;

class WiwiPayLogic 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);

//        $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;
        }

        $service = new WiwiPay();
        $config = $service->config;

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

        // 生成订单信息
        $logic = new OrderLogic();
        $amount = (int) round($pay_amount * NumConfig::NUM_VALUE) ;
        $logic->orderCreate($order_sn, $amount, 'WiwiPay', $userId, '', $GiftsID, $AdId, $eventType);

        $payMethods = [
            1 => 'cashapp',
            2 => 'paypal',
            4 => 'applepay',
            8 => 'googlepay',
//            'cashapp' => 1,
//            'paypal' => 2,
//            'applepay' => 4,
//            'googlepay' => 8,

        ];

        $wwMethod = @$payMethods[$pay_method];

        // 构建支付请求参数
        $params = [
            "mchNo" => $service->mchNo,
            "mchOrderNo" => $order_sn,
            "amount" => $amount,
            "currency" => $config['currency'] ?? "usd",
            "wayCode" => $wwMethod? $wwMethod : ($config['wayCode'] ?? "cashapp"),
            "clientIp" => $buyIP,
            "notifyUrl" => $config['notify'] ?? '',
            "returnUrl" => $config['return'] ?? '',
            "expiredTime" => 1800,
            "wayParam" => [
//                "deviceId" => $userId,
                "clientId" => $userId
            ],
            "timestamp" => round(microtime(true) * 1000), // 13位时间戳
            "signType" => $config['signType'] ?? "MD5"
        ];

        // 签名
        $signedParams = $service->sign($params);

        // 生成用户请求信息日志
        $request_extra = \GuzzleHttp\json_encode($signedParams);
        CreateLog::pay_request($userPhone, $request_extra, $order_sn, $userEmail, $userId, $userName);

        $url = $service->apiUrl;

        $result = $service->curlPost($url, $signedParams);
        $rresult = compact('result', 'signedParams', 'url');
        
        Util::WriteLog('WiwiPay', 'WiwiPay支付请求' . $url . " | " . $request_extra);
        Util::WriteLog('WiwiPay', 'WiwiPay支付结果' . json_encode($rresult));
        
        try {
            $data = \GuzzleHttp\json_decode($result, true);
        } catch (\Exception $e) {
            Util::WriteLog("WiwiPay_error", [$result, $e->getMessage(), $e->getTraceAsString()]);
            $this->error = 'Payment processing error';
            return false;
        }
        
        return $data;
    }

    public function notify($post)
    {
        $order_sn = $post['mchOrderNo'];

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

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

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

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


//            支付订单状态
//0-订单生成
//1-支付中
//2-支付成功
//3-支付失败
//4-已撤销
//5-已退款
//6-订单关闭

            $ordStatus = $post['state'] ??'';
            $GiftsID = $order->GiftsID ?: '';
            $userID = $order->user_id ?: '';
            $AdId = $order->AdId ?: '';
            $eventType = $order->eventType ?: '';
            $post['amount'] = $post['realAmount']??$post['amount'];
            $payAmt = round(intval($post['amount'])/100,2);

            switch ($ordStatus) {
                case 2:    // 支付成功

                    $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('WiwiPay');
                    $body['payment_fee']=$body['amount']*$config['payin_fee'];
                    try {
                        // 获取金额
                        $service = new OrderServices();

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

                    }catch (\Exception $exception) {
                        Util::WriteLog("WiwiPay_error", $exception->getMessage());
                    }

                    break;
                case 3:    // 支付失败
                    $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) != true) {
                Util::WriteLog('WiwiPay','订单更新失败');
                return '{"success":false,"message":"商户自定义出错信息"}';
            }

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

            return 'success';


        } catch (\Exception $exception) {
            Util::WriteLog("WiwiPay_error", $exception->getMessage());
            throw $exception;
        }
    }
}
