<?php

namespace App\Http\Controllers\V1;


use App\Models\User;
use App\Models\UserFollow;
use App\Services\Api\SortService;
use App\Services\Api\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Services\Base\ErrorCode;
use PHPUnit\Util\Exception;
use App\Services\SmsServer;

class UserController extends Controller
{
    public function __construct()
    {
        $this->user = auth('api')->user();
        $this->userId = $this->user ? $this->user->id : 0;

        //如果用户被删除，会自动退出登录
        if (!empty($this->user->deleted_at)) {
            $this->user->online = 0;
            $this->user->save();
            auth('api')->logout();
        }
    }
    /**
     * 获取用户列表
     */
    public function index(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'nickname' => 'required',
        ]);
        if($validator->fails()){
            return $this->error($validator->errors()->first(),ErrorCode::PARAMS_ERROR);
        }
        $search  = ['keyword'=>'1'];

        $where   = ['nickname' => $request->nickname];
        $orderby = ['id'=>'desc','created_at'=>'desc'];
        $pagesize = 10;

        $list = (new UserService())->search($search,$where,$orderby,$pagesize);
        return $this->success($list);
    }
    /**
     * 获取用户详情
     */
    public function show()
    {
        $info = (new UserService())->show($this->userId);
        $info->follow_count = UserFollow::query()->where('user_id',$this->userId)->count();
        return $this->success($info);
    }
    /**
     * 新增用户
     */
    public function create(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'nickname' => 'required',
            'avatar' => 'required',
            'password' => 'required',
            'email' => 'required',
            'mobile' => 'required',
        ]);
        if($validator->fails()){
            return $this->error($validator->errors()->first(),ErrorCode::PARAMS_ERROR);
        }
        $res = (new UserService())->create($request->all());
        return $this->success($res);
    }

    /**
     * 更新用户
     */
    public function upUserInfo(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'nickname' => 'required',
            'name' => 'required',
            'introduce' => 'required',
        ]);
        if($validator->fails()){
            return $this->error($validator->errors()->first(),ErrorCode::PARAMS_ERROR);
        }
        $res = (new UserService())->update($this->userId,$request->all());
        return $this->success($res);
    }

    /**
     * @return void
     * 添加关注
     */
    public function addFollow(Request $request){
        $user = User::query()->where('id',$request->get('user_id'))->first();
        if(!$user){
            return $this->error("用户不存在！");
        }
        $collect = UserFollow::query()->where('user_id',$this->userId)->where('to_user_id',$user->id)->first();
        if($collect){
            return $this->error("您已关注过了！");
        }
        $data =[
            'user_id' => $this->userId,
            'to_user_id' => $user->id,
        ];
        $res = UserFollow::query()->create($data);
        if(!$res){
            return $this->error("操作失败！");
        }
        return $this->success();
    }

    /**
     * 删除用户
     */
    public function destroy(Request $request,$id)
    {
        $res = (new UserService())->destroy($id);
        return $this->success($res);
    }

    /**
     * 更新用户头像
     */
    public function avatar(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'avatar' => 'required',
        ]);
        if($validator->fails()){
            return $this->error($validator->errors()->first(),ErrorCode::PARAMS_ERROR);
        }
        $res = (new UserService())->update($this->userId,$request->all());
        return $this->success($this->userId);
    }

    //按照首字母进行分组排序，类似手机通讯录(注意：get()后面直接 ->toArray()在数据为空的时候导致报错)
    public function groupByInitial(Request $request)
    {
        $keyword = $request->input('keyword', '');

        $list = User::query()
            ->select('id', 'name', 'avatar')
            ->when($keyword, function ($query, $keyword){
                $query->where('name', 'like', '%'.$keyword.'%');
            })
            ->whereNotNull('name')
            ->whereNull('deleted_at')
            ->get();

        if($list->isNotEmpty()){
            $list = $list->toArray();
            $list = SortService::getResultList($list);
        }else{
            $list = [];
        }

        return $this->success($list);
    }

    //绑定或解绑 手机号
    public function bindMobile(Request $request)
    {
        try {
            if(!$this->isAllowUnbound()){
              return $this->output([],ErrorCode::NOT_ALLOW);
            }
            $user = User::find($this->user->id);
            if (!empty($user->mobile)) { //要解绑
                $user->mobile = '';
            } else { //要绑定
                $user->mobile = $request->mobile;
            }
            SmsServer::checkSmsCodeByVerifyKey($request->mobile, $request->smsCode);
            if (!$user->save()) {
              return $this->output([],ErrorCode::DATA_SAVE_FALSE);
            }
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }

        return $this->success();
    }

    //判断是否允许解绑
    public function isAllowUnbound()
    {
        $user = $this->user;
        $n = 0;
        if(!empty($user->mobile)){
            $n++;
        }
        if(!empty($user->email)){
            $n++;
        }
        if(!empty($user->open_id)){
            $n++;
        }
        if($n==1){
            return false;
        }
        return true;
    }

}
