-- 抄表记录菜单与 admin 授权（需在 dev 库执行，父菜单为「日常用电管理」）

INSERT INTO `SYSTEM_MENU` (`PARENT_ID`, `NAME`, `PATH`, `REMARK`, `ICON`, `DISABLED`, `SORT`, `FIXED`, `CREATE_TIME`, `UPDATE_TIME`, `CREATE_USER`, `UPDATE_USER`, `DELETED`, `PARAMS`)
SELECT m.`ID`, '抄表记录', '/business/ywelectricaldata', '电表抄表记录', NULL, 0,
       IFNULL((SELECT MAX(sm.`SORT`) FROM `SYSTEM_MENU` sm WHERE sm.`PARENT_ID` = m.`ID` AND sm.`DELETED` = 0), 0) + 1,
       0, CURRENT_TIMESTAMP, NULL, 1, NULL, 0, NULL
FROM `SYSTEM_MENU` m
WHERE m.`DELETED` = 0 AND m.`NAME` LIKE '%日常用电%'
  AND NOT EXISTS (SELECT 1 FROM `SYSTEM_MENU` x WHERE x.`DELETED` = 0 AND x.`PATH` = '/business/ywelectricaldata')
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/ywelectricaldata' AND menu.`DELETED` = 0
WHERE r.`DELETED` = 0 AND (r.`CODE` = 'admin' OR r.`NAME` = '管理员')
  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
  );

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:ywelectricaldata:query',
    'business:ywelectricaldata:exportExcel',
    'business:ywelectricaldata:sync'
) AND p.`DELETED` = 0
WHERE r.`DELETED` = 0 AND (r.`CODE` = 'admin' OR r.`NAME` = '管理员')
  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
  );
