-- 商户充值：一级菜单 + 2 子菜单 + 超级管理员菜单授权

INSERT INTO `SYSTEM_MENU` (`PARENT_ID`, `NAME`, `PATH`, `REMARK`, `ICON`, `DISABLED`, `SORT`, `FIXED`, `CREATE_TIME`, `UPDATE_TIME`, `CREATE_USER`, `UPDATE_USER`, `DELETED`, `PARAMS`)
SELECT 0, '商户充值', '', '商户电表/空调充值管理', NULL, 0,
       IFNULL((SELECT MAX(sm.`SORT`) FROM `SYSTEM_MENU` sm WHERE sm.`PARENT_ID` = 0 AND sm.`DELETED` = 0), 0) + 1,
       0, CURRENT_TIMESTAMP, NULL, 1, NULL, 0, NULL
WHERE NOT EXISTS (
    SELECT 1 FROM `SYSTEM_MENU` x WHERE x.`DELETED` = 0 AND x.`NAME` = '商户充值' AND (x.`PATH` IS NULL OR x.`PATH` = '')
);

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/ywcustomerrecharge', '商户列表、关联设备、充值', NULL, 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/ywcustomerrecharge')
LIMIT 1;

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/ywcustomerrechargerecord', '电表/空调统一充值记录', NULL, 0, 2, 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/ywcustomerrechargerecord')
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.`DELETED` = 0 AND (
    (menu.`NAME` = '商户充值' AND (menu.`PATH` IS NULL OR menu.`PATH` = ''))
    OR menu.`PATH` IN ('/business/ywcustomerrecharge', '/business/ywcustomerrechargerecord')
)
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
  );
