<?php

namespace App\Http\Controllers\V1\User;

use App\Auth;
use App\Http\Controllers\V1\Controller;
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\RechargeCombo;
use App\Models\Setting;
use App\Models\User;
use App\Models\UserRechargeRecord;
use Carbon\Carbon;
//use Dingo\Api\Http\Request;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use lc\wechat\wxpay\base\WxPayConfig;

class RechargeController extends Controller
{
    public function record(Request $request)
    {
        $limit  = $request->input('limit', 10);
        $page   = $request->input('page', 1);
        $offset = ($page - 1) * 10;
        $date   = $request->input('date');
        $date   = $date ?? Carbon::now()->format('Y-m');
        $lists  = UserRechargeRecord::filterUser()
            ->when($date, function ($query, $date) {
                /* @var Builder  $query */
                return $query->where('created_at', 'like', "$date%");
            })
            ->where('status', 1)
            ->orderByDesc('id')
            ->limit($limit)
            ->offset($offset)
            ->get();

        return $this->success($lists);
    }
    public function pay(Request $request)
    {
        try {
            $id        = $request->post('id', 1);
            $payConfig = PaymentConfig::query()->where('state', 1)->find($id);
            if (!$payConfig) {
                return $this->error('非法请求');
            }
            if ($payConfig->is_new){
                $isOrder = Order::query()->where('user_id',Auth::$userId)->where('state',1)->first();
                if ($isOrder){
                    return  Response::fail('抱歉，此套餐只能新用户专享');
                }
            }
            $order = [
                'user_id' => Auth::$userId,
                'order'   => Helper::generateNonceStr(32),
                'amount'  => $payConfig->amount,
                'diamond' => $payConfig->diamond,
                'config_id' => $payConfig->id,
            ];
            $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']) {
                    $config   = $this->getJsApiParameters($ret['prepay_id']);
                } 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, '_pay');

            return Response::fail($exception->getMessage().$exception->getFile().$exception->getLine());
        }
    }
    /**
     * 获取 JSAPI 支付，前端所需参数数据
     *
     * @param   string  $prepayId   统一下单成功返回的id
     * @return  array
     */
    public  function getJsApiParameters($prepayId)
    {
        $arr = config('swdz.wechatPay');
        $data = [
            'appId'     => $arr['appid'],
            'timeStamp' => (string) time(),
            'nonceStr'  => Helper::generateNonceStr(),
            'package'   => 'prepay_id=' . $prepayId,
            'signType'  => 'MD5',
        ];

        $data['paySign'] = Helper::makeSign($data, $arr['key']);
        return $data;
    }
    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   = RechargeCombo::find($comboId);

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

            if ($recharge) {
                $pay = Pay::find($recharge->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_RECHARGE);
                $recharge           = new UserRechargeRecord();
                $recharge->user_id  = \user()->id;
                $recharge->combo_id = $combo->id;
                $recharge->price    = $combo->price;
                $recharge->gold     = $combo->gold;
                $recharge->gift     = $combo->gift;
                $recharge->pay_id   = $res['pay_id'];
                $recharge->status   = 0;
                $recharge->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'] = $recharge->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());
        }
    }
}
