SET @next_role_id := (SELECT IFNULL(MAX(id), 0) FROM role);

INSERT INTO role (id, tenant_id, role_code, role_name, status, is_deleted, created_by, updated_by)
SELECT
    (@next_role_id := @next_role_id + 1) AS id,
    t.id AS tenant_id,
    'TENANT_ADMIN' AS role_code,
    '单位管理员' AS role_name,
    'ENABLED' AS status,
    0 AS is_deleted,
    0 AS created_by,
    0 AS updated_by
FROM tenant t
LEFT JOIN role r ON r.tenant_id=t.id AND r.role_code='TENANT_ADMIN' AND r.is_deleted=0
WHERE t.is_deleted=0 AND r.id IS NULL;

SET @template_role_id := (
    SELECT id FROM role
    WHERE tenant_id=1 AND role_code='TENANT_ADMIN' AND is_deleted=0
    LIMIT 1
);

SET @next_role_permission_id := (SELECT IFNULL(MAX(id), 0) FROM role_permission);

INSERT INTO role_permission (id, tenant_id, role_id, permission_id)
SELECT
    (@next_role_permission_id := @next_role_permission_id + 1) AS id,
    target_role.tenant_id,
    target_role.id AS role_id,
    template_perm.permission_id
FROM role target_role
JOIN role_permission template_perm ON template_perm.tenant_id=1 AND template_perm.role_id=@template_role_id
LEFT JOIN role_permission existing_perm
    ON existing_perm.tenant_id=target_role.tenant_id
    AND existing_perm.role_id=target_role.id
    AND existing_perm.permission_id=template_perm.permission_id
WHERE target_role.is_deleted=0
  AND target_role.role_code='TENANT_ADMIN'
  AND existing_perm.id IS NULL;

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,
    target_role.tenant_id,
    target_role.id AS role_id,
    template_menu.menu_id
FROM role target_role
JOIN role_menu template_menu ON template_menu.tenant_id=1 AND template_menu.role_id=@template_role_id
LEFT JOIN role_menu existing_menu
    ON existing_menu.tenant_id=target_role.tenant_id
    AND existing_menu.role_id=target_role.id
    AND existing_menu.menu_id=template_menu.menu_id
WHERE target_role.is_deleted=0
  AND target_role.role_code='TENANT_ADMIN'
  AND existing_menu.id IS NULL;
