<?php

namespace App\Helper\UniPlatform\Kuaishou;

use App\Helper\Kuaishou;

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

    private $messageId = '';

    private $fail;

    public function __construct(Kuaishou $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();
        $kwaisign = \request()->header('kwaisign');

        $this->messageId = $notify['message_id'];
        // 获取订单信息
        $notify = array_merge($notify, ['kwaisign' => $kwaisign]);
        \Log::info('快手支付回调==>' . json_encode($notify, JSON_UNESCAPED_SLASHES));
        if ($kwaisign !== $this->app->getNotifySign($notify)) {
            throw new \Exception('签名验证错误');
        }

        return $notify['data'];
    }

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

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