USE jiaheng_erp;

SET NAMES utf8mb4;

START TRANSACTION;

CREATE TABLE IF NOT EXISTS sys_org_employee_binding (
  id BIGINT PRIMARY KEY AUTO_INCREMENT COMMENT '主键ID',
  dept_id BIGINT NOT NULL COMMENT '组织脑图节点ID',
  employee_id BIGINT NOT NULL COMMENT '人员ID',
  sort_no INT NOT NULL DEFAULT 0 COMMENT '排序号',
  status VARCHAR(32) NOT NULL DEFAULT 'ACTIVE' COMMENT '状态',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  UNIQUE KEY uk_org_employee_binding (dept_id, employee_id),
  KEY idx_org_employee_binding_dept (dept_id, sort_no, id),
  KEY idx_org_employee_binding_employee (employee_id),
  CONSTRAINT fk_org_employee_binding_dept FOREIGN KEY (dept_id) REFERENCES sys_department(id),
  CONSTRAINT fk_org_employee_binding_employee FOREIGN KEY (employee_id) REFERENCES hr_employee(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统权限组织脑图人员绑定表';

INSERT INTO sys_department (
  dept_code,
  dept_name,
  parent_id,
  org_node_type,
  dept_type,
  manager_name,
  manager_employee_id,
  status,
  sort_no,
  remark
)
SELECT
  'ORG_ROOT',
  '总公司',
  NULL,
  'COMPANY',
  'ADMIN',
  NULL,
  NULL,
  'ACTIVE',
  0,
  '系统权限管理组织脑图根节点'
FROM DUAL
WHERE NOT EXISTS (
  SELECT 1 FROM sys_department WHERE dept_code = 'ORG_ROOT'
);

COMMIT;
