<?php
/**
 * Created by PhpStorm.
 * User: 思维定制
 * Date: 2018/7/16
 * Time: 18:09
 */

namespace App\Http\Controllers\Api\V1;


use App\Models\UserInfoModel;
use App\Models\WechatAppModel;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class PayController extends Controller
{
    private $config;
    public function __construct()
    {
        $wechat = WechatAppModel::find(1);
        $this->config = [
            // 必要配置
            'app_id'             => $wechat->appId,
            'mch_id'             => $wechat->mchId,
            'key'                => $wechat->key,   // API 密钥

            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            //'cert_path'          => public_path().'/pem/', // XXX: 绝对路径！！！！
            //'key_path'           => public_path().'/pem/',      // XXX: 绝对路径！！！！

            'notify_url'         => '/pay/notify',     // 你也可以在下单时单独设置来想覆盖它
        ];
    }

    public function recharge(Request $request)
    {
        $validator = Validator::make($request->all(),
            [
                'userid' => 'required',
                'price' => 'required',
            ],
            [
                'userid.required' => 'userid不能为空!',
                'price.required' => 'price不能为空!',

            ]
        );


        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $money = $request->input('price');
        $user = UserInfoModel::find($this->getUserId());

        $trade_no = 'Pay'.date('YmdHis').rand(1000,9999);

        $app = Factory::payment($this->config);

        $result = $app->order->unify([
            'body' => '知识付费充值余额',
            'out_trade_no' => $trade_no,
            'total_fee' => $money * 100,
            'trade_type' => 'JSAPI',
            'notify_url' => url('/api/home/notify'),
            'openid' => $user->openid
        ]);



        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $payment = Factory::payment($this->options());
            $jssdk = $payment->jssdk;

            $json = $jssdk->bridgeConfig($result['prepay_id']);

            return $this->api(compact('json'));
        }else{
            $msg = "签名失败，请稍后再试!";

            return $this->api(compact('msg'));
        }
    }


//下面是回调函数
    public function notify()
    {
        $app = Factory::payment($this->options());
        \Log::info("wechat notify start!");
        return $app->handlePaidNotify(function ($notify, $successful) {
            \Log::info($notify);
            if ($notify['result_code'] == 'SUCCESS') {
                $user = UserInfoModel::where('openid',$notify['openid'])->first();
                $data['order_no'] = $notify['out_trade_no'];
                $data['price'] = $notify['total_fee'] / 100;
                $data['user_id'] = $user->id;
                $data['code'] = $user->code;
                \Log::info($data);
                $user->paid_end_time = Carbon::parse("+1 year")->toDateTimeString();
                $this->createQueryInfo($user,1);

                OrderInfoModel::create($data);
                $user->save();
            } else {
                return $successful('通信失败，请稍后再通知我');
            }
            return true;
        });

    }

}