<?php

namespace App\Http\Controllers\V1\User;

use App\Http\Controllers\V1\Controller;
use App\Models\Pay;
use App\Models\Setting;
use App\Models\UserVipRecord;
use App\Models\VipCombo;
use Carbon\Carbon;
use Illuminate\Database\QueryException;

class VipController extends Controller
{
    public function setting()
    {
        $lists = VipCombo::select(['id', 'name', 'price', 'valid_day', 'desc'])->where('status', 1)->get();

        return $this->success($lists);
    }

    public function createOrder()
    {
        try {
            /* @var Setting $setting */
            $setting = Setting::first();
            if ($setting->is_review) {
                throw new \Exception('暂不支持，请联系管理员');
            }
            \DB::beginTransaction();
            $comboId = \request()->input('id');
            $app     = $this->getUniFactory(\user()->info->platform);
            $combo   = VipCombo::find($comboId);

            // 避免重复创建订单 一个小时内有未支付的订单直接使用
            $vip = UserVipRecord::where('user_id', \user()->id)
                ->where('combo_id', $combo->id)
                ->where('status', 0)
                ->where('created_at', '>=', Carbon::now()->subHour()->toDateTimeString())
                ->first();

            if ($vip) {
                $pay = Pay::find($vip->pay_id);
                if (3 == \user()->info->platform) {
                    $res = $app->payment()->jssdk->bridgeConfig($pay->prepay_id);
                    $res = json_decode($res, true);
                } else {
                    $res = [
                        'order_id'    => $pay->prepay_id,
                        'order_token' => $pay->token,
                    ];
                }
            } else {
                $res = app(Pay::class)->create($app, $combo->price, Pay::SOURCE_BUY_VIP);

                $vip            = new UserVipRecord();
                $vip->user_id   = \user()->id;
                $vip->combo_id  = $combo->id;
                $vip->valid_day = $combo->valid_day;
                $vip->pay_id    = $res['pay_id'];
                $vip->status    = 0;
                $vip->save();

                if (3 == \user()->info->platform) {
                    $pay = Pay::find($res['pay_id']);
                    $res = $app->payment()->jssdk->bridgeConfig($pay->prepay_id);
                    $res = json_decode($res, true);
                }
            }
            $res['pay_id'] = $vip->pay_id;
            \DB::commit();

            return $this->success($res);
        } catch (QueryException $e) {
            \DB::rollBack();

            return $this->error('下单失败');
        } catch (\Exception $e) {
            \DB::rollBack();

            return $this->error($e->getMessage());
        }
    }
}
