<?php
/**
 * Created by PhpStorm.
 * User: 思维定制
 * Date: 2018/7/11
 * Time: 15:59
 */

namespace App\Http\Controllers\Api\V1;

use App\Models\UserInfoModel;
use App\Models\WechatAppModel;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Auth;

class LoginController extends Controller
{
    private $config;

    public function __construct()
    {
        $wechat_app = WechatAppModel::find(1);
        //dd($wechat_app);
        $this->config = [
            'app_id' => $wechat_app->appid,
            'secret' => $wechat_app->appsecret,
            'response_type' => 'array',
        ];
    }

    /**
     * @api {post} /api/login 登陆（login）
     * @apiDescription 登陆(login)login
     * @apiGroup Login
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {string}  nickname   手机号码
     * @apiParam {string} avatar
     * @apiParam {string} password   password
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "state": true,
     *     "code": 0,
     *     "message": {
     *         "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjdjYWUyYzFmYTUwMTIyZDI0ZTRiYTZhZGZhNmQxYmZlOWNiMzIxMTBmYWJlZjNjYzIyNmViZjRmNGExNWM3NjllNmU2ZTNiYWE5OGNhOWUzIn0.eyJhdWQiOiIxIiwianRpIjoiN2NhZTJjMWZhNTAxMjJkMjRlNGJhNmFkZmE2ZDFiZmU5Y2IzMjExMGZhYmVmM2NjMjI2ZWJmNGY0YTE1Yzc2OWU2ZTZlM2JhYTk4Y2E5ZTMiLCJpYXQiOjE0NzU0MTE1NTgsIm5iZiI6MTQ3NTQxMTU1OCwiZXhwIjo0NjMxMDg1MTU4LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.E9YGEzuRUOk02aV1EiWLJ_pD0hKoCyW0k_sGy63hM3u5X8K_HI1kVhaU6JNLqLZeszIAroTEDB8XMgZKAqTLlwtL8PLCJcuDoxfk1BRHbfjhDheTsahBysKGalvNEpzRCrGlao0mS0Cg9qDpEsndtypPFS8sfaflToOzbJjiSK2DvQiHSH8xZI3zHJTezgZMz-pB_hPTxp8ajdv0ve1gWtWjs3vERr0Y91X4hngO8X7LuXtAYtfxGZRIye12YE7TuLBMYzj8CCfiRt7Smhyf4palNW5mzKlZpa2l87n6NQ14Iy4oMzQ2PON1j_swrosuE2yZohGOn6fDdSCBRdJ6dLD_emjBdQCQOoB63R7BbhFZgvFX25TjzFJ7r9AdVMiGmebuRKEVSZV_JCGu1C71OIbQk-UK35s00gSr2fmJGBbN2cZTXBRTJpfuMZ_ihFYEZrvVq_Ih2X0xkd36JUuxaUld1BXRgPZvH-9jBuhe0YW2OOlgwpdm6ZB8BMcuS4ftLoi6FipgzFqfIuy-0ZqPMDnJaG7Gycrdpxza00mgOFxYxJtqwZNsUWFRZEVU881l6VC_cy294YXSPQxUwEoyKg-G5Pm8AEB9bqv5z4EU4B8-XTd3zKNqtNba_snHbc711i4EytCiZfYSjNB1hwenq45YYOAhPTwOpFI0kxyRazc",
     *         "msg": '登录成功'
     *     }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     *    1102    INCORRECT_USER_OR_PASS          用户名或密码不正确
     */
    public function login(Request $request)
    {
        $data = $request->input();
       // dd($data);
        $app = Factory::miniProgram($this->config);
        $res = $app->auth->session($data['code']);
        if (!$res || empty($res['openid'])) {
            $message= [
                'code' => 1,
                'msg' => '获取用户OpenId失败',
                'data' => $res,
            ];
            return $this->api($message);
        }
        $check_user = UserInfoModel::where('openid',$res['openid'])->first();
        //dd($check_user);
        if($check_user && Auth::loginUsingId($check_user->id)) {
            $user = Auth::user();

            $success['token'] =  $user->createToken($user->id . '-' . $user->openid)->accessToken;
            $save['nickname'] = preg_replace('/[\xf0-\xf7].{3}/', '', $data['nickname']);
            $save['avatar'] = $data['avatar'];
            $query = UserInfoModel::where('openid',$res['openid'])->update($save);
            //echo 111;die;
            if($query){
                $message = [
                    'msg'=>'登录成功',
                    'token'=>$success['token'],
                ];
                return $this->api($message);
            }
        }else {
            // dd($res);
            $add['nickname'] = preg_replace('/[\xf0-\xf7].{3}/', '', $data['nickname']);
            $add['openid'] = $res['openid'];
            $add['avatar'] = $data['avatar'];
            $res_add = UserInfoModel::create($add);
            if($res_add){
                $data_user = UserInfoModel::where('openid',$res['openid'])->first();
                if(Auth::loginUsingId($data_user->id)) {
                    $user = Auth::user();
                    $success['token'] = $user->createToken($user->id . '-' . $user->openid)->accessToken;
                    $message = [
                        'msg'=>'登录成功',
                        'token'=>$success['token'],
                    ];
                }
            } else {
                $message= [
                    'msg' => '登陆失败',
                ];
            }
            return $this->api($message);
        }
    }
}