<?php
declare(strict_types=1);
namespace app\api\service\auth;

use app\api\service\auth\Adapter;
use think\facade\Cache;
use app\common\model\GroupUser;
use app\common\model\UserToken;
use think\facade\Config;


class ApiAuthGroupService 
{
    protected $allowFields = ['id', 'nickname', 'mobile', 'avatar', 'balance', 'score'];
    

    public function login(string $username, string $password, int $terminal = 0)
    {
        $token=uuid();
        $user=GroupUser::where('username',$username)->find();
        if(!$user){
            throw new \Exception('账号或密码错误');
        }
        if($user->password!=md5(md5($password.$user->salt))){
            //throw new \Exception('账号或密码错误' . md5(md5($password.$user->salt)));
            throw new \Exception('账号或密码错误');
        }
        if($user->status!='normal'){
            throw new \Exception('账号已经被禁用');
        }
        if($terminal==1 && strpos($user->role, "3") === false){
            throw new \Exception('账号已经被禁用');
        }
        //刷新token
        $token = GroupMysqlAdapter::login($token, $user);
        $user->loginfailure = 0;
        $user->logintime = time();
        $user->loginip = request()->ip();
        $user->save();

        Cache::store('redis')->set('user_info_'.$user->id, $user->toArray(), Config::get('app.user_login.keepalive_time'));
        $data = [
            'userinfo' => $user,
            'token' => $token,
            'page' => '',//page:stock_clerk 仓库管理员 worker:打包员工
         ];
        $role_arr = explode(',', $user->role);
        if(in_array('3', $role_arr)){
            $data['page'] = 'stock_clerk';//仓库管理员
        }else if(in_array('4', $role_arr)){
            $data['page'] = 'worker';//打包员工
        }

        return $data;
    }

   


    public function updateToken(int $uid, array $arr)
    {   
        return UserToken::where('user_id', $uid)->update($arr);
    }

}