-- 空调多联机：为超级管理员角色补全权限（可重复执行）
-- 执行后请重新登录以刷新 Redis 中的权限缓存

INSERT INTO `SYSTEM_PERMISSION`(`CODE`, `NAME`, `REMARK`, `FIXED`, `CREATE_USER`, `CREATE_TIME`, `UPDATE_USER`, `UPDATE_TIME`, `DELETED`)
SELECT 'business:ywconditioner:sync', '同步空调内机', '', 0, 1, CURRENT_TIMESTAMP, NULL, NULL, 0
WHERE NOT EXISTS (SELECT 1 FROM `SYSTEM_PERMISSION` WHERE `CODE` = 'business:ywconditioner:sync' AND `DELETED` = 0);

INSERT INTO `SYSTEM_PERMISSION`(`CODE`, `NAME`, `REMARK`, `FIXED`, `CREATE_USER`, `CREATE_TIME`, `UPDATE_USER`, `UPDATE_TIME`, `DELETED`)
SELECT 'business:ywconditioner:operate', '空调内机控制', '', 0, 1, CURRENT_TIMESTAMP, NULL, NULL, 0
WHERE NOT EXISTS (SELECT 1 FROM `SYSTEM_PERMISSION` WHERE `CODE` = 'business:ywconditioner:operate' AND `DELETED` = 0);

INSERT INTO `SYSTEM_ROLE_PERMISSION` (`ROLE_ID`, `PERMISSION_ID`, `CREATE_TIME`, `UPDATE_TIME`, `CREATE_USER`, `UPDATE_USER`, `DELETED`)
SELECT r.`ID`, p.`ID`, CURRENT_TIMESTAMP, NULL, 1, NULL, 0
FROM `SYSTEM_ROLE` r
INNER JOIN `SYSTEM_PERMISSION` p ON p.`CODE` IN (
    'business:ywconditioner:query',
    'business:ywconditioner:create',
    'business:ywconditioner:update',
    'business:ywconditioner:delete',
    'business:ywconditioner:exportExcel',
    'business:ywconditioner:sync',
    'business:ywconditioner:operate',
    'business:ywconditionergateway:query',
    'business:ywconditionergateway:sync',
    'business:ywconditionermeter:query',
    'business:ywconditionermeter:sync',
    'business:ywconditionermeter:operate',
    'business:ywconditionerbilling:query',
    'business:ywconditionerbilling:sync',
    'business:ywconditioneractions:query',
    'business:ywconditioneractions:exportExcel',
    'business:ywconditionerreport:query',
    'business:ywconditionerreport:sync',
    'business:ywconditionerreport:exportExcel'
) AND p.`DELETED` = 0
WHERE r.`DELETED` = 0 AND (r.`CODE` = 'admin' OR r.`NAME` IN ('超级管理员', '管理员'))
  AND NOT EXISTS (
    SELECT 1 FROM `SYSTEM_ROLE_PERMISSION` rp
    WHERE rp.`ROLE_ID` = r.`ID` AND rp.`PERMISSION_ID` = p.`ID` AND rp.`DELETED` = 0
  );

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.`DELETED` = 0 AND (
    (menu.`NAME` = '空调多联机' AND (menu.`PATH` IS NULL OR menu.`PATH` = ''))
    OR menu.`PATH` IN (
        '/business/ywconditioner',
        '/business/ywconditionergateway',
        '/business/ywconditionermeter',
        '/business/ywconditionerbilling',
        '/business/ywconditioneractions',
        '/business/ywconditionerreport'
    )
)
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
  );
