<?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": "",
     *     "data": {
     *         "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjdjYWUyYzFmYTUwMTIyZDI0ZTRiYTZhZGZhNmQxYmZlOWNiMzIxMTBmYWJlZjNjYzIyNmViZjRmNGExNWM3NjllNmU2ZTNiYWE5OGNhOWUzIn0.eyJhdWQiOiIxIiwianRpIjoiN2NhZTJjMWZhNTAxMjJkMjRlNGJhNmFkZmE2ZDFiZmU5Y2IzMjExMGZhYmVmM2NjMjI2ZWJmNGY0YTE1Yzc2OWU2ZTZlM2JhYTk4Y2E5ZTMiLCJpYXQiOjE0NzU0MTE1NTgsIm5iZiI6MTQ3NTQxMTU1OCwiZXhwIjo0NjMxMDg1MTU4LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.E9YGEzuRUOk02aV1EiWLJ_pD0hKoCyW0k_sGy63hM3u5X8K_HI1kVhaU6JNLqLZeszIAroTEDB8XMgZKAqTLlwtL8PLCJcuDoxfk1BRHbfjhDheTsahBysKGalvNEpzRCrGlao0mS0Cg9qDpEsndtypPFS8sfaflToOzbJjiSK2DvQiHSH8xZI3zHJTezgZMz-pB_hPTxp8ajdv0ve1gWtWjs3vERr0Y91X4hngO8X7LuXtAYtfxGZRIye12YE7TuLBMYzj8CCfiRt7Smhyf4palNW5mzKlZpa2l87n6NQ14Iy4oMzQ2PON1j_swrosuE2yZohGOn6fDdSCBRdJ6dLD_emjBdQCQOoB63R7BbhFZgvFX25TjzFJ7r9AdVMiGmebuRKEVSZV_JCGu1C71OIbQk-UK35s00gSr2fmJGBbN2cZTXBRTJpfuMZ_ihFYEZrvVq_Ih2X0xkd36JUuxaUld1BXRgPZvH-9jBuhe0YW2OOlgwpdm6ZB8BMcuS4ftLoi6FipgzFqfIuy-0ZqPMDnJaG7Gycrdpxza00mgOFxYxJtqwZNsUWFRZEVU881l6VC_cy294YXSPQxUwEoyKg-G5Pm8AEB9bqv5z4EU4B8-XTd3zKNqtNba_snHbc711i4EytCiZfYSjNB1hwenq45YYOAhPTwOpFI0kxyRazc",
     *         "user": {
     *             "id": 1,
     *             "name": "15888888888",
     *             "email": "abcdefg@gmail.com",
     *             "type": 2,
     *             "phone": "15888888888",
     *             "avatar": null,
     *             "last_ip": null,
     *             "created_at": "2016-09-30 00:45:13",
     *             "updated_at": "2016-09-29 16:43:36"
     *         }
     *     }
     * }
     * @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();
        $app = Factory::miniProgram($this->config);
        //$res = $app->auth->session($data['code']);
       /* if (!$res || empty($res['openid'])) {
            $user= [
                'code' => 1,
                'msg' => '获取用户OpenId失败',
                'data' => $res,
            ];
            return $this->api($user);
        }*/
        $check_user = UserInfoModel::where('openid',$data['openid'])->first();
        //dd(111);
        if(Auth::loginUsingId($check_user->id)) {
            $user = Auth::user();
            $success['token'] =  $user->createToken('MyApp')->accessToken;
            dd($success);
        }else {
            echo 2;
        }
       /* if(!$check_user){
            $add['nickname'] = preg_replace('/[\xf0-\xf7].{3}/', '', $data['nickname']);
            $add['wechat_open_id'] = $res['openid'];
            $add['avatar'] = $data['avatar'];
            $res = UserInfoModel::create($add);
            if($res){
                $data_user = UserInfoModel::where('wechat_open_id',$res['openid'])->first();
                session(['user_id'=>$check_user->id]);
                $user = [
                    'user_id'=>$data_user['id'],
                    'avatar'=>$data_user['avatar'],
                    'username'=>$data_user['nickname'],
                ];
            } else {
                $user= [
                    'code' => 1,
                    'msg' => '登陆失败',
                ];
            }
        } else {
            //print_r($check);die;
            $save['username'] = preg_replace('/[\xf0-\xf7].{3}/', '', $data['nickname']);
            $save['avatar'] = $data['avatar'];
            $res = UserInfoModel::where('wechat_open_id',$res['openid'])->update($save);
            //echo 111;
            if($res){
                session(['user_id'=>$check_user->id]);
                $user = [
                    'user_id'=>$check_user->id,
                    'avatar'=>$data['avatar'],
                    //'avatar'=>$check_user->avatar,
                    'username'=>$data['nickname'],
                    //'username'=>$check_user->naciname,
                ];
            }
        }
        $this->api($user);*/
    }
}