IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_new_spdepart]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_new_spdepart]
GO
create proc [dbo].[mps_new_spdepart]
@pdpid int,
@cmpid int,
@branchid int,
@userdpid int,
@useruid int,
@userotid int
as
begin
set nocount on
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
declare @operation varchar(50)
declare @errorinfo nvarchar(4000) 

declare @dpid bigint
declare @stddpid bigint
set @dpid = 0;
select @dpid = dp_id,@stddpid =dp_dpstdid from mps_depart where dp_cmpid = @cmpid and dp_bcid = @branchid and dp_code = '' and dp_isdepart = 0
set @dpid = isnull(@dpid,0)
declare @porder int
if @pdpid = 0 -- 判断是否有排序
begin
set @porder = 999
select @porder = MAX(dp_order) from mps_depart where dp_isdepart = 0
set @porder = isnull(@porder,999)
end else 
begin
select @porder = dp_order from mps_depart where dp_id = @pdpid
update mps_depart set dp_order += 2 where dp_id != @pdpid and dp_order >= @porder and dp_isdepart =0
set @porder = @porder + 1
end
if @dpid = 0 
begin
--检查base表有无空
select @dpid = dp_id from mps_depart_base where dp_cmpid = @cmpid and dp_code = '' and dp_depart = ''
if @dpid is null or @dpid =0
begin
insert into mps_depart_base(dp_cmpid,dp_code,dp_depart)
values(@cmpid,'','')
select top 1 @dpid = dp_id from mps_depart_base 
where dp_cmpid =  @cmpid and dp_code = '' and dp_depart = ''  order by dp_id desc
end
if @dpid>0
begin
-- 插入mps_depart表
set @stddpid = @dpid
insert into mps_depart(dp_cmpid,dp_bcid,dp_code,dp_dpstdid,dp_order) values(@cmpid,@branchid,'',@dpid,@porder);
select top 1 @dpid  = dp_id from mps_depart 
where dp_cmpid =  @cmpid and dp_bcid = @branchid and dp_code = '' and dp_dpstdid = @stddpid and dp_order = @porder order by dp_id desc
end
end 
if (dbo.mps_sys_checkkeywords('dpt.beforecreate,dpt.aftercreate',@cmpid,0,'','')=0)   -- 有事件
begin
exec drop_temp_table '#old'
select * into #old from mps_depart where dp_id = @dpid
exec drop_temp_table '#new'
select *  into #new from #old 
end
--部门新建之前
if (dbo.mps_sys_checkkeywords('dpt.beforecreate',@cmpid,0,'','')=0) 
begin
exec mps_depart_newdpt_before @cmpid,@branchid,@userdpid,@useruid,@userotid,@dpid,@operation output,@errorinfo output
if @operation = 'abort' 
begin
delete from mps_depart where dp_id = @dpid
delete from mps_depart_base where dp_id = @stddpid
select @operation operation,@errorinfo errorinfo
return 
end
end

if @dpid >0 
begin
update mps_depart set dp_order = @porder where dp_id = @dpid
update mps_depart_base set dp_order = @porder where dp_id = @stddpid
select @dpid as dp_id
end
else select 0 as dp_id
--部门新建之后
if (dbo.mps_sys_checkkeywords('dpt.aftercreate',@cmpid,0,'','')=0) 
begin
exec mps_depart_newdpt_after @cmpid,@branchid,@userdpid,@useruid,@userotid,@dpid
end


set nocount off
end