-- ============================================================
-- 菜单：客户中心下增加「经销商管理」（幂等）
-- component/path 对齐前端 views/customer/dealer
-- keep_alive：0=开启缓存；affix_tab：0=固定（输出到前端 meta 时取反）
-- 注意：nl_menu 无 type/status 列，勿照搬其它脚手架字段
-- ============================================================

SET @db := DATABASE();
SET @parent_id := (
    SELECT id FROM nl_menu WHERE name = 'Customer' AND deleted_at = 0 LIMIT 1
);

SET @exists := (
    SELECT COUNT(*) FROM nl_menu
    WHERE name = 'CustomerDealer' AND deleted_at = 0
);

-- 插在「微信用户」后：sort=1；企业管理及之后在 menu-sync / 手工时再调序
SET @sql := IF(@parent_id IS NOT NULL AND @exists = 0,
    CONCAT(
        'INSERT INTO `nl_menu` (`title`,`icon`,`name`,`path`,`component`,`redirect`,`keep_alive`,`hide_in_menu`,`affix_tab`,`badge`,`badge_type`,`badge_variants`,`iframe_src`,`pid`,`sort`,`query`,`created_at`,`updated_at`,`deleted_at`) VALUES (',
        '''经销商管理'', ''lucide:handshake'', ''CustomerDealer'', ''/customer/dealer'', ''/customer/dealer/index'', '''', 1, 0, 1, '''', 0, 0, '''', ',
        @parent_id,
        ', 1, '''', UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), 0)'
    ),
    'SELECT ''skip menu CustomerDealer'' AS msg'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- 与 lgp_menu 口径一致：企业/清单/订单 sort 后移（仅当经销商菜单刚存在时幂等更新）
UPDATE `nl_menu` SET `sort` = 2, `updated_at` = UNIX_TIMESTAMP()
WHERE `name` = 'CustomerEnterprise' AND `deleted_at` = 0 AND `sort` < 2;
UPDATE `nl_menu` SET `sort` = 3, `updated_at` = UNIX_TIMESTAMP()
WHERE `name` = 'CustomerList' AND `deleted_at` = 0 AND `sort` < 3;
UPDATE `nl_menu` SET `sort` = 4, `updated_at` = UNIX_TIMESTAMP()
WHERE `name` = 'CustomerOrder' AND `deleted_at` = 0 AND `sort` < 4;

-- 凡已拥有「微信用户」菜单的角色，同步挂上「经销商管理」（幂等）
SET @menu_id := (SELECT id FROM nl_menu WHERE name = 'CustomerDealer' AND deleted_at = 0 LIMIT 1);
SET @wx_user_menu_id := (SELECT id FROM nl_menu WHERE name = 'CustomerWxUser' AND deleted_at = 0 LIMIT 1);
INSERT INTO `nl_role_menu_relations` (`role_id`, `menu_id`, `created_at`)
SELECT r.role_id, @menu_id, UNIX_TIMESTAMP()
FROM `nl_role_menu_relations` r
WHERE @menu_id IS NOT NULL
  AND @wx_user_menu_id IS NOT NULL
  AND r.menu_id = @wx_user_menu_id
  AND NOT EXISTS (
      SELECT 1 FROM `nl_role_menu_relations` x
      WHERE x.role_id = r.role_id AND x.menu_id = @menu_id
  );
