IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_new_prdctg_details]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_new_prdctg_details]
GO
create proc [dbo].[mps_new_prdctg_details]
@cmpid int,
@pc_tag int,
@pcfather int,
@ppcid bigint,
@pc_father bigint,
@pc_type varchar(255),
@pc_code varchar(255)
as
begin
set nocount on

DECLARE @order int
DECLARE @caption nvarchar(100)
DECLARE @pc_full nvarchar(255)
declare @tagorder int = 0,
@fatherorder int = 0,
@level1 int = 0


SELECT TOP 1 @caption=pc_caption FROM mps_prdctg WHERE pc_cmpid=@cmpid AND pc_tag = @pc_tag ORDER BY pc_order DESC,pc_level DESC
if(@pc_code = '_none_' or @pc_code is null) set @pc_code = ''
--判断是否有上级分类
if(@pc_father = -999999999 or @pc_father is null or @pc_father = @pcfather) 
begin
set @pc_father = 0
set @level1 = 1

--SELECT @pc_full = pc_full FROM mps_prdctg WHERE pc_id = @pcfather
--set @pc_full = isnull(@pc_full, '') + '/%'
--判断是否有是在中间插入
if @ppcid = 0 or @ppcid = -999999999 or @ppcid is null
begin
/* select @fatherorder = max(pc_order) from mps_prdctg where pc_father = @pcfather
select @tagorder = pc_order,@ppcid = pc_id from mps_prdctg where pc_ffpcid = @pcfather order by pc_order desc,pc_level desc
set @tagorder = isnull(@tagorder,0)
set @fatherorder = isnull(@fatherorder,0)

if(@fatherorder>@tagorder) set @order = @fatherorder
else set @order = @tagorder
if(@order = 0)
begin
select @order = pc_order from mps_prdctg where pc_id = @pcfather
end */
set @level1 = 0
select @order = max(pc_order) from mps_prdctg where pc_tag = @pc_tag


end else
begin
SELECT TOP 1 @order=pc_order FROM mps_prdctg WHERE pc_id = @ppcid
end

SET @order = ISNULL(@order,0)
update mps_prdctg set pc_order = pc_order +2 where pc_cmpid=@cmpid AND pc_order > @order and pc_id != @ppcid AND pc_tag = @pc_tag

SET @order = ISNULL(@order+1,0)
print @order
end else
begin
SELECT TOP 1 @order=pc_order,@level1 = pc_level FROM mps_prdctg WHERE pc_id = @pc_father
SET @order = ISNULL(@order,0)
update mps_prdctg set pc_order = pc_order +2 where pc_cmpid=@cmpid AND pc_order >= @order and pc_id != @pc_father

SET @order = ISNULL(@order+1,0)
set @level1 = ISNULL(@level1+1,0)
end

INSERT INTO mps_prdctg(pc_cmpid, pc_tag, pc_caption, pc_type, pc_full, pc_order, pc_level,pc_father,pc_code,pc_ffpcid)
VALUES(@cmpid, @pc_tag, @caption, @pc_type, '', @order, @level1 , @pc_father,@pc_code,@pcfather)
--查询插入的分类
declare @id1 int
select top 1 @id1 = pc_id FROM mps_prdctg WHERE pc_cmpid=@cmpid AND pc_type=@pc_type AND pc_tag=@pc_tag and pc_order = @order and pc_father = @pc_father and pc_level = @level1 and pc_code = @pc_code and pc_ffpcid = @pcfather
order by pc_id desc

SELECT *,pc_tag as datagroup FROM mps_prdctg WHERE pc_id = @id1 


exec mps_update_prdctginfo @cmpid,@pc_tag
select @cmpid  as cmpid,@pc_tag as pctag
exec mps_gen_prdctg_power @cmpid,@id1,@pc_father
select @cmpid  as cmpid,@pc_tag as pctag

set nocount off
end