begin;

set search_path to public;

-- 本次正式增量升级脚本
-- 说明：
-- 1. 这份脚本会补齐：
--    - 首页经营分析配置表
--    - 首页卡片相关权限
--    - 商机快照字段 latest_progress / next_plan
--    - 渠道认证级别字段注释修正
--    - 平台菜单权限纠偏
-- 2. 不会写入默认业务卡片，也不会创建 sales_target_plan。
-- 3. 可重复执行。
-- 4. 如使用图形化数据库工具，请整份执行，不要逐行执行。

create table if not exists dashboard_analytics_panel_config (
  id bigint generated by default as identity primary key,
  tenant_id bigint not null,
  enabled boolean not null default false,
  title varchar(100) not null default '经营分析',
  subtitle varchar(255),
  empty_state_text varchar(255),
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now(),
  constraint uk_dashboard_analytics_panel_tenant unique (tenant_id)
);

create table if not exists dashboard_analytics_card_config (
  id bigint generated by default as identity primary key,
  tenant_id bigint not null,
  card_key varchar(100) not null,
  title varchar(100) not null,
  subtitle varchar(255),
  render_type varchar(20) not null default 'metric',
  sql_template text not null,
  value_field varchar(100) not null default 'value',
  description_field varchar(100),
  category_field varchar(100),
  color_field varchar(100),
  display_text_config text,
  unit varchar(20),
  value_type varchar(20) not null default 'number',
  sort_direction varchar(20) not null default 'sql',
  display_limit integer,
  layout_type varchar(20) not null default 'vertical',
  full_row boolean not null default false,
  link_path varchar(255),
  sort_order integer not null default 0,
  enabled boolean not null default true,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now(),
  constraint uk_dashboard_analytics_card_tenant_key unique (tenant_id, card_key)
);

create index if not exists idx_dashboard_analytics_card_tenant_sort
on dashboard_analytics_card_config (tenant_id, sort_order asc, id asc);

alter table if exists crm_opportunity
  add column if not exists latest_progress text,
  add column if not exists next_plan text;

alter table if exists crm_channel_expansion
  add column if not exists certification_level varchar(100);

alter table dashboard_analytics_card_config
  add column if not exists render_type varchar(20) not null default 'metric';

alter table dashboard_analytics_card_config
  add column if not exists category_field varchar(100);

alter table dashboard_analytics_card_config
  add column if not exists color_field varchar(100);

alter table dashboard_analytics_card_config
  add column if not exists display_text_config text;

alter table dashboard_analytics_card_config
  add column if not exists sort_direction varchar(20) not null default 'sql';

alter table dashboard_analytics_card_config
  add column if not exists display_limit integer;

alter table dashboard_analytics_card_config
  add column if not exists layout_type varchar(20) not null default 'vertical';

alter table dashboard_analytics_card_config
  add column if not exists full_row boolean not null default false;

comment on column crm_opportunity.latest_progress is '项目最新进展';
comment on column crm_opportunity.next_plan is '下一步销售计划';
comment on column crm_channel_expansion.certification_level is '汇智内部认证级别';

do $$
declare
  v_has_role_permission_tenant boolean;
begin
  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;

  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
  )
  select
    null, '系统管理', 'system', 'directory', 1, null, null, 'SettingOutlined',
    110, 1, 1, '系统管理目录', '{}'::jsonb, 0, now(), now()
  where not exists (
    select 1
    from sys_permission
    where code = 'system'
  );

  update sys_permission
  set parent_id = null,
      name = '系统管理',
      perm_type = 'directory',
      level = 1,
      path = null,
      component = null,
      icon = 'SettingOutlined',
      sort_order = 110,
      is_visible = 1,
      status = 1,
      description = '系统管理目录',
      meta = '{}'::jsonb,
      is_deleted = 0,
      updated_at = now()
  where perm_id = (
    select perm_id
    from sys_permission
    where code = 'system'
    order by coalesce(is_deleted, 0) asc, perm_id asc
    limit 1
  );

  update sys_permission
  set is_deleted = 1,
      updated_at = now()
  where code = 'system'
    and perm_id <> (
      select perm_id
      from sys_permission
      where code = 'system'
      order by coalesce(is_deleted, 0) asc, perm_id asc
      limit 1
    );

  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
  )
  select
    system_perm.perm_id, '前台首页', 'menu:frontend-home', 'menu', 2, null, null, 'HomeOutlined',
    7, 0, 1, '前台首页相关权限分组', '{}'::jsonb, 0, now(), now()
  from (
    select perm_id
    from sys_permission
    where code = 'system'
    order by coalesce(is_deleted, 0) asc, perm_id asc
    limit 1
  ) system_perm
  where not exists (
    select 1
    from sys_permission
    where code = 'menu:frontend-home'
  );

  update sys_permission
  set parent_id = (
        select perm_id
        from sys_permission
        where code = 'system'
        order by coalesce(is_deleted, 0) asc, perm_id asc
        limit 1
      ),
      name = '前台首页',
      perm_type = 'menu',
      level = 2,
      path = null,
      component = null,
      icon = 'HomeOutlined',
      sort_order = 7,
      is_visible = 0,
      status = 1,
      description = '前台首页相关权限分组',
      meta = '{}'::jsonb,
      is_deleted = 0,
      updated_at = now()
  where perm_id = (
    select perm_id
    from sys_permission
    where code = 'menu:frontend-home'
    order by coalesce(is_deleted, 0) asc, perm_id asc
    limit 1
  );

  update sys_permission
  set is_deleted = 1,
      updated_at = now()
  where code = 'menu:frontend-home'
    and perm_id <> (
      select perm_id
      from sys_permission
      where code = 'menu:frontend-home'
      order by coalesce(is_deleted, 0) asc, perm_id asc
      limit 1
    );

  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
  )
  select
    parent_perm.perm_id, '查看首页待办卡片', 'dashboard_todo_card:view', 'button', 3, null, null, null,
    20, 1, 1, '控制首页待办事项卡片是否可见', '{}'::jsonb, 0, now(), now()
  from (
    select perm_id
    from sys_permission
    where code = 'menu:frontend-home'
    order by coalesce(is_deleted, 0) asc, perm_id asc
    limit 1
  ) parent_perm
  where not exists (
    select 1
    from sys_permission
    where code = 'dashboard_todo_card:view'
  );

  update sys_permission
  set parent_id = (
        select perm_id
        from sys_permission
        where code = 'menu:frontend-home'
        order by coalesce(is_deleted, 0) asc, perm_id asc
        limit 1
      ),
      name = '查看首页待办卡片',
      perm_type = 'button',
      level = 3,
      path = null,
      component = null,
      icon = null,
      sort_order = 20,
      is_visible = 1,
      status = 1,
      description = '控制首页待办事项卡片是否可见',
      meta = '{}'::jsonb,
      is_deleted = 0,
      updated_at = now()
  where perm_id = (
    select perm_id
    from sys_permission
    where code = 'dashboard_todo_card:view'
    order by coalesce(is_deleted, 0) asc, perm_id asc
    limit 1
  );

  update sys_permission
  set is_deleted = 1,
      updated_at = now()
  where code = 'dashboard_todo_card:view'
    and perm_id <> (
      select perm_id
      from sys_permission
      where code = 'dashboard_todo_card:view'
      order by coalesce(is_deleted, 0) asc, perm_id asc
      limit 1
    );

  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
  )
  select
    parent_perm.perm_id, '查看首页最新动态卡片', 'dashboard_activity_card:view', 'button', 3, null, null, null,
    21, 1, 1, '控制首页最新动态卡片是否可见', '{}'::jsonb, 0, now(), now()
  from (
    select perm_id
    from sys_permission
    where code = 'menu:frontend-home'
    order by coalesce(is_deleted, 0) asc, perm_id asc
    limit 1
  ) parent_perm
  where not exists (
    select 1
    from sys_permission
    where code = 'dashboard_activity_card:view'
  );

  update sys_permission
  set parent_id = (
        select perm_id
        from sys_permission
        where code = 'menu:frontend-home'
        order by coalesce(is_deleted, 0) asc, perm_id asc
        limit 1
      ),
      name = '查看首页最新动态卡片',
      perm_type = 'button',
      level = 3,
      path = null,
      component = null,
      icon = null,
      sort_order = 21,
      is_visible = 1,
      status = 1,
      description = '控制首页最新动态卡片是否可见',
      meta = '{}'::jsonb,
      is_deleted = 0,
      updated_at = now()
  where perm_id = (
    select perm_id
    from sys_permission
    where code = 'dashboard_activity_card:view'
    order by coalesce(is_deleted, 0) asc, perm_id asc
    limit 1
  );

  update sys_permission
  set is_deleted = 1,
      updated_at = now()
  where code = 'dashboard_activity_card:view'
    and perm_id <> (
      select perm_id
      from sys_permission
      where code = 'dashboard_activity_card:view'
      order by coalesce(is_deleted, 0) asc, perm_id asc
      limit 1
    );

  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
  )
  select
    parent_perm.perm_id, '查看首页指标卡', 'dashboard_stats_card:view', 'button', 3, null, null, null,
    19, 1, 1, '控制首页顶部指标卡是否可见', '{}'::jsonb, 0, now(), now()
  from (
    select perm_id
    from sys_permission
    where code = 'menu:frontend-home'
    order by coalesce(is_deleted, 0) asc, perm_id asc
    limit 1
  ) parent_perm
  where not exists (
    select 1
    from sys_permission
    where code = 'dashboard_stats_card:view'
  );

  update sys_permission
  set parent_id = (
        select perm_id
        from sys_permission
        where code = 'menu:frontend-home'
        order by coalesce(is_deleted, 0) asc, perm_id asc
        limit 1
      ),
      name = '查看首页指标卡',
      perm_type = 'button',
      level = 3,
      path = null,
      component = null,
      icon = null,
      sort_order = 19,
      is_visible = 1,
      status = 1,
      description = '控制首页顶部指标卡是否可见',
      meta = '{}'::jsonb,
      is_deleted = 0,
      updated_at = now()
  where perm_id = (
    select perm_id
    from sys_permission
    where code = 'dashboard_stats_card:view'
    order by coalesce(is_deleted, 0) asc, perm_id asc
    limit 1
  );

  update sys_permission
  set is_deleted = 1,
      updated_at = now()
  where code = 'dashboard_stats_card:view'
    and perm_id <> (
      select perm_id
      from sys_permission
      where code = 'dashboard_stats_card:view'
      order by coalesce(is_deleted, 0) asc, perm_id asc
      limit 1
    );

  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
  )
  select
    parent_perm.perm_id, '查看首页经营分析卡片', 'dashboard_analytics_card:view', 'button', 3, null, null, null,
    22, 1, 1, '控制首页经营分析卡片是否可见', '{}'::jsonb, 0, now(), now()
  from (
    select perm_id
    from sys_permission
    where code = 'menu:frontend-home'
    order by coalesce(is_deleted, 0) asc, perm_id asc
    limit 1
  ) parent_perm
  where not exists (
    select 1
    from sys_permission
    where code = 'dashboard_analytics_card:view'
  );

  update sys_permission
  set parent_id = (
        select perm_id
        from sys_permission
        where code = 'menu:frontend-home'
        order by coalesce(is_deleted, 0) asc, perm_id asc
        limit 1
      ),
      name = '查看首页经营分析卡片',
      perm_type = 'button',
      level = 3,
      path = null,
      component = null,
      icon = null,
      sort_order = 22,
      is_visible = 1,
      status = 1,
      description = '控制首页经营分析卡片是否可见',
      meta = '{}'::jsonb,
      is_deleted = 0,
      updated_at = now()
  where perm_id = (
    select perm_id
    from sys_permission
    where code = 'dashboard_analytics_card:view'
    order by coalesce(is_deleted, 0) asc, perm_id asc
    limit 1
  );

  update sys_permission
  set is_deleted = 1,
      updated_at = now()
  where code = 'dashboard_analytics_card:view'
    and perm_id <> (
      select perm_id
      from sys_permission
      where code = 'dashboard_analytics_card:view'
      order by coalesce(is_deleted, 0) asc, perm_id asc
      limit 1
    );

  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
  )
  select
    system_perm.perm_id, '首页经营分析配置', 'menu:dashboard-analytics-settings', 'menu', 2,
    '/dashboard-analytics-settings', null, 'FundProjectionScreenOutlined',
    8, 1, 1, '首页经营分析卡片 SQL 配置页面', '{}'::jsonb, 0, now(), now()
  from (
    select perm_id
    from sys_permission
    where code = 'system'
    order by coalesce(is_deleted, 0) asc, perm_id asc
    limit 1
  ) system_perm
  where not exists (
    select 1
    from sys_permission
    where code = 'menu:dashboard-analytics-settings'
  );

  update sys_permission
  set parent_id = (
        select perm_id
        from sys_permission
        where code = 'system'
        order by coalesce(is_deleted, 0) asc, perm_id asc
        limit 1
      ),
      name = '首页经营分析配置',
      perm_type = 'menu',
      level = 2,
      path = '/dashboard-analytics-settings',
      component = null,
      icon = 'FundProjectionScreenOutlined',
      sort_order = 8,
      is_visible = 1,
      status = 1,
      description = '首页经营分析卡片 SQL 配置页面',
      meta = '{}'::jsonb,
      is_deleted = 0,
      updated_at = now()
  where perm_id = (
    select perm_id
    from sys_permission
    where code = 'menu:dashboard-analytics-settings'
    order by coalesce(is_deleted, 0) asc, perm_id asc
    limit 1
  );

  update sys_permission
  set is_deleted = 1,
      updated_at = now()
  where code = 'menu:dashboard-analytics-settings'
    and perm_id <> (
      select perm_id
      from sys_permission
      where code = 'menu:dashboard-analytics-settings'
      order by coalesce(is_deleted, 0) asc, perm_id asc
      limit 1
    );

  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
  )
  select
    parent_perm.perm_id, '查看首页经营分析配置', 'dashboard_analytics_config:view', 'button', 3, null, null, null,
    30, 1, 1, '查看首页经营分析配置', '{}'::jsonb, 0, now(), now()
  from (
    select perm_id
    from sys_permission
    where code = 'menu:dashboard-analytics-settings'
    order by coalesce(is_deleted, 0) asc, perm_id asc
    limit 1
  ) parent_perm
  where not exists (
    select 1
    from sys_permission
    where code = 'dashboard_analytics_config:view'
  );

  update sys_permission
  set parent_id = (
        select perm_id
        from sys_permission
        where code = 'menu:dashboard-analytics-settings'
        order by coalesce(is_deleted, 0) asc, perm_id asc
        limit 1
      ),
      name = '查看首页经营分析配置',
      perm_type = 'button',
      level = 3,
      path = null,
      component = null,
      icon = null,
      sort_order = 30,
      is_visible = 1,
      status = 1,
      description = '查看首页经营分析配置',
      meta = '{}'::jsonb,
      is_deleted = 0,
      updated_at = now()
  where perm_id = (
    select perm_id
    from sys_permission
    where code = 'dashboard_analytics_config:view'
    order by coalesce(is_deleted, 0) asc, perm_id asc
    limit 1
  );

  update sys_permission
  set is_deleted = 1,
      updated_at = now()
  where code = 'dashboard_analytics_config:view'
    and perm_id <> (
      select perm_id
      from sys_permission
      where code = 'dashboard_analytics_config:view'
      order by coalesce(is_deleted, 0) asc, perm_id asc
      limit 1
    );

  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
  )
  select
    parent_perm.perm_id, '修改首页经营分析配置', 'dashboard_analytics_config:update', 'button', 3, null, null, null,
    31, 1, 1, '修改首页经营分析配置', '{}'::jsonb, 0, now(), now()
  from (
    select perm_id
    from sys_permission
    where code = 'menu:dashboard-analytics-settings'
    order by coalesce(is_deleted, 0) asc, perm_id asc
    limit 1
  ) parent_perm
  where not exists (
    select 1
    from sys_permission
    where code = 'dashboard_analytics_config:update'
  );

  update sys_permission
  set parent_id = (
        select perm_id
        from sys_permission
        where code = 'menu:dashboard-analytics-settings'
        order by coalesce(is_deleted, 0) asc, perm_id asc
        limit 1
      ),
      name = '修改首页经营分析配置',
      perm_type = 'button',
      level = 3,
      path = null,
      component = null,
      icon = null,
      sort_order = 31,
      is_visible = 1,
      status = 1,
      description = '修改首页经营分析配置',
      meta = '{}'::jsonb,
      is_deleted = 0,
      updated_at = now()
  where perm_id = (
    select perm_id
    from sys_permission
    where code = 'dashboard_analytics_config:update'
    order by coalesce(is_deleted, 0) asc, perm_id asc
    limit 1
  );

  update sys_permission
  set is_deleted = 1,
      updated_at = now()
  where code = 'dashboard_analytics_config:update'
    and perm_id <> (
      select perm_id
      from sys_permission
      where code = 'dashboard_analytics_config:update'
      order by coalesce(is_deleted, 0) asc, perm_id asc
      limit 1
    );

  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
  )
  select
    parent_perm.perm_id, '预览首页经营分析配置', 'dashboard_analytics_config:preview', 'button', 3, null, null, null,
    32, 1, 1, '预览首页经营分析配置', '{}'::jsonb, 0, now(), now()
  from (
    select perm_id
    from sys_permission
    where code = 'menu:dashboard-analytics-settings'
    order by coalesce(is_deleted, 0) asc, perm_id asc
    limit 1
  ) parent_perm
  where not exists (
    select 1
    from sys_permission
    where code = 'dashboard_analytics_config:preview'
  );

  update sys_permission
  set parent_id = (
        select perm_id
        from sys_permission
        where code = 'menu:dashboard-analytics-settings'
        order by coalesce(is_deleted, 0) asc, perm_id asc
        limit 1
      ),
      name = '预览首页经营分析配置',
      perm_type = 'button',
      level = 3,
      path = null,
      component = null,
      icon = null,
      sort_order = 32,
      is_visible = 1,
      status = 1,
      description = '预览首页经营分析配置',
      meta = '{}'::jsonb,
      is_deleted = 0,
      updated_at = now()
  where perm_id = (
    select perm_id
    from sys_permission
    where code = 'dashboard_analytics_config:preview'
    order by coalesce(is_deleted, 0) asc, perm_id asc
    limit 1
  );

  update sys_permission
  set is_deleted = 1,
      updated_at = now()
  where code = 'dashboard_analytics_config:preview'
    and perm_id <> (
      select perm_id
      from sys_permission
      where code = 'dashboard_analytics_config:preview'
      order by coalesce(is_deleted, 0) asc, perm_id asc
      limit 1
    );

  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
      r.role_id,
      p.perm_id,
      r.tenant_id,
      0,
      now(),
      now()
    from sys_role r
    join sys_permission p
      on p.code in (
        'system',
        'menu:frontend-home',
        'dashboard_todo_card:view',
        'dashboard_activity_card:view',
        'dashboard_stats_card:view',
        'dashboard_analytics_card:view',
        'menu:dashboard-analytics-settings',
        'dashboard_analytics_config:view',
        'dashboard_analytics_config:update',
        'dashboard_analytics_config:preview'
      )
     and coalesce(p.is_deleted, 0) = 0
    where 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%'
      )
      and not exists (
        select 1
        from sys_role_permission rp
        where rp.role_id = r.role_id
          and rp.perm_id = p.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,
         sys_permission p
    where rp.role_id = r.role_id
      and p.perm_id = rp.perm_id
      and coalesce(r.is_deleted, 0) = 0
      and p.code in (
        'system',
        'menu:frontend-home',
        'dashboard_todo_card:view',
        'dashboard_activity_card:view',
        'dashboard_stats_card:view',
        'dashboard_analytics_card:view',
        'menu:dashboard-analytics-settings',
        'dashboard_analytics_config:view',
        'dashboard_analytics_config:update',
        'dashboard_analytics_config:preview'
      )
      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
      r.role_id,
      p.perm_id,
      0,
      now(),
      now()
    from sys_role r
    join sys_permission p
      on p.code in (
        'system',
        'menu:frontend-home',
        'dashboard_todo_card:view',
        'dashboard_activity_card:view',
        'dashboard_stats_card:view',
        'dashboard_analytics_card:view',
        'menu:dashboard-analytics-settings',
        'dashboard_analytics_config:view',
        'dashboard_analytics_config:update',
        'dashboard_analytics_config:preview'
      )
     and coalesce(p.is_deleted, 0) = 0
    where 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%'
      )
      and not exists (
        select 1
        from sys_role_permission rp
        where rp.role_id = r.role_id
          and rp.perm_id = p.perm_id
      );

    update sys_role_permission rp
    set is_deleted = 0,
        updated_at = now()
    from sys_role r,
         sys_permission p
    where rp.role_id = r.role_id
      and p.perm_id = rp.perm_id
      and coalesce(r.is_deleted, 0) = 0
      and p.code in (
        'system',
        'menu:frontend-home',
        'dashboard_todo_card:view',
        'dashboard_activity_card:view',
        'dashboard_stats_card:view',
        'dashboard_analytics_card:view',
        'menu:dashboard-analytics-settings',
        'dashboard_analytics_config:view',
        'dashboard_analytics_config:update',
        'dashboard_analytics_config:preview'
      )
      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 $$;

do $$
declare
  v_has_role_permission_tenant boolean;
  v_system_perm_id bigint;
begin
  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_system_perm_id
  from sys_permission
  where code = 'system'
    and coalesce(is_deleted, 0) = 0
  order by perm_id asc
  limit 1;

  if v_has_role_permission_tenant then
    update sys_role_permission rp
    set is_deleted = 1,
        updated_at = now()
    from sys_role r,
         sys_permission p
    where rp.role_id = r.role_id
      and rp.perm_id = p.perm_id
      and coalesce(rp.is_deleted, 0) = 0
      and coalesce(r.is_deleted, 0) = 0
      and coalesce(p.is_deleted, 0) = 0
      and coalesce(r.tenant_id, 0) <> 0
      and (
        p.code in ('platform', 'menu:platform')
        or p.path = '/platform-settings'
      );

    insert into sys_role_permission (role_id, perm_id, tenant_id, is_deleted, created_at, updated_at)
    select distinct
      r.role_id,
      v_system_perm_id,
      coalesce(rp.tenant_id, r.tenant_id),
      0,
      now(),
      now()
    from sys_role_permission rp
    join sys_role r on r.role_id = rp.role_id
    join sys_permission p on p.perm_id = rp.perm_id
    where v_system_perm_id is not null
      and coalesce(rp.is_deleted, 0) = 0
      and coalesce(r.is_deleted, 0) = 0
      and coalesce(p.is_deleted, 0) = 0
      and p.parent_id = v_system_perm_id
      and not exists (
        select 1
        from sys_role_permission rp_system
        where rp_system.role_id = r.role_id
          and rp_system.perm_id = v_system_perm_id
          and coalesce(rp_system.is_deleted, 0) = 0
      );

    update sys_role_permission rp_system
    set tenant_id = coalesce(rp_system.tenant_id, r.tenant_id),
        is_deleted = 0,
        updated_at = now()
    from sys_role r
    where v_system_perm_id is not null
      and rp_system.role_id = r.role_id
      and rp_system.perm_id = v_system_perm_id
      and coalesce(r.is_deleted, 0) = 0;
  else
    update sys_role_permission rp
    set is_deleted = 1,
        updated_at = now()
    from sys_role r,
         sys_permission p
    where rp.role_id = r.role_id
      and rp.perm_id = p.perm_id
      and coalesce(rp.is_deleted, 0) = 0
      and coalesce(r.is_deleted, 0) = 0
      and coalesce(p.is_deleted, 0) = 0
      and (
        r.role_code in ('TENANT_ADMIN', 'ADMIN', 'SYS_ADMIN')
        or r.role_name ilike '%租户管理员%'
      )
      and (
        p.code in ('platform', 'menu:platform')
        or p.path = '/platform-settings'
      );

    insert into sys_role_permission (role_id, perm_id, is_deleted, created_at, updated_at)
    select distinct
      r.role_id,
      v_system_perm_id,
      0,
      now(),
      now()
    from sys_role_permission rp
    join sys_role r on r.role_id = rp.role_id
    join sys_permission p on p.perm_id = rp.perm_id
    where v_system_perm_id is not null
      and coalesce(rp.is_deleted, 0) = 0
      and coalesce(r.is_deleted, 0) = 0
      and coalesce(p.is_deleted, 0) = 0
      and p.parent_id = v_system_perm_id
      and not exists (
        select 1
        from sys_role_permission rp_system
        where rp_system.role_id = r.role_id
          and rp_system.perm_id = v_system_perm_id
          and coalesce(rp_system.is_deleted, 0) = 0
      );

    update sys_role_permission rp_system
    set is_deleted = 0,
        updated_at = now()
    where v_system_perm_id is not null
      and rp_system.perm_id = v_system_perm_id;
  end if;
end
$$;

commit;
