-- 空调多联机：新增子菜单「空调设备管理」+ 超级管理员授权（可重复执行）

INSERT INTO `SYSTEM_MENU` (`PARENT_ID`, `NAME`, `PATH`, `REMARK`, `ICON`, `DISABLED`, `SORT`, `FIXED`, `CREATE_TIME`, `UPDATE_TIME`, `CREATE_USER`, `UPDATE_USER`, `DELETED`, `PARAMS`)
SELECT p.`ID`, '空调设备管理', '/business/ywconditionerdevice', '空调内机列表与房源关联维护', NULL, 0,
       IFNULL((SELECT MAX(sm.`SORT`) FROM `SYSTEM_MENU` sm WHERE sm.`PARENT_ID` = p.`ID` AND sm.`DELETED` = 0), 0) + 1,
       0, CURRENT_TIMESTAMP, NULL, 1, NULL, 0, NULL
FROM `SYSTEM_MENU` p
WHERE p.`DELETED` = 0 AND p.`NAME` = '空调多联机' AND (p.`PATH` IS NULL OR p.`PATH` = '')
  AND NOT EXISTS (SELECT 1 FROM `SYSTEM_MENU` x WHERE x.`DELETED` = 0 AND x.`PATH` = '/business/ywconditionerdevice')
LIMIT 1;

INSERT INTO `SYSTEM_ROLE_MENU` (`ROLE_ID`, `MENU_ID`, `CREATE_TIME`, `UPDATE_TIME`, `CREATE_USER`, `UPDATE_USER`, `DELETED`)
SELECT r.`ID`, menu.`ID`, CURRENT_TIMESTAMP, NULL, 1, NULL, 0
FROM `SYSTEM_ROLE` r
INNER JOIN `SYSTEM_MENU` menu ON menu.`PATH` = '/business/ywconditionerdevice' AND menu.`DELETED` = 0
WHERE r.`DELETED` = 0 AND (r.`CODE` = 'admin' OR r.`NAME` IN ('超级管理员', '管理员'))
  AND NOT EXISTS (
    SELECT 1 FROM `SYSTEM_ROLE_MENU` rm
    WHERE rm.`ROLE_ID` = r.`ID` AND rm.`MENU_ID` = menu.`ID` AND rm.`DELETED` = 0
  );
