USE jiaheng_erp;

SET NAMES utf8mb4;

START TRANSACTION;

SET @schema_name := DATABASE();

SET @sql := (
  SELECT IF(
    EXISTS (
      SELECT 1
      FROM information_schema.columns
      WHERE table_schema = @schema_name
        AND table_name = 'sys_department'
        AND column_name = 'org_node_type'
    ),
    'SELECT 1',
    'ALTER TABLE sys_department ADD COLUMN org_node_type VARCHAR(32) NOT NULL DEFAULT ''DEPARTMENT'' COMMENT ''组织节点类型：COMPANY/BRANCH/DEPARTMENT'' AFTER parent_id'
  )
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @sql := (
  SELECT IF(
    EXISTS (
      SELECT 1
      FROM information_schema.columns
      WHERE table_schema = @schema_name
        AND table_name = 'sys_department'
        AND column_name = 'manager_employee_id'
    ),
    'SELECT 1',
    'ALTER TABLE sys_department ADD COLUMN manager_employee_id BIGINT NULL COMMENT ''负责人员工ID'' AFTER manager_name'
  )
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @sql := (
  SELECT IF(
    EXISTS (
      SELECT 1
      FROM information_schema.statistics
      WHERE table_schema = @schema_name
        AND table_name = 'sys_department'
        AND index_name = 'idx_department_parent_sort'
    ),
    'SELECT 1',
    'CREATE INDEX idx_department_parent_sort ON sys_department(parent_id, sort_no, id)'
  )
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

INSERT INTO sys_permission (permission_code, permission_name, module_code, action_code, status)
SELECT 'MENU_SYSTEM_PERMISSION', '系统权限管理菜单', 'SYSTEM_PERMISSION', 'VIEW', 'ACTIVE'
FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM sys_permission WHERE permission_code = 'MENU_SYSTEM_PERMISSION');

UPDATE sys_role
SET role_name = '超级管理员', remark = '系统全局权限、角色、人员账号维护'
WHERE role_code = 'ADMIN';

UPDATE sys_role
SET role_name = '采购专员', remark = '供应商、采购订单、到货和采购相关库存查询'
WHERE role_code = 'PURCHASER';

UPDATE sys_role
SET role_name = '仓库管理人员', remark = '到货、质检、嘉恒仓库、发货台账相关作业'
WHERE role_code = 'WAREHOUSE';

UPDATE sys_role
SET role_name = '销售人员', remark = '客户、销售订单、发货台账查询与协同'
WHERE role_code = 'SALES';

INSERT INTO sys_role_permission (role_id, permission_id)
SELECT r.id, p.id
FROM sys_role r
JOIN sys_permission p ON p.permission_code IN ('MENU_SYSTEM_PERMISSION', 'MENU_SYSTEM_EXTENSION')
LEFT JOIN sys_role_permission existing ON existing.role_id = r.id AND existing.permission_id = p.id
WHERE r.role_code = 'ADMIN' AND existing.id IS NULL;

COMMIT;
