<?php


namespace App\Http\Controllers\Api;
use App\Models\User;
use App\Models\UserInfoModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
    /**
     * 选择性别
     */
    public function checksex(Request $request){
        $user = auth('api')->user();
        $validator = Validator::make($request->all(), [
            'sex' => 'required'
        ], [
            'mobile.required'=>"性别必须",
        ]);
        if ($validator->fails()) {
            return $this->response()->errorForbidden($validator->messages()->first());
        }
        $user->sex = $request->sex;
        if (!$user->save()) {
            return $this->response->errorForbidden('设置性别失败');
        }
        return $this->response->noContent();
    }

    /**
     * 设置资料
     */
    public function setinfo(Request $request){
        $user = auth('api')->user();

        $validator = Validator::make($request->all(), [
            'nickname' => 'required|between:2,8',
            'birthday' => 'required',
            'avatar' => 'required',
        ], [
            'nickname.required'=>"昵称不能为空",
            'nickname.between'=>"昵称长度必须在2~8之间",
            'birthday.required'=>"生日不能为空",
            'avatar.required'=>"头像不能为空",
        ]);
        if ($validator->fails()) {
            return $this->response()->errorForbidden($validator->messages()->first());
        }

        if(UserInfoModel::where(['nickname'=>$request->nickname])->where('user_id', '!=' , $user->id)->first()){
            return $this->response->errorForbidden('昵称已被使用');
        }
        //邀请码设置
        $pid = 0;
        if(isset($request->ycode) && $request->ycode!=""){
            if(!$puser = User::where(['ycode'=>$request->ycode])->first()){
                return $this->response->errorForbidden("邀请码不存在");
            }
            $pid = $puser->id;
        }

        DB::beginTransaction();
        try {
            $userinfo = UserInfoModel::firstOrCreate([
                'user_id' => $user->id,
            ]);
            $userinfo->avatar = $request->avatar;
            $userinfo->nickname = $request->nickname;
            $userinfo->birthday = $request->birthday;
            $userinfo->save();

            if($pid!=0){
               $user->pid = $pid;
               $user->save();
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            abort(403, '保存失败');
        }
    }
}
