-- 20260630
-- 新增前台业务按钮权限点：
--   opportunity:create  新增商机
--   expansion:create    新增拓展
-- 执行后可在 frontend1 权限管理与角色权限绑定中维护这些权限。
-- 可重复执行；已执行过旧版本的环境，重新执行本脚本会修复父子关系和管理员授权。

begin;

set search_path to public;

do $$
declare
  v_business_parent_id bigint;
  v_expansion_menu_perm_id bigint;
  v_expansion_create_perm_id bigint;
  v_menu_perm_id bigint;
  v_create_perm_id bigint;
  v_has_role_permission_tenant boolean;
begin
  perform setval('sys_permission_perm_id_seq', coalesce((select max(perm_id) from sys_permission), 0) + 1, false);
  perform setval('sys_role_permission_id_seq', coalesce((select max(id) from sys_role_permission), 0) + 1, false);

  select exists (
    select 1
    from information_schema.columns
    where table_schema = current_schema()
      and table_name = 'sys_role_permission'
      and column_name = 'tenant_id'
  ) into v_has_role_permission_tenant;

  select perm_id
    into v_business_parent_id
  from sys_permission
  where code = 'crm'
  order by perm_id
  limit 1;

  if v_business_parent_id is null then
    insert into sys_permission (
      parent_id, name, code, perm_type, level, path, component, icon,
      sort_order, is_visible, status, description, meta, is_deleted, created_at, updated_at
    ) values (
      null, 'CRM业务', 'crm', 'directory', 1, null, null, 'AppstoreOutlined',
      10, 0, 1, 'CRM前台业务权限分组，仅用于权限管理，不在后台侧边栏显示', '{}'::jsonb, 0, now(), now()
    )
    returning perm_id into v_business_parent_id;
  else
    update sys_permission
    set name = 'CRM业务',
        perm_type = 'directory',
        level = 1,
        path = null,
        component = null,
        icon = coalesce(nullif(icon, ''), 'AppstoreOutlined'),
        sort_order = coalesce(sort_order, 10),
        is_visible = 0,
        status = 1,
        description = 'CRM前台业务权限分组，仅用于权限管理，不在后台侧边栏显示',
        meta = coalesce(meta, '{}'::jsonb),
        is_deleted = 0,
        updated_at = now()
    where perm_id = v_business_parent_id;
  end if;

  select perm_id
    into v_expansion_menu_perm_id
  from sys_permission
  where code = 'menu:expansion'
  order by perm_id
  limit 1;

  if v_expansion_menu_perm_id is null then
    insert into sys_permission (
      parent_id, name, code, perm_type, level, path, component, icon,
      sort_order, is_visible, status, description, meta, is_deleted, created_at, updated_at
    ) values (
      v_business_parent_id, '拓展', 'menu:expansion', 'menu', 2,
      null, null, 'TeamOutlined', 20, 0, 1,
      'CRM前台拓展管理页面权限分组，仅用于权限管理，不在后台侧边栏显示', '{}'::jsonb, 0, now(), now()
    )
    returning perm_id into v_expansion_menu_perm_id;
  else
    update sys_permission
    set parent_id = v_business_parent_id,
        name = '拓展',
        perm_type = 'menu',
        level = 2,
        path = null,
        component = null,
        icon = coalesce(nullif(icon, ''), 'TeamOutlined'),
        sort_order = coalesce(sort_order, 20),
        is_visible = 0,
        status = 1,
        description = 'CRM前台拓展管理页面权限分组，仅用于权限管理，不在后台侧边栏显示',
        meta = coalesce(meta, '{}'::jsonb),
        is_deleted = 0,
        updated_at = now()
    where perm_id = v_expansion_menu_perm_id;
  end if;

  select perm_id
    into v_expansion_create_perm_id
  from sys_permission
  where code = 'expansion:create'
  order by perm_id
  limit 1;

  if v_expansion_create_perm_id is null then
    insert into sys_permission (
      parent_id, name, code, perm_type, level, path, component, icon,
      sort_order, is_visible, status, description, meta, is_deleted, created_at, updated_at
    ) values (
      v_expansion_menu_perm_id, '新增拓展', 'expansion:create', 'button', 3,
      null, null, null, 1, 1, 1, '控制CRM前台拓展管理页面的新增按钮和销售/渠道拓展创建接口', '{}'::jsonb, 0, now(), now()
    )
    returning perm_id into v_expansion_create_perm_id;
  else
    update sys_permission
    set parent_id = v_expansion_menu_perm_id,
        name = '新增拓展',
        perm_type = 'button',
        level = 3,
        path = null,
        component = null,
        icon = null,
        sort_order = 1,
        is_visible = 1,
        status = 1,
        description = '控制CRM前台拓展管理页面的新增按钮和销售/渠道拓展创建接口',
        meta = '{}'::jsonb,
        is_deleted = 0,
        updated_at = now()
    where perm_id = v_expansion_create_perm_id;
  end if;

  select perm_id
    into v_menu_perm_id
  from sys_permission
  where code = 'menu:opportunities'
  order by perm_id
  limit 1;

  if v_menu_perm_id is null then
    insert into sys_permission (
      parent_id, name, code, perm_type, level, path, component, icon,
      sort_order, is_visible, status, description, meta, is_deleted, created_at, updated_at
    ) values (
      v_business_parent_id, '商机', 'menu:opportunities', 'menu', 2,
      null, null, 'BriefcaseOutlined', 30, 0, 1,
      'CRM前台商机储备页面权限分组，仅用于权限管理，不在后台侧边栏显示', '{}'::jsonb, 0, now(), now()
    )
    returning perm_id into v_menu_perm_id;
  else
    update sys_permission
    set parent_id = v_business_parent_id,
        name = '商机',
        perm_type = 'menu',
        level = 2,
        path = null,
        component = null,
        icon = coalesce(nullif(icon, ''), 'BriefcaseOutlined'),
        sort_order = coalesce(sort_order, 30),
        is_visible = 0,
        status = 1,
        description = 'CRM前台商机储备页面权限分组，仅用于权限管理，不在后台侧边栏显示',
        meta = coalesce(meta, '{}'::jsonb),
        is_deleted = 0,
        updated_at = now()
    where perm_id = v_menu_perm_id;
  end if;

  select perm_id
    into v_create_perm_id
  from sys_permission
  where code = 'opportunity:create'
  order by perm_id
  limit 1;

  if v_create_perm_id is null then
    insert into sys_permission (
      parent_id, name, code, perm_type, level, path, component, icon,
      sort_order, is_visible, status, description, meta, is_deleted, created_at, updated_at
    ) values (
      v_menu_perm_id, '新增商机', 'opportunity:create', 'button', 3,
      null, null, null, 1, 1, 1, '控制CRM前台商机储备页面的新增商机按钮和创建接口', '{}'::jsonb, 0, now(), now()
    )
    returning perm_id into v_create_perm_id;
  else
    update sys_permission
    set parent_id = v_menu_perm_id,
        name = '新增商机',
        perm_type = 'button',
        level = 3,
        path = null,
        component = null,
        icon = null,
        sort_order = 1,
        is_visible = 1,
        status = 1,
        description = '控制CRM前台商机储备页面的新增商机按钮和创建接口',
        meta = '{}'::jsonb,
        is_deleted = 0,
        updated_at = now()
    where perm_id = v_create_perm_id;
  end if;

  if v_has_role_permission_tenant then
    insert into sys_role_permission (role_id, perm_id, tenant_id, is_deleted, created_at, updated_at)
    select distinct r.role_id, permission_source.perm_id, r.tenant_id, 0, now(), now()
    from sys_role r
    cross join (
      select unnest(array[v_business_parent_id, v_expansion_menu_perm_id, v_expansion_create_perm_id, v_menu_perm_id, v_create_perm_id]) as perm_id
    ) permission_source
    where coalesce(r.is_deleted, 0) = 0
      and permission_source.perm_id is not null
      and (
        r.role_code in ('TENANT_ADMIN', 'ADMIN', 'SYS_ADMIN', 'PLATFORM_ADMIN', 'SUPER_ADMIN')
        or r.role_name ilike '%管理员%'
        or r.role_name ilike '%admin%'
      )
      and not exists (
        select 1
        from sys_role_permission rp
        where rp.role_id = r.role_id
          and rp.perm_id = permission_source.perm_id
      );

    update sys_role_permission rp
    set tenant_id = coalesce(rp.tenant_id, r.tenant_id),
        is_deleted = 0,
        updated_at = now()
    from sys_role r
    where rp.role_id = r.role_id
      and rp.perm_id in (v_business_parent_id, v_expansion_menu_perm_id, v_expansion_create_perm_id, v_menu_perm_id, v_create_perm_id)
      and coalesce(r.is_deleted, 0) = 0
      and (
        r.role_code in ('TENANT_ADMIN', 'ADMIN', 'SYS_ADMIN', 'PLATFORM_ADMIN', 'SUPER_ADMIN')
        or r.role_name ilike '%管理员%'
        or r.role_name ilike '%admin%'
      );
  else
    insert into sys_role_permission (role_id, perm_id, is_deleted, created_at, updated_at)
    select distinct r.role_id, permission_source.perm_id, 0, now(), now()
    from sys_role r
    cross join (
      select unnest(array[v_business_parent_id, v_expansion_menu_perm_id, v_expansion_create_perm_id, v_menu_perm_id, v_create_perm_id]) as perm_id
    ) permission_source
    where coalesce(r.is_deleted, 0) = 0
      and permission_source.perm_id is not null
      and (
        r.role_code in ('TENANT_ADMIN', 'ADMIN', 'SYS_ADMIN', 'PLATFORM_ADMIN', 'SUPER_ADMIN')
        or r.role_name ilike '%管理员%'
        or r.role_name ilike '%admin%'
      )
      and not exists (
        select 1
        from sys_role_permission rp
        where rp.role_id = r.role_id
          and rp.perm_id = permission_source.perm_id
      );

    update sys_role_permission rp
    set is_deleted = 0,
        updated_at = now()
    from sys_role r
    where rp.role_id = r.role_id
      and rp.perm_id in (v_business_parent_id, v_expansion_menu_perm_id, v_expansion_create_perm_id, v_menu_perm_id, v_create_perm_id)
      and coalesce(r.is_deleted, 0) = 0
      and (
        r.role_code in ('TENANT_ADMIN', 'ADMIN', 'SYS_ADMIN', 'PLATFORM_ADMIN', 'SUPER_ADMIN')
        or r.role_name ilike '%管理员%'
        or r.role_name ilike '%admin%'
      );
  end if;
end $$;

commit;
