<?php

namespace App\Http\Services\V1;

use App\Generated\Exceptions\CustomErrorMessageException;
use App\Generated\Exceptions\ForbiddenException;
use App\Generated\Exceptions\NotFoundException;
use App\Generated\Exceptions\SystemErrorException;
use App\Generated\V1\Messages\Payment\FetchAppWechatPayParamsMessage;
use App\Generated\V1\Messages\Payment\GetCouponDetailMessage;
use App\Generated\V1\Messages\Payment\GetCouponListMessage;
use App\Http\Controllers\Core\Auth;
use App\Models\CouponModel;
use App\Services\Pay\CouponService;
use App\Models\OrderModel;

class PaymentService
{

    public function getCouponDetail(GetCouponDetailMessage $message)
    {
        $couponId = $message->getCouponId();
        $goodsId = $message->getGoodsId();

        $uid = Auth::auth();
        $couponService = new CouponService();
        $coupon = $couponService
            ->setUid($uid)
            ->setCouponId($couponId)
            ->getCoupon();

        if (!$coupon) {
            throw new NotFoundException('优惠券不存在或已过期');
        }

        // 查看状态
        if ($coupon->looked_at == 0) {
            $coupon->looked_at = time();
            $coupon->save();
        }
        if ($goodsId) {
            $couponService->setGoodsId($goodsId)->getSettlementAmount();
            $coupon->total_amount = $couponService->total_amount;
            $coupon->settlement_coupon_amount = $couponService->coupon_amount;
            $coupon->settlement_total_amount = $couponService->settlement_total_amount;
        }

        $message->setResponse($coupon);
    }

    public function getCouponList(GetCouponListMessage $message)
    {
        $type = $message->getType();
        $goodsScope = $message->getGoodsScope();
        $perPage = $message->getPerPage() ?: 20;
        $uid = Auth::auth();
        $coupons = CouponModel::existing($uid)
            ->when($type, function ($query) use ($type) {
                return $query->where('type', $type);
            })
            ->when($goodsScope, function ($query) use ($goodsScope) {
                return $query->where('goods_scope', $goodsScope);
            })
            ->orderBy('get_at', 'asc')
            ->paginate($perPage);
        CouponModel::whereIn('id', $coupons->pluck('id'))->where('looked_at', 0)->update(['looked_at' => time()]);

        $message->setResponse($coupons);
    }

    /**
     * @param  FetchAppWechatPayParamsMessage  $message
     * @throws CustomErrorMessageException
     * @throws ForbiddenException
     * @throws NotFoundException
     * @throws SystemErrorException
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function fetchAppWechatPayParams(FetchAppWechatPayParamsMessage $message)
    {
        $orderId = $message->getOrderId();
        $uid = Auth::auth();
        $order = OrderModel::find($orderId);
        if (!$order) {
            throw new NotFoundException('订单号错误或者不存在');
        }
        if ($order->trade_state != 0) {
            throw new NotFoundException('订单失效' . json_encode($order->toArray()));
        }
        if ($uid != $order->uid) {
            throw new ForbiddenException('用户标识不一致');
        }
        $pay_url = config('api.pay_url') . "/payments/app/{$order->out_trade_no}";
        $result = \Curl::to($pay_url)->asJsonResponse()->get();
        if (isset($result->code) && $result->code == 200) {
            $message->setResponse($result->data);
        } else {
            if (isset($result->code)) {
                throw new CustomErrorMessageException($result->message ?? '系统异常');
            }
            throw new SystemErrorException('系统异常');
        }
    }
}
