-- 客户端连接列表权限初始化（可直接执行，带防重复）
-- 权限标识：xslmes:mes_xsl_client_connection:list

-- 1) 请按你们实际菜单树确认 parent_id
--    优先使用你指定的父菜单 ID；若不指定，脚本会优先挂到“MES基础资料”菜单下
SET @input_parent_id = NULL;
SET @parent_id = COALESCE(
  @input_parent_id,
  (SELECT id FROM sys_permission WHERE name = 'MES基础资料' LIMIT 1),
  (SELECT id FROM sys_permission WHERE perms = 'xslmes' LIMIT 1)
);

-- 2) 新增菜单（目录/菜单），避免重复插入
SET @menu_url = '/xslmes/mesXslClientConnection/list';
SET @menu_name = '客户端连接列表';
SET @menu_id = (
  SELECT id FROM sys_permission
  WHERE url = @menu_url AND menu_type = '1'
  LIMIT 1
);

INSERT INTO sys_permission (
  id, parent_id, name, perms, perms_type, menu_type, url, component, sort_no, status, del_flag, create_by, create_time
)
SELECT
  REPLACE(UUID(), '-', ''), @parent_id, @menu_name, NULL, '1', '1',
  @menu_url, 'xslmes/mesXslClientConnection/MesXslClientConnectionList', 100, '1', 0, 'admin', NOW()
FROM dual
WHERE @menu_id IS NULL AND @parent_id IS NOT NULL;

SET @menu_id = (
  SELECT id FROM sys_permission
  WHERE url = @menu_url AND menu_type = '1'
  LIMIT 1
);

-- 2.1) 若菜单已存在，则强制迁移到“MES基础资料”父菜单，并修正组件路径
UPDATE sys_permission
SET parent_id = @parent_id,
    component = 'xslmes/mesXslClientConnection/MesXslClientConnectionList',
    update_by = 'admin',
    update_time = NOW()
WHERE id = @menu_id
  AND @menu_id IS NOT NULL
  AND @parent_id IS NOT NULL;

-- 3) 新增按钮权限（接口权限点），避免重复插入
INSERT INTO sys_permission (
  id, parent_id, name, perms, perms_type, menu_type, url, component, sort_no, status, del_flag, create_by, create_time
)
SELECT
  REPLACE(UUID(), '-', ''), @menu_id, '查询', 'xslmes:mes_xsl_client_connection:list', '1', '2',
  NULL, NULL, 1, '1', 0, 'admin', NOW()
FROM dual
WHERE @menu_id IS NOT NULL
  AND NOT EXISTS (
    SELECT 1 FROM sys_permission WHERE perms = 'xslmes:mes_xsl_client_connection:list' LIMIT 1
  );

-- 4) 如果 @parent_id 为空，表示没找到 xslmes 菜单，需要你手工设置 @input_parent_id 再执行
SELECT @parent_id AS resolved_parent_id, @menu_id AS resolved_menu_id;
