<?php

namespace App\Helper\UniPlatform\Bytedance;

use App\Helper\ByteDance;
use App\Models\Pay;

/**
 * Class Payment.
 *
 * @property ByteDance $app
 */
class Payment
{
    private $app;

    private $fail;

    public function __construct(ByteDance $app)
    {
        $this->app = $app;
    }

    /**
     * 支付通知.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function payNotify(\Closure $closure)
    {
        try {
            call_user_func($closure, $this->getNoticeData(), [$this, 'fail']);
        } catch (\Exception $e) {
            $this->fail($e->getMessage());
        }

        return $this->toResponse();
    }

    public function fail($msg)
    {
        $this->fail = $msg;
    }

    /**
     * 获取支付通知数据.
     *
     * @throws \Exception
     */
    private function getNoticeData()
    {
        $notify = \request()->all();
        // $notify = '{"msg":"{\"appid\":\"tt5b312d8cc40f46b701\",\"cp_orderno\":\"10022082800824490007\",\"cp_extra\":\"\",\"way\":\"2\",\"channel_no\":\"2022082822001477591433078541\",\"channel_gateway_no\":\"\",\"payment_order_no\":\"PCP2022082822540531221069106962\",\"out_channel_order_no\":\"2022082822001477591433078541\",\"total_amount\":1,\"status\":\"SUCCESS\",\"seller_uid\":\"71227862181355706950\",\"extra\":\"\",\"item_id\":\"\",\"paid_at\":1661698458,\"message\":\"\",\"order_id\":\"7136939355201063205\",\"trade_item_list\":null,\"ec_pay_trade_no\":\"NEP2022082822540409483061846962\"}","msg_signature":"804a60e48936b14a739230cef21fe6204427732e","nonce":"78","timestamp":"1661698459","type":"payment"}';
        // 获取订单信息
        // $notify = json_decode($notify,true);
        \Log::info('抖音支付回调==>' . json_encode($notify, JSON_UNESCAPED_SLASHES));

        if ($notify['msg_signature'] !== $this->app->getNotifySign($notify)) {
            throw new \Exception('签名验证错误');
        }

        return json_decode($notify['msg'], true);
    }

    /**
     * 返回数据.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    private function toResponse()
    {
        $data = [
            'err_no'   => is_null($this->fail) ? 0 : 1,
            'err_tips' => is_null($this->fail) ? 'success' : $this->fail,
        ];

        return response()->json($data);
    }
}
