<?php
namespace app\adminVue\controller;

use think\facade\Cache;
use think\facade\Db;

class V2Auth extends V2Base
{
    public function health()
    {
        if (!$this->request->isGet()) $this->fail('仅支持 GET',405);
        return json(['code'=>0,'data'=>['service'=>'oms-admin-v2','version'=>'1.0'],'msg'=>'']);
    }

    public static function verifyPassword($password, $hash)
    {
        if (!is_string($password) || !is_string($hash) || $hash==='') return false;
        // Other applications share the accounts, so do not change their hash format in this phase.
        return preg_match('/^[a-f0-9]{32}$/iD',$hash)
            ? hash_equals(strtolower($hash),md5(trim($password)))
            : password_verify($password,$hash);
    }

    public function login()
    {
        if (!$this->request->isPost()) $this->fail('仅支持 POST',405);
        $username=$this->request->post('username'); $password=$this->request->post('password');
        if (!is_string($username) || !is_string($password) || trim($username)==='' || $password==='' || strlen($username)>100 || strlen($password)>256) $this->fail('请输入有效账号和密码');
        $rate='admin-v2:attempt:'.hash('sha256',$this->request->ip().'|'.trim($username));
        $attempts=(int)Cache::get($rate,0);
        if ($attempts>=10) $this->fail('尝试次数过多，请十分钟后重试',429);
        Cache::set($rate,$attempts+1,600);
        $user=Db::name('admin_user')->where('username',trim($username))->find();
        if (!$user || (int)$user['status']!==1 || !self::verifyPassword($password,$user['password'])) $this->fail('账号、密码错误或账号不可用',401);
        Cache::delete($rate);
        $token=bin2hex(random_bytes(32)); $expires=time()+28800;
        Cache::set('admin-v2:session:'.hash('sha256',$token),[
            'id'=>$user['id'],'expiresAt'=>$expires,'loginAt'=>time(),
            'credential'=>hash('sha256',(string)$user['password'])
        ],28800);
        return json(['code'=>0,'msg'=>'登录成功','data'=>['access_token'=>$token,'expiresAt'=>$expires,'user'=>$this->profile($user)]]);
    }

    protected function profile(array $user)
    {
        $safe=array_intersect_key($user,array_flip(['id','username','truename','dpt','job','rightid','ext','phone','e_mail']));
        $safe['name']=$user['truename'] ?: $user['username'];
        $org=Db::name('admin_org')->whereIn('id',array_filter([$user['dpt'],$user['job']]))->column('title','id');
        $safe['department']=$org[$user['dpt']] ?? '未设置部门';
        $safe['jobName']=$org[$user['job']] ?? '未设置岗位';
        $safe['roleName']=Db::name('admin_rights')->where('id',$user['rightid'])->value('title') ?: '未设置角色';
        return $safe;
    }

    public function me() { return json(['code'=>0,'msg'=>'','data'=>$this->profile($this->actor)]); }

    public function menus()
    {
        return json(['code'=>0,'msg'=>'','data'=>V2Menu::navigation($this->actor)]);
    }

    public function buttons() { return json(['code'=>0,'msg'=>'','data'=>(object)[]]); }

    public function logout()
    {
        $token=$this->requestToken();
        Cache::delete('admin-v2:session:'.hash('sha256',$token));
        return json(['code'=>0,'msg'=>'已退出登录','data'=>null]);
    }
}
