-- 企业性质：企业可维护，PC 岗位卡片通过岗位关联企业读取。
-- 执行目标：对应环境 HighGo 数据库的 shz schema。
-- 企业性质非必填，具体字典项由后台“业务字典”维护。

BEGIN;

ALTER TABLE "shz"."company"
    ADD COLUMN IF NOT EXISTS "company_nature" VARCHAR(100);

COMMENT ON COLUMN "shz"."company"."company_nature"
    IS '企业性质，对应业务字典 company_nature，非必填';

INSERT INTO "shz"."bussiness_dict_type" (
    "dict_id", "dict_name", "dict_type", "status", "create_by", "create_time", "remark"
)
SELECT
    (SELECT COALESCE(MAX("dict_id"), 0) + 1 FROM "shz"."bussiness_dict_type"),
    '企业性质',
    'company_nature',
    '0',
    'system',
    CURRENT_TIMESTAMP,
    '企业信息及 PC 岗位卡片使用，字典项由业务字典维护'
WHERE NOT EXISTS (
    SELECT 1
    FROM "shz"."bussiness_dict_type"
    WHERE "dict_type" = 'company_nature'
);

-- 历史环境可能已有 company_nature 字典，但名称仍为“企业类型”，统一为需求名称。
UPDATE "shz"."bussiness_dict_type"
SET "dict_name" = '企业性质', "update_by" = 'system', "update_time" = CURRENT_TIMESTAMP
WHERE "dict_type" = 'company_nature' AND "dict_name" <> '企业性质';

-- 企业管理下增加“企业信息”菜单，并将其授权给已有企业管理菜单的角色。
INSERT INTO "shz"."sys_menu" (
    "menu_name", "parent_id", "order_num", "path", "component", "query", "route_name",
    "is_frame", "is_cache", "menu_type", "visible", "status", "perms", "icon",
    "create_by", "create_time", "remark", "menu_id"
)
SELECT
    '企业信息', parent."menu_id", 2, 'company/info/index', 'Company/Info/index', '', '',
    1, 0, 'C', '0', '0', 'cms:company:query', 'ProfileOutlined',
    'system', CURRENT_TIMESTAMP, '企业用户查看和编辑自身企业信息', ids."menu_id"
FROM (
    SELECT "menu_id"
    FROM "shz"."sys_menu"
    WHERE "path" = 'company' AND "menu_name" = '企业管理' AND "menu_type" = 'M'
    ORDER BY "menu_id"
    LIMIT 1
) parent
CROSS JOIN (
    SELECT COALESCE(MAX("menu_id"), 0) + 1 AS "menu_id"
    FROM "shz"."sys_menu"
) ids
WHERE NOT EXISTS (
    SELECT 1
    FROM "shz"."sys_menu"
    WHERE "path" = 'company/info/index'
);

INSERT INTO "shz"."sys_role_menu" ("role_id", "menu_id")
SELECT DISTINCT rm."role_id", target."menu_id"
FROM "shz"."sys_role_menu" rm
JOIN "shz"."sys_menu" parent ON parent."menu_id" = rm."menu_id"
JOIN "shz"."sys_menu" target ON target."parent_id" = parent."menu_id"
    AND target."path" = 'company/info/index'
WHERE parent."path" = 'company'
  AND parent."menu_type" = 'M'
  AND NOT EXISTS (
      SELECT 1
      FROM "shz"."sys_role_menu" existing
      WHERE existing."role_id" = rm."role_id"
        AND existing."menu_id" = target."menu_id"
  );

COMMIT;
