<?php

namespace app\api\controller;

use app\api\service\auth\MysqlAdapter;
use app\api\service\auth\ApiAuthService;
use app\api\validate\User as UserValidate;
use think\exception\ValidateException;
use app\common\model\User as UserModel;

class User extends Base
{

    protected $noNeedLogin = ['login'];


    public function userinfo(UserModel $userModel)
    {
        $user = $userModel->find($this->userinfo['id']);
        return  $this->success('ok', $user);
    }

    //编辑用户
    public function edit(UserModel $userModel){
        $data = $this->request->post();
        try{
            validate(UserValidate::class)->scene('edit')->check($data);
            $user = $userModel->find($this->userinfo['id']);
            if(!$user){
                return $this->error('用户不存在');
            }
            $user->save($data);
            return $this->success('ok');
        }catch (ValidateException $e) {
            return $this->error($e->getError());
        }
    }

    //修改密码
    public function password(UserModel $userModel){
        $data = $this->request->post();
        try{
            validate(UserValidate::class)->scene('password')->check($data);
            $user = $userModel->find($this->userinfo['id']);
            if(!$user){
                return $this->error('用户不存在');
            }
            if($user->password != md5(md5($data['oldpassword'].$user->salt))){
                return $this->error('旧密码错误');
            }
            $user->password = md5(md5($data['password'].$user->salt));
            $user->save();
            return $this->success('ok');
        }catch (ValidateException $e) {
            return $this->error($e->getError());
        }
    }

    public function login(ApiAuthService $authService,UserModel $userModel)
    {
        $data = $this->request->post();
        try{
       
            validate(UserValidate::class)->scene('login')->check($data);
            $terminal = $this->request->post('terminal/d', 0);
            $user = $authService->login($data['username'],$data['password'], $terminal);

        }catch (ValidateException $e) {
          
            return $this->error($e->getError());
        }catch (\Exception $e){
            return $this->error($e->getMessage());
        }
        return  $this->success('ok', $user);
    }


    //退出登录
    public function logout()
    {
        MysqlAdapter::logout($this->userinfo['id']);
        return  $this->success('ok');
    }

    //获取全部人员
    public function getAllUser(UserModel $userModel)
    {
        $list = $userModel->where('status', 'normal')->field('id,nickname,avatar')->select();
        return $this->success('ok', $list);
    }
}