<?php

namespace App\Http\Controllers\V1;

use App\Auth;
use App\libs\helpers\Helper;
use App\libs\helpers\LogHelper;
use App\libs\helpers\Response;
use App\libs\wechat\pay\Wechat;
use App\Models\Order;
use App\Models\Pay;
use App\Models\PaymentConfig;
use App\Models\User;
use Illuminate\Http\Request;

class PayController extends Controller
{
    public function query($payId)
    {
        $pay = Pay::find($payId);
        if (!$pay || $pay->status) {
            return $this->success();
        }

        return $this->error();
    }

    public function pay(Request $request)
    {
        try {
            $id        = $this->request->post('id', 1);
            $payConfig = PaymentConfig::query()->where('state', 1)->find($id);
            var_dump($payConfig->amount);echo 1111;exit();
            if (!$payConfig) {
                return $this->error('非法请求');
            }
            $order = [
                'user_id' => $this->request->user->id,
                'order'   => Helper::generateNonceStr(32),
                'amount'  => $payConfig->amount,
                'diamond' => $payConfig->diamond,
            ];
            var_dump(($payConfig->amount * 100));exit();
            $result = Order::query()->create($order);
            if (!$result) {
                return $this->error('订单提交失败');
            }
            User::query()->where('id', Auth::$userId)->increment('diamond', $payConfig->diamond);
            $ret         = Wechat::addOrder($result,Auth::$user);
            $result->pay = json_encode($ret);
            $result->save();
            $config = [];
            if (isset($ret['return_code'], $ret['result_code'])) {
                if ('SUCCESS' == $ret['result_code'] && 'SUCCESS' == $ret['return_code']) {
                    $app      = Wechat::pay();
                    $utils    = $app->getUtils();
                    $appId    = $ret['appid'];
                    $signType = 'MD5'; // 默认RSA，v2要传MD5
                    $config   = $utils->buildMiniAppConfig($ret['prepay_id'], $appId, $signType); // 返回数组
                } else {
                    return $this->error($ret['err_code_des']);
                }
            } else {
                return $this->error('参数异常，请稍后再试' . json_encode($ret, 256));
            }
            $code = 0;

            return $this->success(compact('config', 'code'));
        } catch (\Exception $exception) {
            LogHelper::exceptionLog($exception, $this->code);

            return Response::fail($exception->getMessage());
        }
    }
}
