<?php
namespace app\mobile\service;
use think\facade\Db;

/** 菜单可见范围来自admin_menus_wx；保留业务自身的操作和记录归属校验。 */
class MobileFeatureAccess
{
    public static function context($account)
    {
        $type=(int)($account['user_type'] ?? 3);$adminId=(int)($account['admin_id'] ?? 0);
        $admin=$adminId>0 ? Db::name('admin_user')->where(['id'=>$adminId,'username'=>$account['username'],'status'=>1])->where('job','<>',79)->field('dpt,rightid')->find() : null;
        if ($admin) return ['type'=>$type,'department'=>(int)$admin['dpt'],'all'=>(int)$admin['rightid']===100];
        // 无有效后台身份的一线人员归入生产部；双身份以有效后台部门为准。
        $member=$type===1 && (int)($account['user_id'] ?? 0)>0
            ? Db::name('member_list')->where(['id'=>$account['user_id'],'eid'=>$account['username'],'status'=>1])->find() : null;
        return ['type'=>$type,'department'=>$member ? 1 : 0,'all'=>false];
    }
    public static function menuAllowed($menu,$context)
    {
        if ($context['all']) return true;
        if (!in_array($context['type'],array_map('intval',explode(',',(string)$menu['user_types'])),true)) return false;
        $departments=trim((string)($menu['department_ids'] ?? ''));
        return $departments==='' || ($context['department']>0 && in_array($context['department'],array_map('intval',explode(',',$departments)),true));
    }
    public static function allows($feature,$context)
    {
        $menu=Db::name('admin_menus_wx')->where(['action'=>$feature,'status'=>1])->field('user_types,department_ids')->find();
        return $menu && self::menuAllowed($menu,$context);
    }
}
