<?php

namespace App\Http\Controllers\Api;

use App\FeedBacks;
use App\Members;
use App\ProductsComments;
use GuzzleHttp\Client;
use Illuminate\Http\Request;

class MembersController extends Controller
{
    public function show($id)
    {
        $member = Members::query()->find($id);
        return $this->ok(array_merge($member->toArray(), [
            'avatarUrl' => $member->pic,
            'nickName' => $member->nickname,
        ]));
    }

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @param $id
     * @return array
     */
    public function members(Request $request, $id)
    {
        Members::query()->find($id)->update([
            'real_name' => $request->input('real_name'),
            'phone_number' => $request->input('phone_number'),
        ]);
        $member = Members::query()->find($id);
        return $this->ok(array_merge($member->toArray(), [
            'avatarUrl' => $member->pic,
            'nickName' => $member->nickname,
        ]));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return array
     */
    public function login(Request $request)
    {
        $client = new Client();
        $response = $client->get('https://api.weixin.qq.com/sns/jscode2session', [
            'query' => [
                'appid' => config('wechat.appid'),
                'secret' => config('wechat.secret'),
                'js_code' => $request->input('code'),
                'grant_type' => 'authorization_code'
            ],
            'verify' => false
        ]);
        $content = $response->getBody()->getContents();
        // 登录
        $info = json_decode($content, true);
        $openid = $info['openid'];
        $member = Members::query()->where('openid', $openid);
        if (!$member->exists()) {
            // avatarUrl, nickname,openid,gender
            $member = $member->create([
                'nickname' => $request->input('nickname'),
                'real_name' => '',
                'phone_number' => '',
                'sex' => $request->input('gender'),
                'pic' => $request->input('avatarUrl'),
                'points' => 0,
                'openid' => $info['openid']
            ]);
        } else {
            $member = $member->first();
        }

        return $this->ok(array_merge($member->toArray(), [
            'avatarUrl' => $member->pic,
            'nickName' => $member->nickname,
        ]));
    }

    public function feedback(Request $request, $id)
    {
        $member = Members::query()->find($id);
        FeedBacks::query()->create([
            'content' => $request->input('content'),
            'images' => $request->input('images'),
            'members_id' => $id,
            'members_name' => $member->nickname,
        ]);

        return $this->ok([]);
    }
}
