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

Create Trigger tr_im_flow on t_im_flow
for Insert
as
--不管理库存的商品，生成进销存t_da_jxc_daysum记录时，结存值，统一记录为0，即settle_qty、settle_amt、settle_amt2全记录为0	zhouzx	2016-2-16
begin
  declare
    @flow_id        	char(18) ,		--流水号
    @item_no         	char(20)      ,	--货品代码
    @real_qty        	numeric(16,4) ,	--数量
    @price           	numeric(16,4) ,
    @cost_price      	numeric(16,4) ,	--成本单价
    @sheet_amt       	numeric(16,4) ,	--金额
    @branch_no       	char(6)      ,	--本店代码
    @trans_no        	char(2)      ,	--库存操作方式
    @db_no           	char(1)      ,	--出入库方式
    @sale_way        	char(1)      ,	--销售方式
    @oper_id         	char(4)      ,	--操作员代码
	@pc_saleprc			numeric(16,4),	--机构价格表售价
	@pc_inprc			numeric(16,4),	--机构价格表进价
	@pc_baseprc			numeric(16,4),	--机构价格表批发价
	@pc_costprc			numeric(16,4),	--机构价格表平均成本价,
    @t_in_price       	numeric(16,4) , --基准进价
    @stock_money		numeric(16,4),	--库存金额
    @ls_operdate		char(10),
    @stock_qty			numeric(16,4),	--库存数量
    @stock_price		numeric(16,4),	--成本价
    @sale_price			numeric(16,4),	--售价
    @sup_no      		char(8),        --供应商客户代码
    @so_price			numeric(16,4),	--批发价
    @item_stock  		char(1),		--商品是否维护库存
    @item_sup_flag 		char(1),		--经营方式 A 购销，C 联营
    @item_sup_rate 		decimal(16,4),	--商品档案联营扣率
    @spec_sup_rate 		decimal(16,4),	--特价联营扣率
    @ass_change			decimal(20,8),	--辅助单位转换值
    @ass_qty            decimal(20,8),  --辅助单位数量
    @ass_stock			decimal(20,8),  --辅助单位库存数量
    @now_date			varchar(10) ,   --当前日期
    @last_max_date		varchar(10),    --最大结存日期
	@db_flag			int
	
	select @flow_id = flow_id, @ls_operdate = convert(char(10),oper_date,121), @item_no = item_no, @real_qty = real_qty,
	 @price = price, @sheet_amt = sheet_amt, @branch_no = branch_no, 
	 @trans_no = trans_no, @db_no = db_no, @sale_way = sale_way, @oper_id = oper_id, @sale_price = sale_price
	from inserted where trans_no <> 'PC'
	
	select @now_date = convert(varchar(10),GETDATE(),121)
	
	--获取商品商品的价格、扣率、辅助单位等基本信息
	SELECT @so_price = base_price, @sale_price = sale_price, @t_in_price = price, 
		 @sup_no = main_supcust, @item_sup_flag = item_sup_flag, @item_sup_rate = sup_rate,
		 @item_stock = item_stock,
		 @ass_change = (case when ass_change=0 then 1 else isnull(ass_change,1) end) 
	FROM t_bd_item_info WHERE item_no = @item_no
	SELECT @ass_qty = @ass_change * @real_qty

	--烘焙9架构模式取价格时优先考虑从机构价格表取价
	if left(@branch_no, 3) <> '000' or @item_stock = '1'
	begin
		select @pc_saleprc = sale_price, @pc_inprc = price, @pc_baseprc = base_price, @pc_costprc = cost_price 
		  from t_pc_branch_price 
		 where item_no = @item_no and branch_no = left(@branch_no, 3)
		if left(@branch_no, 3) <> '000'  --非总部才考虑价格从机构价格表取数(除成本价外)
		begin
			if @pc_saleprc > 0 set @sale_price = @pc_saleprc
			if @pc_inprc > 0 set @t_in_price = @pc_inprc
			if @pc_baseprc > 0 set @so_price = @pc_baseprc
		end
		if @pc_costprc is null or @pc_costprc = 0 set @pc_costprc = @t_in_price
	end

	select @stock_qty = null, @stock_money = null, @stock_price = null
	SELECT @stock_qty = isnull(sum(stock_qty),0), @stock_money = isnull(sum(stock_qty*avg_cost) ,0), @ass_stock = isnull(sum(ass_stock_qty),0)
      FROM t_im_branch_stock 
     WHERE left(branch_no,3)=left(@branch_no,3) and item_no=@item_no
	IF @stock_qty = 0
		Select @stock_qty = 0, @stock_money = 0, @stock_price = @t_in_price
	Else
		select @stock_price = @stock_money / @stock_qty
	
	
	--如果不管理库存的商品有可能进行过成本调价单调价(无库存记录，但有成本价记录)
	if @item_stock = '1' 
		set @stock_price = @pc_costprc
	
	--不再需要自定义设置哪些单据影响成本价,固定以下单据影响成本
	select @cost_price = null
	IF charindex(@trans_no,'/PI/RO/GI/CS/MB/MR/MC/MI/DI/') >= 1
	begin
  		if @db_no = '+'
		begin
			if @stock_qty < 0 and @stock_qty + @real_qty > 0
				select @cost_price = @price
			else if @stock_qty + @real_qty <= 0 or @stock_money + @real_qty * @price < 0
				select @cost_price = @price
			else
				select @cost_price = abs(@stock_money + @real_qty * @price)/abs(@stock_qty + @real_qty)
		end 
		else
		begin
			if  charindex(@trans_no,'/MB/MC/MR/')>=1
				select @cost_price = @stock_price
			else
			begin
				if @stock_qty < 0 and @stock_qty - @real_qty > 0
					select @cost_price = @price
				else if @stock_qty - @real_qty <= 0 or @stock_money - @real_qty * @price < 0
					select @cost_price = @price
				else
					select @cost_price = abs(@stock_money - @real_qty * @price)/abs(@stock_qty - @real_qty)
			end
		end
	end 
	else
	begin
		select top 1 @cost_price = avg_cost from t_im_branch_stock where branch_no = @branch_no and item_no = @item_no
		if @cost_price is null
			select @cost_price = @stock_price
	end
	
	--单据审核触发器中的成本计算有问题，现改成在这里重新计算。
	if @cost_price is null set @cost_price = 0
	update t_im_flow set cost_price = @cost_price where flow_id = @flow_id and isNull(cost_price,0) <> @cost_price
		if @@error != 0 goto myerror

	if @trans_no <> 'IO'
	begin
		--统一更新机构价格表中的成本价
		update t_pc_branch_price set cost_price = @cost_price where item_no = @item_no and branch_no = left(@branch_no, 3) and isNull(cost_price,0) <> @cost_price
		if @@error != 0 goto myerror

		--更新日结信息(后续根据开关是否采用手动日结扩充处理)
		update t_bd_branch_info set daysum_date = convert(datetime, @ls_operdate), daysum_pointer = @flow_id where branch_no = left(@branch_no,3)
		if @@error != 0 goto myerror
	end

	--统一调整同一机构下的成本价信息，后根据仓库信息检测是否有商品信息，存在时更新库存信息，不存在时插入库存信息
	--MC/MB/MK		出入库具有两向性，与是否处理原材料仓库库存相关
	--ME/ML/RE/IO	出入库具有两向性(类似于转仓单，但不需要处理进销存)
	set @db_flag = 1
	if charindex(@trans_no,'GI/PI/RO/MB/MC/MK/MR/ML/ME/RE/MF/MA/MT/SO/RI/PT/LP/DI/DO/MI/MO/OO/PD/MD/CS/IO')>=1
	begin
		if @trans_no <> 'IO'
			update t_im_branch_stock set avg_cost = @cost_price, cost_amt = stock_qty*@cost_price where left(branch_no,3)=left(@branch_no,3) and item_no = @item_no
		if @@error != 0 goto myerror

		--对出库的库存数据单独处理
		if (charindex(@trans_no,'MB/MC/MK/ML/ME/RE/MF/MA/SO/RI/PT/LP/DO/MO/OO/PD/MD/CS/IO')>=1 and @db_no = '-')
			set @db_flag = -1

		IF exists(select 1 from t_im_branch_stock where item_no=@item_no and branch_no = @branch_no)
		begin
			if @trans_no = 'PI'
				update t_im_branch_stock 
				   set avg_cost = @cost_price, last_inprice = @price, oper_date = getdate(), com_flag = '0',
					   cost_amt = round((stock_qty + @real_qty*@db_flag)*@cost_price,4),
					   stock_qty = stock_qty + @real_qty*@db_flag, ass_stock_qty = ass_stock_qty + @ass_qty*@db_flag
				where branch_no=@branch_no and item_no=@item_no		
			else if @trans_no = 'SO'
				update t_im_branch_stock 
				   set avg_cost = @cost_price, last_baseprice = @price, oper_date = getdate(), com_flag = '0',
					   cost_amt = round((stock_qty + @real_qty*@db_flag)*@cost_price,4),
					   stock_qty = stock_qty + @real_qty*@db_flag, ass_stock_qty = ass_stock_qty + @ass_qty*@db_flag
				where branch_no=@branch_no and item_no=@item_no		
			else if @trans_no = 'IO'
				update t_im_branch_stock 
				   set oper_date = getdate(), com_flag = '0',
					   cost_amt = (stock_qty + @real_qty*@db_flag)*avg_cost,
					   stock_qty = stock_qty + @real_qty*@db_flag, ass_stock_qty = ass_stock_qty + @ass_qty*@db_flag
				where branch_no=@branch_no and item_no=@item_no
			else
				update t_im_branch_stock 
				   set avg_cost = @cost_price, oper_date = getdate(), com_flag = '0', cost_amt = round((@stock_qty + @real_qty*@db_flag)*@cost_price,4),
					   stock_qty = stock_qty + @real_qty*@db_flag, ass_stock_qty = ass_stock_qty + @ass_qty*@db_flag
				where branch_no=@branch_no and item_no=@item_no
		end
		ELSE
			insert into t_im_branch_stock (branch_no, item_no, stock_qty, avg_cost, oper_date,cost_amt,ass_stock_qty, last_inprice, last_baseprice)
				values(@branch_no, @item_no, @real_qty*@db_flag, @cost_price, getdate(), @real_qty*@db_flag * @cost_price, @ass_qty*@db_flag, 
						(case @trans_no when 'PI' then @price else 0 end), (case @trans_no when 'SO' then @price else 0 end))
		
		if @@error != 0 goto myerror
	end

	--采购入库、退货、赠送品入库
	if charindex(@trans_no,'PI/RO/GI') >= 1	
	BEGIN
		IF exists(select 1 from t_da_jxc_daysum where(item_no=@item_no and oper_date=@ls_operdate and branch_no=left(@branch_no,3)))
			UPDATE 	t_da_jxc_daysum
			SET 	avg_cost_amt = @cost_price * (so_qty + pos_qty + pos_ret_qty + pos_send_qty), cost_price = @cost_price,
					avg_profit_amt = (so_amt + pos_amt + pos_ret_amt) - @cost_price * (so_qty + pos_qty + pos_ret_qty + pos_send_qty),
					pi_qty = isnull(pi_qty,0) + @real_qty, pi_amt = isnull(pi_amt,0) + @real_qty * @price,
					settle_qty = case when @item_stock = '1' then 0 else @stock_qty + @real_qty end, 
					settle_amt = case when @item_stock = '1' then 0 else (@stock_qty + @real_qty) * @cost_price end,
					settle_amt2 = case when @item_stock = '1' then 0 else (@stock_qty + @real_qty)* @sale_price end, ass_qty=@ass_stock+@ass_qty, com_flag = '0'
			WHERE (item_no=@item_no and oper_date=@ls_operdate and branch_no=left(@branch_no,3))
		ELSE
			INSERT INTO t_da_jxc_daysum (
					item_no, oper_date, branch_no, cost_price, init_qty, init_amt, init_amt2,
					avg_cost_amt, avg_profit_amt,pi_qty, pi_amt, so_qty, so_amt, mi_qty,mi_amt,
					mo_qty, mo_amt, di_qty, di_amt,do_qty, do_amt, pos_qty,pos_amt, pos_ret_qty,pos_ret_amt,
					pos_send_qty,pos_send_amt, oo_qty, oo_amt, 
					settle_qty,
					settle_amt,
					settle_amt2,
					cost_change_amt, pos_dct_amt, main_sup, dec_rate,
					so_price, sale_price, com_flag,item_sup_flag,ass_qty  )
			VALUES ( @item_no, @ls_operdate ,left(@branch_no,3), @cost_price,@stock_qty,@stock_money,@stock_qty*@sale_price,
					0,0,@real_qty,@real_qty * @price,0,0,0,0,
					0,0,0,0,0,0,0,0,0,0,0,0,0,0,
					case when @item_stock = '1' then 0 else @stock_qty + @real_qty end,
					case when @item_stock = '1' then 0 else (@stock_qty + @real_qty) * @cost_price end,
					case when @item_stock = '1' then 0 else (@stock_qty + @real_qty)* @sale_price end,
					0,0,@sup_no,0,
					@so_price, @sale_price, '0',@item_sup_flag,@ass_stock + @ass_qty)
		if @@error != 0 goto myerror
	END 

	--现烤入库单/裱花入库、生产入库单、现烤退回单
	if (charindex(@trans_no,'MB/MC')>=1 and @db_no = '+') or @trans_no = 'MR' or (@trans_no = 'MK' and @db_no = '-')
	BEGIN
		set @db_flag = 1
		if @trans_no='MK' set @db_flag = -1

		IF exists(select 1 from t_da_jxc_daysum where(item_no=@item_no and oper_date=@ls_operdate and branch_no=left(@branch_no,3)))
			UPDATE t_da_jxc_daysum
			   SET  avg_cost_amt = @cost_price * (so_qty + pos_qty + pos_ret_qty + pos_send_qty), cost_price = @cost_price,
					avg_profit_amt = (so_amt + pos_amt + pos_ret_amt) - @cost_price * (so_qty + pos_qty + pos_ret_qty + pos_send_qty),
					made_qty = isnull(made_qty,0) + @real_qty*@db_flag, 
					made_amt = isnull(made_amt,0) + (case @trans_no when 'MK' then @real_qty*@db_flag*@cost_price else @sheet_amt end),
					settle_qty = case when @item_stock = '1' then 0 else @stock_qty + @real_qty*@db_flag end,
					settle_amt = case when @item_stock = '1' then 0 else (@stock_qty + @real_qty*@db_flag) * @cost_price end,
					settle_amt2 = case when @item_stock = '1' then 0 else (@stock_qty + @real_qty*@db_flag)* @sale_price end, ass_qty = @ass_stock + @ass_qty*@db_flag, com_flag = '0'
			WHERE (item_no=@item_no and oper_date=@ls_operdate and branch_no=left(@branch_no,3))

		ELSE
			INSERT INTO t_da_jxc_daysum (
					item_no, oper_date, branch_no, cost_price, init_qty, init_amt, init_amt2,
					avg_cost_amt, avg_profit_amt,pi_qty, pi_amt, so_qty, so_amt, mi_qty,mi_amt,
					mo_qty, mo_amt, di_qty, di_amt,do_qty, do_amt, pos_qty,pos_amt, pos_ret_qty,pos_ret_amt,
					pos_send_qty,pos_send_amt, oo_qty, oo_amt, 
					settle_qty,settle_amt,settle_amt2,ass_qty, 
					cost_change_amt, pos_dct_amt, main_sup, dec_rate,so_price, 
					sale_price, com_flag,item_sup_flag, made_qty, made_amt )
			VALUES ( @item_no, @ls_operdate ,left(@branch_no,3), @cost_price,@stock_qty,@stock_money,@stock_qty*@sale_price,0,0,0,0,0,0,0,0,
					0,0,0,0,0,0,0,0,0,0,0,0,0,0,
					case when @item_stock = '1' then 0 else @stock_qty + @real_qty*@db_flag end,
					case when @item_stock = '1' then 0 else (@stock_qty + @real_qty*@db_flag) * @cost_price end,
					case when @item_stock = '1' then 0 else (@stock_qty + @real_qty*@db_flag)* @sale_price end, 
					@ass_stock + @ass_qty*@db_flag,
					0,0,@sup_no,0,@so_price, 
					@sale_price, '0',@item_sup_flag, @real_qty*@db_flag, (case @trans_no when 'MK' then @real_qty*@db_flag*@cost_price else @sheet_amt end))
		if @@error != 0 goto myerror		
	END 

	--现烤入库单/裱花入库(处理原材料出库部分)、领料出库单/配料间发料/配料间补发料/配料间退料、现烤退回单(处理原材料出库部分)
	IF (charindex(@trans_no,'MB/MC')>=1 and @db_no = '-') or charindex(@trans_no,'ME/MF/MA/MT')>=1 or (@trans_no='MK' and @db_no = '+')
	BEGIN	 
		set @db_flag = 1
		if charindex(@trans_no,'MT/MK') >= 1 set @db_flag = -1
		if charindex(@trans_no,'ME') >= 1 AND @db_no = '+'  set @db_flag = -1
         
		IF exists(select 1 from t_da_jxc_daysum where(item_no=@item_no and oper_date=@ls_operdate and branch_no=left(@branch_no,3)))
			UPDATE 	t_da_jxc_daysum
			SET 	avg_cost_amt = @cost_price * (so_qty + pos_qty + pos_ret_qty + pos_send_qty ), cost_price = @cost_price,
					avg_profit_amt = (so_amt + pos_amt + pos_ret_amt ) - @cost_price * (so_qty + pos_qty + pos_ret_qty + pos_send_qty),
					material_qty = isnull(material_qty,0) + @real_qty*@db_flag, 
					material_amt = isnull(material_amt,0) + (case @trans_no when 'MK' then -@sheet_amt else @real_qty*@db_flag*@cost_price end),
					settle_qty = case when @item_stock = '1' then 0 else @stock_qty - @real_qty*@db_flag end,
					settle_amt = case when @item_stock = '1' then 0 else (@stock_qty - @real_qty*@db_flag) * @cost_price end,
					settle_amt2 = case when @item_stock = '1' then 0 else (@stock_qty - @real_qty*@db_flag)* @sale_price end,  
					ass_qty = @ass_stock - @ass_qty*@db_flag, com_flag = '0'
			WHERE (item_no=@item_no and oper_date=@ls_operdate and branch_no=left(@branch_no,3))
		ELSE
			INSERT INTO t_da_jxc_daysum (
					item_no, oper_date, branch_no, cost_price, init_qty, init_amt, init_amt2,
					avg_cost_amt, avg_profit_amt,pi_qty, pi_amt, so_qty, so_amt, mi_qty,mi_amt,
					mo_qty, mo_amt, di_qty, di_amt,do_qty, do_amt, pos_qty,pos_amt, pos_ret_qty,pos_ret_amt,
					pos_send_qty,pos_send_amt, oo_qty, oo_amt, 
					settle_qty,
					settle_amt,
					settle_amt2,
					ass_qty,
					cost_change_amt, pos_dct_amt, main_sup, dec_rate,so_price, 
					sale_price, com_flag,item_sup_flag,material_qty,material_amt )
			VALUES ( @item_no, @ls_operdate ,left(@branch_no,3), @cost_price,@stock_qty,@stock_money,@stock_qty*@sale_price,
					0, 0,0,0,0,0,0,0,
					0,0,0,0,0,0,0,0,0,0,0,0,0,0,
					case when @item_stock = '1' then 0 else @stock_qty-@real_qty*@db_flag end, 
					case when @item_stock = '1' then 0 else (@stock_qty-@real_qty*@db_flag)*@cost_price end, 
					case when @item_stock = '1' then 0 else (@stock_qty-@real_qty*@db_flag)*@sale_price end, 
					@ass_stock-@ass_qty*@db_flag,
					0,0,@sup_no,0,@so_price, 
					@sale_price, '0',@item_sup_flag,@real_qty*@db_flag, (case @trans_no when 'MK' then -@sheet_amt else @real_qty*@db_flag*@cost_price end))
		if @@error != 0 goto myerror
	END

	IF @trans_no='SO' or @trans_no='RI' --销售
	BEGIN
		IF exists(select 1 from t_da_jxc_daysum where(item_no=@item_no and oper_date=@ls_operdate and branch_no=left(@branch_no,3)))
			UPDATE 	t_da_jxc_daysum
			SET 	avg_cost_amt = @cost_price * (so_qty + pos_qty + pos_ret_qty + pos_send_qty + @real_qty), cost_price = @cost_price,
					avg_profit_amt = (so_amt + pos_amt + pos_ret_amt + @real_qty * @price) - @cost_price * (so_qty + pos_qty + pos_ret_qty + pos_send_qty + @real_qty),
					so_qty = so_qty + @real_qty, so_amt = so_amt + @real_qty * @price,
					settle_qty = case when @item_stock = '1' then 0 else @stock_qty - @real_qty end,
					settle_amt = case when @item_stock = '1' then 0 else (@stock_qty - @real_qty) * @cost_price end,
					settle_amt2 = case when @item_stock = '1' then 0 else (@stock_qty - @real_qty)* @sale_price end, 
					com_flag = '0',ass_qty = @ass_stock - @ass_qty
			WHERE (item_no=@item_no and oper_date=@ls_operdate and branch_no=left(@branch_no,3))
		ELSE
			INSERT INTO t_da_jxc_daysum (
					item_no, oper_date, branch_no, cost_price, init_qty, init_amt, init_amt2,
					avg_cost_amt, avg_profit_amt,pi_qty, pi_amt, so_qty, so_amt, mi_qty,mi_amt,
					mo_qty, mo_amt, di_qty, di_amt,do_qty, do_amt, pos_qty,pos_amt, pos_ret_qty,pos_ret_amt,
					pos_send_qty,pos_send_amt, oo_qty, oo_amt, 
					settle_qty,
					settle_amt,
					settle_amt2,
					cost_change_amt, pos_dct_amt, main_sup, dec_rate,
					so_price, sale_price, com_flag,item_sup_flag,ass_qty )
			VALUES ( @item_no, @ls_operdate ,left(@branch_no,3), @cost_price,@stock_qty,@stock_money,@stock_qty*@sale_price,
					@cost_price * @real_qty, @real_qty * (@price - @cost_price),0,0,@real_qty,@real_qty * @price,0,0,
					0,0,0,0,0,0,0,0,0,0,0,0,0,0,
					case when @item_stock = '1' then 0 else @stock_qty - @real_qty end,
					case when @item_stock = '1' then 0 else (@stock_qty - @real_qty) * @cost_price end,
					case when @item_stock = '1' then 0 else (@stock_qty - @real_qty)* @sale_price end,
					0,0,@sup_no,0,
					@so_price, @sale_price, '0',@item_sup_flag,@ass_stock - @ass_qty)
		if @@error != 0 goto myerror
	END

	--POS零售、礼品兑换
	IF @trans_no='PT' OR @trans_no='LP'
	BEGIN	
		IF exists(select 1 from t_da_jxc_daysum where(item_no=@item_no and oper_date=@ls_operdate and branch_no=left(@branch_no,3)))
		   begin
			  --断网数据跨天上传时，库存取当期进销存表中的结存 ADD BY wangjxin 2016-06-22
		         if @trans_no='PT' and @ls_operdate<@now_date
		         begin
		            select @stock_qty = settle_qty,@ass_stock = ass_qty
		            from t_da_jxc_daysum
		            where(item_no=@item_no and oper_date=@ls_operdate and branch_no=left(@branch_no,3))
		         end
			
		
			if @sale_way = 'A' 
				UPDATE 	t_da_jxc_daysum
				SET 	avg_cost_amt = @cost_price * (so_qty + pos_qty + pos_ret_qty + pos_send_qty + @real_qty), cost_price = @cost_price,
						avg_profit_amt = (so_amt + pos_amt + pos_ret_amt + round(@real_qty * @price,2)) - @cost_price * (so_qty + pos_qty + pos_ret_qty + pos_send_qty + @real_qty),
						pos_qty = pos_qty + @real_qty, pos_amt = pos_amt + round(@real_qty * @price,2),
						settle_qty = case when @item_stock = '1' then 0 else @stock_qty - @real_qty end,
						settle_amt = case when @item_stock = '1' then 0 else (@stock_qty - @real_qty)* @cost_price end,
						settle_amt2 = case when @item_stock = '1' then 0 else (@stock_qty - @real_qty)* @sale_price end,
						com_flag = '0', 
						ass_qty = @ass_stock - @ass_qty
				WHERE (item_no=@item_no and oper_date=@ls_operdate and branch_no=left(@branch_no,3))
			else if @sale_way = 'C'
				UPDATE 	t_da_jxc_daysum
				SET 	avg_cost_amt = @cost_price * (so_qty + pos_qty + pos_ret_qty + pos_send_qty + @real_qty), cost_price = @cost_price,
						avg_profit_amt = (so_amt + pos_amt + pos_ret_amt + round(@real_qty * @price,2)) - @cost_price * (so_qty + pos_qty + pos_ret_qty + pos_send_qty + @real_qty),
						pos_send_qty = pos_send_qty + @real_qty, pos_send_amt = pos_send_amt + round(@real_qty * @price,2),
						settle_qty = case when @item_stock = '1' then 0 else @stock_qty - @real_qty end,
						settle_amt = case when @item_stock = '1' then 0 else (@stock_qty - @real_qty)* @cost_price end,
						settle_amt2 = case when @item_stock = '1' then 0 else (@stock_qty - @real_qty)* @sale_price end,
						com_flag = '0', ass_qty = @ass_stock - @ass_qty
				WHERE (item_no=@item_no and oper_date=@ls_operdate and branch_no=left(@branch_no,3))
			else
				UPDATE 	t_da_jxc_daysum
				SET 	avg_cost_amt = @cost_price * (so_qty + pos_qty + pos_ret_qty + pos_send_qty + @real_qty), cost_price = @cost_price,
						avg_profit_amt = (so_amt + pos_amt + pos_ret_amt + round(@real_qty * @price,2)) - @cost_price * (so_qty + pos_qty + pos_ret_qty + pos_send_qty + @real_qty),
						pos_ret_qty = pos_ret_qty + @real_qty, pos_ret_amt = pos_ret_amt + round(@real_qty * @price,2),						
						settle_qty = case when @item_stock = '1' then 0 else @stock_qty - @real_qty end,
						settle_amt = case when @item_stock = '1' then 0 else (@stock_qty - @real_qty)* @cost_price end,
						settle_amt2 = case when @item_stock = '1' then 0 else (@stock_qty - @real_qty)* @sale_price end,
						com_flag = '0', ass_qty = @ass_stock - @ass_qty
				WHERE (item_no=@item_no and oper_date=@ls_operdate and branch_no=left(@branch_no,3))
			 if @@error != 0 goto myerror	
                  end 
		ELSE
                     begin
		          --断网数据跨天上传时，库存取进销存表中最近一天的结存
			 if @trans_no='PT' and @ls_operdate<@now_date
			 begin
				select @last_max_date =''
				select @last_max_date = max(oper_date) from t_da_jxc_daysum
				where branch_no=left(@branch_no,3) and item_no=@item_no and oper_date<@ls_operdate
				if  len(@last_max_date) > 0
				begin 
				   select @stock_qty = settle_qty,@stock_money = settle_amt,@ass_stock = ass_qty
				   from t_da_jxc_daysum
				   where branch_no=left(@branch_no,3) and item_no=@item_no and oper_date=@last_max_date 
				end
				else
				begin
				   select @stock_qty   = 0
				   select @stock_money = 0
				   select @ass_stock   = 0
				end
			 end
		
			INSERT INTO t_da_jxc_daysum (
					item_no, oper_date, branch_no, cost_price, init_qty, init_amt, init_amt2,
					avg_cost_amt, avg_profit_amt,pi_qty, pi_amt, so_qty, so_amt, mi_qty,mi_amt,
					mo_qty, mo_amt, di_qty, di_amt,do_qty, do_amt, oo_qty, oo_amt, 
					pos_qty,pos_amt, pos_ret_qty,pos_ret_amt,pos_send_qty,pos_send_amt, 
					settle_qty,settle_amt,settle_amt2,
					cost_change_amt, pos_dct_amt, main_sup, dec_rate,
					so_price, sale_price, com_flag ,item_sup_flag,ass_qty)
			VALUES ( @item_no, @ls_operdate ,left(@branch_no,3), @cost_price,@stock_qty,@stock_money,@stock_qty*@sale_price,
					@cost_price * @real_qty, @real_qty * (@price - @cost_price),0,0,0,0,0,0,0,0,0,0,0,0,0,0,
					(case @sale_way when 'A' then @real_qty else 0 end),(case @sale_way when 'A' then round(@real_qty * @price,2) else 0 end),
					(case @sale_way when 'B' then @real_qty else 0 end),(case @sale_way when 'B' then round(@real_qty * @price,2) else 0 end),
					(case @sale_way when 'C' then @real_qty else 0 end),(case @sale_way when 'C' then round(@real_qty * @price,2) else 0 end),
					case when @item_stock = '1' then 0 else @stock_qty - @real_qty end,
					case when @item_stock = '1' then 0 else(@stock_qty - @real_qty) * @cost_price end,
					case when @item_stock = '1' then 0 else (@stock_qty - @real_qty)* @sale_price end,
					0,0,@sup_no,0,
					@so_price, @sale_price, '0',@item_sup_flag,@ass_stock-@ass_qty)
		    if @@error != 0 goto myerror	
                end 
              
	END

	IF charindex(@trans_no,'DI/DO') >=1
	BEGIN
		set @db_flag = 1
		if @db_no = '-' set @db_flag = -1

		IF exists(select 1 from t_da_jxc_daysum where(item_no=@item_no and oper_date=@ls_operdate and branch_no=left(@branch_no,3)))
			if @db_no = '+' 
				UPDATE 	t_da_jxc_daysum
				SET 	avg_cost_amt = @cost_price * (so_qty + pos_qty + pos_ret_qty + pos_send_qty), cost_price = @cost_price,
						avg_profit_amt = (so_amt + pos_amt + pos_ret_amt) - @cost_price * (so_qty + pos_qty + pos_ret_qty + pos_send_qty),
						di_qty = di_qty + @real_qty, di_amt = di_amt + @real_qty * @price,
						settle_qty = case when @item_stock = '1' then 0 else @stock_qty + @real_qty end,
						settle_amt = case when @item_stock = '1' then 0 else (@stock_qty + @real_qty) * @cost_price end,
						settle_amt2 = case when @item_stock = '1' then 0 else (@stock_qty + @real_qty)* @sale_price end, 
						com_flag = '0',ass_qty = @stock_qty + @ass_qty
				WHERE (item_no=@item_no and oper_date=@ls_operdate and branch_no=left(@branch_no,3))
			else
				UPDATE 	t_da_jxc_daysum
				SET 	avg_cost_amt = @cost_price * (so_qty + pos_qty + pos_ret_qty + pos_send_qty), cost_price = @cost_price,
						avg_profit_amt = (so_amt + pos_amt + pos_ret_amt) - @cost_price * (so_qty + pos_qty + pos_ret_qty + pos_send_qty),
						do_qty = do_qty + @real_qty, do_amt = do_amt + @real_qty * @price,
						settle_qty = case when @item_stock = '1' then 0 else @stock_qty - @real_qty end,
						settle_amt = case when @item_stock = '1' then 0 else (@stock_qty - @real_qty) * @cost_price end,
						settle_amt2 = case when @item_stock = '1' then 0 else (@stock_qty - @real_qty)* @sale_price end, 
						com_flag = '0',ass_qty = @ass_stock - @ass_qty
				WHERE (item_no=@item_no and oper_date=@ls_operdate and branch_no=left(@branch_no,3))		
		ELSE
			INSERT INTO t_da_jxc_daysum (
					item_no, oper_date, branch_no, cost_price, init_qty, init_amt, init_amt2,
					avg_cost_amt, avg_profit_amt,pi_qty, pi_amt, so_qty, so_amt, mi_qty,mi_amt,	mo_qty, mo_amt, 
					pos_qty,pos_amt, pos_ret_qty,pos_ret_amt,pos_send_qty,pos_send_amt, oo_qty, oo_amt, 
					di_qty, di_amt, do_qty,do_amt, 
					settle_qty,
					settle_amt,
					settle_amt2,
					cost_change_amt, pos_dct_amt, main_sup, dec_rate,
					so_price, sale_price, com_flag,item_sup_flag,ass_qty )
			VALUES ( @item_no, @ls_operdate ,left(@branch_no,3), @cost_price,@stock_qty,@stock_money,@stock_qty*@sale_price,
					0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
					(case @db_no when '+' then @real_qty else 0 end),(case @db_no when '+' then @real_qty*@price else 0 end),
					(case @db_no when '-' then @real_qty else 0 end),(case @db_no when '-' then @real_qty*@price else 0 end),
					case when @item_stock = '1' then 0 else @stock_qty + @real_qty*@db_flag end,
					case when @item_stock = '1' then 0 else (@stock_qty + @real_qty*@db_flag) * @cost_price end,
					case when @item_stock = '1' then 0 else (@stock_qty + @real_qty*@db_flag)* @sale_price end,
					0,0,@sup_no,0,
					@so_price, @sale_price, '0',@item_sup_flag,@ass_stock+@ass_qty*@db_flag)
		if @@error != 0 goto myerror
	END

	--库存调整单/盘点单/损溢单/组合拆分单
	IF charindex(@trans_no,'OO/PD/MD/CS') >=1 
	BEGIN
		IF @db_no = '-' set @real_qty = - @real_qty

		IF exists(select 1 from t_da_jxc_daysum where(item_no=@item_no and oper_date=@ls_operdate and branch_no=left(@branch_no,3)))
			UPDATE 	t_da_jxc_daysum
			SET 	avg_cost_amt = @cost_price * (so_qty + pos_qty + pos_ret_qty + pos_send_qty), cost_price = @cost_price,
					avg_profit_amt = (so_amt + pos_amt + pos_ret_amt) - @cost_price * (so_qty + pos_qty + pos_ret_qty + pos_send_qty),
					oo_qty = oo_qty + @real_qty, oo_amt = oo_amt + @real_qty * @price,
					settle_qty = case when @item_stock = '1' then 0 else @stock_qty + @real_qty end,
					settle_amt = case when @item_stock = '1' then 0 else (@stock_qty + @real_qty) * @cost_price end,
					settle_amt2 = case when @item_stock = '1' then 0 else (@stock_qty + @real_qty)* @sale_price end, 
					com_flag = '0',ass_qty = @ass_stock + @ass_qty
			WHERE (item_no=@item_no and oper_date=@ls_operdate and branch_no=left(@branch_no,3))
		ELSE
			INSERT INTO t_da_jxc_daysum (
					item_no, oper_date, branch_no, cost_price, init_qty, init_amt, init_amt2,
					avg_cost_amt, avg_profit_amt,pi_qty, pi_amt, so_qty, so_amt, mi_qty,mi_amt,
					mo_qty, mo_amt, di_qty, di_amt,do_qty, do_amt, pos_qty,pos_amt, pos_ret_qty,pos_ret_amt,
					pos_send_qty,pos_send_amt, oo_qty, oo_amt, 
					settle_qty,
					settle_amt,
					settle_amt2,
					cost_change_amt, pos_dct_amt, main_sup, dec_rate,
					so_price, sale_price, com_flag,item_sup_flag,ass_qty )
			VALUES ( @item_no, @ls_operdate ,left(@branch_no,3), @cost_price,@stock_qty,@stock_money,@stock_qty*@sale_price,
					0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,@real_qty,@real_qty * @price,
					case when @item_stock = '1' then 0 else @stock_qty + @real_qty end,
					case when @item_stock = '1' then 0 else (@stock_qty + @real_qty) * @cost_price end,
					case when @item_stock = '1' then 0 else (@stock_qty + @real_qty)* @sale_price end,
					0,0,@sup_no,0,
					@so_price, @sale_price, '0',@item_sup_flag,@ass_stock + @ass_qty)
		if @@error != 0 goto myerror
	END

	-----------------关于联营的扣率与成本，毛利计算--------------------------
	IF @item_sup_flag = 'C' and charindex(@trans_no,'SO/RI/PT/LP') >=1 
	begin
		---联营扣率先去取特价扣率，没有就取商品档案的扣率
		SELECT @spec_sup_rate = (select top 1 discount from t_rm_spec_price 
			where item_no = @item_no and special_type = '0' and branch_no = left(@branch_no,3) and left(sheet_no,2)='PS'
			and	(substring(week, DATEPART(dw, @ls_operdate), 1) = '1') 
			and @ls_operdate between convert(char(10), start_date,121) and convert(char(10), end_date,121))
		if @spec_sup_rate = 0 or @spec_sup_rate is null
			select @spec_sup_rate = @item_sup_rate 

		--写入联营扣率，并更新jxc表中的成本，成本金额与毛利，按联营的方式计算。	
		IF exists(select 1 from t_da_jxc_daysum where(item_no=@item_no and oper_date=@ls_operdate and branch_no=left(@branch_no,3) and( so_qty + pos_qty + pos_ret_qty + pos_send_qty)>0))
			UPDATE 	t_da_jxc_daysum
			SET 	avg_cost_amt = (so_amt + pos_amt + pos_ret_amt) * (1 - @spec_sup_rate), 
					cost_price = (so_amt + pos_amt + pos_ret_amt) * (1 - @spec_sup_rate) / (so_qty + pos_qty + pos_ret_qty + pos_send_qty),
					avg_profit_amt = (so_amt + pos_amt + pos_ret_amt) * @spec_sup_rate,
					sup_ly_rate = @spec_sup_rate,
					settle_amt = settle_qty * (so_amt + pos_amt + pos_ret_amt) *(1 - @spec_sup_rate) / (so_qty + pos_qty + pos_ret_qty + pos_send_qty)
			WHERE (item_no=@item_no and oper_date=@ls_operdate and branch_no=left(@branch_no,3))
		else
			UPDATE 	t_da_jxc_daysum
			SET 	avg_cost_amt = (so_amt + pos_amt + pos_ret_amt) * (1 - @spec_sup_rate), 
					cost_price = (@sale_price)*(1 - @spec_sup_rate) ,
					avg_profit_amt = (so_amt + pos_amt + pos_ret_amt) * @spec_sup_rate ,
					sup_ly_rate = @spec_sup_rate,
					settle_amt = settle_qty * (@sale_price) * (1 - @spec_sup_rate) 
			WHERE (item_no=@item_no and oper_date=@ls_operdate and branch_no=left(@branch_no,3))
		IF @@error != 0 goto myerror

		--同步更新所有库存的成本价及成本金额，机构价格表成本价
		IF exists(select 1 from t_im_branch_stock where item_no=@item_no and branch_no = @branch_no)
		begin
			select @cost_price = cost_price from t_da_jxc_daysum WHERE (item_no=@item_no and oper_date=@ls_operdate and branch_no=@branch_no)
			update t_im_branch_stock set avg_cost = @cost_price, cost_amt = (stock_qty + @real_qty) * @cost_price where left(branch_no,3)=left(@branch_no,3) and item_no=@item_no
			IF @@error != 0 goto myerror

			update t_pc_branch_price set cost_price = @cost_price where item_no = @item_no and branch_no = left(@branch_no, 3) and isNull(cost_price, 0) <> @cost_price
			IF @@error != 0 goto myerror
		end
	end

	--删除不维护库存的商品，并同步将结存数据修正为0
	IF @item_stock = '1'  
	begin
		delete t_im_branch_stock where item_no = @item_no
		IF @@error != 0 goto myerror
		
		--暂不更新结存数据(对成本调价单有影响)
		--update t_da_jxc_daysum set settle_qty = 0, settle_amt = 0, settle_amt2 = 0 where (item_no=@item_no and oper_date=@ls_operdate and branch_no=left(@branch_no,3))
		--IF @@error != 0 goto myerror
	end
	
	--滞后上传的销售数据，后续的进销存数据也要调整过来
	--不管理库存的商品，则不需要调用此重算存储过程	wangjxin	2016-06-22
	select @branch_no = left(@branch_no,3)
    if isnull(@item_stock, '') <> '1' and @trans_no='PT' and @ls_operdate<@now_date and exists(select 1 from t_sys_system where sys_var_id='auto_recalculate_jxc' and sys_var_value='1')
      exec p_calculate_init_settle @ls_operdate,@branch_no,@item_no,@real_qty
	

myerror:
	return
end
go