USE jiaheng_erp;

SET NAMES utf8mb4;

START TRANSACTION;

CREATE TABLE IF NOT EXISTS sys_org_manager_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_manager_binding (dept_id, employee_id),
  KEY idx_org_manager_binding_dept (dept_id, sort_no, id),
  KEY idx_org_manager_binding_employee (employee_id),
  CONSTRAINT fk_org_manager_binding_dept FOREIGN KEY (dept_id) REFERENCES sys_department(id),
  CONSTRAINT fk_org_manager_binding_employee FOREIGN KEY (employee_id) REFERENCES hr_employee(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统权限组织脑图主管绑定表';

INSERT INTO sys_org_manager_binding (
  dept_id,
  employee_id,
  sort_no,
  status
)
SELECT
  d.id,
  d.manager_employee_id,
  1,
  'ACTIVE'
FROM sys_department d
WHERE d.manager_employee_id IS NOT NULL
  AND EXISTS (SELECT 1 FROM hr_employee e WHERE e.id = d.manager_employee_id)
  AND NOT EXISTS (
    SELECT 1
    FROM sys_org_manager_binding b
    WHERE b.dept_id = d.id
      AND b.employee_id = d.manager_employee_id
  );

COMMIT;
