INSERT INTO permission (id, permission_code, permission_name, module)
SELECT t.next_id, 'template.manage', '管理模板', 'template'
FROM (SELECT IFNULL(MAX(id), 0) + 1 AS next_id FROM permission) t
WHERE NOT EXISTS (
    SELECT 1 FROM permission WHERE permission_code = 'template.manage'
);

INSERT INTO permission (id, permission_code, permission_name, module)
SELECT t.next_id, 'template.download.log.read.all', '查看全部模板下载日志', 'template'
FROM (SELECT IFNULL(MAX(id), 0) + 1 AS next_id FROM permission) t
WHERE NOT EXISTS (
    SELECT 1 FROM permission WHERE permission_code = 'template.download.log.read.all'
);

UPDATE permission SET permission_name='管理模板', module='template' WHERE permission_code='template.manage';
UPDATE permission SET permission_name='查看全部模板下载日志', module='template' WHERE permission_code='template.download.log.read.all';

UPDATE menu
SET permission_code='template.manage',
    updated_at=CURRENT_TIMESTAMP
WHERE tenant_id=1 AND route_path='/templates';

UPDATE menu
SET menu_name='模板查看下载',
    permission_code='template.read',
    updated_at=CURRENT_TIMESTAMP
WHERE tenant_id=1 AND route_path='/template-download-logs';

INSERT INTO role_permission (id, tenant_id, role_id, permission_id)
SELECT t.next_id, 1, 101, p.id
FROM (SELECT IFNULL(MAX(id), 0) + 1 AS next_id FROM role_permission) t
JOIN permission p ON p.permission_code = 'template.manage'
WHERE NOT EXISTS (
    SELECT 1 FROM role_permission rp WHERE rp.tenant_id=1 AND rp.role_id=101 AND rp.permission_id=p.id
);

INSERT INTO role_permission (id, tenant_id, role_id, permission_id)
SELECT t.next_id, 1, 101, p.id
FROM (SELECT IFNULL(MAX(id), 0) + 1 AS next_id FROM role_permission) t
JOIN permission p ON p.permission_code = 'template.download.log.read.all'
WHERE NOT EXISTS (
    SELECT 1 FROM role_permission rp WHERE rp.tenant_id=1 AND rp.role_id=101 AND rp.permission_id=p.id
);

SET @next_role_menu_id = (SELECT IFNULL(MAX(id), 0) FROM role_menu);
INSERT INTO role_menu (id, tenant_id, role_id, menu_id)
SELECT
    (@next_role_menu_id := @next_role_menu_id + 1) AS id,
    r.tenant_id,
    r.id,
    m.id
FROM role r
JOIN menu m ON m.tenant_id=r.tenant_id AND m.route_path='/templates' AND m.is_deleted=0
WHERE r.role_code='TENANT_ADMIN'
  AND r.is_deleted=0
  AND NOT EXISTS (
    SELECT 1 FROM role_menu rm WHERE rm.tenant_id=r.tenant_id AND rm.role_id=r.id AND rm.menu_id=m.id
  );

INSERT INTO role_menu (id, tenant_id, role_id, menu_id)
SELECT
    (@next_role_menu_id := @next_role_menu_id + 1) AS id,
    r.tenant_id,
    r.id,
    m.id
FROM role r
JOIN menu m ON m.tenant_id=r.tenant_id AND m.route_path='/template-download-logs' AND m.is_deleted=0
WHERE r.role_code='TENANT_ADMIN'
  AND r.is_deleted=0
  AND NOT EXISTS (
    SELECT 1 FROM role_menu rm WHERE rm.tenant_id=r.tenant_id AND rm.role_id=r.id AND rm.menu_id=m.id
  );
