if exists(select 1 from sysobjects where name='tr_bd_i_item_info')
  drop Trigger tr_bd_i_item_info
go

create trigger tr_bd_i_item_info on t_bd_item_info 
for insert
as
begin
	--检查是否是分部式版，如果不是则返回
	-- if not (select sys_var_value from t_sys_system where lower(sys_var_id)='is_distributed') = '1' return

	--声明变量
	declare @item_no varchar(20),@main_supcust varchar(20),@sales_way varchar(10),@branch_no varchar(10)
	
	--系统默认的仓库
	select @branch_no=sys_var_value from t_sys_system where sys_var_id='g_branch_no'
	select @branch_no = @branch_no + '001'
	
	--插入
	declare insert_item_cur cursor for
		select  item_no,main_supcust from inserted
		for read only
	open insert_item_cur
	fetch insert_item_cur into @item_no,@main_supcust
	while @@fetch_status=0
	begin
		insert into t_sys_cm_data (com_table, change_type, key1, update_date, branch_no)
			values ('t_bd_item_info', 'I', @item_no, getdate(), null)

		if not exists (select item_no from t_bd_supcust_item where item_no = @item_no and supcust_no = @main_supcust)
			insert t_bd_supcust_item (item_no,supcust_no)
			values (@item_no,@main_supcust)
		
		--新增商品同时增加对应的机构价格表 by WangC 2015.4.22
        --加盟店进价取总部配送价 by wangjxin 2016.08.16
		--先删除垃圾数据 
		if(select sys_var_value from t_sys_system where lower(sys_var_id)='is_distributed')in ('0','1')
	   		if exists (select item_no from t_pc_branch_price where ltrim(rtrim(item_no)) = @item_no )
	   		delete t_pc_branch_price where item_no = @item_no

		insert into t_pc_branch_price(item_no, branch_no, price, base_price, sale_price, vip_price, vip_price2, vip_price3, vip_price4, vip_price5, scheme_price, cost_price)
		select a.item_no, b.branch_no, (case b.trade_type when '4' then a.scheme_price else a.price end), base_price, sale_price, vip_price, vip_price2, vip_price3, vip_price4, vip_price5, scheme_price, 0.00
		from inserted a, t_bd_branch_info b
		where a.status = '1' and len(b.branch_no) = 3 
			and not exists(select 1 from t_pc_branch_price c where c.item_no = a.item_no and c.branch_no = b.branch_no)

		fetch insert_item_cur into @item_no,@main_supcust
	end
	close insert_item_cur
	deallocate insert_item_cur
end
go