-- 审批流程多部门关联
create table if not exists approve_process_dept
(
    id                 bigint auto_increment primary key,
    approve_process_id bigint       not null comment '审批流程主键ID',
    approve_dept_id    bigint       not null comment '部门ID',
    approve_dept_name  varchar(255) not null comment '部门名称快照',
    dept_order         int          not null default 1 comment '部门顺序',
    delete_flag        int          not null default 0 comment '逻辑删除标记',
    create_time        datetime     null comment '创建时间',
    unique key uk_approve_process_dept (approve_process_id, approve_dept_id),
    key idx_approve_process_id (approve_process_id),
    key idx_approve_dept_id (approve_dept_id)
) comment '审批流程部门关联表';

-- 历史单部门审批数据迁移为关联记录
insert into approve_process_dept (approve_process_id, approve_dept_id, approve_dept_name, dept_order, delete_flag, create_time)
select p.id, p.approve_dept_id, p.approve_dept_name, 1, 0, now()
from approve_process p
where p.approve_dept_id is not null
  and not exists (
      select 1 from approve_process_dept d
      where d.approve_process_id = p.id
        and d.approve_dept_id = p.approve_dept_id
  );
