<?php

namespace Modules\Mall\Http\Controllers\Api;

use App\Api\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Jason\Api\Api;
use Modules\Mall\Models\Order;

class PayController extends Controller
{

    /**
     * Notes: 微信支付
     *
     * @Author: 玄尘
     * @Date  : 2021/5/20 9:11
     * @param  \Modules\Mall\Models\Order  $order
     * @return mixed
     * @throws \Exception
     */
    public function wechat(Order $order)
    {
        $user = Api::user();

        if (! $order->can('pay')) {
            return $this->failed('支付失败，订单不可支付');
        }

        if ($order->user()->isNot($user)) {
            return $this->failed('支付失败，您没有权限支付');
        }

        $payment = $order->createWechatPayment($user, $order->total, 'app');

        $notify = $payment->getPaymentParams('商品下单', [
            'notify_url' => route('api.payment.notify.wechat'),
        ]);

        return $this->success($notify->getContent());
    }

    /**
     * Notes: 支付宝支付
     *
     * @Author: 玄尘
     * @Date  : 2021/5/20 9:13
     * @param  \Modules\Mall\Models\Order  $order
     * @return mixed
     * @throws \Exception
     */
    public function alipay(Order $order)
    {
        $user = Api::user();

        if (! $order->can('pay')) {
            return $this->failed('支付失败，订单不可支付');
        }

        if ($order->user()->isNot($user)) {
            return $this->failed('支付失败，您没有权限支付');
        }

        $payment = $order->createAlipayPayment($user, $order->total, 'app');

        $notify = $payment->getPaymentParams('商品下单', [
            'notify_url' => route('api.payment.notify.alipay'),
        ]);

        return $this->success($notify->getContent());

    }

    /**
     * Notes: 水滴支付
     *
     * @Author: 玄尘
     * @Date: 2022/9/5 15:51
     * @param  Order  $order
     * @return JsonResponse|mixed
     * @throws \Exception
     */
    public function score(Order $order, Request $request)
    {
        $gateway = $request->gateway ?? 'web';
        $user    = Api::user();

        if (! $order->can('pay')) {
            return $this->failed('支付失败，订单不可支付');
        }

        if ($order->user()->isNot($user)) {
            return $this->failed('支付失败，您没有权限支付');
        }

        if ($user->account->score < $order->total) {
            return $this->failed('支付失败，您水滴积分不足');
        }

        $payment = $order->createScorePayment($user, $order->total, $gateway);

        if ($payment) {
            $payment->paid();
            $payment->order->pay();
            return $this->success('支付成功！');
        } else {
            return $this->failed('未知错误');
        }
    }

}