<?php


namespace App\Http\Controllers\Api;


//use App\Http\logic\api\UuPayCashierLogic;
use App\dao\Pay\AccountPayInfo;
use App\Http\logic\api\GoopagoCashierLogic;
use App\Http\logic\api\GoopagoLogic;
use App\Inter\PayMentInterFace;
use App\Notification\DingDingRobot;
use App\Notification\TelegramBot;
use App\Services\PayConfig;
use App\Util;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class GoopagoController implements PayMentInterFace
{
    private $retryTimes=0;
    public function pay_order($userId, $payAmt, $userName, $userEmail, $userPhone, $GiftsID, $buyIP, $AdId, $eventType, $pay_method = '')
    {

        $logic = new GoopagoLogic();
        try {
            $res = $logic->pay_order($userId, $payAmt, $userPhone, $userEmail, $userName, $GiftsID, $buyIP, $AdId, $eventType);
        } catch (\Exception $exception) {

            Util::WriteLog('goopago_error', $exception);

            TelegramBot::getDefault()->sendProgramNotify("Goopago Except ",$exception->getMessage(),$exception );
            return apiReturnFail($logic->getError());
        }
        //$res = $logic->pay_order($userId, $payAmt, $userPhone, $userEmail, $userName, $GiftsID,$buyIP,$AdId,$eventType);
        if ($res === false) {
//            TelegramBot::getDefault()->sendProgramNotify("Goopago false ", $logic->getError(), $res);
            return apiReturnFail($logic->getError());
        }

//        return $data['resCode'] == 'SUCCESS'?$data['url']:false;

        if (!empty($res) && $res['resCode'] == 'SUCCESS') {
            $data = [
                'content' => urldecode($res['reference']),
                'money' => $payAmt,
                'prdOrdNo' => $res['merchantOrderId'],
            ];
            return apiReturnSuc($data);
//            header("Location: {$res['url']}");
        } else {
            if($this->retryTimes>1) {
                TelegramBot::getDefault()->sendProgramNotify("Goopago RetrunFail ", $logic->getError(), $res);
                return apiReturnFail($logic->getError());
            }else{
                $this->retryTimes++;
                return $this->pay_order($userId, $payAmt, $userName, $userEmail, $userPhone, $GiftsID, $buyIP, $AdId, $eventType);
            }
        }

    }

    // 支付异步回调
    public function notify(Request $request)
    {
        $post = $request->post();

        if (!is_array($post)) {
            $post = \GuzzleHttp\json_decode($post, true);
        }
        Util::WriteLog('goopago', 'Goopago回调订单');
        Util::WriteLog('goopago', $post);
        $order_sn = $post['orderId'];
        $redis = Redis::connection();
//        if ($redis->exists($order_sn)) {
//            Util::WriteLog('goopago', 'Goopago 重复回调订单：' . $order_sn);
//            return 'SUCCESS';
//        }


        $logic = new GoopagoLogic();


        try {
            $ret= $logic->notify($post);
            if($ret=='SUCCESS')$redis->set($order_sn, $order_sn, 3600 * 24);
            return $ret;
        }catch (\Exception $exception){
            TelegramBot::getDefault()->sendProgramNotify("Goopago 订单回调执行 异常 ", json_encode($post),$exception);
            Util::WriteLog("goopago_error",$post);
            return '{"success":false,"message":"商户自定义出错信息"}';
        }
    }

    public function sync_notify(Request $request)
    {
        Log::info('同步回调');
        echo '同步回调';
    }


    // 提现异步回调
    public function cash_notify(Request $request)
    {
        $post = $request->post();

        if (!is_array($post)) {
            $post = \GuzzleHttp\json_decode($post, true);
        }
//        Log::info(var_export('Goopago cash 异步回调：', true), $post);
        Util::WriteLog('goopago', 'Goopago cash 异步回调：');
        Util::WriteLog('goopago', $post);
//        $order_sn = $post['mchOrderNo'] . 'new';
//        $redis = Redis::connection();
//        if ($redis->exists($order_sn)) {
//            Log::info('Goopago 重复回调订单：' . $order_sn);
//            return '{"success":false,"message":"商户自定义出错信息"}';
//        }

//        $redis->set($order_sn, $order_sn, 3600 * 24);
        $logic = new GoopagoCashierLogic();
        try {

            return $logic->notify($post);
        }catch (\Exception $exception){

            TelegramBot::getDefault()->sendProgramNotify("Goopago 提现异步回调执行 异常 ", json_encode($post),$exception);
            Util::WriteLog("goopago_error",$post);
            return '{"success":false,"message":"商户自定义出错信息"}';
        }
    }
}
