<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use JiGuang\JSMS as JSMS;
use Illuminate\Support\Facades\Redis;
use Dingo\Api\Http\Response;
use Validator;
use DB;
use App\Models\User;
use App\Services\SystemService;

class UserController extends ApiController {
	// 利用 Laravel 的自动解析功能注入 CartService 类
	public function __construct(SystemService $systemService) {
		$this->systemService = $systemService;
	}
	/**
	 *
	 * @api {post} user/fastLogin 手机号快捷登录
	 * @apiName user/fastLogin
	 * @apiGroup user
	 * @apiParam {int} mobile 手机号
	 * @apiParam {int} code 验证码
	 * @apiSuccess  {string} token 你懂的
	 * @apiParamExample {curl} Example usage:
	 * http://59.110.137.245:8080/api/user/fastLogin?mobile=13810456667&code=1234
	 */
	function fastLogin(Request $request) {
		$rules = [ 
				'mobile' => [ 
						'required'
				],
				'code' => [ 
						'required'
				]
		];
		$validator = app ( 'validator' )->make ( $request->all (), $rules );
		if ($validator->fails ()) {
			return $this->throwErrors ( $validator );
		}
		$user = User::firstOrCreate ( [ 
				'mobile' => $request->mobile
		] );
		// 验证验证码
		// if(!$this->systemService->checkMobileCode ( $request->mobile, $request->code ))
		// return $this->error ( 90003, '验证码错误' );

		$token = md5 ( $user->id );
		Redis::set ( 'UToken-' . $token, $user->id );
		$resultData ['token'] = $token;

		return $this->success ( $resultData );
	}

	/**
	 *
	 * @api {post} user/update 新建/修改 头像或昵称
	 * @apiName user/update
	 * @apiGroup user
	 * @apiParam {string} avatar 头像 传入阿里云OSS完整地址
	 * @apiParam {string} name 昵称
	 * @apiParamExample {curl} Example usage:
	 * http://59.110.137.245:8080/api/user/update?token=c81e728d9d4c2f636f067f89cc14862c&name=李狗蛋&avatar=http://zfwy.oss-cn-beijing.aliyuncs.com/images/nike.jpg
	 * @apiPermission token 必传
	 */
	public function update(Request $request) {
		$user = User::find ( $request->user_id );
		if ($request->exists ( 'avatar' ))
			$user->avatar = $request->avatar;
		if ($request->exists ( 'name' ))
			$user->name = $request->name;
		$user->save ();

		return $this->success ();
	}
}
