<?php


namespace App\Http\Controllers\Api;


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

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

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

            Redis::set("PayErro_SitoBank",1);
            Redis::expire("PayErro_SitoBank",600);
            Util::WriteLog('SitoBank_error', $exception->getMessage().json_encode($logic->result));

            TelegramBot::getDefault()->sendProgramNotify("SitoBank Except ",$exception->getMessage(),$exception );
            return apiReturnFail($logic->getError());
        }


        if (!empty($res) && isset($res['status'])&&$res['status'] >0) {
            $data = [
                'content' => urldecode($res['reference']),
                'money' => $payAmt,
                'prdOrdNo' => $res['mchOrderNo'],
            ];
            return apiReturnSuc($data);
//            header("Location: {$res['url']}");
        } else if($res==false) {
            return apiReturnFail($logic->getError());
        }else{
            if($this->retryTimes>0) {
                Redis::set("PayErro_SitoBank",1);
                Redis::expire("PayErro_SitoBank",600);
                TelegramBot::getDefault()->sendProgramNotify("SitoBank RetrunFail ", $logic->getError()." | ".json_encode($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)
    {

        $headers = [
            "X-Account"   => $request->header("X-Account"),
            "X-Signature" => $request->header("X-Signature"),
        ];
        $payload = file_get_contents('php://input');
        $service = new SitoBank();
        $verify = $service->verify($payload, $headers['X-Signature']);

        $post = json_decode($payload, true);

        Util::WriteLog('SitoBank', "SitoBank回调订单\n".json_encode(compact("payload", "headers", 'verify')));

        if ($headers['X-Account'] ==$service->config['merchantCode']){
            //稍后处理verify
        }else if(!$verify){
            Util::WriteLog('SitoBank','签名错误');
            return 'fail';
        }
        $order_sn = @$post['mchOrderNo'];
        $logic = new SitoBankLogic();
        try {
            $redis = Redis::connection();
            $ret= $logic->notify($post);
            if($ret=='SUCCESS')$redis->set($order_sn, $order_sn, 3600 * 24);
            return $ret;
        }catch (\Exception $exception){
            Redis::set("PayErro_SitoBank",1);
            Redis::expire("PayErro_SitoBank",600);
            TelegramBot::getDefault()->sendProgramNotify("SitoBank 订单回调执行 异常 ", json_encode($post),$exception);
            Util::WriteLog("SitoBank_error",$post);
            return '{"success":false,"message":"商户自定义出错信息"}';
        }
    }

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


    // 提现异步回调
    public function cash_notify(Request $request)
    {
        $headers = [
            "X-Account"   => $request->header("X-Account"),
            "X-Signature" => $request->header("X-Signature"),
        ];
        $payload = file_get_contents('php://input');
        $service = new SitoBank();
        $verify = $service->verify($payload, $headers['X-Signature']);

        $post = json_decode($payload, true);

        Util::WriteLog('SitoBank', "SitoBank cash 异步回调\n".json_encode(compact("payload", "headers", 'verify')));

        if ($headers['X-Account']==$service->config['merchantCode']) {
            //稍后处理verify
        }else if(!$verify){
            Util::WriteLog('SitoBank cash','签名错误');
            return 'fail';
        }

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

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