<?php
namespace app\adminVue\controller;

/** Stable page bindings. Labels/order/enabled are stored separately from route identity. */
class V2MenuCatalog
{
    public static function definitions()
    {
        $groups = [
            'people'=>['人事管理','UserFilled'], 'training'=>['培训考试','Reading'],
            'logistics'=>['行政后勤','Van'], 'production'=>['生产设备','SetUp'],
            'inventory'=>['库存盘点','Box'], 'safety'=>['安全管理','CircleCheck'],
            'quality'=>['质量售后','DocumentChecked'], 'system'=>['系统管理','Setting']
        ];
        $pages = [
            ['people.employees','people','员工档案','/hr/memberList'],
            ['people.newcomers','people','新员工记录','/hr/newComer'],
            ['people.leaving','people','预离职列表','/hr/memberPerleave'],
            ['people.performance','people','绩效管理','/hr/kpi'],
            ['training.entry-exams','training','入职考试记录','/hr/newComerExam'],
            ['training.plans','training','关键岗位培训','/hr/keyTraining'],
            ['training.skill-exams','training','技能考核管理','/hr/newSkillScore'],
            ['training.questions','training','技能题库','/hr/examList'],
            ['training.papers','training','试卷配置','/hr/examSet'],
            ['logistics.meals','logistics','报餐记录','/hr/mealSummary'],
            ['logistics.meal-collection','logistics','领餐记录','/hr/mealSign'],
            ['logistics.shuttle','logistics','夜班车记录','/hr/nightCar'],
            ['logistics.radio-settings','logistics','巴渝之声管理','/hr/radioSettings'],
            ['production.teams','production','班组管理','/mfg/teamList'],
            ['production.equipment','production','设备点检基础数据','/design/machineCheck'],
            ['production.position-devices','production','岗位设备管理','/design/positionDevice'],
            ['production.check-issues','production','点检异常记录','/mfg/checkIssue'],
            ['production.suggestions','production','合理化建议','/mfg/suggestionList'],
            ['inventory.records','inventory','盘点记录','/pcl/invRecord'],
            ['inventory.locations','inventory','盘点基础数据','/design/address'],
            ['safety.risks','safety','安全风险反馈','/ehs/safeList'],
            ['safety.outplant','safety','物品出厂申请','/ehs/outplantList'],
            ['quality.daily-issues','quality','Daily Issue反馈','/cs/dailyIssue'],
            ['quality.repairs','quality','售后维修记录','/cs/afterSalesRepair'],
            ['system.accounts','system','账号管理','/user/list'],
            ['system.menus','system','菜单管理','/system/menus'],
            ['system.mobile-menus','system','小程序菜单管理','/system/mobileMenus'],
            ['system.template-failures','system','消息发送异常','/user/templateFailures']
        ];
        $result = ['workbench'=>['key'=>'workbench','parentKey'=>'','title'=>'工作台','icon'=>'HomeFilled','sort'=>0,'enabled'=>true,'available'=>true,'path'=>'/home/index','component'=>'/home/index']];
        $index=0;
        foreach ($groups as $key=>$group) $result[$key]=['key'=>$key,'parentKey'=>'','title'=>$group[0],'icon'=>$group[1],'sort'=>++$index*10,'enabled'=>true,'available'=>true,'path'=>'/group-'.$key,'component'=>null];
        $order=[];
        foreach ($pages as $page) {
            $order[$page[1]]=($order[$page[1]] ?? 0)+10;
            $components=['safety.risks'=>'/ehs/safeList','safety.outplant'=>'/ehs/outplantList','system.menus'=>'/system/menus','system.accounts'=>'/user/list','quality.daily-issues'=>'/cs/dailyIssue','quality.repairs'=>'/cs/afterSalesRepair','people.employees'=>'/hr/memberList','production.suggestions'=>'/mfg/suggestionList','people.newcomers'=>'/hr/newComer','training.entry-exams'=>'/hr/newComerExam','logistics.meals'=>'/hr/mealSummary','logistics.meal-collection'=>'/hr/mealSign'];
            $components['training.plans']='/hr/keyTraining';
            $components['training.papers']='/hr/examSet';
            $components['training.questions']='/hr/examList';
            $components['people.performance']='/hr/kpi';
            $components['system.template-failures']='/user/templateFailures';
            $components['people.leaving']='/hr/memberPerleave';
            $components['inventory.locations']='/design/address';
            $components['production.equipment']='/design/machineCheck';
            $components['production.position-devices']='/design/positionDevice';
            $components['production.check-issues']='/mfg/checkIssue';
            $components['inventory.records']='/pcl/invRecord';
            $components['system.mobile-menus']='/system/mobileMenus';
            $components['logistics.radio-settings']='/hr/radioSettings';
            $available=isset($components[$page[0]]);
            $result[$page[0]]=['key'=>$page[0],'parentKey'=>$page[1],'title'=>$page[2],'icon'=>'Document','sort'=>$order[$page[1]],'enabled'=>$available,'available'=>$available,'path'=>$page[3],'component'=>$components[$page[0]] ?? null];
        }
        return $result;
    }

    public static function merge(array $rows)
    {
        $definitions=self::definitions();$items=[];
        foreach ($rows as $row) {
            $key=$row['menu_key']; if (!isset($definitions[$key])) continue;
            // 数据库决定菜单是否存在；代码只提供已注册页面的路由和组件绑定。
            $items[$key]=$definitions[$key];
            $items[$key]['title']=$row['title']; $items[$key]['icon']=$row['icon'];
            $items[$key]['sort']=(int)$row['sort_order']; $items[$key]['enabled']=(bool)$row['enabled'];
            $items[$key]['parentKey']=$row['parent_key'];
        }
        return $items;
    }

    public static function tree(array $items, $navigation=false)
    {
        $roots=[];
        foreach ($items as $item) {
            if ($item['parentKey']!=='') continue;
            if ($navigation && !$item['enabled']) continue;
            $children=array_values(array_filter($items,function ($child) use ($item,$navigation) {
                return $child['parentKey']===$item['key'] && (!$navigation || ($child['enabled'] && $child['available']));
            }));
            usort($children,[self::class,'compare']);
            if ($item['component']===null && !$children) continue;
            if (!$navigation) { if ($children) $item['children']=$children; $roots[]=$item; continue; }
            $node=self::route($item);
            if ($children) $node['children']=array_map([self::class,'route'],$children);
            $roots[]=$node;
        }
        usort($roots, function ($a,$b) use ($items,$navigation) {
            return $navigation ? self::compare($items[$a['menuKey']],$items[$b['menuKey']]) : self::compare($a,$b);
        });
        return $roots;
    }

    public static function compare($a,$b) { return ($a['sort'] <=> $b['sort']) ?: strcmp($a['key'],$b['key']); }
    public static function route($item)
    {
        $node=['menuKey'=>$item['key'],'path'=>$item['path'],'name'=>'oms-'.str_replace('.','-',$item['key']),
            'meta'=>['title'=>$item['title'],'icon'=>$item['icon'],'isAffix'=>$item['key']==='workbench','isKeepAlive'=>false]];
        // Keep the existing home route identity so tabs and cached links remain stable.
        if ($item['key']==='workbench') $node['name']='home';
        if ($item['component']) $node['component']=$item['component'];
        return $node;
    }

    public static function validate($key,$data)
    {
        $defs=self::definitions();
        if (!is_string($key) || !isset($defs[$key]) || !is_array($data)) throw new \InvalidArgumentException('菜单不存在');
        $title=$data['title'] ?? null; $icon=$data['icon'] ?? null; $sort=$data['sort'] ?? null; $enabled=$data['enabled'] ?? null;
        $parent=$data['parentKey'] ?? $defs[$key]['parentKey'];
        if ($defs[$key]['parentKey']==='') {
            if ($parent!=='') throw new \InvalidArgumentException('一级目录不能移动到其他目录');
        } elseif (!is_string($parent) || !isset($defs[$parent]) || $defs[$parent]['component']!==null || $defs[$parent]['parentKey']!=='') {
            throw new \InvalidArgumentException('请选择有效的业务分组');
        }
        if ($key==='system.menus' && $parent!=='system') throw new \InvalidArgumentException('菜单管理入口固定在系统管理');
        if (!is_string($title) || trim($title)==='' || mb_strlen(trim($title))>30 || preg_match('/[<>\x00-\x1F]/u',$title)) throw new \InvalidArgumentException('菜单名称须为1至30个字符');
        if (!is_string($icon) || !preg_match('/^[A-Z][A-Za-z0-9]{0,49}$/D',$icon)) throw new \InvalidArgumentException('请选择有效图标');
        if (!is_int($sort) || $sort<0 || $sort>9999 || !is_bool($enabled)) throw new \InvalidArgumentException('排序或启用状态无效');
        if ($enabled && !$defs[$key]['available']) throw new \InvalidArgumentException('页面尚未迁移，暂不能启用');
        if (in_array($key,['workbench','system','system.menus'],true) && !$enabled) throw new \InvalidArgumentException('工作台和菜单管理入口需要保持启用');
        return ['menu_key'=>$key,'parent_key'=>$parent,'title'=>trim($title),'icon'=>$icon,'sort_order'=>$sort,'enabled'=>(int)$enabled,'updated_at'=>time()];
    }
}
