<?php

namespace App\Http\Controllers\Api;

use App\dao\Pay\AccountPayInfo;
use App\dao\Pay\PayController;
use App\Http\Controllers\Controller;
use App\Http\helper\CreateOrder;
use App\Http\logic\api\AppleStorePayLogic;
use App\Http\logic\api\OrderLogic;
use App\Jobs\Order;
use App\Models\Treasure\GameScoreInfo;
use App\Services\OrderServices;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class GooglePayController extends Controller
{
    public $config = [
        'ruby777.500' => 500,
        'ruby777.5000' => 5000,
        'ruby777.20000' => 20000,
        'com.legends777.coins400' => 400,
        'com.legends777.coins4000' => 4000,
        'com.legends777.coins25000' => 25000,
    ];
    public function pay_order($userId, $pay_amount, $userName, $userEmail, $userPhone, $GiftsID, $buyIp, $AdId, $eventType)
    {

        $productId = \Illuminate\Support\Facades\Request::input('productID');

        if (!isset($this->config[$productId])) {
            return apiReturnFail('unknown product');
        }
        $pay_amount = $this->config[$productId];
        $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 apiReturnFail($this->error);
        }

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

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

        $amount = $pay_amount ;
        $logic->orderCreate(
            $order_sn,
            $amount,
            'GooglePay',
            $userId,
            $productId,
            $GiftsID,
            $AdId,
            $eventType
        );

        return apiReturnSuc([
            'code' => 0,
            'order_sn' => $order_sn,
        ]);
    }
    /**校验谷歌支付
     * @param string $receipt 支付返回给客户端的一串json
     * @param string $signature 支付后返回给客户端的签名字符串
     * @param string $google_public_key 谷歌控制台拿到的公钥
     * @return bool
     */
    public function googlePayVerify(string $receipt,string $signature,string $google_public_key):bool
    {
        $public_key_handle = openssl_pkey_get_public($google_public_key);
        if($public_key_handle===false){
            $public_key = "-----BEGIN PUBLIC KEY-----" . PHP_EOL .
                chunk_split($google_public_key, 64, PHP_EOL) .
                "-----END PUBLIC KEY-----";
            $public_key_handle = openssl_pkey_get_public($public_key);
            if($public_key_handle===false){
                return false;
            }
        }
        $result = openssl_verify($receipt, base64_decode($signature), $public_key_handle, OPENSSL_ALGO_SHA1);
        //从内存中释放和指定的 public_key相关联的密钥
        openssl_free_key($public_key_handle);
        return  $result;
    }
    public function confirm(Request $request)
    {
        Log::channel('googlePay')->info('app store pay validate request', [
            'request' => $request->all(),
        ]);

        $receipt = $request->input('receipt');
        $signature = $request->input('signature');
        $google_public_key="";
        $result=$this->googlePayVerify($receipt,$signature,$google_public_key);

        $result=true;

        $orderSN = $request->input('order_sn');

        if ($result === false) {
            $data = json_decode($response, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                return apiReturnFail(__('messages.api.pay.valid_failed'));
            }
            if (json_last_error() !== JSON_ERROR_NONE || !isset($data['orderId'])) {
                Log::channel('googlePay')->error('curl app server error', [
                    'endpoint' => $endpoint,
                    'data' => $postData,
                    'response' => $response,
                ]);
                return apiReturnFail(__('messages.api.pay.valid_failed'));
            }
            return apiReturnFail(__('messages.api.pay.valid_failed'));
        }
        // 验证成功了
        // 查询订单信息
        $order = DB::connection('write')->table('agent.dbo.order')
            ->where('order_sn', $orderSN)->first();
        if (!$order) {
            Log::channel('googlePay')->info('订单不存在');
            return apiReturnSuc();
        }

        if (!empty($order->pay_at) || !empty($order->finished_at)) {
            Log::channel('googlePay')->info('订单已支付');
            return apiReturnSuc();
        }
        $GiftsID = $order->GiftsID ?: '';
        $userID = $order->user_id ?: '';
        $AdId = $order->AdId ?: '';
        $eventType = $order->eventType ?: '';
        $payAmt = (int)($order->amount/100);
        $body = [
            'payment_sn' => $result['receipt']['in_app'][0]['transaction_id'],
            'updated_at' => date('Y-m-d H:i:s'),
            'pay_status' => 1,
            'pay_at' => date('Y-m-d H:i:s'),
            'finished_at' => date('Y-m-d H:i:s'),
        ];
        $apply_data = [
            'order_id' => $order->id,
            'payment_sn' => $body['payment_sn'],
            'payment_code' => 'GooglePay',
            'return' => \GuzzleHttp\json_encode($result),
            'is_error' => 0,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ];
        // 获取金额
        $service = new OrderServices();
        [$give, $favorable_price, $Recharge, $czReason, $cjReason] = [0,$payAmt,$payAmt,1,45];

        // 增加充值记录
        [$Score] = $service->addRecord(
            $userID,
            $payAmt,
            $favorable_price,
            $orderSN,
            $GiftsID,
            $Recharge,
            $czReason,
            $give,
            $cjReason,
            $AdId,
            $eventType
        );

        // 成功处理回调
        Order::dispatch([$userID, $payAmt, $Score, $favorable_price, $GiftsID, $orderSN]);

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

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

        if (($order_up && $apply) != true) {
            Log::channel('googlePay')->info('订单更新失败');
            return apiReturnFail(__('messages.api.pay.valid_failed'));
        }

        Log::channel('googlePay')->info('success', [
            'order_sn' => $orderSN
        ]);
        $gameScoreInfo = GameScoreInfo::query()->where('UserID', $userID)->first();
        return apiReturnSuc([
            'give' => $give,
            'total' => $gameScoreInfo->Score ?? $give
        ]);
    }

}
